OK, tôi có cách khác. Nó phức tạp hơn và chỉ dành cho các trường hợp cụ thể.
trường hợp của tôi:
Tôi có một hình thức và sau khi gửi tôi gửi dữ liệu đến máy chủ API. Và các lỗi tôi cũng nhận được từ máy chủ API.
định dạng lỗi máy chủ API là:
array(
'message' => 'Invalid postal code',
'propertyPath' => 'businessAdress.postalCode',
)
Mục tiêu của tôi là để có được giải pháp linh hoạt. Cho phép đặt lỗi cho trường tương ứng.
$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);
Vậy đó!
LƯU Ý!addError()
phương thức bỏ qua tùy chọn error_mapping.
hình thức của tôi (hình thức Địa chỉ nhúng theo hình thức Công ty):
Công ty
<?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;
}
}
Địa chỉ
<?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;
}
}
Cảm ơn. Nó đã giải quyết được vấn đề của tôi. – pltvs
@ m2mdas, câu trả lời tuyệt vời! Làm thế nào chúng ta sẽ dịch này? bởi vì khi chúng ta tạo một cá thể FormError, nó sẽ không dịch nó, đúng không? Tôi đã thử và nó không dịch nó, và tôi nghĩ nó có ý nghĩa. Bạn sẽ dịch một cá thể FormError như thế nào? – Mick
Xin chào @Patt, xin lỗi vì đã trả lời muộn. Thành phần Validator sẽ xử lý các thông báo vi phạm ràng buộc biểu mẫu trước khi các thông báo lỗi được thêm vào biểu mẫu. Để thêm lỗi tùy chỉnh, bạn đã dịch thư giống như cách bạn thực hiện đối với các chuỗi khác, ví dụ: '$ this-> get ('translator') -> trans ('thông báo lỗi')' –