Symfony2 entity collection default data and populating select boxes

梦想的初衷 提交于 2019-12-14 03:18:52

问题


I have a small challenge at least for me which I couldn't solve yet. Could you help me to figure it out?

Actually my question consist of two and I can't split them into a different questions.

I have Symfony2 (2.3.1) installed. Here is my entities:

Category:

// src/Acme/DemoBundle/Entity/Category.php

namespace Acme\DemoBundle\Entity;

use Gedmo\Mapping\Annotation as Gedmo;
use Doctrine\ORM\Mapping as ORM;

/**
 * @Gedmo\Tree(type="nested")
 * @ORM\Table(name="categories")
 * use repository for handy tree functions
 * @ORM\Entity(repositoryClass="Gedmo\Tree\Entity\Repository\NestedTreeRepository")
 */
class Category
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue
     */
    private $id;

    /**
     * @Gedmo\Translatable
     * @ORM\Column(name="name", type="string", length=64)
     */
    private $name;

    /**
     * @Gedmo\TreeLeft
     * @ORM\Column(name="lft", type="integer")
     */
    private $lft;

    /**
     * @Gedmo\TreeLevel
     * @ORM\Column(name="lvl", type="integer")
     */
    private $lvl;

    /**
     * @Gedmo\TreeRight
     * @ORM\Column(name="rgt", type="integer")
     */
    private $rgt;

    /**
     * @Gedmo\TreeRoot
     * @ORM\Column(name="root", type="integer", nullable=true)
     */
    private $root;

    /**
     * @Gedmo\TreeParent
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="children")
     * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="CASCADE")
     */
    private $parent;

    /**
     * @ORM\OneToMany(targetEntity="Category", mappedBy="parent")
     * @ORM\OrderBy({"lft" = "ASC"})
     */
    private $children;

Item:

// src/Acme/DemoBundle/Entity/Item.php
namespace Acme\DemoBundle\Entity;

use DoctrineExtensions\Taggable\Taggable;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\Collection;

/**
 * Item entity
 *
 * @ORM\Table(name="items")
 * @ORM\HasLifecycleCallbacks
 * @ORM\Entity
 */
class Item implements Taggable
{
    /**
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    protected $id;

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

    /**
     * @ORM\ManyToMany(targetEntity="Category", inversedBy="items")
     * @ORM\JoinColumn(name="category_id", referencedColumnName="id"),
     *      inverseJoinColumn=(name="item_id", referencedColumnName="id")
     *
     **/
    protected $categories;

     public function getCategories(){
        return $this->categories;
    }

    public function setCategories($categories){
        $this->categories = $categories;

        return $this->categories;
    }

, my form AddItemForm:

// src/Acme/DemoBundle/Controller/ItemController.php
namespace Acme\DemoBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Doctrine\ORM\EntityRepository;
use Symfony\Component\Validator\Constraints\Collection;

/**
 * Add item form
 *
 */
class AddModelForm extends AbstractType
{    public function buildForm(FormBuilderInterface $builder, array $options) {
        $builder->add('categories', 'collection', array(
                                                        'type' => 'entity',
                                                        'allow_add' => true,
                                                        'allow_delete' => true,
                                                        'prototype' => true,
                                                        'show_legend' => false,
                                                        'data' => array(''),
                                                        'widget_add_btn' => array('label' => _('Добавить категорию')),
                                                        'options' => array(
                                                                        'widget_control_group' => false,
                                                                        'label_render' => false,
                                                                        'class' => 'AcmeDemoBundle:Category',
                                                                        'query_builder' => function(EntityRepository $er) {
                                                                            return $er->createQueryBuilder('c')
                                                                                ->where('c.lvl = 0')
                                                                                ->orderBy('c.id', 'ASC');
                                                                        },
                                                                        'property' => 'name',
                                                                        'empty_value' => _('Choose category'),
                                                                    ),

                                                    )
                              );
    }
}

and controller ItemController with simple code:

// src/Acme/DemoBundle/Controller/ItemController.php
...
public function editAction($itemId) {
    $item= $em->getRepository('AcmeDemoBundle:Item')
                  ->findOneById($itemId);

    $form = $this->createForm(new AddItemForm(), $item);
}

public function addAction() {
    $item = new Item();

    $form = $this->createForm(new AddItemForm(), $item);
}
...

My categories contains subcategories and subsubcategories, etc... as it is implemented in nested tree doctrine extensions. What am I trying to achieve:

1) When I add new Item I see this view and have this behavior: http://clip2net.com/s/5jcaix (mirror: https://dl.dropboxusercontent.com/u/31477552/symfony2_form_challenge.png )

Right now I have implemented only 1 category working, where parent loads as {{ form.widget(form.categories) }} and child categories are loading with jquery. I don't like my temp solution very much. That's why I am asking for best practice in this case. May be I don't need to re-invent the wheel.

2) When I go for edit an existing Item, I want to transfer categories data to the form to display the result as we had in the add step. The mapping with a single 'entity' type or just a normal type - is easy and done automatically in Symfony2 (or you can specify 'data-class' in default options). But how to implement it in my case? With collection of entities + correct view display?

May be for someone it will be interesting challenge as well as for me and you can help me to resolve this.

来源:https://stackoverflow.com/questions/17380402/symfony2-entity-collection-default-data-and-populating-select-boxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!