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

时间:2013-11-26 09:24:21

标签: php symfony entities

我有一个产品实体,希望在页面上显示产品列表(来自数据库),然后在控制器中显示所选实体。

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模板:

<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>

控制器:

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

我如何在productUpdateAction()中获取所选产品? 也许我做错了,这不是最好的解决方案?

1 个答案:

答案 0 :(得分:3)

目前尚不清楚你是否已built your form。所以这是显示所选产品的代码:

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(),
    ));    
}

根据您的目标(更新产品?),应更改代码。

修改:如上所述heregetData()将返回该对象,因此您可以使用$form->get('products')->getData()->getId()来访问产品ID。