Archived

Difference between revisions of "Developing a MVC Component/Adding verifications"

From Joomla! Documentation

< Archived:Developing a MVC Component
Line 23: Line 23:
 
?>
 
?>
 
<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">
 
<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">
 
<fieldset class="adminform">
 +
 
<legend><?php echo JText::_( 'COM_HELLOWORLD_HELLOWORLD_DETAILS' ); ?></legend>
 
<legend><?php echo JText::_( 'COM_HELLOWORLD_HELLOWORLD_DETAILS' ); ?></legend>
 +
 
<?php foreach($this->form->getFieldset() as $field): ?>
 
<?php foreach($this->form->getFieldset() as $field): ?>
 
<?php if (!$field->hidden): ?>
 
<?php if (!$field->hidden): ?>
 
<?php echo $field->label; ?>
 
<?php echo $field->label; ?>
 +
 
<?php endif; ?>
 
<?php endif; ?>
 
<?php echo $field->input; ?>
 
<?php echo $field->input; ?>
 +
 
<?php endforeach; ?>
 
<?php endforeach; ?>
 
</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'); ?>
 
</div>
 
</div>
Line 162: Line 168:
 
public function display($tpl = null)  
 
public function display($tpl = null)  
 
{
 
{
 
 
// get the Data
 
// get the Data
 
$form = $this->get('Form');
 
$form = $this->get('Form');
Line 174: Line 179:
 
return false;
 
return false;
 
}
 
}
 
 
// Assign the Data
 
// Assign the Data
 
$this->form = $form;
 
$this->form = $form;
Line 201: Line 205:
 
JToolBarHelper::cancel('helloworld.cancel', $isNew ? 'JTOOLBAR_CANCEL' : 'JTOOLBAR_CLOSE');
 
JToolBarHelper::cancel('helloworld.cancel', $isNew ? 'JTOOLBAR_CANCEL' : 'JTOOLBAR_CLOSE');
 
}
 
}
 
 
/**
 
/**
 
* Method to set up the document properties
 
* Method to set up the document properties
Line 255: Line 258:
 
return JTable::getInstance($type, $prefix, $config);
 
return JTable::getInstance($type, $prefix, $config);
 
}
 
}
 
 
/**
 
/**
 
* Method to get the record form.
 
* Method to get the record form.
Line 266: Line 268:
 
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', array('control' => 'jform', 'load_data' => $loadData));
 
$form = $this->loadForm('com_helloworld.helloworld', 'helloworld', array('control' => 'jform', 'load_data' => $loadData));
Line 275: Line 276:
 
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 285: Line 285:
 
return 'administrator/components/com_helloworld/models/forms/helloworld.js';
 
return 'administrator/components/com_helloworld/models/forms/helloworld.js';
 
}
 
}
 
 
/**
 
/**
 
* Method to get the data that should be injected in the form.
 
* Method to get the data that should be injected in the form.
Line 294: Line 293:
 
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());
Line 303: Line 301:
 
return $data;
 
return $data;
 
}
 
}
}</source>
+
}
 +
</source>
 
</span>
 
</span>
  

Revision as of 19:39, 21 November 2010

This page has been archived. This page contains information for an unsupported Joomla! version or is no longer relevant. It exists only as a historical reference, it will not be improved and its content may be incomplete and/or contain broken links.

Template:Future

Articles in this series[edit]


Introduction[edit]

This tutorial is part of the Developing a Model-View-Controller (MVC) Component for Joomla!1.6 tutorial. You are encouraged to read the previous parts of the tutorial before reading this.

Verifying the form (client side)[edit]

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
// No direct 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); ?>" method="post" name="adminForm" id="helloworld-form" class="form-validate">

	<fieldset class="adminform">

		<legend><?php echo JText::_( 'COM_HELLOWORLD_HELLOWORLD_DETAILS' ); ?></legend>

		<?php foreach($this->form->getFieldset() as $field): ?>
			<?php if (!$field->hidden): ?>
				<?php echo $field->label; ?>

			<?php endif; ?>
			<?php echo $field->input; ?>

		<?php endforeach; ?>
	</fieldset>
	<div>
		<input type="hidden" name="task" value="helloworld.edit" />

		<?php echo JHtml::_('form.token'); ?>
	</div>
</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. And that we added a JHTML::_('behavior.formvalidation'); call to tell Joomla!1.6 to use its javascript form validation.

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 favorite file manager and editor put a file admin/models/forms/helloworld.js containing

admin/models/forms/helloworld.js

window.addEvent('domready', 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 favorite 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 = $$('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!1.6 framework.

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

admin/views/helloworld/view.html.php

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

// import Joomla view library
jimport('joomla.application.component.view');

/**
 * HelloWorld View
 */
class HelloWorldViewHelloWorld extends JView
{
	/**
	 * display method of Hello view
	 * @return void
	 */
	public function display($tpl = null) 
	{
		// get the Data
		$form = $this->get('Form');
		$item = $this->get('Item');
		$script = $this->get('Script');

		// Check for errors.
		if (count($errors = $this->get('Errors'))) 
		{
			JError::raiseError(500, implode('<br />', $errors));
			return false;
		}
		// Assign the Data
		$this->form = $form;
		$this->item = $item;
		$this->script = $script;

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

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

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

	/**
	 * Setting the toolbar
	 */
	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');
	}
	/**
	 * Method to set up the document properties
	 *
	 * @return void
	 */
	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() . $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!1.6 JText::script function.

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

admin/models/helloworld.php

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

// import Joomla modelform library
jimport('joomla.application.component.modeladmin');

/**
 * HelloWorld Model
 */
class HelloWorldModelHelloWorld extends JModelAdmin
{
	/**
	 * Returns a reference to the a Table object, always creating it.
	 *
	 * @param	type	The table type to instantiate
	 * @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
	 */
	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)[edit]

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 used a greeting.php file.

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

admin/models/rules/greeting.php

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

Packaging the component[edit]

Content of your code directory

Create a compressed file of this directory or directly download the archive and install it using the extension manager of Joomla!1.6. 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="1.6.0" method="upgrade">
	<name>COM_HELLOWORLD</name>
	<creationDate>November 2009</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>
	<version>0.0.11</version>
	<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>

	<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>
	</media>
	
	<administration>
		<menu img="../media/com_helloworld/images/tux-16x16.png">COM_HELLOWORLD_MENU</menu>
		<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>controllers</folder>
		</files>		
		<languages folder="admin">
			<language tag="en-GB">language/en-GB/en-GB.com_helloworld.ini</language>
			<language tag="en-GB">language/en-GB/en-GB.com_helloworld.sys.ini</language>
		</languages>
	</administration>

</extension>

Navigate[edit]

Prev: Adding decorations to the backend Next: Adding categories

Contributors[edit]