Joomla Component Development

.

Joomla Component Development
Author Prepared On Revision Approved By

Prabhu Patil

18th January, 2009

This document is solely meant for internal use of the designated programmers at “Carmel” development center and is classified as highly confidential. Please ensure that you don’t leave copies of this document on your local disk drives or circulate in any form without explicit permission. The only controlled copy of this document is the on-line version maintained on VSS server. It is the user's responsibility to ensure that any copy of the controlled version is current and complete, and that the obsolete copies are discarded.

Confidential – All rights reserved.

1

Joomla Component Development

.

Table of Content
Introduction:............................................................................................................................. 3 Section 1: The components' table in joomla's database ........................................................ 4 Section 2: The entry point....................................................................................................... 5 Section 3 – The backend tasks –The default task.................................................................. 8 Section 3.1 the default controller task (display)................................................................ 8 Section 3.2 The model - Getting the students from the DB............................................ 12 The code here it is (Model): ......................................................................................... 13 Section 3.3 - The view - Listing the students .................................................................. 24 Here’s the view code (list):........................................................................................... 24 Here it is: the view’s layout/template .......................................................................... 29 Section 4 – The backend tasks – The edit task.................................................................... 37 Section 4.1 – The controller task: edit ............................................................................. 37 Code for edit method: ................................................................................................... 37 Section 4.2 The model – Getting a student through its id............................................... 38 Section 4.3 The view – form to edit the student.............................................................. 38 Section 5: The backend tasks - Save .................................................................................... 46 Section 5.1 – The controller task: save ............................................................................ 46 Here’s the code (save() method in studentsController.php):...................................... 46 Here is the Code (saveStudent($student) method in …/models/students.php)......... 46 Section 5.2 JTABLE ......................................................................................................... 48 Section 5.3 The Model – Adding the save functionality ................................................ 50 Here is the Code (saveStudent($student) method in …/models/students.php)......... 50 Section 6: The backend tasks – The add task ...................................................................... 52 Section 6.1: The controller task: add ............................................................................... 52 Here’s the add() function in controller code: .............................................................. 52 Section 6.2: The view - Form to edit the student (revisited) .......................................... 52 Here’s the displayAdd() method in view.php code: ................................................... 53 Section 6.3: The model – New students........................................................................... 53 Here’s the getNewStudent() ..//models/students.php code:........................................ 53 Section 7: The backend tasks: The remove task.................................................................. 55 Section 7.1: The controller task: remove ......................................................................... 55 Here is remove() method code in studentsController.php.......................................... 55 Section 7.2: The model – Deleting students .................................................................... 55 Here is the deleteStudents() in ..//models/students.php.............................................. 55 Section 8: Installation............................................................................................................ 58 TEST:................................................................................................................................. 58

Confidential – All rights reserved.

2

Joomla Component Development

.

Component Development with Example: The Backend
Introduction:
This document is about a Joomla component named "Students" that manage our Students List, Add, Edit and Remove feature. This new version of Joomla (1.5) uses an approach to component development based on the Model-View-Component design pattern. So what is this of the Model View Controller pattern? Well, if you look for it in this book “Design patterns – Elements of Reusable Object Oriented Software” (Erich Gamma, et all), which is probably the most popular book about design patterns, you’ll find this: “MVC consists of three kinds of objects. The Model is the application object, the View is its screen presentation, and the Controller defines the way that the user interface reacts to the user input. Before MVC user interface designs tended to lump these objects together…” So the basic idea is that you have a Model of your data, that is unaware of the views that might exists to represent it, you have one or more views of that model that represent it, and you have a controller, which is responsible for receiving input from the views and updating the model. For creating our Joomla component we’ll have to write a model, a view and a controller for it We have to do the backend, which will allow us to manage our Students: List, Add, Edit and Remove them.

Confidential – All rights reserved.

3

Joomla Component Development

.

Section 1: The components' table in joomla's database
The first thing we’ll do is to insert a new record in the Joomla’s table that stores the installed components. By doing this you can test your component while you’re developing it, instead of coding it all. To do this you’ll have to have phpmyadmin or you can use the MySQL command line client. In phpmyadmin this is what you have to do: (I’m using version: 5.2.6 of phpmyadmin) 1. Open phpmyadmin and select the database that you’re using for your joomla installation; 2. Select the table jos_components (it might have a different prefix (jos_), you choose the prefix when you install joomla (jos is the default prefix); 3. Click on the insert tab; 4. Fill the Value column with the values: 1. name: Students 2. link: option=com_students 3. admin_menu_link: option= com_students 4. option: com_students And that’s it, the rest of the fields leave them with the default values. Note: If you want to use the MySQL command line client to do this, remember that option is a reserved keyword, so you have to write it like this `option` when you’re writing your SQL insert statement. Here’s what it should look like: INSERT INTO jos_components (name, link, admin_menu_link, `option`) VALUES (‘Students’, ‘option= com_students’, ‘option= com_students’, ‘com_students’) To use this SQL insert statement in the MySQL command line client you have to login, choose the right database (syntax: use DATABASE_NAME; to view the available databases write: show databases; ) and only then you can use it. So now, if you log in to your joomla site back end you should see, under the components tab, the “Students” component. If you click on it, you get an error (404 – Component not found). If this is what you got, everything is going well, and we can now start to build our component.

Confidential – All rights reserved.

4

Joomla Component Development

.

Section 2: The entry point
The first thing we have to do is the entry point. But for the backend the naming convention for the file that will contain the code of the entry point is different. Instead of being just the component name followed by “.php”, in the backend it’s: admin.[ComponentName].php. So in our case that will be: admin.students.php and it should be located in: Place where you’ve installed joomla/administrator/components/com_students/admin.students.php the entry’s point code in the backend is exactly the same as the frontend’s, here it is:

<?php // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); // Require the controller require_once( JPATH_COMPONENT.DS.'studentsController.php' ); // Create the controller $controller = new StudentsController(); // Perform the Request task $controller->execute( JRequest::getVar( 'task' ) ); // Redirect if set by the controller $controller->redirect(); ?>

Please note that JPATH_COMPONENT now gives you the path to the backend of our component, in this case: place where you’ve installed joomla/administrator/components/com_students Important this about this piece of code: The first line: defined(‘_JEXEC’) or die…: What this means is that if the constant ‘_JEXEC’ is not defined the application exits and the only thing you’ll see is the “Restricted Access” message.

Confidential – All rights reserved.

5

1: The constant _JEXEC is defined in the index. DETAIL 2. If you don’t use the setRedirect method in the controller.” this tells our soon to be created controller which task it should perform.php file directly.php. by typing the URL: http://folder where you’ve installed joomla under apache’s htdocs folder/components/com_students/students. and the execute method from the controller will execute the controller’s default task (the default task is display.php' ). What is important for you to know here is that if task is not defined in the URL the JRequest::getVar(‘task’) returns null.1.php file. This is because the JPATH_COMPONENT constant is defined using another constant. 6 .2: The JPATH_COMPONENT constant contains the frontend’s path to the component if your code is running in the frontend or it has the backend’s path to the component if your code is running in the back end. What you need to know about this is that JPATH_COMPONENT is a joomla constant that contains the path to where your component is. I’ll explain this better when we do the controller).” . the “require_once(JPATH_COMPONENT.1. so if you try to access the students. Confidential – All rights reserved. Forth line: “$controller->execute( JRequest::getVar( 'task' ) ). you’ll get that “Restricted Access” message because _JEXEC won’t be defined. the redirect method just returns false.What you need to know about this is that you can setRedirect in the controller to the URL where the browser should redirect when this method is called.php (frontend) and administrator/index. The actual files where theses constants are defined are: JBASE_PATH: index.DS. Second line of code.php(backend) JPATH_COMPONENT: libraries/joomla/application/component/helper. the JBASE_PATH constant that contains the path to the frontend if you’re in the frontend or the backend if you’re in the backend.Joomla Component Development .'studentsController.” will load the controller we’ll do next. JPATH_COMPONENT_SITE: same as above JPATH_COMPONENT_ADMINISTRATOR: same as above These last two constants contain the path to the frontend part of the component and the backend part of the component and are independent of JBASE_PATH. DETAIL 2. Last line: “$controller->redirect().php (the method you should look for is render Component). and DS is also a joomla constant that means “Directory Separator” (it’s defined this way to work both in windows and unix environments).

. the view and the model. which we will do next. 7 . Don’t try this just yet. it won’t work because we still have to define the controller.Joomla Component Development And that’s the entry point. Confidential – All rights reserved.

application. so put the file here: Folder where you’ve installed joomla/administrator/components/com_students/studentsController. and then do the same for the models and views. edit. So. jimport('joomla.php Here’s the code that handles the default task (display): <?php // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ). Confidential – All rights reserved. describe it.component. 'list' ). remove and display the list of students. 'listlayout' ). do the view and test. then do the model.php we have to put it in the backend folder. It will have to deal with more tasks: add. //This sets the default layout/template for the view $viewLayout = JRequest::getVar( 'layout'.controller'). that will list the students. We’ve called the file studentsController. What I mean is that it is easier if we handle each task at a time.Joomla Component Development . let’s start with the controller. 8 . and then do the other tasks (this way it is easier to test if everything is going well). /** * Students Component Administrator Controller */ class StudentsController extends JController { /** * Method to display the view * * @access public */ function display() { //This sets the default view (second argument) $viewName = JRequest::getVar( 'view'. we do the code for the controller. I think the easiest way to do this is iteratively. if we want to start with the display task. For example. Section 3 – The backend tasks –The default task Section 3.1 the default controller task (display) Our backend controller will be more complex than our frontend’s. It is easier to explain it this way than post all the code from the controller here.

This time we want to load a view named list and a model called students. true). Why did I do this? Just to tell you about the JController’s display method. This file contains the definition of the class JController that we are extending here.component. } } The default task for the controller is display.application. “. the file name has to be all lowercase) model class name: StudentsModelStudents 2nd line of code: “jimport('joomla. } $view->setLayout($viewLayout). The rest is just creating the StudentsController class.controller'). that extends JController and redefining the JController’s display method to do exactly what JController’s display method does.php (Remember that the file name is lowercase) model file: folder where you’ve installed joomla/administrator/com_students/models/students. $view->display().Joomla Component Development .php view class name: StudentsViewList view layout/template file: folder where you’ve installed joomla/administrator/com_students/views/list/tmpl/listlayout. The file and class names: • • • • • view file: folder where you’ve installed joomla/administrator/com_students/views/list/view. // Get/Create the model if ($model = & $this->getModel('students')) { //Push the model into the view (as default) //Second parameter indicates that it is the default model for the view $view->setModel($model. What you need to know about this is that it will require_once the file named controller. To know how the classes and files for the model and view should be named (see below).php (Remember. that even if you name your model with uppercase character.php located in libraries/joomla/application/component. 9 . This default JController’s display method does this: Confidential – All rights reserved. so we redefine the display method. $view = & $this->getView($viewName).

So. the lowercase part is really important! Because if you're working in Windows and you decide to name your layout. and in the MVC. and you'll get an error saying the layout file is not found. o If there’s no view parameter in the request the view name will be the controller class name but without ‘Controller’. the view’s layout/template will be called listlayout. and you forget that the layout file name has to be lowercase (so you name it listLayout. the view’s file name and the layout’s file name that I haven’t told you: • • • The view’s class name [ControllerClassNameWithoutController]View[ViewName] The view’s file name is views/[ViewNameLowercased]/view. don't forget this so that you don't end up banging your head in the wall needlessly. I haven’t told you about it. I wouldn’t call it layout or template though. Confidential – All rights reserved. What will happen is that it will work ok in your local windows machine. and all the HTML mixed with php code in the layout file. In our Students component. I guess the people that developed the JView class(the class that we’ll extend to create our view)decided that it would be nice to have a separate file for the view class definition and the file that will have HTML that actually displays the view (with some php mixed in) . so the view name is ‘students’. This way you have a view class file.Joomla Component Development • .php Layout file name: views/[ViewNameLowercased]/tmpl/[LayoutNameLowercased]. for example.patil@reachwell. Why does this happen? Because file names in Windows environments are not case sensitive. but in Linux environments they are. because it suggests that you can have two layouts for the same view. 10 . You might be wondering right now. o If there is no layout parameter in the request the default layout is called default. shouldn’t that be two different views? That’s just how I see it anyway… Disagree? Feel free to email me(mailto:prabhu. the view’s layout. • Gets the name of the view: o If the parameter view is in the request. maybe I didn’t get it right! Now. but as soon as you upload the component to your website powered by a Linux server it will stop working. what is this thing.php?option=com_students&view=list.php file name. some other important things that you also need to know about the view’s class name.php About the [LayoutNameLowercased]. you have an URL like this: index. the view name will be ‘list’.php). without HTML. Well. for example you have an URL like this: index. Gets the name of the view’s layout from the request o If the parameter layout is in the request. the controller class name is StudentsController. listLayout.php?option=com_students&view=list&layout=listlayout.net?subject=should not be two different views (MVC).html.

and the default folder where the views will look for layouts is tmpl.php?option=com_students&view=list&layout=listlayout • • • View Class file: folder where you’ve installed joomla/components/com_students/views/list/view. Note that this is the method that is called if there is no task parameter in the URL. • base_path: usually has the path to the component. you can change that here. respectively? Well I did too. instead of parsing the name of the controller class to take out the “Controller” part. this will change all that I described earlier. in the JController’s contructor. • • View Class file: folder where you’ve installed joomla/components/com_students/views/students/view. 11 the defaults you have to place your view files under this folder • . Hope I didn’t forget anything. This is the folder where the controller will look for the models.[DocumentType].1.2: Are you wondering why the views’ file and the layout file are under a folder called views and tmpl. Because I’m describing the controller right now.html. • model_path: default value is base_path/models. if you think there is something wrong or unclear feel free to let me know. and the answer to that is: the default folder where the controller will look for the views is views.php) [I don’t really know about DocumentType] View Class Name: StudentsViewStudents View Layout file: folder where you’ve installed joomla/components/com_students/views/students/tmpl/default. name: the controllers name.php Another example: index.php And these are the secrets behind the naming conventions in Joomla component development. the name you put here is used instead. it’s all defaults in this example: • .php (the view file name is always view.php?option=com_students So.html. • view_path: default value is base_path/views. DETAIL 3. that’s why if you use Confidential – All rights reserved. if we have an URL like this: index. I’ll take this chance to tell you about the default parameters that you can change. can’t really remember any reason why you want to change its default value… • default_task: remember I told you that the default task for the controller was display.Joomla Component Development In our case. Here you have it.php View Class Name: StudentsViewList View Layout file: folder where you’ve installed joomla/components/com_students/views/list/tmpl/listlayout.

I still haven’t finished explaining the JController default display method that we’re using.php and be located in models/.Getting the students from the DB Let’s create our model with a method to load all the students in the database and return them in an array. Remember. The class name should be [ControllerNameWithoutController]Model[ModelName]. The view gets linked to the model. or. Remember. so that we can display them in the view. the default view name is the controller’s name without “Controller” if the parameter view is not present in the URL. there’s the how the model file is loaded and how the model class should be named. the default display method. whose default value is the view name or the view parameter value in the url. and in the end calls the view’s display method (we’ll look at it when we create the view). Next. As a curiosity. as ModelName. I’ll show you an alternative to using the JController’s default display method: Section 3. Did I lose you? Well. So a lot goes on in the Controller that at first glance you might not be aware of.php class name: StudentsModelStudents Confidential – All rights reserved. then the view name will have the value specified in the url. If you use the default JController’s display method the name of the view and the name of the model have to be the same. the model is named students. So. So. loads the view and model (with the rules I described above). so you can access the model through the view as we’ll see later. file name: folder where you’ve installed joomla/administrator/components/com_students/models/students. if the parameter view is present in the request URL. the file that contains the definition of the model should be named [ModelName]. 12 .2 The model .Joomla Component Development . From now on. I’ll refer to the model name.

Joomla Component Development . /** * Constructor Confidential – All rights reserved. 13 . The code here it is (Model): <?php //No direct acesss defined('_JEXEC') or die(). jimport('joomla.model'). /** * Items total * @var integer */ var $_total = null.application. class StudentsModelStudents extends JModel { /** * Category ata array * @var array */ var $_data = null.component. /** * Pagination object * @var object */ var $_pagination = null.

0.Joomla Component Development * * @since 1. 'int').list. 'limit'. $limitstart). global $mainframe. // Get pagination request variables $limit = $mainframe->getUserStateFromRequest('global. . $mainframe->getCfg('list_limit').5 */ function __construct(){ parent::__construct().limit'.limitstart'. 14 . $limitstart = $mainframe->getUserStateFromRequest($option. $limit). adjust it $limitstart = ($limit != 0 ? (floor($limitstart / $limit) * $limit) : 0). 'int'). } /** * Method to get Students item data * * @access public * @return array */ Confidential – All rights reserved. $option. 'limitstart'.'. // In case limit has been changed. $this->setState('limitstart'. $this->setState('limit'.

} return $this->_total. } return $this->_data. $this->_total = $this->_getListCount($query).Joomla Component Development function getData(){ // if data hasn't already been obtained. $this>getState('limit')). $this->_data = $this->_getList($query. } . /** * Method to get the total number of student items * @access public * @return integer */ function getTotal() { // Lets load the content if it doesn't already exist if (empty($this->_total)) { $query = $this->_buildQuery(). Confidential – All rights reserved. 15 . $this->getState('limitstart'). load it if (empty($this->_data)) { $query = $this->_buildQuery().

Joomla Component Development } /** * Method to get a pagination object for the Students * * @access public * @return integer */ function getPagination() { // Lets load the content if it doesn't already exist if (empty($this->_pagination)) { jimport('joomla. $this->_pagination = new JPagination( $this->getTotal(). 16 . $this>getState('limitstart'). } . = $this->_buildContentOrderBy().pagination'). $this->getState('limit') ). function _buildQuery() { // Get the WHERE and ORDER BY clauses for the query $where $orderby = $this->_buildContentWhere(). } return $this->_pagination. Confidential – All rights reserved.html.

Joomla Component Development $query = ' SELECT * from #__student AS a ' .' Confidential – All rights reserved. return $query.$where . } else { $orderby a.'filter_order'.'filter_order_Dir'.$filter_order_Dir.'filter_order_Dir'.students_firstname . if ($filter_order == 'a. ''.students_firstname'.'filter_order'. 'word' ).' '.'a. function _buildContentOrderBy() { global $mainframe. } . 17 . $option.ordering '. $filter_order_Dir = $mainframe->getUserStateFromRequest( $option. $filter_order = $mainframe->getUserStateFromRequest( $option.$orderby . } return $orderby. 'cmd' ). } = ' ORDER BY '.'. a.students_firstname'){ $orderby '.$filter_order_Dir.$filter_order.students_firstname'. = ' ORDER BY a.

$where = array(). =& JFactory::getDBO().Joomla Component Development function _buildContentWhere() { global $mainframe.'filter_order'. } if ( $filter_state ) { if ( $filter_state == 'P' ) { $where[] = 'a. 'cmd' ).'%'. ''. 'word' . } else if ($filter_state == 'U' ) { Confidential – All rights reserved.'filter_state'.'filter_order_Dir'.published = 1'.students_firstname'. 'filter_order'. $filter_order = $mainframe->getUserStateFromRequest( $option.'search'. 'word' ). ''.$db->Quote( '%'. 18 .$db->getEscaped( $search. 'string' ). if ($search) { $where[] = 'LOWER(a. $search = $mainframe'search'.students_firstname) LIKE '. $search >getUserStateFromRequest( $option. 'filter_active'. true ). 'filter_order_Dir'. $filter_order_Dir = $mainframe->getUserStateFromRequest( $option. 'a. $option. $filter_active = $mainframe->getUserStateFromRequest( $option. = $mainframe->getUserStateFromRequest( 'filter_state'.'filter_active'. $db $filter_state $option. = JString::strtolower( $search ). ''. ). 0. 'int' ). false ).

= ( count( $where ) ? ' WHERE '.published = 0'.$id. } /** Confidential – All rights reserved. 'Student with ID: '. 19 . $student = $db->loadObject(). implode( ' AND '. if ($student === null) JError::raiseError(500. } function getStudent($id){ $query = 'SELECT * FROM #__student'.students_active = '.Joomla Component Development $where[] = 'a.$id. } $where $where ) : '' ). return $where. $db->setQuery($query).'). .' not found. ' WHERE id = '. } } if ($filter_active > 0) { $where[] = 'a. $db = $this->getDBO().(int) $filter_active. else return $student.

. } // Make sure the student record is valid if (!$studentTableRow->check()) { JError::raiseError(500. 'Invalid data'). } Confidential – All rights reserved. // Bind the form fields to the student table if (!$studentTableRow->bind($student)) { JError::raiseError(500.$errorMessage).Joomla Component Development * Method to store a Student in the DB * @access public */ function saveStudent($student) { //Parameter not necessary because our model is named StudentsModelStudents (used to ilustrate that you can specify an alternative name to the JTable extending class) //getTable('students'). Table class name $studentTableRow =& $this->getTable('students'). 20 . JError::raiseError(500. 'Error binding data: '. 'Error binding data'). Here students is not a table name. } // Insert/update this record in the db if (!$studentTableRow->store()) { $errorMessage = $studentTableRow->getError().

$studentTableRow->students_state = ''. $studentTableRow->students_schoolstate = ''. $studentTableRow->students_firstname = ''. Confidential – All rights reserved. Table class name $studentTableRow =& $this->getTable('students'). /** * Method that returns an empty student with id 0 * @access public */ function getNewStudent(){ //getTable('students'). then everythign went well } . $studentTableRow->students_lastname = ''. $studentTableRow->students_email = ''. Here students is not a table name. 21 . $studentTableRow->students_schoolname = ''. $studentTableRow->students_uid = 0. $studentTableRow->students_zip = ''. $studentTableRow->id = 0. $studentTableRow->students_city = ''.Joomla Component Development //If we get here and with no raiseErrors. $studentTableRow->students_street = ''. $studentTableRow->students_grade_id = 0.

$studentTableRow->students_p1_phone1 = ''. $studentTableRow->students_p1_lastname = ''. $studentTableRow->students_observedst = 0. $studentTableRow->students_p1_firstname = ''. $studentTableRow->studetns_deleted = 0. $studentTableRow->students_p1_email = ''. $studentTableRow->students_p2_lastname = ''. Confidential – All rights reserved. $studentTableRow->students_phone1 = ''. 22 . $studentTableRow->students_p2_phone2 = ''. $studentTableRow->students_p1_relationship = ''. $studentTableRow->students_type = 0. $studentTableRow->students_p2_relationship = ''. . $studentTableRow->students_phone2 = ''. $studentTableRow->students_p2_firstname = ''. $studentTableRow->students_p2_email = ''.Joomla Component Development $studentTableRow->students_timezone = ''. $studentTableRow->students_p1_email = ''. $studentTableRow->students_gender = ''. $studentTableRow->students_created_on = ''. $studentTableRow->students_requirements = ''. $studentTableRow->students_active =0. $studentTableRow->students_p1_phone2 = ''. $studentTableRow->students_p2_phone1 = ''.

$db->setQuery($query). } function deleteStudents($arrayIDs) { $query = "DELETE FROM #__student WHERE id IN (".'. 'Error deleting students: '.implode('. $arrayIDs). $db = $this->getDBO(). JError::raiseError(500. Confidential – All rights reserved. if (!$db->query()){ $errorMessage = $this->getDBO()->getErrorMsg(). } } } ?> This code included pagination & filter both we will discuss later.Joomla Component Development .$errorMessage).")". 23 . return $studentTableRow.

php (Remember that the view file is not called view. jimport( 'joomla.php because we use the getView method in the controller without specifying its second parameter.Listing the students This view will access the model to get the list of students. $option.3 . Note that we will be returning from the model not a list of strings. The attributes will be id.html.application. global $mainframe. Confidential – All rights reserved. JToolBarHelper::editListX().php Here’s the view code (list): <?php // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ). then make that list of students available for the view’s layout/template and then use the JView default display method to output the html generated by the layout/template. I’ll call those objects row and you’ll see that each attribute they have corresponds to a database field from the table we’ve created for our component. JToolBarHelper::addNewX(). The files and classnames for the view: view file: folder where you’ve installed joomla/administrator/components/com_students/views/list/view. view class name: StudentsViewList layout file: folder where you’ve installed joomla/administrator/components/com_students/views/list/tmpl/listlayout. students_firstname.view'). /** * HTML View class for the Students Component (List) * * @package Students */ class StudentsViewList extends JView { function display() { JToolBarHelper::title('Students Manager'. the view type).component. but a list of objects created from what was returned from the database. 'generic. =& JFactory::getURI().Joomla Component Development . Section 3.png'). etc. 24 . $db $uri =& JFactory::getDBO(). JToolBarHelper::deleteList().The view .

= & $this->get( 'Total'). // Get data $items $total $pagination from the model = & $this->get( 'Data'). // state filter $lists['state'] ). 'id'. 'filter_active'. Confidential – All rights reserved. .submit().state'. 'search'. intval( $filter_active ) ). } } = JHTML::_('grid. 'word' ). // table ordering $lists['order_Dir'] = $filter_order_Dir. $lists). $this->assignRef('items'."'. $catlist. 0. 'string' ). $pagination). $catlist[] = JHTML::_('select. 25 . 'word' ). ''.'filter_active'. = & $this->get( 'Pagination' ). //Push data into the template $this->assignRef('user'. // build list of active //$javascript = 'onchange="document. $items). // search filter $lists['search']= $search. $filter_state JFactory::getUser()). $db->setQuery($sql).'filter_state'. $filter_order_Dir = $mainframe->getUserStateFromRequest( $option. $option.active'.'filter_order'. $search = JString::strtolower( $search ). 'cmd' ). $db->loadObjectList() ). intval( $filter_active). parent::display(). $lists['active'] = JHTML::_('select. $filter_order = $mainframe->getUserStateFromRequest( $option. 'a.genericlist'. 'filter_active'.'search'. 'active'. 'filter_order_Dir'. '0'.'filter_order_Dir'. $this->assignRef('lists'.Joomla Component Development $filter_state = $mainframe->getUserStateFromRequest( $option. 'students_active' ). JText::_( 'Select Active -' ). //$lists['active'] = JHTML::_('list. $search = $mainframe->getUserStateFromRequest( $option.adminForm.'id'. $sql = 'SELECT DISTINCT students_active FROM #__student'. 'class="inputbox" size="1" onchange="document. $this->assignRef('pagination'. $javascript ). 'students_active'. $lists['order'] = $filter_order. 'int' ).option'. 'filter_state'.students_firstname'. $filter_active = $mainframe->getUserStateFromRequest( $option. 'filter_order'.submit(). ''."'.adminForm. ''. // build the active list $db =& JFactory::getDBO(). $catlist = array_merge( $catlist.

The JToolBarHelper::deleteList(). submitbutton('edit')}" class="toolbar"> <span class="icon-32-edit" title="Edit"> </span> Edit </a> </td> First. This is always true for all forms that you do in the backend. For example the editListX: <td class="button" id="toolbar-edit"> <a href="#" onclick="javascript:if(document.value==0){alert('Please make a selection from the list to edit'). Some buttons. JToolBarHelper::editListX(). in our component. 26 . this view we’re doing right now will display a list of students. so don’t worry. There are a few naming conventions used here that will become clear as soon as I show you an example of the html and javascript generated for one of those buttons. When you press these buttons some javascript is executed that will eventually submit the form we will define in layout/template file for this view. like the button generated with editListX. I’ll tell you how that happens when we see the form in the layout/template file). the first line (JToolBarHelper::title) sets the title you’ll see in the toolbar. assume you have a hidden field named boxchecked that contains the number of selected items.png that you can find in folder where you’ve installed joomla/administrator/images). it just has to be defined in the form.}else{ hideMainMenu(). For example. JToolBarHelper::addNewX() add a delete. Confidential – All rights reserved.adminForm. The first four lines in the display method output the javascript/html that will make up the toolbar for our component (Figure 1). Some new things here: the toolbar code. edit and add buttons to the toolbar.Joomla Component Development ?> . and it will be updated automatically. so boxchecked will contain the number of students selected (you don’t have to worry about updating boxchecked. They are always assumed to be named adminForm. and the image (generic. the html form (defined in the layout/template we’ll do next) has to be named adminForm.boxchecked. Figure 1 – Toolbar But it is not too hard to use.

the buttons call a joomla javascript function named submitbutton that has one parameter called pressbutton. because all the other buttons will be inactive. and then submits the adminForm.php?option=com_students&task=edit (This is not actually true. 27 . hence the task hidden field). option. What this javascript function does is it sets a hidden field named task in the adminForm form (in this example with ‘edit’). This is useful when you’re adding or editing (in our case students) because the user will have to click on one of the buttons you put in the toolbar (typically Save and Cancel). hence the option hidden field.Joomla Component Development We used editListX (and addNewX). when we press the edit button created by the JToolBarHelper::editListX the submitform will be called with the parameter edit: submitbutton(‘edit’). The difference between them is that the X versions also calls a javascript function named hideMainMenu that will set the value of a hidden input in the form (if that input exists) named hidemainmenu to 1. We’ll also have to add a hidden field name option that contains the name of the component prefixed by “com_”. . we’ll see all that next. So you see that we also have to have a hidden field named task in our form. you know that we have to do a layout/template for this view with a form named adminForm and 4 hidden fields named boxchecked. task and hidemainmenu. joomla makes the administrator menu (Site Menus Content Components … ) inactive. because we’ll POST the form but the important thing here to remember is that joomla needs to know which component is being executed. When the form is submitted and if hidemainmenu is in the request and has a value of 1. Finally. which are alternative versions of editList and addNew. You also know that we have to list the students. This is necessary so that when the form is submitted you get an url equivalent to this (using our component as an example and the edit task): index. and that there are a few naming conventions that we’ll have to follow. and which task is going to be executed for that component. Confidential – All rights reserved. So now. For example.

submitform) in here: folder where you’ve installed joomla/includes/js/joomla. DETAIL NOTE 3. a confirm box will display the message $msg.When$msg is not empty. $alt = 'Publish') – Note that the task string used in this one is the same as the one above.1: You can check the code of JToolBarHelper here: Joomla Component Development folder where you’ve installed joomla/administrator/includes/toolbar. publish($task = 'publish'. Fields that have to be defined in the form: task. boxchecked. unpublish($task = 'unpublish'. editList($task = 'edit'. boxchecked. $alt = 'Cancel') Fields that have to be defined in the form: task.javascript. deleteList($msg = ''. $task = 'remove'. addNew($task = 'add'.2: You can check the joomla javascript (hideMainMenu.DETAIL NOTE 3. unpublishList($task = 'unpublish'.back(). cancel($task = 'cancel'. $alt = 'Save') Fields that have to be defined in the form: task. editListX($task = 'edit'. Fields that have to be defined in the form: task. $alt = 'New') – Generates a Add button. $alt = 'New') same as above. addNewX($task = 'add'. 28 . $alt = 'Publish') Fields that have to be defined in the form: task. $alt = 'Edit') Fields that have to be defined in the form: task. hidemainmenu. $alt = 'Unpublish') Fields that have to be defined in the form: task. publishList($task = 'publish'. (the $alt is the text that is displayed below the button).js Confidential – All rights reserved. boxchecked.php.') – Generates a button that when you click on it makes the browser go to the previous page. Fields that have to be defined in the form: task. $href = 'javascript:history. $alt = 'Edit') Fields that have to be defined in the form: task. Here’s a list of the most common button generator methods from JToolBarHelper and what they do to the form (see the toolbar code for all the buttons): back($alt = 'Back'. $alt = 'Delete'). . save($task = 'save'.3. boxchecked.3. hidemainmenu. $alt = 'Unpublish') Fields that have to be defined in the form: task. But causes the menu to stay inactive. submitbutton.

adminForm.this. Here it is: the view’s layout/template. 'First Name'. ?> </td> </tr> <table class="adminlist"> <thead> <tr> <th width="10"><?php echo JText::_( 'NUM' ). The file should be here: folder where you’ve installed joomla/administrator/components/com_students/views/list/tmpl/listlayout. 'a.students_firstname'.?>" class="text_area" onchange="document. ?>)" /></th> <th> <!--First Name--> <?php echo JHTML::_('grid."><?php echo JText::_( 'Go' ). 'a.getElemen tById('filter_state').students_uid'. 'Last Name'. 'User Name'. ?></button> </td> <td nowrap="nowrap"> <?php echo $this->lists['state'].submit(). ?> </th> <th> Confidential – All rights reserved. It displays the list of students read from the DB (Figure 2). ?> </th> <th> <?php echo JHTML::_('grid.this. $this>lists['order'] ). ?> <form action="index.Joomla Component Development .sort'. $this>lists['order'] ).form." /> <button onclick="this. 'a.sort'. ?>: <input type="text" name="search" id="search" value="<?php echo $this->lists['search']."><?php echo JText::_( 'Reset' ).value=''.form. $this->lists['order_Dir'].php <?php // no direct access defined('_JEXEC') or die('Restricted access').submit(). echo $this->lists['active']. ?></th> <th width="10"><input type="checkbox" name="toggle" value="" onclick="checkAll(<?php echo count($this>items). 29 .sort'. ?></button> <button onclick="document.submit().getElementById('search'). $this->lists['order_Dir'].students_lastname'. $this>lists['order'] ).php" method="POST" name="adminForm"> <tr> <td align="left" width="100%"> <?php echo JText::_( 'Filter' ). ?> </th> <th> <?php echo JHTML::_('grid.form.value=''. $this->lists['order_Dir'].

$this->lists['order_Dir']. $i ). ?> </th> <th> <?php echo JHTML::_('grid. $i ). $row->id. 'Active'. 'a. $this->lists['order_Dir'].published'. 'a. ?> </th> <th> <?php echo JHTML::_('grid. $this->lists['order_Dir'].students_type'. 30 . $row->id). 'Email ID'.?></td> <td><?php echo $checked.?>"> <!--<td><?php echo $row->id. ?> </th> </tr> </thead> <tfoot> <tr> <td colspan="9"> <?php echo $this->pagination>getListFooter(). $row. $link = JRoute::_( 'index.students_phone1'. ?> <tr class="<?php echo "row$k". ?> </td> </tr> </tfoot> <tbody> <?php $k = 0.students_email'. Confidential – All rights reserved.php?option='. $this->lists['order'] ).published'. $i < $n. 'Phone'. 'Student Type'. $n=count( $this->items ). $this>lists['order'] ).sort'. $ordering = ($this->lists['order'] == 'a. $i++) { $row = &$this->items[$i]. 'a.sort'. $this->lists['order'] ).ordering').id'. $this>lists['order'] ). $row. $this>lists['order'] ). ?></td> .sort'.sort'.students_active'. $this->lists['order_Dir']. 'published'. $checked = JHTML::_('grid. ?> </th> <th> <?php echo JHTML::_('grid. 'a.checkedout'.Joomla Component Development <?php echo JHTML::_('grid. $this->lists['order_Dir']. $i.'&hidemainmenu=1' ). 'a. //$checked = JHTML::_('grid. ?> </th> <th> <?php echo JHTML::_('grid.sort'.JRequest::getVar('option').'&task=edit&cid[]='. for ($i=0. $published = JHTML::_('grid.

Confidential – All rights reserved. $row->checked_out ) ) { echo $this>escape($row->students_lastname).?></a></td> <td align="center"><a href="<?php echo $link.Joomla Component Development <td align="center"><a href="<?php echo $link.?>"><?php echo $row->students_phone1. ?> </td> <td> <?php echo $checked.?></a></td> <td align="center"><a href="<?php echo $link.?></a></td> <td align="center"><a href="<?php echo $link. ?>"> <a href="<?php echo $link.?></a></td> <td align="center"><a href="<?php echo $link.?>"><?php echo $row->students_uid. ?></a></span> <?php } ?> </td> <td> <?php if ( JTable::isCheckedOut($this->user->get ('id'). $row->checked_out ) ) { echo $this>escape($row->students_firstname). } else { ?> <span class="editlinktip hasTip" title="<?php echo JText::_( 'Edit Student' ).?>::<?php echo $this->escape($row->students_firstname).?>"><?php echo $row->students_firstname.?>"><?php echo $row->students_type.?></a></td>--> <td> <?php echo $this>pagination->getRowOffset( $i ).?>"><?php echo $row->students_lastname.?>::<?php echo $this->escape($row->students_firstname). } else { ?> <span class="editlinktip hasTip" title="<?php echo JText::_( 'Edit Student' ). ?>"> <?php echo $this>escape($row->students_firstname). ?>"> <a href="<?php echo $link. ?>"> <?php echo $this>escape($row->students_lastname). 31 .?></a></td> <td align="center"><a href="<?php echo $link.?></a></td> <td align="center"><a href="<?php echo $link. ?></a></span> .?>"><?php echo $row->students_active. ?> </td> <td> <?php if ( JTable::isCheckedOut($this->user->get ('id').?>"><?php echo $row->students_email.

$row->checked_out ) ) { echo $this>escape($row->students_phone1). ?>"> <a href="<?php echo $link.?>::<?php echo $this->escape($row->students_firstname). ?></a></span> <?php } ?> </td> <td> <?php if ( JTable::isCheckedOut($this->user->get ('id'). } else { ?> <span class="editlinktip hasTip" title="<?php echo JText::_( 'Edit Student' ).?>::<?php echo $this->escape($row->students_firstname). ?></a></span> . ?></a></span> <?php } ?> </td> <td> <?php if ( JTable::isCheckedOut($this->user->get ('id'). ?>"> <?php echo $this>escape($row->students_phone1). 32 . ?>"> <?php echo $this>escape($row->students_email). $row->checked_out ) ) { echo $this>escape($row->students_email). ?>"> <?php echo $this>escape($row->students_uid).Joomla Component Development <?php } ?> </td> <td> <?php if ( JTable::isCheckedOut($this->user->get ('id'). } else { ?> <span class="editlinktip hasTip" title="<?php echo JText::_( 'Edit Student' ). ?>"> <a href="<?php echo $link. $row->checked_out ) ) { echo $this>escape($row->students_uid).?>::<?php echo $this->escape($row->students_firstname). ?>"> <a href="<?php echo $link. Confidential – All rights reserved. } else { ?> <span class="editlinktip hasTip" title="<?php echo JText::_( 'Edit Student' ).

} else { ?> <span class="editlinktip hasTip" title="<?php echo JText::_( 'Edit Student' ). ?>"> <a href="<?php echo $link. ?>"> <?php echo $this>escape($row->students_type). ?>"> <?php echo $this>escape($row->published). ?></a></span> <?php } ?> </td> <td> <?php if ( JTable::isCheckedOut($this->user->get ('id'). $row->checked_out ) ) { echo $this>escape($row->published).?>::<?php echo $this->escape($row->students_firstname). ?>"> <a href="<?php echo $link. ?>"> <a href="<?php echo $link. $row->checked_out ) ) { echo $this>escape($row->students_type).?>::<?php echo $this->escape($row->students_firstname). Confidential – All rights reserved. ?></a></span> . } else { ?> <span class="editlinktip hasTip" title="<?php echo JText::_( 'Edit Student' ). ?>"> <?php echo $this>escape($row->students_active).?>::<?php echo $this->escape($row->students_firstname).Joomla Component Development <?php } ?> </td> <td> <?php if ( JTable::isCheckedOut($this->user->get ('id'). } else { ?> <span class="editlinktip hasTip" title="<?php echo JText::_( 'Edit Student' ). $row->checked_out ) ) { echo $this>escape($row->students_active). 33 . ?></a></span> <?php } ?> </td> <td> <?php if ( JTable::isCheckedOut($this->user->get ('id').

php and the name of the form has to be adminForm.?>"/> <input type="hidden" name="task" value=""/> <input type="hidden" name="boxchecked" value="0"/> <input type="hidden" name="hidemainmenu" value="0"/> <input type="hidden" name="filter_order" value="<?php echo $this->lists['order'].Joomla Component Development <?php } ?> </td> </tr> <?php $k = 1 . The html table’s css class: adminlist is a css class name used in joomla. the form action is index. Figure 2 – List the students There are a few things you have to know. I don’t think template details are very important here. have Confidential – All rights reserved. because we’re working in the backend.$k. If you want. The css classes are defined by joomla templates. } ?> </tbody> </table> <input type="hidden" name="option" value="<?php echo JRequest::getVar( 'option' ). so just trust me about using that css class. //$i++.token' ). and a few more that I’ll mention. ?>" /> <input type="hidden" name="filter_order_Dir" value="<?php echo $this->lists['order_Dir']. ?> </form> . 34 . ?>" /> <?php echo JHTML::_( 'form. the adminlist css class is defined in a backend template. In this case. Joomla templates have sufficient material for several tutorials. First.

Joomla Component Development a look at the css from the default template for the backend that comes with joomla 1.css and general_rt. We’re using JRoute’s ‘_’ function to build the url. The checkAll javascript method is defined in folder where you’ve installed joomla/includes/js/joomla. This is a php thing: when you add ‘[]’ to the name of a checkbox and you have several checkboxes with that same name followed by ‘[]’ you can read an array from the request with the value of the checked checkboxes. when we read cid from the request we’ll get an array that contains the values of the checked checkboxes. 35 . and checks or unchecks them depending on the of checkbox named toggle being checked or not.php?option=com_students&task=edit&cid[]=ID_OF_THE_ROW_WE_WANT_TO _EDIT&hidemainmenu=1. and what it does is that it checks to see if a checkbox named toggle inside a form named adminForm is checked or not. The table header will display something like this: # [checkbox] First Name (Figure 2). this checkbox has to be named toggle. the number of items are the students). First.5. $row->id). where X goes from 0 to the number you pass as argument to checkAll-1.js.javascript. you select/deselect all items (in our case students). cb2. $i. cb1.id'. and it’s onclick event handler has to be checkAll([Number of items listed]) (in our case. you don’t have to worry about that because the code: JHTML::_('grid. Each of the students displayed is a link. that also happens when we click the edit button because we use JToolBar::editListX : the X version of editList). $i.css. JHTML is used to generate the html for several html elements DETAIL NOTE 3.3. and then it goes through the checkboxes with id cbX. since joomla 1. . Confidential – All rights reserved. In our case. So now you know that the checkboxes to select each individual item have to have an id: cb0. We should do that because the ‘_’ method from JRoute rewrites the url to a Search Engine Friendly(SEF) form if SEF is enabled in Joomla (To enable SEF go to Site->Global Configuration). There are a few things you need to know about that checkbox. generates that for you. However.The hidemainmenu parameter is set to 1 in the url so that the joomla’s administrator menu stays disabled when editing (remember. This will work if we respect joomla’s naming conventions for the checkboxes. $row->id). SEF doesn’t work on the backend so you won’t see any difference in the url. but still it’s good practice to use it because if you want to reuse some of the code in the frontend you won’t have to worry about the urls . the files that define the class adminlist are general. Its behaviour is that when you click on it. etc.id'.3: If you see the actual HTML generated when you do JHTML::_('grid. you’ll see that the name of the checkboxes is actually cid[].5 (named khepri). But fortunately. that when you click on it redirects you to the url: index. the css is in folder where you’ve installed jooma/administrator/templates/khepri/css.

The css classes row0 and row1 have different background colors making it easier for you to distinguish between each item in the list (in our case. if it is being unchecked it subtracts 1. The rest is each table row displays the student’s id.id'. $i. $i. each student).4: This note is about how the boxchecked hidden field is updated.js. followed by a checkbox that was generated by JHTML::_('grid. is something like this: <input id="cb0" name="cid[]" value="1" onclick="isChecked(this. we’re using a trick to change the css class of every <TR>. About the actual listing of the students (the foreach’s code). in the form of a link that. and then the actual student. What it does is if the checkbox is being checked it adds 1 to the boxchecked adminForm’s hidden input.3. You can see the code for isChecked here: folder where you’ve installed joomla/includes/js/joomla. DETAIL NOTE 3. The javascript isChecked method is the one that updated boxchecked hidden input field.Joomla Component Development . 36 ." type="checkbox"> . $row->id). Confidential – All rights reserved.checked).javascript. The code generated by JHTML::_('grid. when pressed will create a request for our backend’s component with the task edit and with the parameter cid (that will be an array) with the value of the id of the student we want to edit (we still have to code the edit task). $row->id).id'.

'array' ). Especially because if we’re just editing one student. To do that we just have to add a method named edit to our controller that will load a view named studentForm. We’ll call a method named displayEdit in the view and pass the id of the student as a parameter to it (we’ll do the view’s displayEdit method in Section 4. DEFAULT_VALUE. 'cid parameter missing from the request').1 – The controller task: edit Now let’s do the edit task. I just make the view name and layout fixed to studentForm and studentformlayout respectively. So. When you click on it. and it should be located in folder where you’ve installed joomla/administrator/components/com_students/studentsController. There is a detail about reading the id from the request. //get the first id from the list (we can only edit one student at a time) $view = & $this->getView('studentForm'). HASH. then POST and then FILE $cids = JRequest::getVar('cid'.php. } $studentId = (int)$cids[0].php. You might be asking yourself right now why did I used cid[] as a parameter. //Reads cid as an array if($cids === null){ //Make sure the cid parameter was in the request JError::raiseError(500. Remember that our controller file is named studentsController. with a layout/template named studentformlayout.3). In this task we’ll read the id of the student we want to edit. Code for edit method: function edit(){ //getVar(PARAMETER_NAME. and the selected students will go in the request in the cid[] parameter. Remember that when we listed the student we put a link in each one: index. We will use the same model we used for listing the students although we’ll add a new method that will return an object that represents a row in the students table in the database (we’ll look at that in Section 4. I’m not reading the viewname and layout from the request in this task. Where ID is the actual ID for the student we want to edit. why do we need to put it in an array? The answer to that is: it’s because of the Edit button in the toolbar. it submits the form that has the list of student. that’s why we called the parameter with the id of the student cid[] . Section 4 – The backend tasks – The edit task Section 4. // Get/Create the model if ($model = & $this->getModel('students')) { Confidential – All rights reserved. so that we could handle both cases (clicking on the link and clicking the edit button in the toolbar) the same way.php?option=com_student&task=edit&cid[]=ID.Joomla Component Development . TYPE) //The HASH is where to read the parameter from: //The default is its default value: getVar will look for the parameter in //GET. null. 'default'.2). 37 .

Remember that our model file is named students.').$id. If you remember the code that we did for the default task (display) that displays a list of the students read from the database.3 The view – form to edit the student Confidential – All rights reserved.2 The model – Getting a student through its id We have to add a method to our model that gets a student from the database based on its id. $view->displayEdit($studentId). So our new method for the model will do just that: get the student from the database with a specific id. Where. Something like this: index. $db->setQuery($query).php and that it is located in folder where you’ve installed joomla/administrator/components/com_students/models/students.php Here’s the code getStudents() method: function getStudent($id){ $query = 'SELECT * FROM #__student'. ' WHERE id = '. in this example the 1 is the id of the student we want to edit.' not found.php?option=com_students&task=edit&cid[]=1. else return $student. true). if ($student === null) JError::raiseError(500. $db = $this->getDBO(). Let’s call that method getStudent. 38 . 'Student with ID: '. } Section 4. } . $student = $db->loadObject(). you’ll remember that in that list each student has a link. Section 4. } $view->setLayout('studentformlayout').$id.Joomla Component Development //Push the model into the view (as default) //Second parameter indicates that it is the default model for the view $view->setModel($model.

$student). This view we’re about to do will display a form that will allow us to edit a student (Figure 3) . } function displayAdd(){ JToolBarHelper::title('Student'.': [<small>Edit</small>]'). This view will have two buttons on its toolbar: Save and Cancel.application. JToolBarHelper::cancel(). $this->assignRef('student'. Confidential – All rights reserved. JToolBarHelper::cancel().php Here’s the code for the view: <?php // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ). We’ll create a method named displayEdit that gets as a parameter the id of the student we want to edit. This view will have to be located in: folder where you’ve installed joomla/administrator/components/com_students/views/studentForm/view.Joomla Component Development .view'). $student = $model->getNewStudent(). $student). $model = $this->getModel(). parent::display(). jimport( 'joomla. $student = $model->getStudent($studentId). /** * HTML View class for the backend of the Students Component edit task * @package Students */ class StudentsViewStudentForm extends JView { function displayEdit($studentId) { JToolBarHelper::title('Student'.': [<small>Add</small>]'). parent::display().component.php The view’s class name is: StudentsViewStudentForm And the layout/template file: joomla/administrator/components/com_students/views/studentForm/tmpl/studentformlay out. JToolBarHelper::save(). JToolBarHelper::save(). $this->assignRef('student'. 39 . then we use the getStudent method from the model associated with this view to get the actual student from the database and then display it in the form in the layout/template. $model = $this->getModel().

?>" /> </td> </tr> <tr> <td class="key">Street</td> <td> <input type="text" name="students_street" id="students_street" size="32" maxlength="250" value="<?php echo $this->student->students_street. ?>" /> </td> </tr> <tr> <td class="key">Gender *</td> <td> <input type="text" name="students_gender" id="students_gender" size="32" maxlength="250" value="<?php echo $this->student->students_gender.php" method="POST" name="adminForm" id="adminForm"> <fieldset class="adminform"> <legend>Student Details</legend> <table class="admintable"> <tr> <td class="key">First Name *</td> <td> <input type="text" name="students_firstname" id="students_firstname" size="32" maxlength="250" value="<?php echo $this->student->students_firstname.Joomla Component Development } } ?> . ?> <form action="index. ?>" /> </td> Confidential – All rights reserved. ?>" /> </td> </tr> <tr> <td class="key">Email ID *</td> <td> <input type="text" name="students_email" id="students_email" size="32" maxlength="250" value="<?php echo $this->student->students_email.php The code is here: <?php // no direct access defined('_JEXEC') or die('Restricted access'). 40 . ?>" /> </td> </tr> <tr> <td class="key">Last Name *</td> <td> <input type="text" name="students_lastname" id="students_lastname" size="32" maxlength="250" value="<?php echo $this->student->students_lastname. Remember that the layout/template for this view is named studentformlayout and should be located in: folder where you’ve installed joomla/administrator/com_students/views/studentForm/tmpl/studentformlayout.

?>" /> </td> </tr> <tr> <td class="key">Phone 2</td> <td> <input type="text" name="students_phone2" id="students_phone2" size="32" maxlength="250" value="<?php echo $this->student->students_phone2. 41 .Joomla Component Development . ?>" /> </td> </tr> <tr> <td class="key">State</td> <td> <input type="text" name="students_state" id="students_state" size="32" maxlength="250" value="<?php echo $this->student->students_state. ?>" /> </td> Confidential – All rights reserved. </tr> <tr> <td class="key">City</td> <td> <input type="text" name="students_city" id="students_city" size="32" maxlength="250" value="<?php echo $this->student->students_city. ?>" /> </td> </tr> <tr> <td class="key">Phone 1</td> <td> <input type="text" name="students_phone1" id="students_phone1" size="32" maxlength="250" value="<?php echo $this->student->students_phone1. ?>" /> </td> </tr> <tr> <td class="key">School State *</td> <td> <input type="text" name="students_schoolstate" id="students_schoolstate" size="32" maxlength="250" value="<?php echo $this->student->students_schoolstate. ?>" /> </td> </tr> <tr> <td class="key">Time Zone *</td> <td> <input type="text" name="students_timezone" id="students_timezone" size="32" maxlength="250" value="<?php echo $this->student->students_timezone. ?>" /> </td> </tr> <tr> <td class="key">ZIP</td> <td> <input type="text" name="students_zip" id="students_zip" size="32" maxlength="250" value="<?php echo $this->student->students_zip.

?>" /> </td> </tr> <tr> <td class="key">Status</td> <td> <input type="text" name="students_active" id="students_active" size="32" maxlength="250" value="<?php echo $this->student->students_active. </tr> <tr> <td class="key">Student Type</td> <td> <input type="text" name="students_type" id="students_type" size="32" maxlength="250" value="<?php echo $this->student->students_type. ?>" /> </td> </tr> <tr> <td class="key">Relationship</td> <td> <input type="text" name="students_p1_relationship" id="students_p1_relationship" size="32" maxlength="250" value="<?php echo $this->student>students_p1_relationship. 42 . ?>" /> </td> </tr> Confidential – All rights reserved. ?>" /> </td> </tr> </table> <legend>Parent/Guardian</legend> <table class="admintable"> <tr> <td class="key">First Name *</td> <td> <input type="text" name="students_p1_firstname" id="students_p1_firstname" size="32" maxlength="250" value="<?php echo $this->student>students_p1_firstname.Joomla Component Development . ?>" /> </td> </tr> <tr> <td class="key">Phone 1 *</td> <td> <input type="text" name="students_p1_phone1" id="students_p1_phone1" size="32" maxlength="250" value="<?php echo $this->student->students_p1_phone1. ?>" /> </td> </tr> <tr> <td class="key">Last Name *</td> <td> <input type="text" name="students_p1_lastname" id="students_p1_lastname" size="32" maxlength="250" value="<?php echo $this->student>students_p1_lastname.

?>"/> <input type="hidden" name="id" value="<?php echo $this->student->id. ?>"/> <input type="hidden" name="task" value=""/> </form> . ?>" /> </td> </tr> <tr> <td class="key">Email Address *</td> <td> <input type="text" name="students_p1_email" id="students_p1_email" size="32" maxlength="250" value="<?php echo $this->student->students_p1_email. Figure – 3 The Edit Form Confidential – All rights reserved.Joomla Component Development <tr> <td class="key">Phone 2</td> <td> <input type="text" name="students_p1_phone2" id="students_p1_phone2" size="32" maxlength="250" value="<?php echo $this->student->students_p1_phone2. ?>" /> </td> </tr> </table> </fieldset> <input type="hidden" name="option" value="<?php echo JRequest::getVar( 'option' ). 43 .

Confidential – All rights reserved. There is an important detail here. which is: the form has to have inputs with the same name as the fields in our jos_students table. When we do the save task it will be clear why. the Save button causes this form to be submitted with the hidden field task with value ‘save’ and the Cancel button submits the form with the hidden field task with value ‘cancel’. that’s why there is a hidden field named id.Joomla Component Development Remember that we used the Save and Cancel buttons in the toolbar. 44 . .

Confidential – All rights reserved.Joomla Component Development . 45 .

after using the model to save the edited student we’ll use the JController’s method setRedirect to make joomla redirect to the page where the students are listed (our components default task.Save Section 5. Finally. and you’ll see that at the end a method named redirect from the controller is executed. it is named saveStudent).1: If you’re wondering how setRedirect will redirect you to the link you pass as a parameter look at our entry point file. it will read the data posted by the form we did for the studentForm view. $model->saveStudent($student).JRequest::getVar('option'). So we need to do the method to handle that task. So let’s add that method to our backend controller.1.'&task=display'). DETAIL NOTE 5.1 – The controller task: save When we edit a student and click on the save button the form we just did before is going to be submitted with the task parameter set to save. 46 .php) /** * Method to store a student in the DB */ function saveStudent($student) Confidential – All rights reserved.php Here’s the code (save() method in studentsController. } Here is the Code (saveStudent($student) method in …/models/students. That will cause the save task to be executed in the controller. located in: folder where you’ve installed joomla/administrator/com_student/studentsController. display). That method is what actually causes the browser to redirect to the link we supply as a parameter to setRedirect. Then it will use a method in the model that will get that post data as a parameter and will use it to update the database record that corresponds to the student we’re editing (we need to add that method to our model. and that method has to be named save.php): function save(){ $student = JRequest::get( 'POST' ). Section 5: The backend tasks .Joomla Component Development .php?option='. We are editing controller file. $this->setRedirect($redirectTo. $redirectTo = JRoute::_('index. 'Student Saved!'). $model = & $this->getModel('students').

} // Make sure the student record is valid if (!$studentTableRow->check()) { JError::raiseError(500. 'Error binding data'). 'Error binding data: '. } } . JError::raiseError(500. Table class name $studentTableRow =& $this->getTable('students').Joomla Component Development { //Parameter not necessary because our model is named StudentsModelStudents (used to illustrate that you can specify an alternative name to the JTable extending class) //getTable('students'). 47 . // Bind the form fields to the student table if (!$studentTableRow->bind($student)) { JError::raiseError(500. } // Insert/update this record in the db if (!$studentTableRow->store()) { $errorMessage = $studentTableRow->getError(). Here students is not a table name. Confidential – All rights reserved.$errorMessage). 'Invalid data').

you can specify a name in the JModel’s getTable method.) Confidential – All rights reserved. in the backend: folder where you’ve installed joomla/admistrator/components/com_students/tables. The JModel specifies methods to get instances of JTABLE following some naming conventions. which correspond to the jos_students database table fields with the same name. You can use a JModel’s method named getTable without parameters to get the class that extends JTABLE following JModel’s naming conventions for table classes. this tries to get an instance for a class named TableMyTable located in joomla/administrator/components/[COMPONENT_NAME]/tables/mytable.. the class that we’re going to write that extends JTABLE has many attributes. JTABLE is a class we can extend that has methods that help us interact with the database. First.Joomla Component Development . The convention is: • • The class extending JTABLE should be named Table[ModelName]. in the frontend it’s the same without administrator (you can change the default location in the model’s constructor). for example getTable(‘Mytable’). We also have to specify in the constructor which of the fields is the key for the database and also the table’s name.php for the backend (the same for the frontend without administrator.php (the file name has to be in lowercase).students_lastname. students_firstname. Remember that the model’s class name is build by: [ControllerName]Model[ModelName]. the default location for JTABLE files is. If you want. 48 .2 JTABLE To have our saveStudent method in the model we’re going to use an instance of a class we’ll do that extends JTABLE. for example named id. especially if we want to update or add records to a database table. where [ModelName] is the model’s name from where we’re using the JModel’s gettable method without parameters. Using our jos_students table as an example. And should be named [ModelName]. Section 5. The class that extends JTable should be located in folder where you’ve installed joomla/administrator/components/[COMPONENT_NAME]/tables where [COMPONENT_NAME] is the name of the component where our model is. etc. To use the functionalities that JTABLE has we have to create a class that extends JTABLE and has a direct correspondence between the names of its attributes and the names of the fields in the database table we’re dealing with.

and specify in the config array.2. public $students_p1_lastname = null. public $students_schoolstate = null. } Confidential – All rights reserved. public $students_p1_relationship = null. a parameter named table_path. For example. public $students_p1_email = null. public $students_phone2 = null.Joomla Component Development DETAIL NOTE 5. public $students_p1_phone1 = null. 49 . that the constructor gets as argument. public $students_gender = null.php function __construct(){ parent::__construct(array('table_path'=>JPATH_COMPONENT.DS. public $students_active =null. $db). public $students_zip = null. public $students_firstname = null. public $students_street = null.'myTablesFolder' )). public $students_city = null.1: To change the default location of the classes that extend JTable you have to override the default constructor ofthe model class you’re using. public $students_p1_phone2 = null. } . public $students_email = null. 'id'. public $students_phone1 = null. if we want to change the tables folder in our model for the students (in the backend) we would add this code to our model file located in: folder where you’ve installed joomla/administrator/components/com_students/models/students. it has to be located in: folder where you’ve installed joomla/administrator/components/com_students/tables and the file will be named students.php: <?php defined('_JEXEC') or die('Restricted Access'). public $students_timezone = null. function TableStudents(&$db){ parent::__construct('#__student'. public $students_state = null. public $students_lastname = null. class TableStudents extends JTable { public $id = null. public $students_p1_firstname = null. public $students_type = null. Here’s the code for the class that will extend JTable that we will be using to add and update students in our students’ database table.

'Error binding data'). } // Insert/update this record in the db if (!$studentTableRow->store()) { $errorMessage = $studentTableRow->getError().Joomla Component Development } ?> . 50 . Table class name $studentTableRow =& $this->getTable('students'). this file is located in: folder where you’ve installed joomla/administrator/com_students/models/students. 'Error binding data: '. if you remember from the controller’s code. Here students is not a table name. Remember. This is where we’ll use the functionalities offered by JTable. // Bind the form fields to the student table if (!$studentTableRow->bind($student)) { JError::raiseError(500. 'Invalid data'). we’re invoking there and passing a parameter to it with the data we’re getting from the request (that will contain the values from the inputs of the from that is outputted by the studentForm view).$errorMessage). JError::raiseError(500. Section 5. I’ll show you the code and then talk a little bit about the methods we’re using from JTable.php Here is the Code (saveStudent($student) method in …/models/students.php) /** * Method to store a student in the DB */ function saveStudent($student) { //Parameter not necessary because our model is named StudentsModelStudents (used to illustrate that you can specify an alternative name to the JTable extending class) //getTable('students'). } // Make sure the student record is valid if (!$studentTableRow->check()) { JError::raiseError(500. } } Confidential – All rights reserved.3 The Model – Adding the save functionality We’re adding a new method to our model named saveStudent that.

51 . Also note that if an attribute is in the table class. DETAIL 5. If for some reason you have attributes in your table class that you don’t want to update with the values from $from.. you put them in $ignore. This gets really simple with an example. It has mnay attributes: id. Confidential – All rights reserved. Imagine our TableStudents class that extends JTable. The JTable’s bind method we’re using ($studentTableRow->bind($student)) uses reflection to get all the attributes from the class.com_jdwiki/Itemid. What it’s for is to specify a list of attributes to be ignored in the binding process. What bind does is it sets the attribute id with the value from the form input id. And remember that the form from the studentForm view has among other form inputs. and make it return true if the attributes are valid and false otherwise Finally. no error is produced and bind still returns true. The idea behind the check method is that you should override it when you extend JTable. but not in $from. What the JTable’s check method does is … well it just returns true.references:joomla.org/component/option./id. After the bind we do the check.joomla. we store. students_firstname. or it updates the record whose primary key has the same value as the value of the attribute we specify as key in the JTable’s class constructor (in our case.3. and the same for student. etc. . TableStudent id attribute with value X not 0. will cause an update to the student with id X).1: Doc..Joomla Component Development The $student parameter will be an array that will contain the values from the input fields from the form (that we did in the studentForm view) indexed by the names of the inputs. and then sets them with the values from the array passed as a parameter that have a key with the same name as the attributes in the class. What store does is it inserts a new record in the database if the attribute that represents the table key is 0 (in our case if the Tablestudent id attribute is 0 a new record is inserted). an input named id and student. $ignore ) you’ll notice that it has a second parameter. I just put it there so I could tell you about it.framework:table:jtable-bind/ If you look at bind’s signature: boolean bind ( $from. page for JTable::bind: http://dev. students_lastname.

} Now let’s do add the displayAdd method to the view named studentForm. We’re editing the view named studentForm which is located here: Confidential – All rights reserved.1: The controller task: add For the add task we’re doing something very similar to the edit task. and then it’s the same thing as we did for editing a student.php Here’s the add() function in controller code: function add(){ $view = & $this->getView('studentForm'). We need to add method to our controller file located in folder where you’ve installed joomla/administrator/com_students/studentsController. This is the task that will be executed when you click on the toolbar’s Add button when our component is displaying the list of students (default display task). } $view->setModel($model. if (!$model){ JError::raiseError(500. $model = & $this->getModel('students'). 52 . and the actual student will be an empty string. What we will do in the controller code is we will add a method named add that will get the model named students and the view named studentForm and call a method from that view named disaplyAdd that we’ll do later. Section 6. The only difference is that we will be editing a student with id 0.2: The view . $view->setLayout('studentformlayout'). 'Model named students not found'). Section 6: The backend tasks – The add task Section 6.Joomla Component Development . $view->displayAdd(). What this method will do is. it will call a method from the model named getNewStudent (that we’ll do later) that returns an “empty” student with id 0. true).Form to edit the student (revisited) We have to add a method named displayAdd that has no arguments to the view named studentForm.

php Here’s the getNewStudent() . Section 6.//models/students. We’re editing the students model file located in: folder where you’ve installed joomla/administrator/components/com_students/models/students. 53 . $studentTableRow->students_timezone = ''.php code: function displayAdd(){ JToolBarHelper::title('Student'. $studentTableRow->students_zip = ''. Here’s the displayAdd() method in view. Confidential – All rights reserved. $studentTableRow->students_lastname = ''. JToolBarHelper::save(). $studentTableRow->students_email = ''. $studentTableRow->students_firstname = ''.3: The model – New students We have to add the getNewStudent method to the students model.': [<small>Add</small>]').. $studentTableRow->id = 0. $this->assignRef('student'. } That’s it for the view. Here students is not a table name. $studentTableRow->students_uid = 0.php code: /** * Method that returns an empty student with id 0 */ function getNewStudent(){ //getTable('students'). JToolBarHelper::cancel(). $studentTableRow->students_street = ''. $studentTableRow->students_grade_id = 0.Joomla Component Development folder where you’ve installed joomla/administrator/components/com_students/views/studentForm/view. now let’s do the model. $studentTableRow->students_city = ''. $student). parent::display(). Table class name $studentTableRow =& $this->getTable('students'). $studentTableRow->students_schoolname = ''. $student = $model->getNewStudent(). $studentTableRow->students_schoolstate = ''. $model = $this->getModel(). What this method will do is it will get an instance form the table class (the one that implements JTBALE) and set that instance’s id attribute to 0 and the student attribute to the empty string. $studentTableRow->students_state = ''.php .

it is like you’re editing a student with id 0. } . $studentTableRow->students_phone1 = ''. $studentTableRow->students_observedst = 0. $studentTableRow->students_p2_firstname = ''. $studentTableRow->students_p1_firstname = ''. $studentTableRow->students_p2_phone2 = ''. but when you click the save button. you get a new record in the database. return $studentTableRow. $studentTableRow->students_p1_email = ''. $studentTableRow->students_type = 0. Why are we doing this? Remember when I explained how the JTable’s store method worked? That when the attribute associated with the table’s primary key was 0 the store method would insert a new record in the database. $studentTableRow->students_p1_phone1 = ''. $studentTableRow->students_p1_relationship = ''. $studentTableRow->students_p1_email = ''. $studentTableRow->students_p2_email = ''. $studentTableRow->students_p2_phone1 = ''.Joomla Component Development $studentTableRow->students_gender = ''. and the save task is executed. $studentTableRow->students_p2_relationship = ''. $studentTableRow->students_created_on = ''. $studentTableRow->students_p2_lastname = ''. $studentTableRow->studetns_deleted = 0. $studentTableRow->students_p1_lastname = ''. Confidential – All rights reserved. That’s what happening here. 54 . $studentTableRow->students_requirements = ''. $studentTableRow->students_active =0. $studentTableRow->students_p1_phone2 = ''. $studentTableRow->students_phone2 = ''.

php function deleteStudents($arrayIDs) { $query = "DELETE FROM #__student WHERE id IN (".//models/students.'). We’re editing the model named students’ file.’b’. null.php function remove(){ $arrayIDs = JRequest::getVar('cid'. $arrayIDs). //Reads cid as an array if($arrayIDs === null){ //Make sure the cid parameter was in the request JError::raiseError(500. } Section 7..’c’)) you’d get a string like this: ‘a. and then use the JController’s setRedirect method to redirect to the list of the students. $model->deleteStudents($arrayIDs). 'cid parameter missing from the request').'. $this->setRedirect($redirectTo.’. We’re editing the controller’s class located in: folder where you’ve installed joomla/administrator/com_students/studentsController.")". 'Deleted. Section 7: The backend tasks: The remove task Section 7. } $model = & $this->getModel('students').b.Joomla Component Development . 'array' ). 'default'. $redirectTo = JRoute::_('index.php Here is the deleteStudents() in . array(‘a’. Imagine you use implode with arguments (‘. 55 .implode('..2: The model – Deleting students Where doing the deleteStudents method in our students model that gets an array with the id’s of the students to be deleted as input.c’. located in: folder where you’ve installed joomla/administrator/com_students/models/students.1: The controller task: remove To do the remove task we have to get the id of the student we want to remove (like we did for the student to edit. the separator and the array. Then we’ll call a method from the model named deleteStudents to which we will supply the array with the ids of the student as a parameter (we’ll do deleteStudents later). Confidential – All rights reserved..php Here is remove() method code in studentsController. We’re using php’s implode method that has two arguments. in the edit task).JRequest::getVar('option')).php?option='.

$errorMessage). If there’s an error while the query is being executed (query method) getErrorMsg returns the SQL error that describes what happened. JError::raiseError(500. 'Error deleting students: '.Joomla Component Development $db = $this->getDBO(). Note that we’re using the getErrorMsg method from JDatabase to get the error message. Confidential – All rights reserved. 56 . $db->setQuery($query). if (!$db->query()){ $errorMessage = $this->getDBO()->getErrorMsg(). } } .

Joomla Component Development . 57 . Confidential – All rights reserved.

That’s it..sql (sql query) Place com_students folder in joomla path .\\administrator\components\ Execute jos_components.Joomla Component Development . Click on component. 58 . You will find: • • • • Com_students (component) Joomla_Component_Development . Section 8: Installation Unzip Student_Component.doc (Document) jos_components. Find ‘Manage Student’ link. please free to mail me. (mailto:prabhu.sql on mysql joomla database.net?subject=Joomla Queries) Thank you. Click on this & Explore.sql (sql query) jos_Students. TEST: Login to Joomla. Prabhu Patil Confidential – All rights reserved. If you have any queries.sql and jos_Students.patil@reachwell.

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.