我有一个允许用户上传和保存头像的用户配置文件。
我有一个UserProfile实体和一个Document实体:实体/UserProfile.php
namespace Acme'AppBundle'Entity'Profile;
use Doctrine'ORM'Mapping as ORM;
/**
* @ORM'Entity
* @ORM'Table(name="ISUserProfile")
*/
class UserProfile extends GenericProfile
{
/**
* @ORM'OneToOne(cascade={"persist", "remove"}, targetEntity="Acme'AppBundle'Entity'Document")
* @ORM'JoinColumn(name="picture_id", referencedColumnName="id", onDelete="set null")
*/
protected $picture;
/**
* Set picture
*
* @param Acme'AppBundle'Entity'Document $picture
*/
public function setPicture($picture)
{
$this->picture = $picture;
}
/**
* Get picture
*
* @return Acme'AppBundle'Entity'Document
*/
public function getPicture()
{
return $this->picture;
}
}
实体/Document.php
namespace Acme'AppBundle'Entity;
use Doctrine'ORM'Mapping as ORM;
use Symfony'Component'HttpFoundation'File'UploadedFile;
use Symfony'Component'Validator'Constraints as Assert;
/**
* @ORM'Entity
* @ORM'HasLifecycleCallbacks
*/
class Document
{
/**
* @ORM'Id
* @ORM'Column(type="integer")
* @ORM'GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM'Column(type="string", length=255, nullable=true)
*/
private $path;
/**
* @Assert'File(maxSize="6000000")
*/
private $file;
public function getAbsolutePath()
{
return null === $this->path ? null : $this->getUploadRootDir().'/'.$this->path;
}
public function getWebPath()
{
return null === $this->path ? null : $this->getUploadDir().'/'.$this->path;
}
protected function getUploadRootDir()
{
// the absolute directory path where uploaded documents should be saved
return __DIR__.'/../../../../web/'.$this->getUploadDir();
}
protected function getUploadDir()
{
// get rid of the __DIR__ so it doesn't screw when displaying uploaded doc/image in the view.
return 'uploads/documents';
}
/**
* @ORM'PrePersist()
* @ORM'PreUpdate()
*/
public function preUpload()
{
if (null !== $this->file) {
$this->path = sha1(uniqid(mt_rand(), true)).'.'.$this->file->guessExtension();
}
}
/**
* @ORM'PostPersist()
* @ORM'PostUpdate()
*/
public function upload()
{
if (null === $this->file) {
return;
}
$this->file->move($this->getUploadRootDir(), $this->path);
unset($this->file);
}
/**
* @ORM'PostRemove()
*/
public function removeUpload()
{
if ($file = $this->getAbsolutePath()) {
unlink($file);
}
}
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set path
*
* @param string $path
*/
public function setPath($path)
{
$this->path = $path;
}
/**
* Get path
*
* @return string
*/
public function getPath()
{
return $this->path;
}
/**
* Set file
*
* @param string $file
*/
public function setFile($file)
{
$this->file = $file;
}
/**
* Get file
*
* @return string
*/
public function getFile()
{
return $this->file;
}
}
我的用户配置文件表单类型添加了一个文档表单类型,以便在用户配置文件页面上包含文件上传器:
形式/UserProfileType.php
namespace Acme'AppBundle'Form;
use Symfony'Component'Form'FormBuilderInterface;
use Symfony'Component'OptionsResolver'OptionsResolverInterface;
class UserProfileType extends GeneralContactType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
/*
if(!($pic=$builder->getData()->getPicture()) || $pic->getWebPath()==''){
$builder->add('picture', new DocumentType());
}
*/
$builder
->add('picture', new DocumentType());
//and add some other stuff like name, phone number, etc
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme'AppBundle'Entity'Profile'UserProfile',
'intention' => 'user_picture',
'cascade_validation' => true,
));
}
public function getName()
{
return 'user_profile_form';
}
}
形式/DocumentType.php
namespace Acme'AppBundle'Form;
use Symfony'Component'Form'AbstractType;
use Symfony'Component'Form'FormBuilderInterface;
use Symfony'Component'OptionsResolver'OptionsResolverInterface;
class DocumentType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('file')
;
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Acme'AppBundle'Entity'Document',
));
}
public function getName()
{
return 'document_form';
}
}
在我的控制器中,我有一个更新配置文件操作:
控制器/ProfileController.php
namespace Acme'AppBundle'Controller;
class AccountManagementController extends BaseController
{
/**
* @param Symfony'Component'HttpFoundation'Request
* @return Symfony'Component'HttpFoundation'Response
*/
public function userProfileAction(Request $request) {
$user = $this->getCurrentUser();
$entityManager = $this->getDoctrine()->getEntityManager();
if($user && !($userProfile = $user->getUserProfile())){
$userProfile = new UserProfile();
$userProfile->setUser($user);
}
$uploadedFile = $request->files->get('user_profile_form');
if ($uploadedFile['picture']['file'] != NULL) {
$userProfile->setPicture(NULL);
}
$userProfileForm = $this->createForm(new UserProfileType(), $userProfile);
if ($request->getMethod() == 'POST') {
$userProfileForm->bindRequest($request);
if ($userProfileForm->isValid()) {
$entityManager->persist($userProfile);
$entityManager->flush();
$this->get('session')->setFlash('notice', 'Your user profile was successfully updated.');
return $this->redirect($this->get('router')->generate($request->get('_route')));
} else {
$this->get('session')->setFlash('error', 'There was an error while updating your user profile.');
}
}
$bindings = array(
'user_profile_form' => $userProfileForm->createView(),
);
return $this->render('user-profile-template.html.twig', $bindings);
}
}
现在,这段代码工作了…但它丑得要命。为什么我必须检查上传文件的请求对象并将图片设置为null,以便Symfony意识到它需要持久化一个新的文档实体?
当然有一个简单的用户配置文件页面与选项上传图像作为个人资料图片应该比这更简单?
我错过了什么??
(我不认为你现在期待一些反馈,几个月后,但也许它有助于其他人有同样的问题)
我有一个类似的设置和目标,发现这篇文章,在复制了一些代码后,我发现我不需要"$uploadedFile"片段,你指的是"丑陋"。我覆盖了fos注册表单,所有我需要添加的是一个DocumentType.php和一个RegistrationFormType.php(像你的用户UserProfileType)。
我不明白为什么你的版本需要这么难看的代码。(或者当我在编写Update表单时可能会遇到同样的问题?)。