Skip to content

Instantly share code, notes, and snippets.

@1e4
Last active August 29, 2015 14:11
Show Gist options
  • Save 1e4/ab7965abec9d7ebaecf0 to your computer and use it in GitHub Desktop.
Save 1e4/ab7965abec9d7ebaecf0 to your computer and use it in GitHub Desktop.
#Twig Field Errors
Currently there was no easy way of adding errors to a standard twig / laravel build, so I created a quick filter and thought I would share, nothing crazy but hopefully someone else might find it useful.
##Install
Copy the below code into `lwig.php` within the extensions directory, if you don't have one follow the quick step below
#####If no extension directory:
* Create a directory under `app/` named `lextra` (or whateer you want).
* In your composer make sure you are autoloading that directory `"app/lextra"`.
* Run `composer dumpautoload` to generate the autoload file
##Code
<?php
namespace Ext;
class Lwig extends \Twig_extension {
public function getFilters()
{
return array(
new \Twig_SimpleFilter('hasError', array($this, 'hasError'))
);
}
public function getName()
{
return 'Lwig';
}
/**
* Usage on twig 'FIELD_NAME'|hasError(errors)
* @param $field
* @param $errorBag
*
* @return string Class name to add to the field
*/
public function hasError($field, $errorBag)
{
//If field error exists in the $errorBag
//return the class you want to add, maybe `has-success`?
if($errorBag->first($field) === "")
return '';
//If it has an error add the error class
return ' has-error';
}
}
##Usage
Assuming you are just using bootstrap you will want to add the class `has-error`
`address_two` is the field name and `errors` is the messagebag sent when you `Redirect::back()->withInput()->withErrors()`
<div class="form-group{{ 'address_two'|hasError(errors) }}">
{{ Form.label('address_two', 'Address 2')|raw }}
{{ Form.text('address_two', '', {'class':'form-control'})|raw }}
</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment