Contents
Añadiendo una barra de herramientas
En Joomla, el administrador interactua generalmente con los componentes mediante el uso de una barra de herramientas. En el fichero admin/views/helloworlds/view.html.php pon este contenido. Creará una barra de herramientas básica y un título para el componente.
Los argumentos usados en el ejemplo. JToolBarHelper::addNew se utiliza para establecer una instancia del controlador que será utilizado cuando se pulse el botón.
admin/views/helloworlds/view.html.php
<?php // No direct access to this file defined('_JEXEC') or die('Restricted access'); // import Joomla view library jimport('joomla.application.component.view'); /** * HelloWorlds View */ class HelloWorldViewHelloWorlds extends JView { /** * HelloWorlds view display method * @param string $tpl The name of the template file to parse; automatically searches through the template paths. * * @return mixed A string if successful, otherwise a JError object. */ function display($tpl = null) { // Get data from the model $items = $this->get('Items'); $pagination = $this->get('Pagination'); // Check for errors. if (count($errors = $this->get('Errors'))) { JError::raiseError(500, implode('<br />', $errors)); return false; } // Assign data to the view $this->items = $items; $this->pagination = $pagination; // Set the toolbar $this->addToolBar(); // Display the template parent::display($tpl); } /** * Setting the toolbar */ protected function addToolBar() { JToolBarHelper::title(JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLDS')); JToolBarHelper::deleteList('', 'helloworlds.delete'); JToolBarHelper::editList('helloworld.edit'); JToolBarHelper::addNew('helloworld.add'); } }
Puedes encontrar otras acciones clásicas del backend en el fichero administrator/includes/toolbar.php de tu instalación Joomla.
Ya que la vista puede realizar algunas acciones, tenemos que introducir algunos datos. Con tu editor de texto favorito, pon lo siguiente en el fichero admin/views/helloworlds/tmpl/default.php
<?php // No direct access to this file defined('_JEXEC') or die('Restricted Access'); // load tooltip behavior JHtml::_('behavior.tooltip'); ?> <form action="<?php echo JRoute::_('index.php?option=com_helloworld'); ?>" method="post" name="adminForm" id="adminForm"> <table class="adminlist"> <thead><?php echo $this->loadTemplate('head');?></thead> <tfoot><?php echo $this->loadTemplate('foot');?></tfoot> <tbody><?php echo $this->loadTemplate('body');?></tbody> </table> <div> <input type="hidden" name="task" value="" /> <input type="hidden" name="boxchecked" value="0" /> <?php echo JHtml::_('form.token'); ?> </div> </form>
Añadiendo controladores específicos
Se han añadido tres acciones:
- helloworlds.delete
- helloworld.edit
- helloworld.add
Estaos son tareas compuestas (controller.task). Así que tenemos que codificar dos nuevos controladores HelloWorldControllerHelloWorlds
y HelloWorldControllerHelloWorld
.
admin/controllers/helloworlds.php
<?php // No direct access to this file defined('_JEXEC') or die('Restricted access'); // import Joomla controlleradmin library jimport('joomla.application.component.controlleradmin'); /** * HelloWorlds Controller */ class HelloWorldControllerHelloWorlds extends JControllerAdmin { /** * Proxy for getModel. * @since 2.5 */ public function getModel($name = 'HelloWorld', $prefix = 'HelloWorldModel') { $model = parent::getModel($name, $prefix, array('ignore_request' => true)); return $model; } }
admin/controllers/helloworld.php
<?php // No direct access to this file defined('_JEXEC') or die('Restricted access'); // import Joomla controllerform library jimport('joomla.application.component.controllerform'); /** * HelloWorld Controller */ class HelloWorldControllerHelloWorld extends JControllerForm { }
Añadiendo una vista de edición
Crea el fichero admin/views/helloworld/view.html.php
con el siguiente contenido:
<?php // No direct access to this file defined('_JEXEC') or die('Restricted access'); // import Joomla view library jimport('joomla.application.component.view'); /** * HelloWorld View */ class HelloWorldViewHelloWorld extends JView { /** * display method of Hello view * @return void */ public function display($tpl = null) { // get the Data $form = $this->get('Form'); $item = $this->get('Item'); // Check for errors. if (count($errors = $this->get('Errors'))) { JError::raiseError(500, implode('<br />', $errors)); return false; } // Assign the Data $this->form = $form; $this->item = $item; // Set the toolbar $this->addToolBar(); // Display the template parent::display($tpl); } /** * Setting the toolbar */ protected function addToolBar() { $input = JFactory::getApplication()->input; $input->set('hidemainmenu', true); $isNew = ($this->item->id == 0); JToolBarHelper::title($isNew ? JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLD_NEW') : JText::_('COM_HELLOWORLD_MANAGER_HELLOWORLD_EDIT')); JToolBarHelper::save('helloworld.save'); JToolBarHelper::cancel('helloworld.cancel', $isNew ? 'JTOOLBAR_CANCEL' : 'JTOOLBAR_CLOSE'); } }
Esta vista mostrará datos mediante un diseño (layout).
Crea el fichero admin/views/helloworld/tmpl/edit.php
que contenga:
<?php // No direct access defined('_JEXEC') or die('Restricted access'); JHtml::_('behavior.tooltip'); ?> <form action="<?php echo JRoute::_('index.php?option=com_helloworld&layout=edit&id='.(int) $this->item->id); ?>" method="post" name="adminForm" id="adminForm"> <fieldset class="adminform"> <legend><?php echo JText::_( 'COM_HELLOWORLD_HELLOWORLD_DETAILS' ); ?></legend> <ul class="adminformlist"> <?php foreach($this->form->getFieldset() as $field): ?> <li><?php echo $field->label;echo $field->input;?></li> <?php endforeach; ?> </ul> </fieldset> <div> <input type="hidden" name="task" value="helloworld.edit" /> <?php echo JHtml::_('form.token'); ?> </div> </form>
Añadiendo un modelo y modificando el existente
La vista HelloWorldViewHelloWorld
solicita el formulario y los datos de un modelo. Este modelo tiene que proveer un método getTable, un método getForm y un método loadData (llamado desde el controlador JModelAdmin)
admin/models/helloworld.php
<?php // No direct access to this file defined('_JEXEC') or die('Restricted access'); // import Joomla modelform library jimport('joomla.application.component.modeladmin'); /** * HelloWorld Model */ class HelloWorldModelHelloWorld extends JModelAdmin { /** * Returns a reference to the a Table object, always creating it. * * @param type The table type to instantiate * @param string A prefix for the table class name. Optional. * @param array Configuration array for model. Optional. * @return JTable A database object * @since 2.5 */ public function getTable($type = 'HelloWorld', $prefix = 'HelloWorldTable', $config = array()) { return JTable::getInstance($type, $prefix, $config); } /** * Method to get the record form. * * @param array $data Data for the form. * @param boolean $loadData True if the form is to load its own data (default case), false if not. * @return mixed A JForm object on success, false on failure * @since 2.5 */ public function getForm($data = array(), $loadData = true) { // Get the form. $form = $this->loadForm('com_helloworld.helloworld', 'helloworld', array('control' => 'jform', 'load_data' => $loadData)); if (empty($form)) { return false; } return $form; } /** * Method to get the data that should be injected in the form. * * @return mixed The data for the form. * @since 2.5 */ protected function loadFormData() { // Check the session for previously entered form data. $data = JFactory::getApplication()->getUserState('com_helloworld.edit.helloworld.data', array()); if (empty($data)) { $data = $this->getItem(); } return $data; } }
Este modelo hereda de otra clase JModelAdmin
y utiliza el método loadForm. Este método buscará formularios en el directorio forms
.
Con tu editor favorito, crea el fichero admin/models/forms/helloworld.xml
con el siguiente contenido:
<?xml version="1.0" encoding="utf-8"?> <form> <fieldset> <field name="id" type="hidden" /> <field name="greeting" type="text" label="COM_HELLOWORLD_HELLOWORLD_GREETING_LABEL" description="COM_HELLOWORLD_HELLOWORLD_GREETING_DESC" size="40" class="inputbox" default="" /> </fieldset> </form>
Empaquetando el componente
Contenido de tu directorio
- helloworld.xml
- site/index.html
- site/helloworld.php
- site/controller.php
- site/views/index.html
- site/views/helloworld/index.html
- site/views/helloworld/view.html.php
- site/views/helloworld/tmpl/index.html
- site/views/helloworld/tmpl/default.xml
- site/views/helloworld/tmpl/default.php
- site/models/index.html
- site/models/helloworld.php
- site/language/index.html
- site/language/en-GB/index.html
- site/language/en-GB/en-GB.com_helloworld.ini
- admin/index.html
- admin/helloworld.php
- admin/controller.php
- admin/sql/index.html
- admin/sql/install.mysql.utf8.sql
- admin/sql/uninstall.mysql.utf8.sql
- admin/sql/updates/index.html
- admin/sql/updates/mysql/index.html
- admin/sql/updates/mysql/0.0.1.sql
- admin/sql/updates/mysql/0.0.6.sql
- admin/models/index.html
- admin/models/fields/index.html
- admin/models/fields/helloworld.php
- admin/models/forms/index.html
- admin/models/forms/helloworld.xml
- admin/models/helloworld.php
- admin/models/helloworlds.php
- admin/views/index.html
- admin/views/helloworlds/index.html
- admin/views/helloworlds/view.html.php
- admin/views/helloworlds/tmpl/index.html
- admin/views/helloworlds/tmpl/default.php
- admin/views/helloworlds/tmpl/default_head.php
- admin/views/helloworlds/tmpl/default_body.php
- admin/views/helloworlds/tmpl/default_foot.php
- admin/views/helloworld/index.html
- admin/views/helloworld/view.html.php
- admin/views/helloworld/tmpl/index.html
- admin/views/helloworld/tmpl/edit.php
- admin/tables/index.html
- admin/tables/helloworld.php
- admin/language/en-GB/en-GB.com_helloworld.ini
- admin/language/en-GB/en-GB.com_helloworld.sys.ini
- admin/controllers/index.html
- admin/controllers/helloworld.php
- admin/controllers/helloworlds.php
- language/en-GB/en-GB.ini
Crea un archivo comprimido de este directorio o directamente descarga el archivo, modifica el código en /admin/models/helloworld.php
e instalalo mediante el gestor de extensiones de Joomla. Puedes añadir un elemento de menú de este componente usando el administrador de menús en el backend.
helloworld.xml
<?xml version="1.0" encoding="utf-8"?> <extension type="component" version="2.5.0" method="upgrade"> <name>Hello World!</name> <!-- The following elements are optional and free of formatting constraints --> <creationDate>November 2009</creationDate> <author>John Doe</author> <authorEmail>john.doe@example.org</authorEmail> <authorUrl>http://www.example.org</authorUrl> <copyright>Copyright Info</copyright> <license>License Info</license> <!-- The version string is recorded in the components table --> <version>0.0.9</version> <!-- The description is optional and defaults to the name --> <description>COM_HELLOWORLD_DESCRIPTION</description> <install> <!-- Runs on install --> <sql> <file driver="mysql" charset="utf8">sql/install.mysql.utf8.sql</file> </sql> </install> <uninstall> <!-- Runs on uninstall --> <sql> <file driver="mysql" charset="utf8">sql/uninstall.mysql.utf8.sql</file> </sql> </uninstall> <update> <!-- Runs on update; New in 2.5 --> <schemas> <schemapath type="mysql">sql/updates/mysql</schemapath> </schemas> </update> <!-- Site Main File Copy Section --> <!-- Note the folder attribute: This attribute describes the folder to copy FROM in the package to install therefore files copied in this section are copied from /site/ in the package --> <files folder="site"> <filename>index.html</filename> <filename>helloworld.php</filename> <filename>controller.php</filename> <folder>views</folder> <folder>models</folder> <folder>language</folder> </files> <administration> <!-- Administration Menu Section --> <menu>COM_HELLOWORLD_MENU</menu> <!-- Administration Main File Copy Section --> <!-- Note the folder attribute: This attribute describes the folder to copy FROM in the package to install therefore files copied in this section are copied from /admin/ in the package --> <files folder="admin"> <!-- Admin Main File Copy Section --> <filename>index.html</filename> <filename>helloworld.php</filename> <filename>controller.php</filename> <!-- SQL files section --> <folder>sql</folder> <!-- tables files section --> <folder>tables</folder> <!-- models files section --> <folder>models</folder> <!-- views files section --> <folder>views</folder> <!-- controllers files section --> <folder>controllers</folder> </files> <languages folder="admin"> <language tag="en-GB">language/en-GB/en-GB.com_helloworld.ini</language> <language tag="en-GB">language/en-GB/en-GB.com_helloworld.sys.ini</language> </languages> </administration> </extension>