Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to rename a field in a form in Symfony2?

I'm using symfony2, I wondering if its possible to rename a field in a Form.

I mean... suppose i have an entity

class MyEntity{
    private $name 
    //more code
}

And i create a type for this entity:

class MyEntityType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'AppBundle\Entity\MyEntity'
        ));
    }

    public function getName()
    {
        return 'entity';
    }
}

Is there a way to rename the field name in the form but the mapping to name attribute works. something like:

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('MySuperName', null, array("mapping" => "name"))
            ;
    }

So the form param name becomes entity[MySuperName] instead of entity[name] but fills the name property on entity?

like image 558
Pipe Avatar asked Feb 24 '16 23:02

Pipe


1 Answers

Use property_path:

$builder
    ->add('MySuperName', null, array('property_path' => 'name'))

Another option would be to add get/set aliases to your name field:

public function getMySuperName()
{
    return $this->name;
}

public function setMySuperName($mySuperName)
{
    $this->name = $mySuperName;

    return $this;
}
like image 115
Jason Roman Avatar answered Oct 23 '22 05:10

Jason Roman