Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
<form name="CreatePerson" type="single" target="createPracticePerson">
      <auto-fields-service service-name="createPracticePerson"/>
      <field name="submitButton" title="Create" widget-style="smallSubmit"><submit button-type="button"/></field>
</form>

Step - 2 : Write CRUD CrUD operations for person entity.this is a code for createPracticePerson in services.xml

...

What is AJAX: AJAX stands for Asynchronous JavaScript and XML. It is used for allowing the client side of an application to communitcate with the server side of the application. Before AJAX, there was no way for the client side of a web application to communicate directly with the server. Instead, you would have to use page loads. With AJAX, the client and server can communicate freely with one another without page laodsreloads.

In OFBiz we use prototype framework. Prototype is a Open Source JavaScript Framework that aims to ease development of dynamic web applications. Here is the official link: prototypejs

...

  • This will allow .js files which are under /js folder to load.
  • Step -7 will make you understand more, why we are doing this entry here.
Code Block


<init-param>
    <param-name>allowedPaths</param-name>
    <param-value>/control:/select:/index.html:/index.jsp:/default.html:/default.jsp:/images:/includes/maincss.css:/js</param-value>
</init-param>

  • Here you must not miss that this will require a server startrestart.

Step - 2 : Include validation.js and prototype.js in main-decorator in practice/widget/CommonScreens.xml. For this you have to write below given code in <actions> block of main-decorator.

  • We are including these library files in main-decorator screen, because all other screens uses main-decorator and thus both the libraries will be available in other screens as well.
Code Block


<set field="layoutSettings.javaScripts[+0]" value="/images/prototypejs/validation.js" global="true"/>
<set field="layoutSettings.javaScripts[]" value="/images/prototypejs/prototype.js" global="true"/>

validation.js and prototype.js are located at framework/images/webapp/images/prototypejs/

Step - 3 : Add another menu item to application menu bar by name "Ajax". Below given is the controller entry:

Code Block

<!-- Request Mapping -->

<request-map uri="Ajax">
    <security https="true" auth="true"/>
    <response name="success" type="view" value="PersonFormByAjax"/>
</request-map>

<!-- View Mapping -->

<view-map name="PersonFormByAjax" type="screen" page="component://practice/widget/PracticeScreens.xml#PersonFormByAjax"/>

Step - 4 : Create new screen called "PersonFormByAjax" in PracticeScreens.xml. Example code is given below:

  • PracticeApp.js is the custom js file where we will be writing our custom js code for ajaxifying our request.
  • person.ftl is the same file we created above.
  • CreatePerson.ftl is a new file which you need to create now. This file contains form for creating new person, which is same as we created in step-1 of Part-3 under "Writing CRUD CrUD operations for Person entity" section. Only difference is that this form is written in freemarker.
Code Block

<screen name="PersonFormByAjax">
        <section>
            <actions>
                <set field="headerItem" value="ajax"/>
                <set field="titleProperty" value="PageTitlePracticePersonForm"/>
                <property-map resource="PartyUiLabels" map-name="uiLabelMap" global="true"/>
                <set field="layoutSettings.javaScripts[]" value="/practice/js/PracticeApp.js" global="true"/>
                <entity-condition entity-name="Person" list="persons"/>
            </actions>
            <widgets>
                <decorator-screen name="CommonPracticeDecorator" location="${parameters.mainDecoratorLocation}">
                    <decorator-section name="body">
                        <platform-specific>
                            <html>
                                <html-template location="component://practice/webapp/practice/person.ftl"/>
                                <html-template location="component://practice/webapp/practice/CreatePerson.ftl"/>
                            </html>
                        </platform-specific>
                    </decorator-section>
                </decorator-screen>
            </widgets>
        </section>
    </screen>

Step - 5 : Create new file CreatePerson.ftl explained above in practice/webapp/practice/ and place below given code:

  • Also notice ids used in this .ftl file.
  • We will be using this these ids in our js file.
Code Block


<h2>${uiLabelMap.PartyCreateNewPerson}</h2>
<div id="createPersonError" style="display:none"></div>
<form method="post" id="createPersonForm" action="<@ofbizUrl>createPracticePersonByAjax</@ofbizUrl>">
    <fieldset>
      <div>
        <label>${uiLabelMap.FormFieldTitle_salutation}</label>
        <input type="text" name="salutation" value=""/>
      </div>
      <div>
        <label>${uiLabelMap.PartyFirstName}*</label>
        <input type="text" name="firstName"  value=""/>
      </div>
      <div>
        <label>${uiLabelMap.PartyMiddleName}</label>
        <input type="text" name="middleName" value=""/>
      </div>
      <div>
        <label>${uiLabelMap.PartyLastName}*</label>


        <input type="text" name="lastName" class="required" value=""/>
      </div>
      <div>
        <label>${uiLabelMap.PartySuffix}</label>
        <input type="text" name="suffix" value=""/>
      </div>
      <div>
        <a id="createPerson" href="javascript:void(0);" class="buttontext">${uiLabelMap.CommonCreate}</a>
      </div>
    </fieldset>
</form>

  • Click on "Ajax" menu to observe the PersonFormByAjax screen.

...

  • Here on first line, Event.observe(element, eventName, handler), registers an event handler on a DOM element.
    • Argument 1: The DOM element you want to observe; as always in Prototype, this can be either an actual DOM reference, or the ID string for the element.
    • Argument 2: The standardized event name, as per the DOM level supported by your browser. This can be as simple as 'click'.
    • Argument 3: The handler function. This can be an anonymous function you create on-the-fly, a vanilla function.
  • So here on window load, on-the-fly function is called. where form validations and request calling is done.
  • Important thing to notice is why we write other observation code on window load event, and answer is here we keep restriction, that on window load, all the elements of the form will get activated and then we put observation on form's elements.
  • In CreatePerson.ftl you see that class="required" are used on forms's input element, You then activate validation by passing the form or form's id attribute as done in second line. More on this can be learned from learn validation
  • On third line, observer is on "createPerson" which is id of anchor tag (button) in CreatePerson.ftl,
  • so that when end user clicks "create button" , the instance method, validate(), will return true or false. This will activate client side validation.
  • And then createPerson function is called which is out of the scope of window load observer.
  • In request variable, createPersonForm's action is stored. $('createPersonForm') is again a id of form in CreatePerson.ftl.
  • new Ajax.Request(url) : Initiates and processes an AJAX request.
  • The only proper way to create a requester is through the new operator. As soon as the object is created, it initiates the request, then goes on processing it throughout its life-cyle.
  • Request life cycle:
    • Created
    • Initialized
    • Request sent
    • Response being received (can occur many times, as packets come in)
    • Response received, request complete
  • So here createPracticePersonByAjax request will be called from controller.xml, which will call createPracticePerson service and do needful entries.
  • Form's elements are serialized and passed as a parameter in ajax request. This is represented in last line of createPerson function.
  • Now if response is successful and server has not returned an error, "new Ajax.Updater($('personList'), 'UpdatedPersonList'" will be executed.
  • Ajax updater, performs an AJAX request and updates a container's contents based on the response text. To get more on this please read : ajax updater
  • So "personList" is the id of div in person.ftl, which will be replaced by response of UpdatedPersonList request.
Code Block

Event.observe(window, 'load', function() {
    var validateForm = new Validation('createPersonForm', {immediate: true, onSubmit: false});
    Event.observe('createPerson', 'click', function() {
       if (validateForm.validate()) {
           createPerson();
       }
    });
});

function createPerson() {
    var request = $('createPersonForm').action;
    new Ajax.Request(request, {
        asynchronous: true,
        onComplete: function(transport) {
            var data = transport.responseText.evalJSON(true);
            var serverError = getServerError(data);
            if (serverError != "") {
                Effect.Appear('createPersonError', {duration: 0.0});
                $('createPersonError').update(serverError);
            } else {
                Effect.Fade('createPersonError', {duration: 0.0});
                new Ajax.Updater($('personList'), 'UpdatedPersonList', {evalScripts: true});
            }
        }, parameters: $('createPersonForm').serialize(), requestHeaders: {Accept: 'application/json'}
    });
}

getServerError = function (data) {
    var serverErrorHash = [];
    var serverError = "";
    if (data._ERROR_MESSAGE_LIST_ != undefined) {
        serverErrorHash = data._ERROR_MESSAGE_LIST_;

        serverErrorHash.each(function(error) {
            if (error.message != undefined) {
                serverError += error.message;
            }
        });
        if (serverError == "") {
            serverError = serverErrorHash;
        }
    }
    if (data._ERROR_MESSAGE_ != undefined) {
        serverError += data._ERROR_MESSAGE_;
    }
    return serverError;
};

Step - 8: Now do required controller.xml entries :

...

Note
  • One important thing to remember is "id" used in form should always be unique. And if you use same id on different elements then prototype may get confused and your javascript will be blocked. these can well observed using firbug.
  • Also installation of firebug is suggested from get firebug, for debugging javascript in Mozilla.

...

If you have followed all the steps and developed practice application from this application tutorial then this will really help you in understanding other implementations in OFBiz. These things are basic foundation of working in OFBiz. Now you know that how you can start the development in OFBiz. Don't leave the extra links provided in this tutorial as they will really help you a lot in understanding the things which are there.
Here is another good reading will be help you a lot is available at FAQ Tips Tricks Cookbook HowTo
Now the next thing comes in mind is the business process which is really needed to work onread out for understanding OOTB implemention in OFBiz, flow of these processes and data model, so for this, books are available at : OFBiz Related Books. Here you can also find books other than business processes.

Now you are ready to dive in. Welcome to OFBiz world.

All the best


Pranay Pandey