Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@stefanvangastel
Created March 17, 2015 09:50
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stefanvangastel/3fd27e9c02fe999dde53 to your computer and use it in GitHub Desktop.
Save stefanvangastel/3fd27e9c02fe999dde53 to your computer and use it in GitHub Desktop.
CakePHP 3 form validation message by AngularJS directive
var appDirectives = angular.module('appDirectives', []);
/**
* Add potential validation fields to form-control form elements (CakePHP 3 with Bootstrap)
*
* Requirement: $scope.errors contains option (validation) errors in default CakePHP 3 JSON response
*/
appDirectives.directive('formControl', function($compile) {
return {
restrict: 'C', //Match all elements with form-control class
link: function(scope,element,attrs){
//Get the model and fieldname (name.field)
var elements = attrs.ngModel.split(".");
//Create a placeholder for error(s)
var template = "<span ng-repeat='(type, error) in errors." + elements[1] + "' class='help-block'><p class='text-danger'>{{error}}</p></span>";
//Compile the template and append it to the parent of the form-control element
element.parent().append($compile(template)(scope));
}
}
});
@stefanvangastel
Copy link
Author

Expects (validation)errors in a $scope.errors variable.

Example is based on Bootstrap css class, change to whatever works for you.

@solitud
Copy link

solitud commented May 22, 2016

Thanks, very useful!

@mferak
Copy link

mferak commented Jun 3, 2016

Works like charm, thank you!

Any suggestions how to perhaps make this work well with ng-messages?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment