I came across an issue with Symfony2 forms that I can't figure out, namely, on the form there are 5 checkboxes for user roles. These are defined in an entity as constants and added to the form type, like such:
public static $GENERAL_ROLES = array(
"ROLE_ADMIN" => "ROLE_ADMIN",
"ROLE_USER" => "ROLE_USER",
"ROLE_WORKER" => "ROLE_WORKER",
"ROLE_PM" => "ROLE_PM",
"ROLE_PM_MANAGER" => "ROLE_PM_MANAGER"
);
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('username', null, array('required' => true, 'label' => "Login"))
->add('expiresAt', 'date', array(
'label' => "End account date"
'required' => false,
'widget' => 'single_text',
'format' => 'dd-MM-yyyy',
))
->add('plainPassword', 'repeated', array(
'type' => 'password',
'options' => array('translation_domain' => 'FOSUserBundle'),
'first_options' => array('label' => 'Mot de passe'),
'second_options' => array('label' => 'Confirmation'),
'invalid_message' => 'fos_user.password.mismatch',
))
->add('roles', 'choice', array(
'label' => 'Role',
'mapped' => true,
'expanded' => true,
'multiple' => true,
'attr' => array('class' => 'control-label'),
'choices' => \FullSix\ProjectForecastBundle\Entity\Login::$GENERAL_ROLES
))
;
}
So far so good, the choices appear on the form. When I submit with all roles checked, if I check $_POST, all the roles are there, all good. However, when I do $form->bind($request), things start to go south. In the validator,
class LoginValidator extends ConstraintValidator
{
public function validate($login, Constraint $constraint)
{
if ($login->getPlainPassword() || $login->getUsername() || $login->getRoles() || $login->getExpiresAt()) {
if (!$login->getPlainPassword()) {
$this->context->addViolation($constraint->noPasswordMessage);
}
if (!$login->getUsername()) {
$this->context->addViolation($constraint->noUsernameMessage);
}
if (!$login->getRoles()) {
$this->context->addViolation($constraint->noRole);
}
}
}
}
only 4 of the 5 roles are still here, specifically all except ROLE_USER. The funny thing is, if I change the value from ROLE_USER into anything else, it works fine. It only breaks with this particular value.
I couldn't find any info on weather symfony has something against using this name, or what.
Anyway, I'm really curious why this issue occurs, so if anyone could enlighten me that would be great :). Thank you.