My Profile Photo

David Freund


Business Analyst, amateur Developer (PHP, Ruby - in my leisure time and with mixed results)

New Laravel Gist: Twitter Bootstrap Forms

Working on a Laravel App refactoring (will post more on this soon), I discovered a challenge: Integrating Twitter Bootstrap Form layouts into Laravel Blade templates.

Twitter Bootstrap has a whole lot of design options for forms:

  • Validation states (success/error)
  • Validation marks
  • Error messages
  • …

However, using them, requires wrapping each form element in his own div, adding classes based on status etc. Doing this for every single one of them is rather tiring, so I wrote (up to now) two blades, that display password and text fields and wraps them accordingly.

You can find them here on Github.

<?php
// Check if error messages exists for this field -> Form group will be marked as "error"
if ($errors->has($field) ):
	echo "<div class='form-group has-error has-feedback'>";
// Check if Old Input exists without error messages -> Field group will be marked as "succes"
elseif ( Input::old($field) && ! $errors->has($field) ):
	echo "<div class='form-group has-success has-feedback'>";
else:
	echo "<div class='form-group'>";
endif;
?>


<?php
  if ($errors->has($field) ):
  		echo '<span class="fa fa-exclamation-triangle form-control-feedback"></span>';
  elseif ( Input::old($field) && ! $errors->has($field) ):
  		echo '<span class="fa fa-check-square form-control-feedback"></span>';
	endif;
?>
  @foreach($errors->get($field) as $message)
    <p class="help-block"></p>
  @endforeach
</div>

The Laravel blade assumes that three variables are given:

  • $field:  The name of the field
  • $context: The context, which is basically the name of the appropriate language file
  • $error: The Laravel error messages bag

Further, the language variable should be like this

  • ‘field’ - Name of the field
  • field_placeholder - Placeholder of the input field

For example,for the field email I would include this blade by using

  <?php
  @include('__partials.form.text', array('context'=>'user', 'field'=>'email', 'errors'=>$errors) )
  ?>

While having the following within lang/en/user.php

<?php
return array(
/*
|--------------------------------------------------------------------------
| User Language Lines
|--------------------------------------------------------------------------
|
/*
*  User attributes
*/
  "email" => 'Email',

/*
* Form texts
*/
  'email_placeholder'=> 'Enter your email address',
);

This drastically reduces the amount of code, I have to write to insert a new field and allows to make central changes to all forms, if required.

Feel free to comment, copy or branch :D