Reputation: 382
I am trying to populate a dropdown menu on form from database, The choice labels are coming fine but I am unable to return proper values (Ids) against those options in the dropdown, How to write code for 'choices' in the following?
public function newModelAction(Request $request)
{
$product = $this->getDoctrine()
->getRepository('coreBundle:brand')
->findAll();
if (!$product) {
throw $this->createNotFoundException(
'No product found for id '.$productId
);
}
$model = new model();
$form = $this->createFormBuilder($model)
->add('brand_id',ChoiceType::class,array(
'label'=>'Brand Name',
'choices'=>array($product),
'choice_label' => function($product, $key, $index) {
return strtoupper($product->getName());
},
))
->add('name',TextType::class,array('label'=>'Model Name'))
->add('comment',TextType::class,array('label'=>'Comments'))
->add('save',SubmitType::class, array('label'=>'Add Model'))
->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->persist($model);
$em->flush();
return $this->render('coreBundle:layouts:newItem.html.twig',
array('form'=>$form->createView(),));
}
// ... do something, like pass the $product object into a template
return $this->render('coreBundle:layouts:newModel.html.twig',
array('form'=>$form->createView(),));
}
Form Image, Choices are populating from Db but does not return Id upon submission
I am getting following Exception:
An exception occurred while executing 'INSERT INTO model (brand_id, name, image_url, comment) VALUES (?, ?, ?, ?)' with params [null, "ABC", null, "XYZ"]: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'brand_id' cannot be null
Ignore the Image_url being null,
Upvotes: 0
Views: 2006
Reputation: 1209
first solution : Change ChoiceType by EntityType and pass your model entity to your form so symfony can do the mapping alone
second solution : get the brand_id with form->getData() and set it to your model entity
Upvotes: 1