douqi1928 2016-10-15 10:31
浏览 31
已采纳

将实体设置为默认值[symfony2]

I have a form where a user can upload a picture once the picture is upload it's also persist as true. I would like only the latest picture upload to be set as default (true) and the other picture of that particular user_id are set to true to be persist as false. I don't want a user to have many pictures as default.

This is what I have done:

public function avatarUserAction(Request $request)
{
    $em = $this->getDoctrine()->getManager();
    $user = $this->container->get('security.token_storage')->getToken()->getUser();
    $entity = new Avatar();
    $form = $this->createForm( new AvatarType(),$entity);
    if ($this->get('request')->getMethod() == 'POST') {
        $form->handleRequest($request);
        if ($form->isSubmitted() && $form->isValid()) {

            $entity->setCreatedAt(new \DateTime());
            $entity->setDefaultPicture(true);
            $entity->setUser($this->container->get('security.token_storage')->getToken()->getUser());
            $em->persist($entity);
            $em->flush();
        }
        return $this->redirect($this->generateUrl('avatarUser'));
    }

    return $this->render('ApplicationSonataUserBundle:Profile:avatar.html.twig', array('user' => $user,'entity' => $entity,
        'form' => $form->createView()));
}

.

public function avatarUserAllAction()
{
    $em = $this->getDoctrine()->getManager();
    $user = $this->container->get('security.token_storage')->getToken()->getUser();
    $entity = $em->getRepository('ApplicationSonataUserBundle:Avatar')->byAvatar($user);
    return $this->render('ApplicationSonataUserBundle:Profile:avatar_all_image.html.twig', array('user' => $user,'entity' => $entity));
}

Routing.yml

avatarUser:
    pattern:  /profile/picture
    defaults: { _controller: FLYBookingsBundle:Post:avatarUser }

avatarUserAll:
    pattern:  /profile/picture
    defaults: { _controller: FLYBookingsBundle:Post:avatarUserAll }

UserRepository

public function byAvatar($user)
{
    $qb = $this->createQueryBuilder('u')
        ->select('u')
        ->where('u.user = :user')
        ->orderBy('u.createdAt', 'DESC')
        ->setParameter('user', $user);
    return $qb->getQuery()
        ->getResult();
}

Avatar.php

class Avatar
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @var User
     * @ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User", inversedBy="avatar")
     */
    protected $user;

    /**
     * @var boolean
     * @ORM\Column(name="defaultPicture", type="boolean")
     */
    protected $defaultPicture;

    public function __construct()
    {
        $this->defaultPicture = false;
        $this->createAt = new \DateTime();
    }

    /**
     * @var \DateTime
     * @ORM\Column(name="createdAt", type="datetime", nullable=true)
     */
    protected $createdAt;

    /**
     * NOTE: This is not a mapped field of entity metadata, just a simple property.
     *
     * @Vich\UploadableField(mapping="user_image", fileNameProperty="imageName")
     *
     * @var File
     */
    private $imageFile;

    /**
     * @ORM\Column(type="string", length=255)
     *
     * @var string
     */
    private $imageName;

    /**
     * @ORM\Column(type="datetime")
     *
     * @var \DateTime
     */
    private $updatedAt;

    /**
     * If manually uploading a file (i.e. not using Symfony Form) ensure an instance
     * of 'UploadedFile' is injected into this setter to trigger the  update. If this
     * bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
     * must be able to accept an instance of 'File' as the bundle will inject one here
     * during Doctrine hydration.
     *
     * @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $image
     *
     * @return Avatar
     */
    public function setImageFile(File $image = null)
    {
        $this->imageFile = $image;

        if ($image) {
            // It is required that at least one field changes if you are using doctrine
            // otherwise the event listeners won't be called and the file is lost
            $this->updatedAt = new \DateTime('now');
        }

        return $this;
    }

    /**
     * @return File|null
     */
    public function getImageFile()
    {
        return $this->imageFile;
    }

    /**
     * @param string $imageName
     *
     * @return Avatar
     */
    public function setImageName($imageName)
    {
        $this->imageName = $imageName;

        return $this;
    }

    /**
     * @return string|null
     */
    public function getImageName()
    {
        return $this->imageName;
    }


    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set defaultPicture
     *
     * @param boolean $defaultPicture
     * @return Avatar
     */
    public function setDefaultPicture($defaultPicture)
    {
        $this->defaultPicture = $defaultPicture;

        return $this;
    }

    /**
     * Get defaultPicture
     *
     * @return boolean
     */
    public function getDefaultPicture()
    {
        return $this->defaultPicture;
    }

    /**
     * Set createdAt
     *
     * @param \DateTime $createdAt
     * @return Avatar
     */
    public function setCreatedAt($createdAt)
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * Get createdAt
     *
     * @return \DateTime
     */
    public function getCreatedAt()
    {
        return $this->createdAt;
    }

    /**
     * Set updatedAt
     *
     * @param \DateTime $updatedAt
     * @return Avatar
     */
    public function setUpdatedAt($updatedAt)
    {
        $this->updatedAt = $updatedAt;

        return $this;
    }

    /**
     * Get updatedAt
     *
     * @return \DateTime
     */
    public function getUpdatedAt()
    {
        return $this->updatedAt;
    }

    /**
     * Set user
     *
     * @param \Application\Sonata\UserBundle\Entity\User $user
     * @return Avatar
     */
    public function setUser(\Application\Sonata\UserBundle\Entity\User $user = null)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \Application\Sonata\UserBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }
}
  • 写回答

1条回答 默认 最新

  • ds342222222 2016-10-15 11:08
    关注

    Set defaultPicture to false for all user avatars before creating new one.

    if ($form->isSubmitted() && $form->isValid()) {
        foreach ($this->container->get('security.token_storage')->getToken()->getUser()->getAvatar() as $avatar) {
            $avatar->setDefaultPicture(false);
        }
    
        ...
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 请求分析基于spring boot+vue的前后端分离的项目
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥200 关于#c++#的问题,请各位专家解答!网站的邀请码
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?