Symfony 1.4 Twitter Bootstrap 3.0 form formatter

Few days ago I decided to use free Twitter Bootstrap themes fromĀ bootswatch.com.

In my Symfony 1.4 project I use a lot of Symfony Forms and I needed to adjust them according to Twitter Bootstrap 3.0 rules.

So I created customĀ sfWidgetFormSchemaFormatter:

<?php
/**
 * Class sfWidgetFormSchemaFormatterTwitterBootstrap
 */
class sfWidgetFormSchemaFormatterTwitterBootstrap extends sfWidgetFormSchemaFormatter
{
    protected
        $rowFormat = "<div class=\"form-group %row_class%\">\n %label%\n %field%\n  %error%\n  %help%\n  %hidden_fields%\n </div>\n",
        $errorRowFormat = '%errors%',
        $errorListFormatInARow = "<p class=\"help-block\">%errors%</p>\n",
        $errorRowFormatInARow = "%error% ",
        $namedErrorRowFormatInARow = "%name%: %error% ",
        $helpFormat = '<p class="help-block">%help%</p>',
        $decoratorFormat = '%content%';

    public function __construct(sfWidgetFormSchema $widgetSchema)
    {
        foreach ($widgetSchema->getFields() as $field) {
            if (get_class($field) == 'sfWidgetFormInputText') {
                $field->setAttribute('class', 'form-control ' . $field->getAttribute('class'));
            }
        }
        parent::__construct($widgetSchema);
    }

    public function formatRow($label, $field, $errors = array(), $help = '', $hiddenFields = null)
    {
        $row = parent::formatRow(
            $label,
            $field,
            $errors,
            $help,
            $hiddenFields
        );

        return strtr($row, array(
            '%row_class%' => count($errors) ? ' has-error' : '',
        ));
    }

    public function generateLabel($name, $attributes = array())
    {
        if (isset($attributes['class'])) {
            $attributes['class'] .= ' control-label';
        } else {
            $attributes['class'] = 'control-label';
        }
        return parent::generateLabel($name, $attributes);
    }
}

There is important thing in this class on lines 18-22:

 

        foreach ($widgetSchema->getFields() as $field) {
            if (get_class($field) == 'sfWidgetFormInputText') {
                $field->setAttribute('class', 'form-control ' . $field->getAttribute('class'));
            }
        }

Here we have adjustment of the text input field with Twitter Bootstrap form class, to make it 100% width. You can also adjust other form controls by checking class names of the form widgets.

Hope this saved some time for you, enjoy!

Symofny 1.4 form: add validator for alternative email or secret question

I had a case recently – the registration form with alternative email and secret question.
In this form user needed to enter alternative email OR/AND secret question for password reminder function – at least one field must be filled. So I used approach of adding form validators dynamically.


Continue reading “Symofny 1.4 form: add validator for alternative email or secret question”