Wednesday 18 April 2012

Developing Alloy UI custom component

Hello,
    In this post I want to describe how AUI components can be developed.
    Before it, few words related Alloy UI framework. This framework built on top of Yahoo UI library. Some comparation of syntax Jquery and AUI you can find here.

    Let's develop component which will validate some form.
    First what we need form:

<%@ taglib uri="http://java.sun.com/portlet_2_0" prefix="portlet"%>
<%@ taglib uri="http://liferay.com/tld/aui" prefix="aui"%>
<%@ taglib uri="http://liferay.com/tld/portlet" prefix="liferay-portlet"%>
<%@ taglib uri="http://liferay.com/tld/theme" prefix="liferay-theme"%>
<%@ taglib uri="http://liferay.com/tld/ui" prefix="liferay-ui"%>
<%@ taglib uri="http://liferay.com/tld/util" prefix="liferay-util"%>



 
  
   
    
    
    

    
     
    
   
  
 




  new Liferay.Portlet.FormValidationComponent({
   ns: ''
  }).render();

       Now let's create custom component:
                   1) add form-validation-component.js to html/js
                   2) add                   
/js/form-validation-component.js
                       to liferay-portlet.xml
                   3) add code to form-validation-component.js:
AUI().add('form-validation-component', function(A) {
 // some component's variables
 var NS = 'ns';

 // component FormValidationComponent will be created at namespace
 // Liferay.Portlet
 Liferay.Portlet.FormValidationComponent = A.Component.create({
  // component name
  NAME : 'form-validation-component',

  EXTENDS : A.Component,

  // Component's attributes, something similar to constructor
  ATTRS : {
   ns : {}
  },

  // Base component's method which extends
  prototype : {
   bindUI : function() {
    var instance = this;
    instance._initValidation();

   },

   // Init vvalidation method
   _initValidation : function() {
    var instance = this, rules = {},
    // gets form by id
    form = A.one('#' + instance.get(NS) + 'user-form');

    // filling rules for formvalidator
    rules[instance.get(NS) + 'first-name'] = {
     required : true
    };
    rules[instance.get(NS) + 'last-name'] = {
     required : true
    };

    // create form validator
    instance.formValidatorForInputs = new A.FormValidator({
     boundingBox : '#' + form.getAttribute('id'),
     rules : rules
    });

    // binding form submit event
    form.on('submit', function(event) {
     event.preventDefault();

     if (!instance.formValidatorForInputs.hasErrors()) {
      form.io.start();
     }
    });
   }

  }
 });
}, '1.0', {
 // component's dependency
 requires : [ 'aui-form-validator-messages' ]
});

After this form will be validatable with some custom component.
Here you can find attached project's sourcecodes.

BR,
Paul

No comments:

Post a Comment