Ich versuche, eine benutzerdefinierte Validator Einschränkung in Symfony 3.Individuelle Validator Einschränkung in Symfony 3
Ich habe, natürlich zu schaffen, folgte das doc Ende mit dieser endete:
#AppBundle\Validator\Constraint\Device.php
namespace AppBundle\Validator\Constraint;
/**
* @Annotation
*/
class Device extends \Symfony\Component\Validator\Constraint
{
public $message = 'Device "%device%" is not valid';
public $shortMessage = 'Device ID is too short';
public $chunkMessage = 'Device ID doesn\'t have a correct number of parts';
}
Constraint
#AppBundle\Validator\DeviceValidator.php
namespace AppBundle\Validator;
use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;
class DeviceValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint) : void
{
if (!$myconstraint) {
//A lot of code here
$this->context->buildViolation($constraint->shortMessage)->addViolation();
}
}
}
Und Formtype
#AppBundle\Form\Type\LoginType.php
namespace AppBundle\Form\Type;
use AppBundle\Validator\Constraint\Device;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Validator\Constraints\Length;
class LoginType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username', TextType::class, ['required' => true, 'constraints' => [new Length(['min' => 3, 'minMessage' => 'Username is too short'])]])
->add('password', TextType::class, ['required' => true, 'constraints' => [new Length(['min' => 3, 'minMessage' => 'Password is too short'])]])
->add('device', TextType::class, ['required' => true, 'constraints' => [new Device()]]);
}
}
Formular wird wie folgt erstellt:
$loginForm = Forms::createFormFactoryBuilder()->addExtension(new HttpFoundationExtension())->getFormFactory()->create(LoginType::class);
Aber was auch immer ich tue, ich diese Antwort bekam:
{ "Code": 500, "message": "Die Option \" Constraints \" ist nicht vorhanden. Definierte Optionen sind: \ "action \", \ "attr \", \ "auto_initialize \", \ "block_name \", \ "by_reference \", \ "compound \", \ "data \", \ "data_class \" "," behinderte "," leere_Daten "," Fehlerbubbing "," inherit_data "," label "," label_attr "," label_format "," mapped ", \ "method \" \ "post_max_size_message \" \ "property_path \" \ "erforderlich \" \ "translation_domain \" \ "trim \" \ "upload_max_size_message \".“ }
nach doc, «Zwang» erlaubt ist, wo ich es und ich weiß wirklich nicht, warum Symfony hier weint.
Jede Idee? vielen Dank.
"Diese Option (Einschränkungen) wird in der FormTypeValidatorExtension-Formularerweiterung hinzugefügt." http://symfony.com/doc/current/reference/forms/types/form.html#constraints – Cerad