ठीक है दोस्तों, मेरे पास एक और तरीका है। यह अधिक जटिल है और केवल विशिष्ट मामलों के लिए है।
मेरा मामला:
मेरे पास एक फॉर्म है और सबमिट करने के बाद मैं एपीआई सर्वर पर डेटा पोस्ट करता हूं। और त्रुटियाँ मुझे एपीआई सर्वर से भी मिलीं।
एपीआई सर्वर त्रुटि प्रारूप है:
array(
'message' => 'Invalid postal code',
'propertyPath' => 'businessAdress.postalCode',
)
मेरा लक्ष्य लचीला समाधान प्राप्त करना है। इसी फ़ील्ड के लिए त्रुटि सेट करें।
$vm = new ViolationMapper();
$error['propertyPath'] = 'children['. str_replace('.', '].children[', $error['propertyPath']) .']';
$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;
}
}