Using jquery to find a selected option in a drop down list

If you have a drop down list in your HTML form, automatically setting the index isn't a slam dunk. jQuery doesn't make it intuitive.


How to test if an option has been selected:

Option #1 - assign an id to the options in your select input. This makes it easier to compare the selected index with your target option.

if ($("#my_select option:selected").attr("id") == "id_of_the_desired_option")
{
   ...
}

// or

if ($("#id_of_the_desired_option").attr("selected") == "selected")
{
   ...
} 

Option #2 - look at the specific value of the selected option. I don't like this because now you are hardcoding values into the code, and values can change easily, breaking your code. But it's an option, nonetheless.


if ($("#my_select option:selected").val() == "this is the option value")
{
   ...
}



Symfony forms - setting an empty value for an entity


It appears there is a bit of a bug in Symfony2, although it may have been patched with the more recent versions.

If you have created a formtype and one of your inputs is an entity, you may wish to have the first element in the drop down list to be empty (null).

To do this, you just specify 'empty_value' as a parameter when adding the input to the builder:

$builder->add
(
    'person',
    'entity',
    array
    (
        'class' => 'Me\MyBundle\Entity\Person',
        'empty_value' => 'Please choose a person'
    )
);

If you do this, then the first option will have a null value, and a label 'Please choose a person'.

This works great. However, the current symfony2 documentation says that this null option appears automatically if the input is NOT mandatory. In order to disable this first empty option, you have to turn off the empty_value parameter by doing this:

$builder->add
(
    'person',
    'entity',
    array
    (
        'class' => 'Me\MyBundle\Entity\Person',
        'empty_value' => false
    )
);

But this doesn't work. If you do this, you will get an error message:

Notice: Undefined variable: emptyValue in /home/one45dev/workspace/platform/vendor/symfony/src/Symfony/Component/Form/Extension/Core/Type/ChoiceType.php line 85 

In fact, if you want to disable the first empty option, you have to set empty_value to null , not false:


$builder->add
(
    'person',
    'entity',
    array
    (
        'class' => 'Me\MyBundle\Entity\Person',
        'empty_value' => null
    )
);

Legacy code. Bill Gates would have been proud

Our site is going through a port to Symfony2 from an  patchwork of in-house framework attempts. Every now and then, we stumble across land mines as we are refactoring. Like this one.

    /**
     * probably returns this object's primary key in the db
     *
     * @return int
     * @todo What the hell? PROBABLY returns it?
     */
    public function getId()
    {
        return $this->id;
    }