douyi6960 2013-11-26 09:24
浏览 54

如何在symfony2中获取控制器的实体

I have a Product entity and want display a list of products (from database) on page and after that get selected entity in controller.

ProductsType:

class ProductsType extends AbstractType
{

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {

    }

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('products', 'entity', array(
                'class' => 'MyBundle:Product',
                'property' => 'description',
                'label' => false,
                'query_builder' => function(EntityRepository $er) {
                    return $er->createQueryBuilder('u')
                        ->orderBy('u.description', 'DESC');
                },
            ));
    }

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

Twig template:

<form action="{{ path('mgmt_product_update', { 'id': product.id }) }}" method="post" {{ form_enctype(form) }}>
    <strong>Product:</strong>{{ form_widget(form.products) }}
    <button value="update" name="update">Update</button>
</form>

Controller:

...
public function productUpdateAction() // ?
...

How i can get selected product in productUpdateAction() ? Maybe I'm doing it all wrong and this is not the best solution?

  • 写回答

1条回答 默认 最新

  • dongmacheng3222 2013-11-26 10:14
    关注

    It's not clear if you already built your form. So here is the code to display the selected product:

    public function productUpdateAction($id)
    {
        $product = $this->getDoctrine()
            ->getRepository('MyBundle:Product')
            ->find($product_id);
    
        $form = $this->createForm(new ProductsType(),
            $product)
            ->getForm();
    
        $form->handleRequest($request);
    
        if ($form->isValid())
        {
            # get and display the selected product
            return new Response($form->get('products')->getData()->getId());
    
            # get back to the page once the form was submitted
            return $this->redirect($this->generateUrl('mgmt_product_update',
                array('id' => $id));
        }
    
        return $this->render('YOUR_TWIG_TEMPLATE', array(
            'form' => $form->createView(),
        ));    
    }
    

    Depending on what your goal is (updating the product?), the code should be changed.

    Edit: as described here, getData() will return the object, so you can use $form->get('products')->getData()->getId() to access the product ID.

    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大