J3.x

Developing an MVC Component/Adding verifications: Difference between revisions

From Joomla! Documentation

No edit summary
GregJPreece (talk | contribs)
Noting that Joomla core behaviours need to be specified, or JS will error on load
 
(28 intermediate revisions by 13 users not shown)
Line 1: Line 1:
{{:J3.1:Developing a MVC Component}}
<noinclude><languages /></noinclude>
{{:J3.1:Developing an MVC Component/<translate><!--T:1-->
en</translate>}}
<translate>== Introduction == <!--T:2--></translate>
<translate><!--T:3-->
This tutorial is part of the [[S:MyLanguage/J3.2:Developing an MVC Component|Developing an MVC Component for Joomla! 3.2]] tutorial. You are encouraged to read the previous parts of the tutorial before reading this.</translate>
<translate><!--T:4-->
See [[S:MyLanguage/Form validation|Form validation]] for some more general info on form validation (rules).</translate>


{{review}}
<translate><!--T:30--> You can watch a video associated with this step at [https://youtu.be/xzYRI3R--CE Step 11, adding verifications]. This and subsequent videos are recorded in HD; click on the YouTube settings wheel to vieiw at best resolution.</translate>


This is a multiple-article series of tutorials on how to develop a Model-View-Contoller [[Component]] for Joomla! Version {{JVer|{{CurrentSTSVer|minor}}}}.
{{#widget:YouTube|id=xzYRI3R--CE}}
 
== Introduction ==
This tutorial is part of the [[J3.2:Developing a MVC Component | Developing a MVC Component for Joomla! 3.2]] tutorial. You are encouraged to read the previous parts of the tutorial before reading this.
 
See [[Form validation]] for some more general info on form validation (rules).
 
== Verifying the form (client side) ==
 
Forms can be verified on the client side using javascript code.
 
'''''NOTE''''': ''Javascript verification will work only if there is a button type = "submit" in the page.
The toolbar buttons in Joomla 3.x backend have no type specified.''
 
''A possible workaround is to add to those buttons the type via javascript or to clone them below the form adding the type.''
 
In the ''[[#admin/views/helloworld/tmpl/edit.php|admin/views/helloworld/tmpl/edit.php]]'' file, put these lines


<translate>== Verifying the form (client side) == <!--T:5--></translate>
<translate>
<!--T:31-->
See [[S:MyLanguage/Client-side_form_validation|Client-side form validation]] for further tutorial information relating to client-side verification.</translate>
<translate><!--T:6-->
Forms can be verified on the client side using javascript code.</translate>
<translate><!--T:7-->
In the ''[[#admin/views/helloworld/tmpl/edit.php|admin/views/helloworld/tmpl/edit.php]]'' file, put these lines:</translate>
<span id="admin/views/helloworld/tmpl/edit.php">
<span id="admin/views/helloworld/tmpl/edit.php">
''admin/views/helloworld/tmpl/edit.php''
<tt>admin/views/helloworld/tmpl/edit.php</tt>
<source lang="php">
<source lang="php" highlight="15">
<?php
<?php
/**
* @package    Joomla.Administrator
* @subpackage  com_helloworld
*
* @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
* @license    GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access
// No direct access
defined('_JEXEC') or die('Restricted access');
defined('_JEXEC') or die('Restricted access');
JHtml::_('behavior.tooltip');
JHtml::_('behavior.formvalidation');
?>
?>
<form action="<?php echo JRoute::_('index.php?option=com_helloworld&layout=edit&id=' . (int) $this->item->id); ?>"
<form action="<?php echo JRoute::_('index.php?option=com_helloworld&layout=edit&id=' . (int) $this->item->id); ?>"
Line 43: Line 48:
                         </div>
                         </div>
                     <?php endforeach; ?>
                     <?php endforeach; ?>
                 <div>
                 </div>
             <div>
             </div>
         </fieldset>
         </fieldset>
     <div>
     </div>
     <input type="hidden" name="task" value="helloworld.edit" />
     <input type="hidden" name="task" value="helloworld.edit" />
     <?php echo JHtml::_('form.token'); ?>
     <?php echo JHtml::_('form.token'); ?>
</form>
</form>
</source>
</source>
</span>
</span>


You may have noted that the html form contained in the ''[[#admin/views/helloworld/tmpl/edit.php|admin/views/helloworld/tmpl/edit.php]]'' file now has the ''form-validate'' css class. And that we added a ''JHTML::_('behavior.formvalidation');'' call to tell Joomla to use its javascript form validation.
<translate><!--T:8-->
You may have noted that the html form contained in the ''[[#admin/views/helloworld/tmpl/edit.php|admin/views/helloworld/tmpl/edit.php]]'' file now has the ''form-validate'' css class.</translate>


Modify the ''admin/models/forms/helloworld.xml'' file to indicate that the ''greeting'' field has to be verified:
<translate><!--T:9-->
Modify the <tt>admin/models/forms/helloworld.xml</tt> file to indicate that the ''greeting'' field has to be verified:</translate>


<span id="admin/models/forms/helloworld.xml">
<span id="admin/models/forms/helloworld.xml">
<source lang="xml">
<source lang="xml" highlight="2-4,16-18">
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<form
<form
addrulepath="/administrator/components/com_helloworld/models/rules"
addrulepath="/administrator/components/com_helloworld/models/rules"
>
>
<fieldset>
<fieldset>
Line 71: Line 79:
name="greeting"
name="greeting"
type="text"
type="text"
                label="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_LABEL"
label="COM_HELLOWORLD_HELLOWORLD_GREETING_LABEL"
                description="COM_HELLOWORLD_HELLOWORLD_FIELD_GREETING_DESC"
description="COM_HELLOWORLD_HELLOWORLD_GREETING_DESC"
size="40"
size="40"
                class="inputbox validate-greeting"
class="inputbox validate-greeting"
                validate="greeting"
validate="greeting"
                required="true"
required="true"
default=""
default=""
/>
/>
Line 84: Line 92:
</span>
</span>


Note for the moment that the css class is now ''"inputbox validate-greeting"'' and that the attribute ''required'' is set to ''true''. It means that this field is required and has to be verified by a handler of the form validator framework of Joomla
<translate><!--T:10-->
Note for the moment that the css class is now ''"inputbox validate-greeting"'' and that the attribute ''required'' is set to ''true''. It means that this field is required and has to be verified by a handler of the form validator framework of Joomla.</translate>


With your favorite file manager and editor put a file ''admin/models/forms/helloworld.js'' containing
<translate><!--T:11-->
With your favourite file manager and editor put a file <tt>admin/models/forms/helloworld.js</tt> containing:</translate>


<span id="admin/models/forms/helloworld.js">
<span id="admin/models/forms/helloworld.js">
''admin/models/forms/helloworld.js''
<tt>admin/models/forms/helloworld.js</tt>
<source lang="javascript">
<source lang="javascript">
window.addEvent('domready', function() {
jQuery(function() {
document.formvalidator.setHandler('greeting',
    document.formvalidator.setHandler('greeting',
function (value) {
        function (value) {
regex=/^[^0-9]+$/;
            regex=/^[^0-9]+$/;
return regex.test(value);
            return regex.test(value);
});
        });
});
});
</source>
</source>
</span>
</span>


It adds a handler to the form validator of Joomla for fields having the ''"validate-greeting"'' css class. Each time the ''greeting'' field is modified, the handler will be executed to verify its validity (no digits).
<translate><!--T:12-->
 
It adds a handler to the form validator of Joomla for fields having the ''"validate-greeting"'' css class. Each time the ''greeting'' field is modified, the handler will be executed to verify its validity (no digits).</translate>
The final step is to verify the form when the save button is clicked.
<translate><!--T:13-->
 
The final step is to verify the form when the save button is clicked.</translate>
With your favorite file manager and editor put a file ''admin/views/helloworld/submitbutton.js'' containing
<translate><!--T:14-->
With your favourite file manager and editor put a file <tt>admin/views/helloworld/submitbutton.js</tt> containing:</translate>


<span id="admin/views/helloworld/submitbutton.js">
<span id="admin/views/helloworld/submitbutton.js">
''admin/views/helloworld/submitbutton.js''
<tt>admin/views/helloworld/submitbutton.js</tt>
<source lang="javascript">
<source lang="javascript">
Joomla.submitbutton = function(task)
Joomla.submitbutton = function(task)
Line 122: Line 133:
if (action[1] != 'cancel' && action[1] != 'close')
if (action[1] != 'cancel' && action[1] != 'close')
{
{
var forms = $$('form.form-validate');
var forms = jQuery('form.form-validate');
for (var i=0;i<forms.length;i++)
for (var i = 0; i < forms.length; i++)
{
{
if (!document.formvalidator.isValid(forms[i]))
if (!document.formvalidator.isValid(forms[i]))
Line 149: Line 160:
</span>
</span>


This function will verify that all forms which have the ''"form-validate"'' css class are valid. Note that it will display an alert message translated by the Joomla framework.
<translate><!--T:15-->
This function will verify that all forms which have the ''"form-validate"'' css class are valid. Note that it will display an alert message translated by the Joomla framework.</translate>


The ''HelloWorldViewHelloWorld'' view class has to be modified to use these javascript files:
<translate><!--T:16-->
The ''HelloWorldViewHelloWorld'' view class has to be modified to use these javascript files:</translate>


<span id="admin/views/helloworld/view.html.php">
<span id="admin/views/helloworld/view.html.php">
''admin/views/helloworld/view.html.php''
<tt>admin/views/helloworld/view.html.php</tt>
<source lang="php">
<source lang="php" highlight="39,100-101,107-110">
<?php
<?php
/**
* @package    Joomla.Administrator
* @subpackage  com_helloworld
*
* @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
* @license    GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access to this file
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
defined('_JEXEC') or die('Restricted access');
// import Joomla view library
jimport('joomla.application.component.view');


/**
/**
  * HelloWorld View
  * HelloWorld View
*
* @since  0.0.1
  */
  */
class HelloWorldViewHelloWorld extends JViewLegacy
class HelloWorldViewHelloWorld extends JViewLegacy
{
{
    /**
/**
* View form
* View form
*
*
* @var form
* @var         form
*/
*/
protected $form = null;
protected $form = null;


/**
/**
* display method of Hello view
* Display the Hello World view
* @return void
*
* @param  string  $tpl  The name of the template file to parse; automatically searches through the template paths.
*
* @return void
*/
*/
public function display($tpl = null)
public function display($tpl = null)
{
{
// get the Data
// Get the Data
$form = $this->get('Form');
$this->form = $this->get('Form');
$item = $this->get('Item');
$this->item = $this->get('Item');
        $script = $this->get('Script');
$this->script = $this->get('Script');


// Check for errors.
// Check for errors.
Line 193: Line 216:
return false;
return false;
}
}
// Assign the Data
 
$this->form = $form;
$this->item = $item;
        $this->script = $script;


// Set the toolbar
// Set the toolbar
Line 209: Line 229:


/**
/**
* Setting the toolbar
* Add the page title and toolbar.
*
* @return  void
*
* @since  1.6
*/
*/
protected function addToolBar()
protected function addToolBar()
{
{
$input = JFactory::getApplication()->input;
$input = JFactory::getApplication()->input;
// Hide Joomla Administrator Main menu
$input->set('hidemainmenu', true);
$input->set('hidemainmenu', true);
$isNew = ($this->item->id == 0);
$isNew = ($this->item->id == 0);
JToolBarHelper::title($isNew ? JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLD_NEW') : JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLD_EDIT'));
 
JToolBarHelper::save('helloworld.save');
if ($isNew)
JToolBarHelper::cancel('helloworld.cancel', $isNew ? 'JTOOLBAR_CANCEL' : 'JTOOLBAR_CLOSE');
{
$title = JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLD_NEW');
}
else
{
$title = JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLD_EDIT');
}
 
JToolbarHelper::title($title, 'helloworld');
JToolbarHelper::save('helloworld.save');
JToolbarHelper::cancel(
'helloworld.cancel',
$isNew ? 'JTOOLBAR_CANCEL' : 'JTOOLBAR_CLOSE'
);
}
}
/**
/**
Line 227: Line 267:
protected function setDocument()  
protected function setDocument()  
{
{
JHtml::_('behavior.framework');
JHtml::_('behavior.formvalidator');
$isNew = ($this->item->id < 1);
$isNew = ($this->item->id < 1);
$document = JFactory::getDocument();
$document = JFactory::getDocument();
$document->setTitle($isNew ? JText::_('COM_HELLOWORLD_HELLOWORLD_CREATING')
$document->setTitle($isNew ? JText::_('COM_HELLOWORLD_HELLOWORLD_CREATING') :
                          : JText::_('COM_HELLOWORLD_HELLOWORLD_EDITING'));
                JText::_('COM_HELLOWORLD_HELLOWORLD_EDITING'));
        $document->addScript(JURI::root() . $this->script);
$document->addScript(JURI::root() . $this->script);
$document->addScript(JURI::root() . "/administrator/components/com_helloworld"
$document->addScript(JURI::root() . "/administrator/components/com_helloworld"
                                  . "/views/helloworld/submitbutton.js");
                                  . "/views/helloworld/submitbutton.js");
Line 237: Line 281:
}
}
}
}
</source>
</source>
</span>
</span>


This view now
<translate><!--T:17-->
This view now:
* verifies if the model has no error;
* verifies if the model has no error;
* adds two javascript files;
* adds two javascript files;
* injects javascript translation using the Joomla ''JText::script'' function.
* injects javascript translation using the Joomla <tt>JText::script</tt> function.</translate>


The final step is to implement a ''getScript'' function in the ''HelloWorldModelHelloWorld'' model:
You will also notice our two lines adding additional behaviors when injecting our scripts. By default, Joomla injects the Javascript we specify into the page <i>before</i> its own global Javascript libraries, such as jQuery and Joomla Core. As our Javascript code directly utilises the <tt>Joomla</tt> object, loading it onto the page before the global Javascript libraries will result in immediate failure, and the form validation will not run.
 
By specifying these two behaviors via the JHtml helper class prior to injecting our own Javascript, we ensure they are loaded first on the page, and our code will execute correctly. You would normally see JHtml used inside a template, but as our Javascript is added for each child template, it's better to specify the external dependency here.
 
<translate><!--T:18-->
The final step is to implement a <tt>getScript</tt> function in the ''HelloWorldModelHelloWorld'' model:</translate>


<span id="admin/models/helloworld.php">
<span id="admin/models/helloworld.php">
''admin/models/helloworld.php''
<tt>admin/models/helloworld.php</tt>
<source lang="php">
<source lang="php" highlight="65-73">
<?php
<?php
/**
* @package    Joomla.Administrator
* @subpackage  com_helloworld
*
* @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
* @license    GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access to this file
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
defined('_JEXEC') or die('Restricted access');
// import Joomla modelform library
jimport('joomla.application.component.modeladmin');


/**
/**
  * HelloWorld Model
  * HelloWorld Model
*
* @since  0.0.1
  */
  */
class HelloWorldModelHelloWorld extends JModelAdmin
class HelloWorldModelHelloWorld extends JModelAdmin
{
{
/**
/**
* Returns a reference to the a Table object, always creating it.
* Method to get a table object, load it if necessary.
*
* @param  string  $type    The table name. Optional.
* @param  string  $prefix  The class prefix. Optional.
* @param  array  $config  Configuration array for model. Optional.
*
*
* @param      type    The table type to instantiate
* @return  JTable A JTable object
* @param      string A prefix for the table class name. Optional.
* @param      array  Configuration array for model. Optional.
*
*
* @return      JTable  A database object
* @since   1.6
* @since       2.5
*/
*/
public function getTable($type = 'HelloWorld', $prefix = 'HelloWorldTable', $config = array())
public function getTable($type = 'HelloWorld', $prefix = 'HelloWorldTable', $config = array())
Line 280: Line 339:
* Method to get the record form.
* Method to get the record form.
*
*
* @param       array   $data     Data for the form.
* @param   array   $data     Data for the form.
* @param       boolean $loadData True if the form is to load its own data (default case), false if not.
* @param   boolean $loadData True if the form is to load its own data (default case), false if not.
*
* @return  mixed    A JForm object on success, false on failure
*
*
* @return      mixed   A JForm object on success, false on failure
* @since   1.6
* @since      2.5
*/
*/
public function getForm($data = array(), $loadData = true)
public function getForm($data = array(), $loadData = true)
{
{
// Get the form.
// Get the form.
$form = $this->loadForm('com_helloworld.helloworld', 'helloworld',
$form = $this->loadForm(
array('control' => 'jform', 'load_data' => $loadData));
'com_helloworld.helloworld',
'helloworld',
array(
'control' => 'jform',
'load_data' => $loadData
)
);
 
if (empty($form))
if (empty($form))
{
{
Line 298: Line 365:
return $form;
return $form;
}
}
    /**
/**
* Method to get the script that have to be included on the form
* Method to get the script that have to be included on the form
*
*
Line 310: Line 377:
* Method to get the data that should be injected in the form.
* Method to get the data that should be injected in the form.
*
*
* @return     mixed   The data for the form.
* @return mixed The data for the form.
* @since       2.5
*
* @since   1.6
*/
*/
protected function loadFormData()
protected function loadFormData()
{
{
// Check the session for previously entered form data.
// Check the session for previously entered form data.
$data = JFactory::getApplication()->getUserState('com_helloworld.edit.helloworld.data', array());
$data = JFactory::getApplication()->getUserState(
'com_helloworld.edit.helloworld.data',
array()
);
 
if (empty($data))
if (empty($data))
{
{
Line 325: Line 397:
}
}
}
}
</source>
</source>
</span>
</span>


== Verifying the form (server side) ==
<translate>== Verifying the form (server side) == <!--T:19--></translate>
Verifying the form on the server side is done by inheritance of ''JControllerForm'' class. We have specified in the ''[[#admin/models/forms/helloworld.xml|admin/models/forms/helloworld.xml]]'' file that the validate server function will use a ''greeting.php'' file.
<translate>
<!--T:32-->
See [[S:MyLanguage/Server-side_form_validation|Server-side form validation]] for further tutorial information relating to server-side verification.</translate>
<translate><!--T:20-->
Verifying the form on the server side is done by inheritance of <tt>JControllerForm</tt> class. We have specified in the ''[[#admin/models/forms/helloworld.xml|admin/models/forms/helloworld.xml]]'' file that the validate server function will use a <tt>greeting.php</tt> file.</translate>


With your favorite file manager and editor, put a ''admin/models/rules/greeting.php'' file containing:
<translate><!--T:21-->
With your favourite file manager and editor, put a <tt>admin/models/rules/greeting.php</tt> file containing:</translate>


<span id="admin/models/rules/greeting.php">
<span id="admin/models/rules/greeting.php">
''admin/models/rules/greeting.php''
<tt>admin/models/rules/greeting.php</tt>
<source lang="php">
<source lang="php">
<?php
<?php
/**
* @package    Joomla.Administrator
* @subpackage  com_helloworld
*
* @copyright  Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
* @license    GNU General Public License version 2 or later; see LICENSE.txt
*/
// No direct access to this file
// No direct access to this file
defined('_JEXEC') or die('Restricted access');
defined('_JEXEC') or die('Restricted access');
 
// import Joomla formrule library
jimport('joomla.form.formrule');
 
/**
/**
  * Form Rule class for the Joomla Framework.
  * Form Rule class for the Joomla Framework.
Line 357: Line 440:
protected $regex = '^[^0-9]+$';
protected $regex = '^[^0-9]+$';
}
}
</source>
</source>
</span>
</span>


Note there is no function here - this is inherited from JFormRule (located in: libraries/joomla/form /rule.php). All that is needed is the regex string to test against.
<translate><!--T:22-->
Note there is no function here - this is inherited from JFormRule (located in: libraries/joomla/form /rule.php). All that is needed is the regex string to test against.</translate>


== Packaging the component ==
<translate>== Packaging the component == <!--T:23--></translate>
 
<translate><!--T:24-->
Content of your code directory
Content of your code directory. Each file link below takes you to the step in the tutorial which has the latest version of that source code file.</translate>
* ''[[#helloworld.xml|helloworld.xml]]''
* ''[[#helloworld.xml|helloworld.xml]]''
* ''[[J3.2:Developing_a_MVC_Component/Adding_a_view_to_the_site_part#site/helloworld.php|site/helloworld.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_a_view_to_the_site_part#site/helloworld.php|site/helloworld.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|site/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|site/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Adding_a_view_to_the_site_part#site/controller.php|site/controller.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_a_view_to_the_site_part#site/controller.php|site/controller.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|site/views/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|site/views/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|site/views/helloworld/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|site/views/helloworld/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Adding_a_view_to_the_site_part#site/views/helloworld/view.html.php|site/views/helloworld/view.html.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_a_view_to_the_site_part#site/views/helloworld/view.html.php|site/views/helloworld/view.html.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|site/views/helloworld/tmpl/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|site/views/helloworld/tmpl/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Using_the_database#site/views/helloworld/tmpl/default.xml|site/views/helloworld/tmpl/default.xml]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Using_the_database#site/views/helloworld/tmpl/default.xml|site/views/helloworld/tmpl/default.xml]]''
* ''[[J3.2:Developing_a_MVC_Component/Adding_a_view_to_the_site_part#site/views/helloworld/tmpl/default.php|site/views/helloworld/tmpl/default.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_a_view_to_the_site_part#site/views/helloworld/tmpl/default.php|site/views/helloworld/tmpl/default.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|site/models/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|site/models/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Using_the_database#site/models/helloworld.php|site/models/helloworld.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Using_the_database#site/models/helloworld.php|site/models/helloworld.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|site/language/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|site/language/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|site/language/en-GB/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|site/language/en-GB/index.html]]''
* [[J3.x:Developing a MVC Component/Adding language management#site.2Flanguage.2Fen-GB.2Fen-GB.com_helloworld.ini|site/language/en-GB/en-GB.com_helloworld.ini]]
* [[S:MyLanguage/J3.x:Developing an MVC Component/Adding language management#site.2Flanguage.2Fen-GB.2Fen-GB.com_helloworld.ini|site/language/en-GB/en-GB.com_helloworld.ini]]
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|admin/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Basic_backend#admin/helloworld.php|admin/helloworld.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_decorations_to_the_backend#admin/helloworld.php|admin/helloworld.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Basic_backend#admin/controller.php|admin/controller.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Basic_backend#admin/controller.php|admin/controller.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|admin/sql/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/sql/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Using_the_database#admin/sql/install.mysql.utf8.sql|admin/sql/install.mysql.utf8.sql]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Using_the_database#admin/sql/install.mysql.utf8.sql|admin/sql/install.mysql.utf8.sql]]''
* ''[[J3.2:Developing_a_MVC_Component/Using_the_database#admin/sql/uninstall.mysql.utf8.sql|admin/sql/uninstall.mysql.utf8.sql]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Using_the_database#admin/sql/uninstall.mysql.utf8.sql|admin/sql/uninstall.mysql.utf8.sql]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|admin/sql/updates/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/sql/updates/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|admin/sql/updates/mysql/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/sql/updates/mysql/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#admin/sql/updates/mysql/0.0.1.sql|admin/sql/updates/mysql/0.0.1.sql]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#admin/sql/updates/mysql/0.0.1.sql|admin/sql/updates/mysql/0.0.1.sql]]''
* ''[[J3.2:Developing_a_MVC_Component/Using_the_database#admin/sql/install.mysql.utf8.sql|admin/sql/updates/mysql/0.0.6.sql]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Using_the_database#admin/sql/install.mysql.utf8.sql|admin/sql/updates/mysql/0.0.6.sql]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|admin/models/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/models/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|admin/models/fields/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/models/fields/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Using_the_database#admin/models/fields/helloworld.php|admin/models/fields/helloworld.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Using_the_database#admin/models/fields/helloworld.php|admin/models/fields/helloworld.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Basic_backend#admin/models/helloworlds.php|admin/models/helloworlds.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_decorations_to_the_backend#admin/models/helloworlds.php|admin/models/helloworlds.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Adding_backend_actions#admin/models/helloworlds.php|admin/models/helloworld.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_verifications#admin/models/helloworld.php|admin/models/helloworld.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Adding_backend_actions#admin/models/helloworlds.php|admin/models/forms/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding decorations to the backend#admin/models/forms/filter_helloworlds.xml|admin/models/forms/filter_helloworlds.xml]]''
* ''[[J3.2:Developing_a_MVC_Component/Adding_backend_actions#admin/models/forms/helloworld.xml|admin/models/forms/helloworld.xml]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/models/forms/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Adding_backend_actions#admin/controllers/helloworld.php|admin/controllers/helloworld.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_verifications#admin/models/forms/helloworld.js|admin/models/forms/helloworld.js]]''
* ''[[J3.2:Developing_a_MVC_Component/Adding_backend_actions#admin/controllers/helloworlds.php|admin/controllers/helloworlds.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_verifications#admin/models/forms/helloworld.xml|admin/models/forms/helloworld.xml]]''
* ''[[J3.2:Developing_a_MVC_Component/Adding_backend_actions#admin/models/helloworlds.php|admin/controllers/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_verifications#admin/models/rules/greeting.php|admin/models/rules/greeting.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|admin/views/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/models/rules/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Adding_backend_actions#admin/views/helloworld/view.html.php|admin/views/helloworld/view.html.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_backend_actions#admin/controllers/helloworld.php|admin/controllers/helloworld.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Adding_backend_actions#admin/views/helloworld/tmpl/edit.php|admin/views/helloworld/tmpl/edit.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_backend_actions#admin/controllers/helloworlds.php|admin/controllers/helloworlds.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|admin/views/helloworlds/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/controllers/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Basic_backend#admin/views/helloworlds/view.html.php|admin/views/helloworlds/view.html.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/views/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|admin/views/helloworlds/tmpl/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/views/helloworld/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Basic_backend#admin/views/helloworlds/tmpl/default.php|admin/views/helloworlds/tmpl/default.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_verifications#admin/views/helloworld/view.html.php|admin/views/helloworld/view.html.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Basic_backend#admin/views/helloworlds/tmpl/default_head.php|admin/views/helloworlds/tmpl/default_head.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/views/helloworld/tmpl/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Basic_backend#admin/views/helloworlds/tmpl/default_body.php|admin/views/helloworlds/tmpl/default_body.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_verifications#admin/views/helloworld/tmpl/edit.php|admin/views/helloworld/tmpl/edit.php]]''
* ''[[J3.2:Developing_a_MVC_Component/Basic_backend#admin/views/helloworlds/tmpl/default_foot.php|admin/views/helloworlds/tmpl/default_foot.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_verifications#admin/views/helloworld/submitbutton.js|admin/views/helloworld/submitbutton.js]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|admin/tables/index.html]]''
* ''[[J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/views/helloworlds/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Using_the_database#admin/tables/helloworld.php|admin/tables/helloworld.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_decorations_to_the_backend#admin/views/helloworlds/view.html.php|admin/views/helloworlds/view.html.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/views/helloworlds/tmpl/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Adding_decorations_to_the_backend#admin/views/helloworlds/tmpl/default.php|admin/views/helloworlds/tmpl/default.php]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|admin/tables/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Using_the_database#admin/tables/helloworld.php|admin/tables/helloworld.php]]''
* ''[[#admin/language/index.html|admin/language/index.html]]''
* ''[[#admin/language/index.html|admin/language/index.html]]''
* ''[[#admin/language/en-GB/index.html|admin/language/en-GB/index.html]]''
* ''[[#admin/language/en-GB/index.html|admin/language/en-GB/index.html]]''
* ''[[J3.x:Developing a MVC Component/Adding language management#admin.2Flanguage.2Fen-GB.2Fen-GB.com_helloworld.ini|admin/language/en-GB/en-GB.com_helloworld.ini]]''
* ''[[S:MyLanguage/J3.x:Developing an MVC Component/Adding_decorations_to_the_backend#admin.2Flanguage.2Fen-GB.2Fen-GB.com_helloworld.ini|admin/language/en-GB/en-GB.com_helloworld.ini]]''
* ''[[J3.x:Developing a MVC Component/Adding language management#admin.2Flanguage.2Fen-GB.2Fen-GB.com_helloworld.sys.ini|admin/language/en-GB/en-GB.com_helloworld.sys.ini]]''
* ''[[S:MyLanguage/J3.x:Developing an MVC Component/Adding_decorations_to_the_backend#admin.2Flanguage.2Fen-GB.2Fen-GB.com_helloworld.sys.ini|admin/language/en-GB/en-GB.com_helloworld.sys.ini]]''
* ''[[J3.x:Developing a MVC Component/Adding language management#admin.2Flanguage.2Fen-GB.2Fen-GB.com_helloworld.sys.ini|language/en-GB/en-GB.com_helloworld.sys.ini]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|media/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|media/index.html]]''
* ''[[S:MyLanguage/J3.2:Developing_an_MVC_Component/Developing_a_Basic_Component#index.html|media/images/index.html]]''
* ''[[J3.2:Developing_a_MVC_Component/Developing_a_Basic_Component#index.html|media/images/index.html]]''
* ''[[S:MyLanguage/J3.x:Developing_an_MVC_Component/Adding_decorations_to_the_backend#Adding_some_icons|media/images/tux-16x16.png]]''
* ''[[J3.x:Developing_a_MVC_Component/Adding_decorations_to_the_backend#Adding_some_icons|media/images/tux-16x16.png]]''
* ''[[S:MyLanguage/J3.x:Developing_an_MVC_Component/Adding_decorations_to_the_backend#Adding_some_icons|media/images/tux-48x48.png]]''
* ''[[J3.x:Developing_a_MVC_Component/Adding_decorations_to_the_backend#Adding_some_icons|media/images/tux-48x48.png]]''


Create a compressed file of this directory [[archive]] or directly download the archive and install it using the extension manager of Joomla. You can add a menu item of this component using the menu manager in the backend.
<translate><!--T:25-->
Create a compressed file of this directory [https://github.com/scionescire/Joomla-3.2-Hello-World-Component/archive/step-11-adding-verifications.zip archive] or directly download the archive and install it using the extension manager of Joomla. You can add a menu item of this component using the menu manager in the backend.</translate>


<span id="helloworld.xml">
<span id="helloworld.xml">
''helloworld.xml''
<tt>helloworld.xml</tt>
<source lang="xml">
<source lang="xml" highlight="13">
<?xml version="1.0" encoding="utf-8"?>
<?xml version="1.0" encoding="utf-8"?>
<extension type="component" version="3.2.0" method="upgrade">
<extension type="component" version="3.0" method="upgrade">
 
<name>COM_HELLOWORLD</name>
<name>COM_HELLOWORLD</name>
<!-- The following elements are optional and free of formatting constraints -->
<!-- The following elements are optional and free of formatting constraints -->
<creationDate>January 2014</creationDate>
<creationDate>January 2018</creationDate>
<author>John Doe</author>
<author>John Doe</author>
<authorEmail>john.doe@example.org</authorEmail>
<authorEmail>john.doe@example.org</authorEmail>
Line 442: Line 531:
<!-- The description is optional and defaults to the name -->
<!-- The description is optional and defaults to the name -->
<description>COM_HELLOWORLD_DESCRIPTION</description>
<description>COM_HELLOWORLD_DESCRIPTION</description>
 
<install> <!-- Runs on install -->
<install> <!-- Runs on install -->
<sql>
<sql>
Line 453: Line 542:
</sql>
</sql>
</uninstall>
</uninstall>
<update> <!-- Runs on update; New in 2.5 -->
<update> <!-- Runs on update; New since J2.5 -->
<schemas>
<schemas>
<schemapath type="mysql">sql/updates/mysql</schemapath>
<schemapath type="mysql">sql/updates/mysql</schemapath>
</schemas>
</schemas>
</update>
</update>
 
<!-- Site Main File Copy Section -->
<!-- Site Main File Copy Section -->
<!-- Note the folder attribute: This attribute describes the folder
<!-- Note the folder attribute: This attribute describes the folder
Line 469: Line 558:
<folder>views</folder>
<folder>views</folder>
<folder>models</folder>
<folder>models</folder>
<folder>language</folder>
</files>
</files>
 
        <languages folder="site/language">
<language tag="en-GB">en-GB/en-GB.com_helloworld.ini</language>
        </languages>
 
<media destination="com_helloworld" folder="media">
<media destination="com_helloworld" folder="media">
<filename>index.html</filename>
<filename>index.html</filename>
<folder>images</folder>
<folder>images</folder>
</media>
</media>
 
<administration>
<administration>
<!-- Administration Menu Section -->
<!-- Administration Menu Section -->
<menu img="../media/com_helloworld/images/tux-16x16.png">COM_HELLOWORLD_MENU</menu>
<menu link='index.php?option=com_helloworld' img="../media/com_helloworld/images/tux-16x16.png">COM_HELLOWORLD_MENU</menu>
<!-- Administration Main File Copy Section -->
<!-- Administration Main File Copy Section -->
<!-- Note the folder attribute: This attribute describes the folder
<!-- Note the folder attribute: This attribute describes the folder
Line 497: Line 589:
<!-- views files section -->
<!-- views files section -->
<folder>views</folder>
<folder>views</folder>
                        <!-- admin languages files section -->
                        <folder>language</folder>
<!-- controllers files section -->
<!-- controllers files section -->
<folder>controllers</folder>
<folder>controllers</folder>
</files>
</files>
<languages folder="admin/language">
        <language tag="en-GB">en-GB/en-GB.com_helloworld.ini</language>
                        <language tag="en-GB">en-GB/en-GB.com_helloworld.sys.ini</language>
</languages>
</administration>
</administration>
</extension>
</extension>
</source>
</source>
</span>
</span>
{{:J3.2:Developing a MVC Component/Navigate
|prev=Adding decorations to the backend <!-- previous article subpage name -->
|next=Adding categories <!-- next article subpage name -->}}


== Contributors ==
<translate>== Contributors == <!--T:26--></translate>
*[[User:cdemko|Christophe Demko]]
*[[User:cdemko|Christophe Demko]]
*[[User:oaksu|Ozgur Aksu]]
*[[User:oaksu|Ozgur Aksu]]
*[[User:Scionescire|Scionescire]]
*[[User:Scionescire|Scionescire]]


<div class="row">
<div class="large-6 columns">{{Basic button|<translate><!--T:27-->
S:MyLanguage/J3.x:Developing_an_MVC_Component/Adding decorations to the backend|Prev: Adding decorations to the backend</translate>|class=expand success}}</div>
<div class="large-6 columns">{{Basic button|<translate><!--T:28-->
S:MyLanguage/J3.x:Developing_an_MVC_Component/Adding categories|Next: Adding categories</translate>|class=expand}}</div>
</div>
__NOTOC__
<noinclude>
<translate>
<!--T:29-->
[[Category:Joomla! 3.x]]
[[Category:Joomla! 3.0]]
[[Category:Joomla! 3.0]]
[[Category:Joomla! 3.1]]
[[Category:Joomla! 3.1]]
[[Category:Joomla! 3.2]]
[[Category:Joomla! 3.2]]
[[Category:Joomla! 3.3]]
[[Category:Joomla! 3.4]]
[[Category:Beginner Development]]
[[Category:Beginner Development]]
[[Category:Component Development]]
[[Category:Component Development]]
[[Category:Tutorials]]
[[Category:Tutorials in a Series]]
</translate>
</noinclude>

Latest revision as of 17:19, 24 September 2019

Joomla! 
3.x
Tutorial
Developing an MVC Component



This is a multiple-article series of tutorials on how to develop a Model-View-Controller Component for Joomla! VersionJoomla 3.x.

Begin with the Introduction, and navigate the articles in this series by using the navigation button at the bottom or the box to the right (the Articles in this series).



Introduction

This tutorial is part of the Developing an MVC Component for Joomla! 3.2 tutorial. You are encouraged to read the previous parts of the tutorial before reading this. See Form validation for some more general info on form validation (rules).

You can watch a video associated with this step at Step 11, adding verifications. This and subsequent videos are recorded in HD; click on the YouTube settings wheel to vieiw at best resolution.

Verifying the form (client side)

See Client-side form validation for further tutorial information relating to client-side verification. Forms can be verified on the client side using javascript code. In the admin/views/helloworld/tmpl/edit.php file, put these lines: admin/views/helloworld/tmpl/edit.php

<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

// No direct access
defined('_JEXEC') or die('Restricted access');
?>
<form action="<?php echo JRoute::_('index.php?option=com_helloworld&layout=edit&id=' . (int) $this->item->id); ?>"
    method="post" name="adminForm" id="adminForm" class="form-validate">
    <div class="form-horizontal">
        <fieldset class="adminform">
            <legend><?php echo JText::_('COM_HELLOWORLD_HELLOWORLD_DETAILS'); ?></legend>
            <div class="row-fluid">
                <div class="span6">
                    <?php foreach ($this->form->getFieldset() as $field): ?>
                        <div class="control-group">
                            <div class="control-label"><?php echo $field->label; ?></div>
                            <div class="controls"><?php echo $field->input; ?></div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </fieldset>
    </div>
    <input type="hidden" name="task" value="helloworld.edit" />
    <?php echo JHtml::_('form.token'); ?>
</form>

You may have noted that the html form contained in the admin/views/helloworld/tmpl/edit.php file now has the form-validate css class.

Modify the admin/models/forms/helloworld.xml file to indicate that the greeting field has to be verified:

<?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_GREETING_LABEL"
				description="COM_HELLOWORLD_HELLOWORLD_GREETING_DESC"
				size="40"
				class="inputbox validate-greeting"
				validate="greeting"
				required="true"
				default=""
				/>
	</fieldset>
</form>

Note for the moment that the css class is now "inputbox validate-greeting" and that the attribute required is set to true. It means that this field is required and has to be verified by a handler of the form validator framework of Joomla.

With your favourite file manager and editor put a file admin/models/forms/helloworld.js containing:

admin/models/forms/helloworld.js

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

It adds a handler to the form validator of Joomla for fields having the "validate-greeting" css class. Each time the greeting field is modified, the handler will be executed to verify its validity (no digits). The final step is to verify the form when the save button is clicked. With your favourite file manager and editor put a file admin/views/helloworld/submitbutton.js containing:

admin/views/helloworld/submitbutton.js

Joomla.submitbutton = function(task)
{
	if (task == '')
	{
		return false;
	}
	else
	{
		var isValid=true;
		var action = task.split('.');
		if (action[1] != 'cancel' && action[1] != 'close')
		{
			var forms = jQuery('form.form-validate');
			for (var i = 0; i < forms.length; i++)
			{
				if (!document.formvalidator.isValid(forms[i]))
				{
					isValid = false;
					break;
				}
			}
		}
	
		if (isValid)
		{
			Joomla.submitform(task);
			return true;
		}
		else
		{
			alert(Joomla.JText._('COM_HELLOWORLD_HELLOWORLD_ERROR_UNACCEPTABLE',
			                     'Some values are unacceptable'));
			return false;
		}
	}
}

This function will verify that all forms which have the "form-validate" css class are valid. Note that it will display an alert message translated by the Joomla framework.

The HelloWorldViewHelloWorld view class has to be modified to use these javascript files:

admin/views/helloworld/view.html.php

<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

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

/**
 * HelloWorld View
 *
 * @since  0.0.1
 */
class HelloWorldViewHelloWorld extends JViewLegacy
{
	/**
	 * View form
	 *
	 * @var         form
	 */
	protected $form = null;

	/**
	 * Display the Hello World view
	 *
	 * @param   string  $tpl  The name of the template file to parse; automatically searches through the template paths.
	 *
	 * @return  void
	 */
	public function display($tpl = null)
	{
		// Get the Data
		$this->form = $this->get('Form');
		$this->item = $this->get('Item');
		$this->script = $this->get('Script');

		// Check for errors.
		if (count($errors = $this->get('Errors')))
		{
			JError::raiseError(500, implode('<br />', $errors));

			return false;
		}


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

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

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

	/**
	 * Add the page title and toolbar.
	 *
	 * @return  void
	 *
	 * @since   1.6
	 */
	protected function addToolBar()
	{
		$input = JFactory::getApplication()->input;

		// Hide Joomla Administrator Main menu
		$input->set('hidemainmenu', true);

		$isNew = ($this->item->id == 0);

		if ($isNew)
		{
			$title = JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLD_NEW');
		}
		else
		{
			$title = JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLD_EDIT');
		}

		JToolbarHelper::title($title, 'helloworld');
		JToolbarHelper::save('helloworld.save');
		JToolbarHelper::cancel(
			'helloworld.cancel',
			$isNew ? 'JTOOLBAR_CANCEL' : 'JTOOLBAR_CLOSE'
		);
	}
	/**
	 * Method to set up the document properties
	 *
	 * @return void
	 */
	protected function setDocument() 
	{
		
		JHtml::_('behavior.framework');
		JHtml::_('behavior.formvalidator');

		$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() . $this->script);
		$document->addScript(JURI::root() . "/administrator/components/com_helloworld"
		                                  . "/views/helloworld/submitbutton.js");
		JText::script('COM_HELLOWORLD_HELLOWORLD_ERROR_UNACCEPTABLE');
	}
}

This view now:

  • verifies if the model has no error;
  • adds two javascript files;
  • injects javascript translation using the Joomla JText::script function.

You will also notice our two lines adding additional behaviors when injecting our scripts. By default, Joomla injects the Javascript we specify into the page before its own global Javascript libraries, such as jQuery and Joomla Core. As our Javascript code directly utilises the Joomla object, loading it onto the page before the global Javascript libraries will result in immediate failure, and the form validation will not run.

By specifying these two behaviors via the JHtml helper class prior to injecting our own Javascript, we ensure they are loaded first on the page, and our code will execute correctly. You would normally see JHtml used inside a template, but as our Javascript is added for each child template, it's better to specify the external dependency here.

The final step is to implement a getScript function in the HelloWorldModelHelloWorld model:

admin/models/helloworld.php

<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

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

/**
 * HelloWorld Model
 *
 * @since  0.0.1
 */
class HelloWorldModelHelloWorld extends JModelAdmin
{
	/**
	 * Method to get a table object, load it if necessary.
	 *
	 * @param   string  $type    The table name. Optional.
	 * @param   string  $prefix  The class prefix. Optional.
	 * @param   array   $config  Configuration array for model. Optional.
	 *
	 * @return  JTable  A JTable object
	 *
	 * @since   1.6
	 */
	public function getTable($type = 'HelloWorld', $prefix = 'HelloWorldTable', $config = array())
	{
		return JTable::getInstance($type, $prefix, $config);
	}

	/**
	 * Method to get the record form.
	 *
	 * @param   array    $data      Data for the form.
	 * @param   boolean  $loadData  True if the form is to load its own data (default case), false if not.
	 *
	 * @return  mixed    A JForm object on success, false on failure
	 *
	 * @since   1.6
	 */
	public function getForm($data = array(), $loadData = true)
	{
		// Get the form.
		$form = $this->loadForm(
			'com_helloworld.helloworld',
			'helloworld',
			array(
				'control' => 'jform',
				'load_data' => $loadData
			)
		);

		if (empty($form))
		{
			return false;
		}

		return $form;
	}
	/**
	 * Method to get the script that have to be included on the form
	 *
	 * @return string	Script files
	 */
	public function getScript() 
	{
		return 'administrator/components/com_helloworld/models/forms/helloworld.js';
	}
	/**
	 * Method to get the data that should be injected in the form.
	 *
	 * @return  mixed  The data for the form.
	 *
	 * @since   1.6
	 */
	protected function loadFormData()
	{
		// Check the session for previously entered form data.
		$data = JFactory::getApplication()->getUserState(
			'com_helloworld.edit.helloworld.data',
			array()
		);

		if (empty($data))
		{
			$data = $this->getItem();
		}

		return $data;
	}
}

Verifying the form (server side)

See Server-side form validation for further tutorial information relating to server-side verification. Verifying the form on the server side is done by inheritance of JControllerForm class. We have specified in the admin/models/forms/helloworld.xml file that the validate server function will use a greeting.php file.

With your favourite file manager and editor, put a admin/models/rules/greeting.php file containing:

admin/models/rules/greeting.php

<?php
/**
 * @package     Joomla.Administrator
 * @subpackage  com_helloworld
 *
 * @copyright   Copyright (C) 2005 - 2018 Open Source Matters, Inc. All rights reserved.
 * @license     GNU General Public License version 2 or later; see LICENSE.txt
 */

// No direct access to this file
defined('_JEXEC') or die('Restricted access');
 
/**
 * Form Rule class for the Joomla Framework.
 */
class JFormRuleGreeting extends JFormRule
{
	/**
	 * The regular expression.
	 *
	 * @access	protected
	 * @var		string
	 * @since	2.5
	 */
	protected $regex = '^[^0-9]+$';
}

Note there is no function here - this is inherited from JFormRule (located in: libraries/joomla/form /rule.php). All that is needed is the regex string to test against.

Packaging the component

Content of your code directory. Each file link below takes you to the step in the tutorial which has the latest version of that source code file.

Create a compressed file of this directory archive or directly download the archive and install it using the extension manager of Joomla. You can add a menu item of this component using the menu manager in the backend.

helloworld.xml

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

	<name>COM_HELLOWORLD</name>
	<!-- The following elements are optional and free of formatting constraints -->
	<creationDate>January 2018</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 recorded in the components table -->
	<version>0.0.11</version>
	<!-- The description is optional and defaults to the name -->
	<description>COM_HELLOWORLD_DESCRIPTION</description>

	<install> <!-- Runs on install -->
		<sql>
			<file driver="mysql" charset="utf8">sql/install.mysql.utf8.sql</file>
		</sql>
	</install>
	<uninstall> <!-- Runs on uninstall -->
		<sql>
			<file driver="mysql" charset="utf8">sql/uninstall.mysql.utf8.sql</file>
		</sql>
	</uninstall>
	<update> <!-- Runs on update; New since J2.5 -->
		<schemas>
			<schemapath type="mysql">sql/updates/mysql</schemapath>
		</schemas>
	</update>

	<!-- Site Main File Copy Section -->
	<!-- 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>
	</files>

        <languages folder="site/language">
		<language tag="en-GB">en-GB/en-GB.com_helloworld.ini</language>
        </languages>

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

	<administration>
		<!-- Administration Menu Section -->
		<menu link='index.php?option=com_helloworld' img="../media/com_helloworld/images/tux-16x16.png">COM_HELLOWORLD_MENU</menu>
		<!-- Administration Main File Copy Section -->
		<!-- 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">
			<!-- Admin Main File Copy Section -->
			<filename>index.html</filename>
			<filename>helloworld.php</filename>
			<filename>controller.php</filename>
			<!-- SQL files section -->
			<folder>sql</folder>
			<!-- tables files section -->
			<folder>tables</folder>
			<!-- models files section -->
			<folder>models</folder>
			<!-- views files section -->
			<folder>views</folder>
			<!-- controllers files section -->
			<folder>controllers</folder>
		</files>
		<languages folder="admin/language">
        		<language tag="en-GB">en-GB/en-GB.com_helloworld.ini</language>
                        <language tag="en-GB">en-GB/en-GB.com_helloworld.sys.ini</language>
		</languages>
	</administration>

</extension>

Contributors