A form to the site front end allows users to submit information that can be saved to the database or sent to emails. For example, front-end forms in Joomla are used to create article (com_content), contact form (com_contact), user registration form (com_users).
To create a form on the front-end, you need:
Then, you need to handle the HTTP POST requests when the user submits the form.
The model will extend JModelAdmin which supports forms, and saving records to the database. Even though it's called JModelAdmin, it is still available within the site part.
The controller will extend JControllerForm which includes the cancel() and save() methods.
First, create a new form (add-form.xml) in the forms subdirectory in the site models directory.
The view file is located at:
The view file calls the model file for the form.
public function display($tpl = null)
// Get the form to display
$this->form = $this->get('Form');
// Call the parent display to display the layout file
It will look for the function getForm() in the model file.
The model is almost same as the admin equivalent. It is located at:
public function getForm($data = array(), $loadData = true)
// Get the form.
$form = $this->loadForm('com_helloworld.form', 'add-form', array('control' => 'jform', 'load_data' => $loadData));
$errors = $this->getErrors();
throw new Exception(implode("\n", $errors), 500);
The first argument in the loadForm() is the name which is set to component_name.view_name. The second argument is the source of form which is the name of XML file.
The layout file is located at:
site/views/form/tmpl/edit.php or site/views/form/tmpl/default.php
You display the actual form in this file:
You also need to pass the task (controller.task) for handling the form. For example,
<input type="hidden" name="option" value="com_contact" />
<input type="hidden" name="task" value="contact.edit" />
This will run the edit() function in the subcontroller file contact.php. The file is located at the directory: site/controllers.
As in the admin case, you need to create a new controller in the /controllers subdirectory. In this file, you need to define the methods used for the processing of the form.
public function save($key = null, $urlVar = null)
$app = JFactory::getApplication();
$input = $app->input;
$model = $this->getModel('form');
// get the data from the HTTP POST request
$data = $input->get('jform', array(), 'array');
The $data is array that contains the information submitted by the user.