dongpaocuan7498 2014-02-25 09:58
浏览 45
已采纳

Symfony2表单集合字段未显示

I'll explain what I'm trying to do.

I have the following entities, Dealers Brands and Types.

1 Dealer can have many brands associated and each relation will have one type associated as well, that's why is a manyToMany relationship with an intermediate table.

I want to create a Form to Add dealers to our system and when doing so they can choose which brands are associated (there are few brands so we want to display them as checkboxes) and of what type, but trying to show this form with the brands is been tricky until now.

Brand Entity

/**
 * Brand
 *
 * @ORM\Table()
 * @ORM\Entity
 */

class Brand
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;

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

/**
 * @ORM\ManyToMany(targetEntity="TypeBrand")
 * @ORM\JoinTable(name="brand_type",
 *      joinColumns={@ORM\JoinColumn(name="brand_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="type_id", referencedColumnName="id")}
 *      )
 */
private $type;

/**
 * @ORM\OneToMany(targetEntity="DealerBrand", mappedBy="brand")
*/
private $dealerBrand;

public function __construct()
{
    $this->type = new ArrayCollection();
    $this->dealerBrand = new ArrayCollection();
}

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

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

/**
 * Set name
 *
 * @param string $name
 * @return Brand
 */
public function setName($name)
{
    $this->name = $name;
    $this->setSlug($name);

    return $this;
}

/**
 * Get name
 *
 * @return string 
 */
public function getName()
{
    return $this->name;
}

public function addType(TypeBrand $type)
{
    $this->type[] = $type;
}

public function getType()
{
    return $this->type;
}

public function addDealerBrand($dealerBrand)
{
    $this->dealerBrand[] = $dealerBrand;
}

public function getDealerBrand()
{
    return $this->dealerBrand;
}

}

Dealer Entity

/**
* Dealer
*
* @ORM\Table("dealer")
* @ORM\Entity(repositoryClass="Project\DealersBundle\Entity\Repository\DealerRepository")
* @Gedmo\Loggable
*/
class Dealer
{
/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="AUTO")
 */
private $id;

/**
 * @var string
 *
 * @ORM\Column(name="name", type="string", length=255, unique=true)
 * @Assert\NotBlank()
 * @Assert\Length(min = "10")
 */
private $name;

/**
 * @ORM\OneToMany(targetEntity="DealerBrand", mappedBy="dealer")
 *
*/
private $dealerBrand;

public function __construct()
{
    $this->dealerBrand = new ArrayCollection();
}

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

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

/**
 * Set name
 *
 * @param string $name
 * @return Dealer
 */
public function setName($name)
{
    $this->name = $name;

    return $this;
}

/**
 * Get name
 *
 * @return string
 */
public function getName()
{
    return $this->name;
}

public function addDealerBrand($dealerBrand)
{
    $this->dealerBrand[] = $dealerBrand;
}

public function getDealerBrand()
{
    return $this->dealerBrand;
}
}

DealerBrand Entity

/**
* DealerBrand
*
* @ORM\Table("dealer_brand")
* @ORM\Entity
*/
class DealerBrand
{
/**
 * @var integer
 *
 * @ORM\Id
 * @ORM\ManyToOne(targetEntity="Dealer", inversedBy="dealerBrand")
 */
private $dealer;

/**
 * @var integer
 *
 * @ORM\Id
 * @ORM\ManyToOne(targetEntity="Brand", inversedBy="dealerBrand")
 */
private $brand;

/**
 * Set dealer
 *
 * @param integer $dealer
 * @return DealerBrand
 */
public function setDealer($dealer)
{
    $this->dealer = $dealer;

    return $this;
}

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

/**
 * Set brand
 *
 * @param integer $brand
 * @return DealerBrand
 */
public function setBrand($brand)
{
    $this->brand = $brand;

    return $this;
}

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

Now this are my formtypes

DealerBrandType

class DealerBrandType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('brand', 'entity', array(
                'class'     => 'Project\DealersBundle\Entity\Brand',
                'property'  => 'name',
                'multiple'  => true,
                'expanded'  => true,
            ));
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(
        array(
            'data_class' => 'Project\DealersBundle\Entity\DealerBrand'
        )
    );
}

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

}

DealerType

    class DealerType extends AbstractType
    {
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('dealerBrand', 'collection', array(
                    'type'          => new DealerBrandType(),
                    'allow_add'     => true,
                    'allow_delete'  => true,
                ))
            ->add('Save', 'submit');
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(
            array(
                'data_class' => 'Project\DealersBundle\Entity\Dealer'
            )
        );
    }

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

And this is my controller

public function addAction()
{
        $dealer = new Dealer();

        $form = $this->createForm(new DealerType(), $dealer);

        $form->handleRequest($this->getRequest());

        if ($form->isValid()) {

            $this->getDoctrine()->getManager()->persist($dealer);
            $this->getDoctrine()->getManager()->flush();

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

        return $this->render(
            'ProjectDealersBundle:Dealers:AddDealer.html.twig',
            array(
                'form' => $form->createView()
            )
        );
    }

If this is not the correct approach please tell me, tell me also if you see bad code, that way I can improve

* EDIT *

This is the result i need

http://tinypic.com/r/24pkzdc/8

You can see there the brands and so .. so the idea is that when saving the Dealer you also save the association with the brands

* END EDIT *

Thank you!

  • 写回答

1条回答 默认 最新

  • duanji9264 2014-02-25 10:12
    关注

    I'm not sure this is the best answer ever but you can achieve it by making a custom query in your form :

            ->add('contact', 'entity', array(
                'class'         => 'AcmeBundle:Entity'
                'query_builder' => function ( \acme\bundle\Entity\entityRepository $c){
    
                    $qb = $c->createQueryBuilder('a');
    
                    return  $qb->orderBy('a.nom', 'ASC')
                                ->join('a.categories', 'c')
                                ->where( $qb->expr()->in ( 'c.id', ':listCategories') )
                                    ->setParameter( 'listCategories', array (
                                        7, 
                                    ));
                },
                'attr'          => array( 'class' => 'other')                
            ))
        ;
    }
    

    by using an 'entity' field type, i can inject custom query with the option 'query_builder' ( for more information : http://symfony.com/doc/current/reference/forms/types/entity.html )

    then, inside i declare an anonymous function ( http://php.net/manual/en/functions.anonymous.php ) to create my custom query with the createQueryBuilder.

    With the createQueryBuilder , you create your custom query ( here i had almost like you a many to many relationship and i wanted to get only some of them with a filtering array ( the set parameter ) .

    here is the doc for custom query : http://symfony.com/doc/current/book/doctrine.html

    the results of the query, if not null , will be displayed in your form

    /** ALTERNATIVE ANSWER **/

    if you want to display your dealers AND brands with a tree in your select then your have to :

    1) make a query to return an object container your dealers and brands

    2) make an array with depth that the select will display as a tree :

    here is an example to illustrate :

        ->add('contact', 'entity', array(
            'class'         => 'AcmeBundle:Entity'
            'query_builder' => function ( \acme\bundle\Entity\entityRepository $c){
    
                $dealers = $c->yourFunctionThatReturnesDealers('d');
    
                $dealersGroupedByBrands = array();
        foreach ( $dealers as $dealer) {
                        foreach ($dealers->getBrands() as $brand) {
                $dealersGroupedByBrands[$brand->getName()][] = $dealer;
            }
    
                return  $dealersGroupedByBrands;
            },
            'attr'          => array( 'class' => 'other')                
        ))
    ;
    
        }
    

    pretty cool , no ?

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)