Steven Brown

Tag: php

Symfony 2 Bootstrap CSS Form Templates

by on Aug.26, 2011, under CSS, PHP, Symfony

I have been playing around a bit with the Twitter Bootstrap CSS toolkit and I wanted to style the forms in a Symfony 2 project accordingly. On its own this is not a difficult task, you can do the following:

<form>
    <div class="clearfix">
        {{ form_label(form.email, 'Email Address') }}
        <div class="input">
            {{ form_widget(form.email) }}
            <span class="help-inline">{{ form_errors(form.email) }}</span>
        </div>
    </div>
    {{ form_rest(form) }}
    <input type="submit" />
</form>

This is fine enough, but it would be great to be able to do all of this using {{ form_row(form.email) }} instead of having to copy and paste the code for every field in every form.

As it turns out, creating your own templates for this stuff is pretty easy. One thing to note is if we want to mark the row as an “error” we need to add that class to the main div as well as the field itself. I also wanted to get rid of the bullet list, though you could probably achieve something similar with CSS modifications. The end result was:

{% extends 'form_div_layout.html.twig' %}
 
{% block field_errors %}
{% spaceless %}
    <span class="help-inline">
        {% if errors|length > 0 %}
            {% for error in errors %}
                {{ error.messageTemplate|trans(error.messageParameters, 'validators') }}<br />
            {% endfor %}
        {% endif %}
    </span>
{% endspaceless %}
{% endblock field_errors %}
 
{% block field_row %}
    <div class="clearfix {% if errors|length > 0 %}error{% endif %}">
        {{ form_label(form, label) }}
        <div class="input">
            {% set class = '' %}
            {% if errors|length > 0 %}
                {% set class = 'error' %}
            {% endif %}
            {{ form_widget(form, { 'attr': { 'class': class } }) }}
            {{ form_errors(form) }}
        </div>
    </div>
{% endblock field_row %}

One additional trick I added here is to be able to specify the field label in the form_row() call, something that doesn’t seem to be possible by default. Now you can add a Bootstrap ready form field row with:

{% form_theme form 'BootstrapCssBundle:Form:fields.html.twig' %}
<form>
    {{ form_row(form.email, { 'label': 'Email Address' }) }}
    {{ form_rest(form) }}
    <input type="submit" />
</form>

That’s all you need! You can put the form theme command before your form and do {{ form_widget(form) }} if you want to output the entire form in one go, as usual.

I actually broke out the styles into a few files in my Github repository.

4 Comments :, , , , , , , more...

Symfony 2 Field Comparison Validator

by on Aug.25, 2011, under PHP, Symfony

Symfony 2 comes with a range of predefined validators you can use to validate your forms, however I recently came across the need to validate that one field is equal to another. This is actually quite common since most registration forms will require you to enter your email and/or password twice.

You could easily embed a custom validator within the form itself:

use Symfony\Component\Validator\Constraints as Assert;
 
class User
{
    public $password;
 
    public $confirmationPassword;
 
    /**
     * @Assert\True(message = "The password and confirmation password do not match")
     */
    public function isPasswordEqualToConfirmationPassword()
    {
        return ($this->password === $this->confirmationPassword);
    }
}

I don’t really like that the error is added to the form rather than the individual field, and since this comparison is used often it would be much easier if it could be easily added via annotation.

In order to do this, we need two classes. The first defines the validator annotation, also known as a constraint:

use Symfony\Component\Validator\Constraint;
 
/**
* @Annotation
*/
class EqualsField extends Constraint
{
    public $message = 'This value does not equal the {{ field }} field';
    public $field;
 
    /**
     * {@inheritDoc}
     */
    public function getDefaultOption()
    {
        return 'field';
    }
 
    /**
     * {@inheritDoc}
     */
    public function getRequiredOptions()
    {
        return array('field');
    }
}

There is only one option for this constraint, that’s the name of the field we want to compare the current field against. In order to accept this field, we want to make it required and make it the default option, which means it will be populated with the first argument in the annotation (I think).

Notice how when we set the message we can use Twig style tokens, in this case {{ field }} will hold the name of the field we are comparing against.

Next, we add the validator itself, which accepts the form value and the constraint above, performs the comparison and returns whether or not it is valid:

use Symfony\Component\Validator\ConstraintValidator;
use Symfony\Component\Validator\Constraint;
 
class EqualsFieldValidator extends ConstraintValidator
{
    /**
     * Checks if the passed value is valid.
     *
     * @param mixed      $value      The value that should be validated
     * @param Constraint $constraint The constrain for the validation
     *
     * @return Boolean Whether or not the value is valid
     */
    public function isValid($value, Constraint $constraint)
    {
        if ($value !== $this->context->getRoot()->get($constraint->field)->getData()) {
 
            $this->setMessage($constraint->message, array(
                '{{ field }}' => $constraint->field,
            ));
 
            return false;
        }
 
        return true;
    }
}

Things are a bit tricky here, we don’t receive the comparison field or even the form to work with. Instead we get the form from the execution context ($this->context->getRoot()), from this we can get the field ($constraint->field from the constraint class we just created), then we get the data from it.

If the two values are not equal, we set the message with the field name and return false, essentially saying it’s invalid.

Now you can easily implement the validator with annotations:

use Skjb\Component\Validator\Constraint\EqualsField;
 
class User
{
    public $password;
 
    /**
     * @EqualsField('password', message = "The password and confirmation password do not match")
     */
    public $confirmationPassword;
}

Notice how we can still make our own nice message, we could actually use the {{ field }} token here if we wanted to.

I imagine you could easily create similar validators for less than, greater than, multiple of, or any other situation where a field is validated against another field.

You can find the code for this post at https://github.com/skjb/symfony2

Leave a Comment :, , , , , , more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!