addError on a form according to field values

symfony

165 просмотра

2 ответа

360 Репутация автора

I'm trying to add a custom field validation to my fields but I can't make it work... Here is my code :

public function buildForm(FormBuilderInterface $builder, array $options)
{

    $builder
            ->add('somefields', ChoiceType::Class, array(
                '...'
            ))
            ->add('tel', TextType::class, array(
                'label' => "Téléphone :",
                'required' => false
            ))
            ->add('cell', TextType::class, array(
                'label' => "Port. :",
                'required' => false
            ))
    ;

    $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) use ($options) {
        $data = $event->getData();
        $form = $event->getForm();

        if (empty($data['tel']) && empty($data['cell'])) {
            $form->get('tel')->addError(new FormError('error message'));
        }
    });
}

What I want : if both fields are empty, warn that at least one field must be filled... I'm trying different things for days, but I can't find any solution. I guess the answer is easy though...

Thank you for your time.

Автор: ThEBiShOp Источник Размещён: 18.07.2016 07:24

Ответы (2)


0 плюса

6609 Репутация автора

Have you tried something like this:

if ( ($form->get('tel')->getData() == '') && ($form->get('cell')->getData() == '') ) {
     $form->get('tel')->addError(new FormError('error message'));
}

See if that works, not certain that it will or not.

Автор: Alvin Bunk Размещён: 18.07.2016 02:47

0 плюса

360 Репутация автора

Решение

Well, I managed to do it in another way. I've added a callback in my entity

/**
 * @Assert\Callback
 */
public function validate(ExecutionContextInterface $context, $payload) {
    if (empty($this->getTel()) && empty($this->getCell())) {
        $context->buildViolation('validation message')
                ->atPath('tel')
                ->addViolation();
        $context->buildViolation('validation message')
                ->atPath('cell')
                ->addViolation();
    }
}
Автор: ThEBiShOp Размещён: 29.07.2016 12:40
Вопросы из категории :
32x32