This is an earlier Symfony2 Custom Type Type or Extension question.
I am trying to attach a custom field type for a product in an order. The name field will contain the product name, and the identifier field will be the product identifier.
I use FormEvents :: PRE_SET_DATA to try to fill in the data, but it throws an error, getData () returns Form \ Type \ ProductAutoCompleteType.
How can I fix the code?
OrderType has the following:
$builder->add('product', new Type\ProductAutoCompleteType(), array(
'data_class' => 'Acme\TestBundle\Entity\Product'
));
ProductAutoCompleteType:
class ProductAutoCompleteType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options) {
$builder
->add('name');
$builder
->add('id');
/
}
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
}
public function getParent()
{
return 'form';
}
public function getName()
{
return 'productAutoComplete';
}
}
Update
Error: FatalErrorException: Error: calling the getProduct () member function for a non-object in the line /var/www/symblog/src/Acme/TestBundle/Form/Type/ProductAutoCompleteType.php 26
controller
$em = $this->getDoctrine()->getManager();
$order = $em->getRepository('AcmeTestBundle:Order')->find(6);
$form = $this->createForm(new OrderType(), $order);
Updated 2
[product] [id] , , , [product] [id], [product]?
"id", "setId()", " set()" "__call()" "Proxies__CG\Acme\TestBundle\Entity\".
3
, submit , , , ?
$data = $request->request->get($form->getName());
if ($data['product']['id']) {
$product = $em->getRepository('AcmeTestBundle:Product')->find($data['product']['id']);
if ($product) {
if ($product->getShop()->getId() != $order->getShop()->getId()) {
$form->get('product')->get('name')->addError(new FormError('Invalid shop product'));
}
$form->getData()->setProduct($product);
} else {
$form->get('product')->get('name')->addError(new FormError('A product must be selected'));
}
}