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:

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

 

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!

  • James White

    Thanks alot Alex, i think there is a bug line 19, sfWidgetFormInputText doesn’t exist ? I’m using sf1.4.

    Here is what i wrote :

    <?php
    /**
    * Class sfWidgetFormSchemaFormatterTwitterBootstrap
    */
    class sfWidgetFormSchemaFormatterTwitterBootstrap extends sfWidgetFormSchemaFormatter
    {
    protected
    $rowFormat = "n %label%n %field%n %error%n %help%n %hidden_fields%n n”,
    $errorRowFormat = ‘%errors%’,
    $errorListFormatInARow = “%errors%n”,
    $errorRowFormatInARow = “%error% “,
    $namedErrorRowFormatInARow = “%name%: %error% “,
    $helpFormat = ‘%help%’,
    $decoratorFormat = ‘%content%’;

    public function __construct(sfWidgetFormSchema $widgetSchema)
    {
    foreach ($widgetSchema->getFields() as $field) {
    if (get_class($field) == ‘sfWidgetFormInput’) {
    $field->setAttribute(‘class’, ‘form-control ‘ . $field->getAttribute(‘class’));
    }
    if (get_class($field) == ‘sfWidgetFormTextarea’) {
    $field->setAttribute(‘class’, ‘form-control ‘ . $field->getAttribute(‘class’));
    }
    if (get_class($field) == ‘sfWidgetFormChoice’) {
    $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);
    }
    }

  • ian

    Hi Alex, can you show me how to use it in a template?For example in indexSucess.php where I have form and divs

    • This should not be used in a template directly, this formatter is for *automatic* form generation.
      First you need to create a form in your action like $this->form = new MyBeautifulForm() and after that you can display it in your template like echo $form;.