i have created my form in symfony2 form type and i used an entity type for user to choose his/her address from it like this:
$builder->add('sladdress', 'entity', array(
'class' => 'myClass\UserBundle\Entity\UserAddresses',
'property' => 'address',
'label' => 'label.your_addresses_list',
'translation_domain' => 'labels',
'mapped' => false
));
i have an UserAddresses Entity which has a ManyToOne relation to the Users Entity and saves the user's Addresses. the problem remains is that what should i do so that sladdress type loads only the Addresses that's are owned to the user?(By default the sladdress form field loads all of the addresses that exist in this entity) what is the fast way?
i found the solution , we should use the 'query_builder' argument of the symfony form types like this:
$builder->add('sladdress', 'entity', array('class' => 'myClass\UserBundle\Entity\UserAddresses', 'property' => 'address', 'label' => 'label.your_addresses_list', 'translation_domain' => 'labels', 'mapped' => false,
'query_builder' => function (EntityRepository $er) {
return $er->createQueryBuilder('u')
->where('u.user = ?1')
->setParameter(1, $this->context->getToken()->getUser());
},));
but what should we note is that we can't use $this->context in symfony formTypes so we should create a private variable named $context in this formType like this :
private $context;
and then create a constructor method in this formType that gives the security context from the controller that called the $form->createFromBuilder() on this form type:
public function __construct($context)
{
$this->context = $context;
}
and finally when we call the FormType in the controller with passing the SecurityContext as parameter to it, like this:
$form = $this->createForm(new SelectAddressType($this->get('security.context')), null, array(
'action' => $this->generateUrl('frontend_order_checkout', array('vendor_code' => $vendor_id)),
));
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments