User

Rvsjoen/tutorial/Developing an MVC Component/Part 11

From Joomla! Documentation

< User:Rvsjoen‎ | tutorial/Developing an MVC Component

Adding validation[edit]

So we would very much like to have some validation of our fields, Joomla! supports two kinds of validation. Client-side validation is implemented in javascript and is used to inform the user that the field is wrongly filled in prior to the form being submitted, however, this can of course be circumvented and we need another layer of validation namely, server-side validation. Server-side validation there is no way to circumvent since it is executed on the server, and the rules are implemented in PHP. We will start by creating two rules for our greeting field, one for client-side and one for server-side validation.

Client side validation[edit]

With your favorite editor, create the following file

media/js/helloworld.js

window.addEvent('domready', function() {
        document.formvalidator.setHandler('greeting',
                function (value) {
                        regex=/^[^0-9]+$/;
                        return regex.test(value);
        });
});

Server side validation[edit]

With your favorite editor, create the following file

admin/models/rules/greeting.php

// No direct access to this file
defined('_JEXEC') or die;

jimport('joomla.form.formrule');

class JFormRuleGreeting extends JFormRule
{
        protected $regex = '^[^0-9]+$';
}

JFormRule provides some functionality for us already, so all we really have to do is to implement the regular expression that determines if the field is valid or not.

Adding validation rules to the form[edit]

Next thing we need to do, is to tell the form that this field needs to be validated and which rules to use for validation.

With your favorite editor, modify the following file to look like this

admin/models/forms/helloworld.xml

<?xml version="1.0" encoding="utf-8"?>
<form addrulepath="/administrator/components/com_helloworld/models/rules">
        <fieldset>
                <field
                        name="id"
                        type="hidden"
                />
                <field
                        name="greeting"
                        type="text"
                        label="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_LABEL"
                        description="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_DESC"
                        size="40"
                        class="inputbox validate-greeting"
                        validate="greeting"
                        required="true"
                        default=""
                />
        </fieldset>

As you can see we have added two things, the validate="greeting" attribute is used to determine the server-side validation rule, and the CSS class validate-greeting is used to determine which rule is used for client-side validation. We also include an addrulepath property to the <form> tag to tell it where to look for validation rules.

Adding validation support to the view[edit]

Now the only thing that is left, is to have the view load the client-side validation rule which we stored in a separate javascript file in our media folder, and also tell the view to enable form validation.

With your favorite editor, modify the following file to look like this

admin/views/helloworld/view.html.php

// No direct access to this file
defined('_JEXEC') or die;

jimport('joomla.application.component.view');

class HelloWorldViewHelloWorld extends JView
{
        public function display($tpl = null) 
        {
                // get the Data
                $form = $this->get('Form');
                $item = $this->get('Item');

                // Assign the Data
                $this->form = $form;
                $this->item = $item;

                // Set the toolbar
                $this->addToolBar();

                // Display the template
                parent::display($tpl);

                // Set the document
                $this->setDocument();
        }

        protected function addToolBar() 
        {
                JRequest::setVar('hidemainmenu', true);
                $isNew = ($this->item->id == 0);
                JToolBarHelper::title($isNew ? JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLD_NEW') 
                        : JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLD_EDIT'), 'helloworld');
                JToolBarHelper::save('helloworld.save');
                JToolBarHelper::cancel('helloworld.cancel', $isNew ? 'JTOOLBAR_CANCEL' : 'JTOOLBAR_CLOSE');
        }

        protected function setDocument() 
        {
                $isNew = ($this->item->id < 1);
                $document = JFactory::getDocument();
                $document->setTitle($isNew ? JText::_('COM_HELLOWORLD_HELLOWORLD_CREATING') : JText::_('COM_HELLOWORLD_HELLOWORLD_EDITING'));
                $document->addScript(JURI::root() . "media/com_helloworld/js/helloworld.js");
        }
}

Here we are simply adding the script which contains our validation rule for greeting to the document.

With your favorite editor, modify the following file to look like this

admin/views/helloworld/tmpl/edit.php

// No direct access to this file
defined('_JEXEC') or die;

JHtml::_('behavior.tooltip');
JHtml::_('behavior.formvalidation');
?>
<form action="<?php echo JRoute::_('index.php?option=com_helloworld&layout=edit&id='. (int) $this->item->id); ?>" 
        method="post" name="adminForm" id="helloworld-form" class="form-validate">
        <fieldset class="adminform">
                <legend><?php echo JText::_( 'COM_HELLOWORLD_HELLOWORLD_DETAILS' ); ?></legend>
                <ul class="adminformlist">
                <?php foreach($this->form->getFieldset() as $field): ?>
                        <li><?php echo $field->label;echo $field->input;?></li>
                <?php endforeach; ?>
                </ul>
        </fieldset>
        <div>
                <input type="hidden" name="task" value="helloworld.edit" />
                <?php echo JHtml::_('form.token'); ?>
        </div>
</form>

The important things to notice here is that we have added the class form-validate to the <form> tag (line 8) in order to tell Joomla! that this form is supposed to be validated client-side. In addition we are also loading the form validation libraries on line 5.

Installation manifest[edit]

The changes to the installation manifest are the version number and addition of the js folder in the media section.

There are no changes to the manifest except for the version number

helloworld.xml

<?xml version="1.0" encoding="utf-8"?>
<extension type="component" version="2.5.0" method="upgrade">

        <name>COM_HELLOWORLD</name>
        <!-- The following elements are optional and free of formatting constraints -->
        <creationDate>June 2011</creationDate>
        <author>John Doe</author>
        <authorEmail>john.doe@example.org</authorEmail>
        <authorUrl>http://www.example.org</authorUrl>
        <copyright>Copyright Info</copyright>
        <license>License Info</license>
        <!--  The version string is stored in the components table -->
        <version>0.0.11</version>
        <!-- The description is optional and defaults to the name -->
        <description>COM_HELLOWORLD_DESCRIPTION</description>

        <install>
                <sql>
                        <file driver="mysql" charset="utf8">sql/install.mysql.utf8.sql</file>
                </sql>
        </install>
        <uninstall>
                <sql>
                        <file driver="mysql" charset="utf8">sql/uninstall.mysql.utf8.sql</file>
                </sql>
        </uninstall>

        <!-- Note the folder attribute: This attribute describes the folder
                to copy FROM in the package to install therefore files copied
                in this section are copied from "site/" in the package -->
        <files folder="site">
                <filename>index.html</filename>
                <filename>helloworld.php</filename>
                <filename>controller.php</filename>
                <folder>views</folder>
                <folder>models</folder>
                <folder>language</folder>
        </files>

        <media destination="com_helloworld" folder="media">
                <filename>index.html</filename>
                <folder>images</folder>
                <folder>js</folder>
        </media>

        <administration>
                <menu img="../media/com_helloworld/images/tux-16x16.png">COM_HELLOWORLD_MENU</menu>
                <!-- Note the folder attribute: This attribute describes the folder
                        to copy FROM in the package to install therefore files copied
                        in this section are copied from "admin/" in the package -->
                <files folder="admin">
                        <filename>index.html</filename>
                        <filename>helloworld.php</filename>
                        <filename>controller.php</filename>
                        <folder>sql</folder>
                        <folder>tables</folder>
                        <folder>models</folder>
                        <folder>views</folder>
                        <folder>language</folder>
                        <folder>controllers</folder>
                </files>
        </administration>

</extension>

Testing your component[edit]

For details on how to install the component into your Joomla! site, refer to the information provided in Part 01.

Edit a greeting and try to input a value that contains numbers, then click outside the field to remove the focus from the input field and the client-side validation should execute and report the field as not valid. In order to test the server-side validation, try saving the greeting with an invalid field.

File listing[edit]

Download this part[edit]

Download example package

Articles in this series[edit]

This tutorial is supported by the following versions of Joomla!

Joomla 2.5