Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 9074007
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 16, 20262026-06-16T18:32:29+00:00 2026-06-16T18:32:29+00:00

I’m using Symfony2 form component to build and validate forms. Now I need to

  • 0

I’m using Symfony2 form component to build and validate forms. Now I need to setup validator groups based on a single field value, and unfortunately it seems that every example out there is based on entities – which im not using for several reasons.

Example:
If task is empty, all constraint validators should be removed, but if not, it should use the default set of validators (or a validator group).

In other words, what I’m trying to achieve is making subforms optional, but still be validated if a key field is populated.

Can someone possible give me an example how to configure it?

<?php
namespace CoreBundle\Form\Type;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\Validator\Constraints as Assert;
use CoreBundle\Form\Type\ItemGroupOption;

class ItemGroup extends AbstractType
{

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('title', 'text', array(
            'label' => 'Titel',
            'attr' => array('class' => 'span10 option_rename'),
            'required' => false
        ));
        $builder->add('max_selections', 'integer', array(
            'label' => 'Max tilvalg',
            'constraints' => array(new Assert\Type('int', array('groups' => array('TitleProvided')))),
            'attr' => array('data-default' => 0)
        ));
        $builder->add('allow_multiple', 'choice', array(
            'label' => 'Tillad flere valg',
            'constraints' => array(new Assert\Choice(array(0,1))),
            'choices'  => array(0 => 'Nej', 1 => 'Ja')
        ));
        $builder->add('enable_price', 'choice', array(
            'label' => 'Benyt pris',
            'constraints' => array(new Assert\Choice(array(0,1))),
            'choices'  => array(0 => 'Nej', 1 => 'Ja'),
            'attr' => array('class' => 'option_price')
        ));
        $builder->add('required', 'choice', array(
            'label' => 'Valg påkrævet',
            'constraints' => array(new Assert\Choice(array(0,1))),
            'choices'  => array(0 => 'Nej', 1 => 'Ja')
        ));
        $builder->add('options', 'collection', array(
            'type' => new ItemGroupOption(),
            'allow_add' => true,
            'allow_delete' => true,
            'by_reference' => false
            )
        );
        $builder->add('sort', 'hidden');
    }

    public function getName()
    {
        return 'item_group';
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        global $app;

        $resolver->setDefaults(array(
            'validation_groups' => function(FormInterface $form) use ($app) {

                // Get submitted data
                $data = $form->getData();

                if (count($app['validator']->validateValue($data['title'], new Assert\NotBlank())) == 0) {
                    return array('TitleProvided');
                } else {
                    return false;
                }
            },
        ));
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-16T18:32:30+00:00Added an answer on June 16, 2026 at 6:32 pm

    If you are using 2.1 you may want to have a look at “Groups based on submitted data”.

    Update

    Example using the demo contact page /demo/contact in the default AcmeDemoBundle provided with Symfony Standard Edition :

    The form type with conditional validation groups :

    namespace Acme\DemoBundle\Form;
    
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;
    use Symfony\Component\Form\FormInterface;
    use Symfony\Component\OptionsResolver\OptionsResolverInterface;
    use Symfony\Component\Validator\Constraints as Assert;
    
    class ContactType extends AbstractType
    {
        // Inject the validator so we can use it in the closure
        /**
         * @var Validator
         */
        private $validator;
    
        /**
         * @param Validator $validator
         */
        public function __construct(Validator $validator)
        {
            $this->validator = $validator;
        }
    
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder->add('email', 'email');
            $builder->add('message', 'textarea', array(
                // Added a constraint that will be applied if an email is provided
                'constraints' => new Assert\NotBlank(array('groups' => array('EmailProvided'))),
            ));
        }
    
        public function setDefaultOptions(OptionsResolverInterface $resolver)
        {
            // This is needed as the closure doesn't have access to $this
            $validator = $this->validator;
    
            $resolver->setDefaults(array(
                'validation_groups' => function(FormInterface $form) use ($validator) {
                    // Get submitted data
                    $data = $form->getData();
                    $email = $data['email'];
    
                    // If email field is filled it will not be blank
                    // Then we add a validation group so we can also check message field
                    if (count($validator->validateValue($email, new Assert\NotBlank())) == 0) {
                        return array('EmailProvided');
                    }
                },
            ));
        }
    
        public function getName()
        {
            return 'contact';
        }
    }
    

    Don’t forget to inject the validator service in the form type :

    <?php
    
    namespace Acme\DemoBundle\Controller;
    
    //...
    
    class DemoController extends Controller
    {
        // ...
    
        public function contactAction()
        {
            $form = $this->get('form.factory')->create(new ContactType($this->get('validator')));
    
            // ...
        }
    }
    

    As you can see validation of the message field will be triggered only if the email field is filled.

    Use a diff tool to catch the differences.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

We're building an app, our first using Rails 3, and we're having to build
I have thousands of HTML files to process using Groovy/Java and I need to
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
That's pretty much it. I'm using Nokogiri to scrape a web page what has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
Configuring TinyMCE to allow for tags, based on a customer requirement. My config is
I have a jquery bug and I've been looking for hours now, I can't
I am using JSon response to parse title,date content and thumbnail images and place
I am trying to find ID3V2 tags from MP3 file using jid3lib in Java.
this is what i have right now Drawing an RSS feed into the php,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.