Last active
August 29, 2015 14:07
-
-
Save orasik/e144122ea44611718b9c to your computer and use it in GitHub Desktop.
[Symfony] Injecting object to form type to generate related data only
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* This example is to inject object into the form type in order to generate entity field with related data only. Rather than loading the whole entity | |
* So if we have Order and we want to list its order lines. | |
* | |
* To call this code from Contoller | |
* | |
* $order = $this->getDoctrine()->getRepository('OrderBundle:Order')->find(100); | |
* $form = $this->createForm(new ReturnOrderType($order), $order); | |
*/ | |
use Symfony\Component\Form\AbstractType; | |
use Symfony\Component\Form\FormBuilderInterface; | |
use Symfony\Component\OptionsResolver\OptionsResolverInterface; | |
use Oras\OrderBundle\Entity\Order; | |
/** | |
* This class will generate the form builder for rules | |
*/ | |
class ReturnOrderType extends AbstractType | |
{ | |
protected $order; | |
public function __construct(Order $order) | |
{ | |
$this->order = $order; | |
} | |
/** | |
* @param FormBuilderInterface $builder | |
* @param array $options | |
*/ | |
public function buildForm(FormBuilderInterface $builder, array $options) | |
{ | |
$order = $this->order; | |
$builder | |
->add('orderLines', 'entity', array( | |
'class' => 'Worldstores\OrderBundle\Entity\OrderLine', | |
'property' => 'id', | |
'multiple' => true, | |
'expanded' => true, | |
'query_builder' => function(\Doctrine\ORM\EntityRepository $er) use ($order) { | |
$qb = $er->createQueryBuilder('ol') | |
->leftJoin('ol.order', 'o') | |
->where('o = :order') | |
->setParameter(':order',$order); | |
return $qb; | |
} | |
); | |
); | |
} | |
/** | |
* @param OptionsResolverInterface $resolver | |
*/ | |
public function setDefaultOptions(OptionsResolverInterface $resolver) | |
{ | |
$resolver->setDefaults(array( | |
'data_class' => 'Oras\OrderBundle\Entity\Order' | |
)); | |
} | |
/** | |
* @return string | |
*/ | |
public function getName() | |
{ | |
return 'oras_orderbundle_orderlines'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment