在Symfony2中使用上载的映像更新用户配置文件

时间:2013-01-03 17:08:02

标签: php symfony

我有一个用户个人资料,允许用户上传和保存个人资料照片。

我有一个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意识到它需要持久保存新的Document实体?

当然有一个简单的用户个人资料页面,可以选择将图像上传为个人资料图片吗?

我错过了什么?

1 个答案:

答案 0 :(得分:0)

(我不认为你现在会在几个月之后得到一些反馈,但也许它可以帮助其他人解决同样的问题)

我有类似的设置和目标,发现这篇文章并在复制了一些我发现的代码后,我不需要你所称的“$ uploadedFile”-snippet作为“丑陋”。我重写了fos注册表单,我需要添加的是DocumentType.php和RegistrationFormType.php(就像你的用户UserProfileType一样)。

我不知道为什么你的版本需要丑陋的代码。 (或者,当我编写更新表单时,我可能遇到同样的问题?)。