2017-03-03 22 views
1

我無法設置附加DataTransformer的表格字段的默認值。使用DataTransformer的表格字段默認值

讓我們從official documentation on DataTransformers的例子:

class TaskType extends AbstractType 
{ 
    public function buildForm(FormBuilderInterface $builder, array $options) 
    { 
     $builder 
     ->add('description', TextareaType::class) 
     ->add('issue', TextType::class) 
    ; 
} 

public function configureOptions(OptionsResolver $resolver) 
{ 
    $resolver->setDefaults(array(
     'data_class' => Task::class, 
    )); 
} 

在這個例子中,一個ModelTransformer被添加到「問題」字段,轉化發行對象爲一個字符串(問題編號)繪製表格時,並在表單提交後將其轉化爲問題。

現在我經過建設者選項設置問題字段的默認值:

public function buildForm(FormBuilderInterface $builder, array $options) 
{ 
    $issue = $options['issue']; //$issue contains an Issue Object from the controller 
    $builder 
     ->add('description', TextareaType::class) 
     ->add('issue', TextType::class, array(
      'data' => $issue 
     )) 
    ; 
} 

當渲染我碰到下面的錯誤形式:

The form's view data is expected to be an instance of class AppBundle/Entity/Issue, but is a(n) string. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) string to an instance of AppBundle/Entity/Issue.

  • 傾銷$問題返回問題對象
  • 將data_class選項設置爲null,建議返回相同的錯誤
  • 傳遞$發出─>的getId()代替$問題讓我以下錯誤:「調用一個成員函數的getId()整數」

我真的不明白這個錯誤,我希望你」將能夠幫助!

+0

我覺得你錯了。您似乎想將對象傳遞給文本字段,根據定義,它只能將字符串作爲參數。如果你的對象有一個方法__toString(),但我認爲它不合邏輯,也許它有效。 –

+0

@AlphonseD。我認爲是這樣,但通過$問題 - > getId()而不是$ issue作爲'數據'值拋出另一個異常,說getId()不能在字符串值上調用,而它不是一個字符串時轉儲到buildForm中)功能,所以我真的很困惑。 – alpadev

回答

0

IssueSelectorType(孩子TextType)期望一個字符串作爲初始值和數據轉換器裏面,將其轉換爲問題實例,所以您需要改爲傳遞問題id。

然而,data選項不工作一如既往默認值:

The default values for form fields are taken directly from the underlying data structure. The data option overrides this default value (Doc.)

看到這個答案的詳細信息:How to set a default value in a Symfony 2 form field?

+0

這也是我的第一個猜測,而不是傳遞問題ID,但然後我得到「調用成員函數getId()整數」,因爲我的ModelTransformer嘗試將其轉換爲整數。這是否意味着在使用DataTransformer時爲字段設置默認值的唯一方法是通過setData()? – alpadev

+0

我試着用你的FormExtension解決方案,我仍然得到相同的錯誤 – alpadev

+0

NVM,它的工作原理,謝謝!好的解決方案 – alpadev