繁体   English   中英

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

[英]How to make symfony 2 auto select the drop down field in edit action

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

我已经尝试过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'
        ));
    }        

}
categoryid 

不是实体,因此您必须在ProductEntity添加一个名为category的属性,并在那里建立关系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(
            )
                )
        )

就这样,尽情享受吧!

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

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

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

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

关键是使用jQuery。

您可以在我的博客(西班牙语)中查看详细说明(包括图像), 网址为http : //symfonyandme.com/2013/10/09/como-usar-select-dependientes-zh-symfony-1-4-con -tres-手鼓/

这里是相同的解决方案: Symfony 1.4和AJAX jQuery。 如何改善AJAX的功能,其中包含一个依赖于另一个选择框的选择框?

然后,您将为Symfony 2调整此示例

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM