如何使symfony 2自动选择编辑操作中的下拉字段

时间:2014-03-31 00:18:49

标签: php forms symfony

我有一个类别表和产品表。这些类别在下拉选择框中以产品形式列出。当我编辑产品时,应在产品编辑表单的类别下拉列表中自动选择保存在产品表中的类别(选中="选择")。

我已经尝试过empty_data和empty_value但它们不起作用。

我在2天内搜索解决方案,但找不到任何教程或此类示例。如果有人可以推荐我的教程或者可以看下面的代码来解决问题,我将非常感激:

控制器

<?php

// src/Scsp/CmsBundle/Controller/ProductController.php

namespace Scsp\CmsBundle\Controller;    
use Scsp\CmsBundle\Entity\CategoryEntity;
use Scsp\CmsBundle\Entity\ProductEntity;
use Scsp\CmsBundle\Form\ProductForm;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\HttpFoundation\Session\Session;

class ProductController extends Controller {     

    public function editAction($id, $request) {

        $em = $this->getDoctrine()->getManager();
        $product = $em->getRepository('ScspCmsBundle:ProductEntity')->find($id);

        if (!$product){ 
            throw $this->createNotFoundException('No product found for id ' . $id);
        }

        $productForm=new ProductForm($id);

        $form = $this->createForm($productForm, $product, array(            
            'attr' => array('class' => 'form-horizontal')
        ));

        $form->handleRequest($request);

        if ($request->isMethod('POST') && $form->isValid()) {

                $product->setCategoryid(3);                

                $em->persist($product);
                $em->flush();                
                $this->session->getFlashBag()->add('success', $product->getProducts() . ' successfully edited!');
                return $this->redirect($this->generateUrl('scsp_cms_products', array('action' => 'list', 'id' => 0)));           
        }

        return $this->render('ScspCmsBundle:Default:form.html.twig', array(
                    'form' => $form->createView(),
                    'page_title' => 'Edit product',
                    'type' => 'products',
                    'id' => $id
        ));
    }

}

产品实体:

<?php

// src/Scsp/CmsBundle/Entity/ProductEntity.php

namespace Scsp\CmsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity(repositoryClass="Scsp\CmsBundle\Repository\ProductRepository")
 * @ORM\Table(name="products")
 */
class ProductEntity {

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

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $products;

    /**
     * @ORM\Column(type="integer")
     * @ORM\ManyToOne(targetEntity="CategoryEntity", inversedBy="products")
     * @ORM\JoinColumn(name="categoryid", referencedColumnName="id")
     */
    protected $categoryid;

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

     /**
     * Set id
     *
     * @param string $id
     * @return Id
     */
    public function setId($id) {
        $this->id = $id;

        return $this;
    }

    /**
     * Set products
     *
     * @param string $products
     * @return ProductEntity
     */
    public function setProducts($products)
    {
        $this->products = $products;

        return $this;
    }

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

    /**
     * Set categoryid
     *
     * @param integer $categoryid
     * @return ProductEntity
     */
    public function setCategoryid($categoryid)
    {
        $this->categoryid = $categoryid;

        return $this;
    }

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

类别实体:

<?php

// src/Scsp/CmsBundle/Entity/CategoryEntity.php

namespace Scsp\CmsBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;

/**
 * @ORM\Entity(repositoryClass="Scsp\CmsBundle\Repository\CategoryRepository")
 * @ORM\Table(name="categories")
 */
class CategoryEntity {

    /**
     * @ORM\OneToMany(targetEntity="ProductEntity", mappedBy="categorid")
     */
    protected $products;

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

    /**
     * @ORM\Column(type="string", length=100)
     */
    protected $categories;

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

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

     /**
     * Set id
     *
     * @param string $id
     * @return Id
     */
    public function setId($id) {
        $this->id = $id;

        return $this;
    }

    /**
     * Set categories
     *
     * @param string $categories
     * @return Categories
     */
    public function setCategories($categories) {
        $this->categories = $categories;

        return $this;
    }

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

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

    /**
     * Add products
     *
     * @param \Scsp\CmsBundle\Entity\ProductEntity $products
     * @return CategoryEntity
     */
    public function addProduct(\Scsp\CmsBundle\Entity\ProductEntity $products)
    {
        $this->products[] = $products;

        return $this;
    }

    /**
     * Remove products
     *
     * @param \Scsp\CmsBundle\Entity\ProductEntity $products
     */
    public function removeProduct(\Scsp\CmsBundle\Entity\ProductEntity $products)
    {
        $this->products->removeElement($products);
    }

    /**
     * Get products
     *
     * @return \Doctrine\Common\Collections\Collection 
     */
    public function getProducts()
    {
        return $this->products;
    }
}

产品表格:

<?php

// src/Scsp/CmsBundle/Form/ProductForm.php

namespace Scsp\CmsBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use \Scsp\CmsBundle\Entity\ProductEntity;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Form\FormInterface;

class ProductForm extends AbstractType
{
    private $id;


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

    public function buildForm(FormBuilderInterface $builder, array $options)
    {

        if($this->id>0){

            $builder->add('id', 'text', 
                    array(
                        'label' => false,                        
                        'attr' => array(
                                    'class' => 'form-control',
                                    'readonly' => 'readonly'
                                  )
                        )
            ); 
        }       

        $builder     
            ->add('products', 'text', 
                    array(
                        'label' => false,                        
                        'max_length' => 100,
                        'attr' => array(
                                    'class' => 'form-control',
                                    'autocomplete' => 'off'
                                  )
                        )
                 )

            ->add('categoryid', 'entity', array(
                'label' => false,
                'class' => 'ScspCmsBundle:CategoryEntity',
                'property' => 'categories',
                'data'=>$builder->getData()->getCategoryId(),
                'attr' => array(
                )
                    )
            )

            ->add('save', 'submit',array(
                    'attr' => array(
                            'formnovalidate' => 'formnovalidate',
                            'class' => 'btn btn-primary',
                            'label' => 'Save Changes'
                        )
                    )   
                 )

            ->getForm();
    }

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

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'empty_data' => 'Scsp\CmsBundle\Entity\CategoryEntity'
        ));
    }        

}

3 个答案:

答案 0 :(得分:1)

categoryid 

不是实体,因此您必须在category中添加名为ProductEntity的属性,并在那里建立关系 ManyToOne ,代码:

/**
* @ORM\Column(type="integer")
* @ORM\ManyToOne(targetEntity="CategoryEntity", inversedBy="products")
* @ORM\JoinColumn(name="categoryid", referencedColumnName="id")
*/
protected $categoryid;

必须替换为

/**
* @ORM\Column(name="categoryid", type="integer")
*/
protected $categoryid;

/**
* @var CategoryEntity
* @ORM\ManyToOne(targetEntity="CategoryEntity", inversedBy="products")
* @ORM\JoinColumn(name="categoryid", referencedColumnName="id")
*/
protected $category;

//Here generate the get and the set customized
 /**
 * @return CategoryEntity
 */
public function getCategory()
{
    return $this->category;
}

/**
 * @param CategoryEntity $category
 * @return $this
 */
public function setCategory($category)
{
    //this is the owning side
    //all changes will be detected
    //in this side by doctrine
    $category->addProduct($this);
    $this->category= $category;

    //The line below is important to set the categoryid 
    //field in the product table
    $this->setCategoryid($category->getId());
    return $this;
}

现在在产品表单中替换:

->add('categoryid', 'entity', array(
            'label' => false,
            'class' => 'ScspCmsBundle:CategoryEntity',
            'property' => 'categories',
            'data'=>$builder->getData()->getCategoryId(),
            'attr' => array(
            )
                )
        )

 ->add('category', 'entity', array(
            'label' => false,
            'class' => 'ScspCmsBundle:CategoryEntity',
            'property' => 'categories',
            'attr' => array(
            )
                )
        )

就是这样,享受吧!

答案 1 :(得分:0)

我在表单类型中看到很多错误,但是,您要查找的是字段定义中的data选项:

->add('categoryid', 'entity', 
        array(
            'label' => false,
            'class' => 'ScspCmsBundle:CategoryEntity',
            'property' => 'categories',
            'data' => $builder->getData()->getCategoryId()
        )
     )

data字段必须包含select value属性,即categoryId,至少在正常情况下使用entity字段类型时。我不知道这是否适用于你当前的设置!

答案 2 :(得分:0)

我有一个Symfony 1.4.18的解决方案。

关键是使用jQuery。

您可以在我的博客(西班牙语)中查看详细说明(包括图片):constructor reference

此处的解决方案相同:http://symfonyandme.com/2013/10/09/como-usar-select-dependientes-en-symfony-1-4-con-tres-tablas/

然后你可以为Symfony 2

调整这个例子