php - Symfony2 Form ManyToOne Entity-Type -
this entity:
class myentity { /** * @var \otherentity * * @orm\manytoone(targetentity="otherentity") * @orm\joincolumns({ * @orm\joincolumn(name="otherentity_id", referencedcolumnname="id") * }) */ private $otherentity; // other fields }
my controller's action:
someaction(request $request) { $em = $this->getdoctrine()->getentitymanager(); // simplified step here id=5, entities of class myentity link otherentity id=5 $otherentity = $this->getdoctrine()->getrepository('mytestbundle:otherentity')->find(5); $myentity = new myentity(); $myentity->setotherentity($otherentity); $form = $this->createform(new myentitytype(), $myentity); // form stuff isvalid, ismethod('post') etc. }
this formtype:
class myentitytype extends abstracttype { public function buildform(formbuilderinterface $builder, array $options) { parent::buildform($builder, $options); $builder->add('name', 'text'); // how add entity join added myentity otherentity (with id=5)? // tried this: ->add('otherentity', 'entity', array('class' => 'my\mytestbundle\entity\otherentity', 'read_only' => true, 'property' => 'id', 'query_builder' => function ( \doctrine\orm\entityrepository $repository) { return $repository->createquerybuilder('o') ->where('o.id = ?1') ->setparameter(1, 5); } )
) // ... other fields } // standard formtype methods etc. }
so question is, have choose $builder->add adding otherentity, if $em->persist($myentity)
inside controller persist added myentity through form, have record in database:
id | name | otherentity_id 1 | 'test' | 5
note: don't want persist new otherentity, want create new myentity , add foreign-key of otherentity.
can't use entity form type this:
$builder->add('otherentity', 'entity', array( 'class' => 'mytestbundle:otherentity' ));
Comments
Post a Comment