2012-10-14 40 views
0

Symfony2中有一种方法可以自定义Type类型上的字段名称吗?自定义Symfony2上的表单字段名称

我想是这样的:

<?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'; 
    } 

} 

但我的字段仍然General[useField]名(其中一般是我的表单名称)。

我也想保持验证工作。

回答

1

Okey我在发布我的问题之前找到了我的答案,但我认为这可能对其他人有用。

我的错误是我试图动态更改字段名称,但正确的方法是更改​​表单名称。

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

以这样的方式,我的字段名变为:General80wm4kxsss[useField]而且是唯一的。