Reputation: 49
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?
Upvotes: 1
Views: 9467
Reputation: 10513
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.
Upvotes: 3