1
votes

I have 2 entities: User and Location.

namespace mk\MyBundle\Entity;

use mk\MyBundle\Entity\Location;

class User 
{
    protected $user_id;
    protected $first_name;
    protected $last_name;
    protected $location;
}

and

namespace mk\MyBundle\Entity;

class Location
{
    public $country_id;
    public $country_name;
    public $state_id;
    public $state_name;
    public $city_id;
    public $city_name;
}

I'm storing user's location as a location object, within proper variable.

In profile edit page I've prepared FormType class UserType's where location is shown using nested object call:

$builder->add('location.country_id', 'country')

And when I'm using that with plain {{ form_rest(form) }} everything is ok, but when I want to address that stuff directly, like:

{{ form_widget(form.location.country_id) }} 

Twig throws me an error: Method "location" for object "Symfony\Component\Form\FormView" does not exist in MyBundle:User:profile.html.twig at line 69

What I'm doing wrong? Thanks in advance.

Updated

2
Have you found a solution?pagliuca

2 Answers

1
votes

It's fail because you are calling method "location" for object FormView. But you want to call a method from your form.

You should try

{{ form_widget(form.location.country_id) }}

Hope it's work :)

0
votes

Perhaps you found a solution in the meantime, but let me answer this for future reference to help others.

It seems unclear to me which version of symfony2 you are using, but my solution should work for Symfony 2.0 upwards.

First, a form field name containing . is illegal in symfony2.

The name "location.id" contains illegal characters. Names should start with a letter, digit or underscore and only contain letters, digits, numbers, underscores ("_"), hyphens ("-") and colons (":"). 

Do it this way instead: in your XType::buildForm(...) function use the property_path option.

$builder->add('this_is_a_valid_name_you_can_choose',
              'text', // yourtype
              array(
                  'property_path' => 'location.country_id',
              ));

This should do the trick, and your field is accessible in twig by {{ form_widget(this_is_a_valid_name_you_can_choose) }}.

For older releases I have seen some people use a path option, but I never found this documented.