OKみんな、別の方法があります。それはより複雑で、特定の場合のみです。
私の場合:
私はフォームを持っているとした後、私はAPIサーバーにデータをポスト提出します。また、APIサーバーからもエラーが発生しました。
APIサーバーエラーのフォーマットは次のとおりです。
array(
'message' => 'Invalid postal code',
'propertyPath' => 'businessAdress.postalCode',
)
私の目標は、柔軟なソリューションを取得することです。対応するフィールドのエラーを設定します。
$vm = new ViolationMapper();
// Format should be: children[businessAddress].children[postalCode]
$error['propertyPath'] = 'children['. str_replace('.', '].children[', $error['propertyPath']) .']';
// Convert error to violation.
$constraint = new ConstraintViolation(
$error['message'], $error['message'], array(), '', $error['propertyPath'], null
);
$vm->mapViolation($constraint, $form);
これだけです!
注記!addError()
メソッドは、error_mappingオプションをバイパスします。
マイフォーム(会社の形で埋め込まれたアドレス形式):
会社
<?php
namespace Acme\DemoBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints;
class Company extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('companyName', 'text',
array(
'label' => 'Company name',
'constraints' => array(
new Constraints\NotBlank()
),
)
)
->add('businessAddress', new Address(),
array(
'label' => 'Business address',
)
)
->add('update', 'submit', array(
'label' => 'Update',
)
)
;
}
public function getName()
{
return null;
}
}
住所
<?php
namespace Acme\DemoBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints;
class Address extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// ...
->add('postalCode', 'text',
array(
'label' => 'Postal code',
'constraints' => array(
new Constraints\NotBlank()
),
)
)
->add('town', 'text',
array(
'label' => 'Town',
'constraints' => array(
new Constraints\NotBlank()
),
)
)
->add('country', 'choice',
array(
'label' => 'Country',
'choices' => $this->getCountries(),
'empty_value' => 'Select...',
'constraints' => array(
new Constraints\NotBlank()
),
)
)
;
}
public function getName()
{
return null;
}
}
感謝。それは私の問題を解決しました。 – pltvs
@ m2mdas、すばらしい答え!私たちはこれをどのように翻訳しますか?一旦FormErrorインスタンスを作成すると、それは翻訳されないため、そうですか?私は試してみましたが、それを翻訳していないので、意味があると思います。 FormErrorインスタンスをどのように変換しますか? – Mick
こんにちは@Patt、遅く返事を申し訳ありません。 Validatorコンポーネントは、エラーメッセージがフォームに追加される前にフォーム制約違反メッセージの変換を処理します。カスタムエラーを追加するには、 '$ this-> get( 'translator') - > trans( 'エラーメッセージ')のように他の文字列と同じようにメッセージを翻訳してください。 –