Starting to work on backend – Adding a view

Although the frontend and backend of Joomla are designed to do different things, they still use the same MVC pattern for organising code. The major purpose of the backend is to manage data.

Creating a basic view:

In your Joomla component directory, open com_breed. In this step, you have to create following files.

Create  controller.php        /administrator/controller.php

Create  breed.php        /administrator/models/breed.php

Create  view.html.php       /administrator/views/breed/view.html.php

Create  default.php           /administrator/views/breed/tmpl/default.php

Update  breed.php          /administrator/breed.php

Update  breed.xml          /breed.xml

 /administrator/breed.php

	<?php

defined('_JEXEC') or die;

// Access check.
if (!JFactory::getUser()->authorise('core.manage', 'com_breed'))
{
	throw new Exception(JText::_('JERROR_ALERTNOAUTHOR'));
}

// Include dependancies
jimport('joomla.application.component.controller');

$controller = JControllerLegacy::getInstance('Breed');
$controller->execute(JFactory::getApplication()->input->get('task'));
$controller->redirect();

Now download the attached code zip file and open the breed.php file located in the administrator folder; you will find the above-listed code there. The first code block from lines 6 to 9 checks for access to determine whether the current user has the rights to go through this component or not. With the help of the getUser method of the JFactory class, we are getting the user object, and the technique for this that we are using here is called method chaining. More than one method can be called in a single request using PHP function or method chaining.Beside Joomla, this sort of implementation could also be seen in Zend and Magento. Here is our code: we are passing two arguments to the authorise method, which we have called through the getUser method; the first is “core.manage,” and the second is the name of our component, “com_breed,” which defines the context for permissions. It is the core.manage component that actually controls access to the component. Ok, so what all this will do is check whether the currently logged-in user has the right to manage the com_breed component backend. Now if that user is not allowed to manage, on line 8, we are throwing an exception to raise an error by using Joomla’s JError class.

After that, on line 12, we are importing the JController class if we have granted access through the previous permissions check code. Then we instantiate the controller using JController’s getInstance method by passing the component name to it, and it will automatically find the class we will declare in the main controller.php file. Next on line 15, we are again applying the PHP method chaining approach to execute the task we have gotten from the request. When the execute method has successfully run the request, it will come back, and on line 16, through the redirect() method, we are applying a redirect in the controller. We will examine this redirection process when we move forward in developing our breed component.

/administrator/controller.php

	<?php

defined('_JEXEC') or die;

jimport('joomla.application.component.controller');

class BreedController extends JControllerLegacy
{
	public function display($cachable = false, $urlparams = false)
	{
		$view = JFactory::getApplication()->input->getCmd('view', 'breeds');
		JFactory::getApplication()->input->set('view', $view);

		parent::display($cachable, $urlparams);

		return $this;
	}
}

Open the /administrator/controller.php file, which is our base controller file, and in this, on line 6, we are calling the controller library through the import method, which is normally used to pull a library. On line 7, we have a controller class that is extending the main controller JControllerLegacy class, which is available to controllers in Joomla. In the definition of this, first the name of the component is used, and in our case, it is “breed,” which comes along with the word “controller.” This is how a base controller is named. After that, on line 9, we are defining a function called “display,” whose job is to pull the main page and pass it to the Joomla library, which will then be processed and sent to the browser for displaying to the user.

In the display method, on line 11 of above mentioned controller code, we are getting the view and if the view request is blank or not set, we are passing the default value of “breeds”, which is our main breeds listing view page. Again there is a chaining method approach as we are utilizing the JFactory class getApplication() method and calling its getCmd function through input method. After that we set the view through getApplication set method and call the display method to display the view.

/administrator/models/breeds.php

<?php

defined('_JEXEC') or die;

jimport('joomla.application.component.modellist');

class BreedModelBreeds extends JModelList
{

	protected $message;
 
	public function getMsg()
	{
		if (!isset($this->message))
		{
			$this->message = 'Breeds List at backend';
		}
 
		return $this->message;
	}
}
}

In the above-mentioned breed.php model file, first we have imported the Joomla model items library on line 5, and then on line 7, we have created a class “BreedModelBreeds” extending the main JModelList class, which will enable us to use all available methods for creating a list view. For demonstrating how the model works, first we have created a test method called getMsg(), which just returns a string. We will fetch the outcome of this method in the view.html.php file of the view and then load it in the default.php file, which will send this to the browser.

 /administrator/views/breed/view.html.php

<?php

defined('_JEXEC') or die;

jimport('joomla.application.component.view');

class BreedViewBreeds extends JViewLegacy
{

	function display($tpl = null)
	{
		// Assign data to the view
         	$this->msg = $this->get('Msg');
		
			if (count($errors = $this->get('Errors')))
		{
			throw new Exception(implode("\n", $errors));
		}
 
		// Display the view
		parent::display($tpl);
	}

}
}

This view is almost identical to what we have developed before when working on the frontend view, but let me go through it briefly to refresh those things. A request to Joomla is normally made through a url that contains the component and view names, as well as a task if necessary; if viewing a single record, there will be an id in the url identifying that record, and if you are on fontend, there will also be an Itemid in the url identifying that record. In this step, we will be talking about the view part. Joomla fetches the name of the component and view and passes them to the respective controller for processing. The controller extracts the view name from the request and attempts to load the view; if no view name is passed, it will attempt to load the default view, which in our case is “breeds.”

Now we come to the view.html.php file, which Joomla runs through first before calling the actual default.php file, which contains the HTML code. This file allows us to add any data to the view before displaying it. On line 5, we have imported the view library, and after that, on line 7, we have declared the actual view class, named BreedViewBreeds, where the prefix “Breed” refers to the name of the component in which we are, then the name “view,” which tells Joomla that it is a view class and not a controller or model, and then “Breeds,” which is the name of our current view.

After that, we have a method called “display.” It allows us to add data to the view before it is displayed. Then on the next line, we are setting a message and calling the parent display function on line 21, which will pull the default.php file from the view tmpl directory.

To track any errors in this process, we are throwing an exception before calling the parent display method, so that if there are any issues or bugs, they could be tracked and code should be stopped for further execution.

 /administrator/views/breed/tmpl/default.php

<?php

// No direct access
defined('_JEXEC') or die;
?>

<h1><?php echo $this->msg; ?></h1>

This default.php template view file is the actual file that contains our HTML code. The HTML and text listed here will be fetched by the view.html.php file in the component view and then displayed to the user. For demonstration purposes, we are simply getting and displaying the message that was fetched by the view.html.php file via the model, and then passing it here to the default.php file so that it can be presented in proper h1 tags. In future steps, I would be adding a lot of code to this file for making proper breed listings, applying filters, grid sorting, searching, and other stuff, so this file is really going to expand.

/breed.xml

- - - - - 
 <files folder="administrator">

            <filename>index.html</filename>

            <filename>breed.php</filename>

            <filename>controller.php</filename>

            <folder>views</folder>  
                    
            <folder>models</folder>      

            <folder>sql</folder>                   

        </files>

According to which files we have added in this part of tutorial, we are making changes to our main breed.xml manifest file by adding a few files and folder tags to “administrator” portion of the file, including “controller.php“, “views” and “models”. After that, just zip the component and install it to joomla. After that go to Components –> Breeds and you will see the following screen.                thanks.

Download Component

Next –> Creating a list view at backend

Add a Comment

Your email address will not be published. Required fields are marked *

ABOUT CODINGACE

My name is Nohman Habib and I am a web developer with over 10 years of experience, programming in Joomla, Wordpress, WHMCS, vTiger and Hybrid Apps. My plan to start codingace.com is to share my experience and expertise with others. Here my basic area of focus is to post tutorials primarily on Joomla development, HTML5, CSS3 and PHP.

Nohman Habib

CEO: codingace.com

Request a Quote









PHP Code Snippets Powered By : XYZScripts.com