1

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?

1 Answer 1

1

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)),
    ));
Sign up to request clarification or add additional context in comments.

4 Comments

Why do you pass whole security.context while you could pass only User from token?
Also, your security context token can return anon. users
@DonCallisto yes i could pass just User from the token , but i may need other things fom the context in the future
@Mohammad: "in the future" ... if you're not sure, don't pass whole security.context, is not a good practice ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.