私のコントローラーで自分のフォームのフィールドを「編集」するソリューションを策定するのに問題があります。コントローラのフォームのフィールドを編集するにはどうすればよいですか?
は私が私のコントローラ内の関数で呼び出すサービスとして登録Symfony2のフォームを持っている:
は、ここで私が持っているものです。私はこの他のフォームのために必要ではないフィールドの束を削除しています。私はユーザに指示してからいくつかのものを追加しています。 (私は別のフォームを作成して別のサービスを作成することができることを認識していますが、私の目的のためにはこれはちょっと残酷かもしれません。 )
このフォームの1つのフィールドを基本的に「編集」したいと思います。「職業」フィールド。このフィールドは、choice
フィールドであり、ラジオボタンとして機能し、選択肢の配列によって配置されます。それはrequired
であり、元の状態ではempty_value
という要件はありません。
しかし私は、false
とnull
のempty_value
のrequired
値と同じ正確な値を持つように私のコントローラ機能でそれを編集したいと思います。
結果の下にコメントアウトされたコードは、「新しい」フォームのoccupation
フィールドの消失であり、空のドロップダウンに置き換えられます。私は下のフィールド全体をオーバーライドしているからだと思いますが、単純に編集する方法を理解できません。
コード:
/**
* Explanation of addAndRemoveFieldsInRegisterForm function:
* The function gets the 'registration' form and removes any
* fields not needed for the 'in_registration' form
* and then adds the necessary fields to the form.
*/
private function addAndRemoveFieldsInRegisterForm($user)
{
$form = $this->createForm('user_registration', $user);
// http://stackoverflow.com/questions/10920006/pass-custom-options-to-a-symfony2-form ---
// --- use that to help. Look at changing the value of array.
$form->remove('title');
$form->remove('company');
$form->remove('username');
$form->remove('city');
$form->remove('state');
$form->remove('country');
$form->remove('gender');
$form->remove('age');
$form->remove('roles');
// $form->remove('occupation');
// $pr = $form->get('occupation');
// $pr->set('required' => false);
// $form->get('occupation')->add('required'=>false, 'empty_value'=>null);
// $form->add('occupation','choice', array(
// 'required' => false,
// 'empty_value' => null,
//));
// echo "<pre>";
// var_dump(get_class_methods($form));die;
$form->add('occupation','choice', array(
'required' => false,
'empty_value' => null,
));
$form->add('canEmail', 'checkbox', array(
'label' => 'Can Email?',
'required' => false,
));
$form->add('sendEmail', 'choice', array(
'label' => 'Send Welcome Email? ',
'required' => true,
'mapped' => false,
'expanded' => true,
'choices' => array(
"yes" => "Yes",
"no" => "No"
),
));
return $form;
}
オリジナルフォーム(サービスとして使われています1)
private $requireOccupation;
$this->requireOccupation = true;
->add('occupation','choice', $options['occupation'])
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$occupation = array(
"label" => "Which of these currently describes you best? (Occupation):",
"expanded" => true,
'required'=> $this->requireOccupation,
"choices" => array(
"X" => "X",
"B" => "B",
"C" => "C",
"J" => "J",
),
'constraints' => array(
new NotBlank()
));
$resolver->setDefaults(array(
'occupation' => $occupation,
));
}
新しいデフォルト値を持つようにウィジェットを編集するか、デフォルト値を考慮するためにユーザーが入力したデータを編集しますか? – goto
私は新しいデフォルト値を持つようにウィジェットを編集したいだけでなく、他の(編集されていない)値も保持します。 – Ale