类型字符串的预期参数,给定的对象 - Symfony2

时间:2012-09-19 10:14:01

标签: php symfony doctrine-orm

我有朋友和类别 - 每个朋友都有一个类别。在主页上可以看到所有朋友的列表,并且有一个包含所有类别和提交按钮的下拉菜单 - 当您选择类别并单击它时,您只能看到此类别中的朋友。

这是 Category.php

<?php

namespace EM\MyFriendsBundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * EM\MyFriendsBundle\Entity\Category
 * @ORM\Entity
 * @ORM\Table(name="categories")
 * @ORM\Entity(repositoryClass="EM\MyFriendsBundle\Entity\SameRepository")
 */
class Category 
{
    /**
     * @ORM\Column(type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

    /**
     * @ORM\Column(type="string", length=100)
     * @Assert\NotBlank()
     * @Assert\MinLength(
     *         limit=3,
     *         message="The name is too short." )
     */
    protected $name;

    /**
     * @ORM\Column(type="string", length=225, nullable=true)
     */
    protected $description;

     /**
     * @ORM\ManyToOne(targetEntity="User", inversedBy="categories")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
    protected $user;

    /**
     * @ORM\OneToMany(targetEntity="Friend", mappedBy="category")
     * @ORM\OrderBy({"name" = "ASC"})
     */
    protected $friends;

    public function __construct()
    {
        $this->friends = new \Doctrine\Common\Collections\ArrayCollection();
    } 

    public function getId()
    {
        return $this->id;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getName()
    {
        return $this->name;
    }

    public function setDescription($description)
    {
        $this->description = $description;
    }

    public function getDescription()
    {
        return $this->description;
    }

    public function setUser(\EM\MyFriendsBundle\Entity\User $user)
    {
        $this->user = $user;
    }

    public function getUser()
    {
        return $this->user;
    }

    public function addFriend(\EM\MyFriendsBundle\Entity\Friend $friend)
    {
        $this->friends[] = $friend;
    }

    public function getFriends()
    {
        return $this->friends;
    }
} 

ChooseCatType.php

<?php

namespace EM\MyFriendsBundle\Entity;

use Symfony\Component\Form\FormBuilder;
use Symfony\Component\Form\AbstractType;

class ChooseCatType extends AbstractType
{
    protected $user;

    function __construct($user) 
    {
        $this->user = $user;
    }

    public function buildForm(FormBuilder $builder, array $options)
    {
        $user = $this->user;

        $builder->add('name', 'entity', array(
            'class' => 'EMMyFriendsBundle:Category',
            'property' => 'name',
            'empty_value' => 'All friends',
            'required' => false,
            'query_builder' => function ($repository) use ($user)
                { return $repository->createQueryBuilder('cat')
                                    ->select('cat')
                                    ->where('cat.user = :user')
                                    ->orderBy('cat.name', 'ASC')
                                    ->setParameter('user', $user);
                }, ));
    }

    public function getName()
    {
        return 'choose_category';
    }
}

这是控制者的行动:

public function filterAction(Request $request)
   {
       $this->init();

       $cat = new Category();

       $dd_form = $this->createForm(new ChooseCatType($this->user), $cat);

       if($request->getMethod() == 'POST') { 
           $dd_form->bindRequest($request);

           if($cat->getName() == null) {      
               return $this->redirect($this->generateUrl('home_display'));
           }

           $filter = $cat->getName()->getId();

           if ($dd_form->isValid()) {   
               $friends = $this->em->getRepository('EMMyFriendsBundle:Friend')
                   ->filterFriends($filter);

               if(!$friends) {
                   $this->setFlash('There are no frieds in this category.', 'error');
                   return $this->redirect($this->generateUrl('home_display'));
               }
           }

           return $this->render('EMMyFriendsBundle:Home:filtered_home.html.twig', array(
                   'friends' => $friends, 'category' => $cat->getName()->getName(), 
                   'dd_form' => $dd_form->createView()));   
       }

       return $this->redirect($this->generateUrl('home_display'));
   }
}

其中init()设置$this->em = $this->getDoctrine()->getEntityManager();$this->user = $this->get('security.context')->getToken()->getUser();

我收到错误:Expected argument of type string, object given,但无法理解它来自哪里以及如何解决它。有什么帮助吗?真的很感激。我认为它出现在这一行$dd_form->bindRequest($request);上,因为当我把exit;放在它之前程序退出时,但当我把它放在它之后,它会显示错误。

另一件事是当我删除

@Assert\MinLength(
         *         limit=3,
         *         message="The name is too short." )

位于 Category.php 中的name属性之上,一切都很完美。

任何想法都会有所帮助!谢谢你的时间!

还有一件事 - 为什么要获得我应该使用$cat->getName()->getId();类别的ID?我认为它应该只是$cat->getId(),但事实并非如此。

1 个答案:

答案 0 :(得分:3)

当您使用“实体”字段类型时,从中获取的内容是实体,因此将此字段称为“名称”没有意义。所以我会将您的构建器更改为:

$builder->add('category', 'entity', array(
...

然后,您不需要将Category对象传递给此表单构建器。这通常在表单使用对象属性连接每个字段时完成,但事实并非如此。您没有使用此表单来获取Category对象的“category”属性。这只是一个表单,它将返回一个Category对象,您可以从表单数据中获取该对象。所以将控制器更改为:

public function filterAction(Request $request)
   {
       $this->init();

       $dd_form = $this->createForm(new ChooseCatType($this->user));

       if($request->getMethod() == 'POST') { 
           $dd_form->bindRequest($request);

           if ($dd_form->isValid()) {   
               $data = $form->getData();
               $cat = $data['category'];

               $filter = $cat->getId();
               $friends = $this->em->getRepository('EMMyFriendsBundle:Friend')
                   ->filterFriends($filter);

               if(!$friends) {
                   $this->setFlash('There are no frieds in this category.', 'error');
                   return $this->redirect($this->generateUrl('home_display'));
               }
               return $this->render('EMMyFriendsBundle:Home:filtered_home.html.twig', array(
                   'friends' => $friends, 'category' => $cat->getName(), 
                   'dd_form' => $dd_form->createView()));   
           }

       }

       return $this->redirect($this->generateUrl('home_display'));
   }
}