Alain
Alain

Reputation: 36954

Customise form field names on Symfony2

Is there a way in Symfony2 to customise field names on Type classes ?

I tried something like this :

<?php

// src/Fuz/TypesBundle/Form/Editor/GeneralType.php

namespace Fuz\TypesBundle\Form\Editor;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Fuz\TypesBundle\Entity\Editor\GeneralData;

class GeneralType extends AbstractType
{

    /**
     * Root node ID
     *
     * @access private
     * @var rootId
     */
    private $rootId;

    /**
     * Current node ID
     *
     * @access private
     * @var rootId
     */
    private $currentId;

    /**
     * Constructor
     *
     * @access public
     * @param string $rootId
     * @param string $currentId
     */
    public function __construct($rootId, $currentId)
    {
        $this->rootId = $rootId;
        $this->currentId = $currentId;
    }

    /**
     * General form fields
     *
     * @access public
     * @param FormBuilder $builder
     * @param array $options
     */
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('useField', 'text',
           array (
                'required' => false,
                'label' => 'types.general.use_field',
                'read_only' => ($this->rootId == $this->currentId),
                'attr' => array(
                        'name' => "useField{$this->currentId}",
                )
        ));
        // ...
    }

    /**
     * Form name
     *
     * @access public
     * @return string
     */
    public function getName()
    {
        return 'General';
    }

}

But my field has still the General[useField] name (where General is my form name).

I also want to keep validation to work.

Upvotes: 0

Views: 2057

Answers (1)

Alain
Alain

Reputation: 36954

Okey I found my answer before posting my question, but I think this could be useful for somebody else.

My mistake was I tried to change dynamically the field names, but the right way was to change the form name.

/**
 * Form name
 *
 * @access public
 * @return string
 */
public function getName()
{
    return 'General' . $this->currentId;
}

In such a way, my field name becomes : General80wm4kxsss[useField] and is unique.

Upvotes: 1

Related Questions