User

Over/Step by step to a Joomla Module - A form and ajax

From Joomla! Documentation

< User:Over
Documentation all together tranparent small.png
Under Construction

This user page or section is in the process of an expansion or major restructuring. You are welcome to assist in its construction by editing it as well. If this user page or section has not been edited in several days, please remove this template.
This page was last edited by Sandra97 (talk| contribs) 4 years ago. (Purge)


module tutorial

This is a multiple article series on how to develop a module for Joomla! version Joomla 3.x. We go step by step from basic functionality to some more advanced. At the end of the tutorial we'll use your custom module to show you, how you can use the powerful output override ( = change ) methods provided by Joomla!. The only prerequisite for overrides is that the module or component comply to the Joomla! best practices. Navigate the articles in this series by using the navigation box to the right (the Articles in this series). Start with the first and follow them one by one. The next article builds on the knowledge and the files from the previous.

A Tip!

As the links on this page are references, you should open them in a new browser window/tab.

Should have's to complete this tutorial

You should have some knowledge in web technology but you don't have to be an expert at all. If you want to customise or even administrate a web site you will have to learn a little of everything e.g, Html coding, Css styling, Php programming, Sql database, using Javascript and about web servers. If you want to develop extensions for Joomla!, in small or large, you better start with a module before you try a larger project with a component. It is also a nice start to get knowledge on how to modify your sites template design. A Joomla! module is similar to a widget in other contexts. Even if plugins are the shortest extension type in sake of code, they require a little more advanced system knowledge to implement.


Introduction[edit]

In this part of the tutorial we will use the form functionality of Joomla!. In a second step we'll add the Joomla! Ajax functionality to the module. If you want to keep the custom module you created up till now, you should use the knowledge you've got from this tutorial and fork it. i.e. you copy all the files to a new local folder and change all filenames to a new name. Then you change all texts in the files including the old module name to a new at your choise, create an installation file and install the new module. We will still use yourmodule as name, so you'll have to adopt your own as before.

Ajax = short for asynchronous JavaScript + XML

A Tip!

We will not mention the name adoption anymore and be less specific about file update.

If you have a MVC component related to your module, it's easier and recommended to include the form functionality a.k.a. JForm by using the components methods. We'll add it without a component in this example.

Why use JForm for html forms? You get a lot for "free", like fields html code, client and server side validation.

We first need a xml form declaration. In the folder where you unzipped the downloaded file you can find a models folder. Copy this to your modules web 'root' folder. A module doesn't follow the MVC pattern, but let us use models as folder name. For a component you'll find forms, fields and rules in this path. You can find examples of custom fields and rules in those folders.

The form[edit]

Open models/forms/yourmodule_form.xml for edit.

message.xml[edit]

<?xml version="1.0" encoding="utf-8"?>
<form>
   <fieldset addfieldpath="modules/mod_yourmodule/models/fields"
             addrulepath="modules/mod_yourmodule/models/rules">  
      <field name="subject"
         type="text"
         size="60"
         description="MOD_YOURMODULE_MESSAGE_SUBJECT_DESC"
         label="MOD_YOURMODULE_MESSAGE_SUBJECT_LABEL"
         filter="string"
         validate="yourmessagesubject"
         required="true"/>
      <field name="message"
         type="textarea"
         cols="50"
         rows="10"
         description="MOD_YOURMODULE_ENTER_MESSAGE_DESC"
         label="MOD_YOURMODULE_ENTER_MESSAGE_LABEL"
         filter="safehtml"
         validate="yourmessage"
         required="true"/>
   </fieldset>
</form>

To be able to use our own fields and rules we add 'addfieldpath' and 'addrulepath'. Explaning the details of the declarations is outside the scope of this tutorial. Only so far: we add two fields 'subject' and 'message'. As you can see we use the same xml pattern as is used for the module options. Change the labels and descriptions. Do NOT change 'your' in the validate lines or you have to edit the rules files.

More about Form fields

You can find examples of form declarations in the core components. e,g. /administrator/com_content/models/forms/article.xml

The language strings[edit]

We have to add the language strings to the .ini file

en-GB.mod_yourmodule.ini Form texts[edit]

MOD_YOURMODULE_MESSAGE_SUBJECT_DESC="The subject of yor message"
MOD_YOURMODULE_MESSAGE_SUBJECT_LABEL="Subject"
MOD_YOURMODULE_ENTER_MESSAGE_DESC="Add your message"
MOD_YOURMODULE_ENTER_MESSAGE_LABEL="Message"

Add the form to the output[edit]

default.php With a form[edit]

defined('_JEXEC') or die('Restricted access');
?>
<h3>A form your module</h3>

<form id="mod_yourmodule_<?php echo $module->id;?>" action="<?php echo JRoute::_('index.php'); ?>" method="post" class="form-validate">
	<fieldset class="well">
    <?php
      echo $form->renderField('subject');
      echo $form->renderField('message');

   if (!$messageSent)
   {
      echo '<button class="btn btn-primary validate" type="submit">'.JText::_('JSUBMIT').'</button>';
      echo '<input type="hidden" name="mod_yourmodule" value="1" />';
      echo JHtml::_('form.token');
	}
	?>

	</fieldset>
</form>

We will make some changes to this code, when we add Ajax handling to the module. Add this if you first want to test the form without Ajax.

Load and use the model[edit]

We load the message model and use it to get our form.

mod_yourmodule.php Use a model[edit]

   defined('_JEXEC') or die('Restricted access');

   //the class suffix from parameter
   $moduleclass_sfx = htmlspecialchars($params->get('moduleclass_sfx'));

   $jinput = JFactory::getApplication()->input;

   $messageSent = $jinput->post->get( 'mod_yourmodule', 0, 'INT');

   if ($messageSent)
   {
      //check the security token
      JSession::checkToken() or jexit(JText::_( 'JINVALID_TOKEN' ));

      $data     = $jinput->post->get( 'jform', array(), 'ARRAY' );
   }

   // Include the helper that handles the data
   JLoader::import( 'helper',JPATH_ROOT .'/modules/mod_yourmodule' );

   // Include the model that provide the form functionality
   JLoader::import( 'message',JPATH_ROOT .'/modules/mod_yourmodule/models' );

   $model = JModelLegacy::getInstance( 'Message', 'YourmoduleModel', array('ignore_request' => true));

   $form = $model->getForm( array() , $loadData = true);

   if ($messageSent)
   {

      // Test whether the data is valid.
      $validData = $model->validate( $form, $data );

      // Check for validation errors.
      if ( $validData === false )
      {
         JFactory::getApplication()->enqueueMessage($model->getError(), 'error');
      }
      else
      {
         JFactory::getApplication()->enqueueMessage('Thanks for sending us a message');
      }
   }

require JModuleHelper::getLayoutPath('mod_yourmodule', $params->get('layout', 'default'));

Note the lines:

$jinput = JFactory::getApplication()->input;

and

$data     = $jinput->post->get( 'jform', array(), 'ARRAY' );

That is the way you get data more secure from the HTTP request with Joomla . In this case an array variable named jform from the $_POST. Default is an empty array. Do not use $_REQUEST directly. See Retrieving request data using JInput

We will make some changes to this code as well, when we add Ajax handling to the module. Add this if you first want to test the form without Ajax.

If you chose to change the code, you should now see a submitable form in your module position.

Add Ajax functionality[edit]

We remind you of the best practice to use a component for Ajax response. Since Joomla! version 3.2 a new component com_ajax is included in the Joomla! package. If you don't have a component, you can use that to get more secure handling for modules and plugins. We will use this interface here.

Read more Using Joomla Ajax Interface. You can also follow the examples from that document.