2014-01-29 90 views
0

幾小時前,我會參考my question I asked,現在我將嘗試詢問更具體的問題。使用Symfony2自定義表單字段

我遵循了official cookbookthis article的指導原則。

我在Me\MyBundle\Controller\Form\Type中增加了新的class MyType extends AbstractType direcory。

我已經爲該自定義字段類型創建了一個模板。

我在config.yml中添加了正確的條目,以便在表單中使用新模板。

但我該如何使用該自定義字段?

比方說,我有控制器,它看起來像這樣:->add('my_type', new MyType(), array('param' => 0))

namespace Me\MyBundle\Controller; 

use Symfony\Bundle\FrameworkBundle\Controller\Controller; 
use Me\MyBundle\Form\Type\MyType; 

class DefaultController extends Controller 
{ 
    public function indexAction() 
    { 
     $form = $this->createFormBuilder() 
      ->add('my_type', new MyType(), array('param' => 0)) 
      ->getForm() 
     ; 
     return $this->render('MyBundle::index.html.twig', array(
      'form'  => $form->createView(), 
     )); 
    } 
} 

行似乎並沒有對生成表單有任何影響。也沒有錯誤。

如何讓我的自定義字段在同一表單中多次重複使用,使用不同的params

編輯:

MyType類看起來是這樣的:

class MyType extends AbstractType 
{ 
    public function setDefaultOptions(OptionsResolverInterface $resolver) 
    { 
     $resolver->setDefaults(array(
      'param' => 1, 
      ) 
     )); 
    } 

    public function getParent() 
    { 
     return 'text'; 
    } 

    public function getName() 
    { 
     return 'my_type'; 
    } 
} 
+0

你有沒有爲MyType的類一些代碼? –

+0

@DerickF,是的,我有。我編輯了我的問題並添加了該課程的內容。 – mkas

+0

您應該通過輸入' - > add('whatever_name','my_type',array('param'=> 0))來添加它。' –

回答

0

可嘗試工具buildForm方法:

/** 
* @param FormBuilderInterface $builder 
* @param array $options 
*/ 
public function buildForm(FormBuilderInterface $builder, array $options 
{ 
    $builder->add(...); 
} 
+0

也許嘗試使用MyType :: class或null而不是新的MyType()! –