Разработка компонента joomla3 на практике часть 2

Практический урок по разработке компонента на joomla 3.  Вторая часть. 

Разработка редактирования товаров в админке нашего компонента. 

Скачать эту часть компонента можно по ссылке Скачать компонент .
Компонент устанавливается стандартно через установщик joomla.

Для разработки нужно создать такие файлы в папке admin

 Для продуктов в админке придумаем английское название пункта product
в папке controller создадим два файла product.php  - для формы редактирования 
и products.php для списка. Если понадобятся другие пункты админки то также берется любое имя на английском и создаются по аналогии с product теже файлы.


Cодержимое файла products.php  в папке controllers

<?php

defined('_JEXEC') or die;
jimport('joomla.application.component.controlleradmin');

class KatalogControllerProducts extends JControllerAdmin

{
//Функция для сортировки в списке товаров

      public function saveOrderAjax()

{

$pks = $this->input->post->get('cid', array(), 'array');

$order = $this->input->post->get('order', array(), 'array');

 

// Sanitize the input

JArrayHelper::toInteger($pks);

JArrayHelper::toInteger($order);

 

// Get the model

$model = $this->getModel();

 

// Save the ordering

$return = $model->saveorder($pks, $order);

 

if ($return)

{

echo "1";

}

 

// Close the application

JFactory::getApplication()->close();

}

    

 //Прописываем наше имя product для получения модели

public function getModel($name = 'Product', $prefix = 'KatalogModel', $config = array('ignore_request' => true))

{

$model = parent::getModel($name, $prefix, $config);

 

return $model;

}

 

}

Содержимое файла product.php в папке controllers

<?php

defined('_JEXEC') or die();

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

 

class KatalogControllerProduct extends JControllerForm

{

 

protected$option = 'com_katalog';

 

   

protected function allowAdd($data = array())

{

return parent::allowAdd($data);

}

 

protected function allowEdit($data = array(), $key = 'id')

{

// Initialise variables.

$recordId= (int) isset($data[$key]) ? $data[$key] : 0;

$user= JFactory::getUser();

$userId= $user->get('id');

 

// Check general edit permission first.

if ($user->authorise('core.edit', 'com_katalog.product.'.$recordId)) {

 

return true;

}

 

// Since there is no asset tracking, revert to the component permissions.

return parent::allowEdit($data, $key);

}

 

}



Далее создадим в папке models два файла product.php и products.php

Содержимое файла products.php в папке models (cписок товаров)

<?php

 

 

defined( '_JEXEC' ) or die();

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

 

class KatalogModelProducts extends JModelList

{

protected$option = 'com_katalog';

 

 

  public function __construct($config = array())

//перечисляем те поля таблицы наших товаров по которым будет сорировать
if (empty($config['filter_fields'])) {

$config['filter_fields'] = array(

'id', 'a.id',

'title', 'a.title',

'alias', 'a.alias', 

                'price', 'a.price',

                'published', 'a.published',

                'ordering', 'a.ordering',

              

);

}

 

parent::__construct($config);

}

  

 

  protected function populateState()

{

// Initialise variables.

$app = JFactory::getApplication('administrator');

 

// Получаем параметры для выборки 
                
//Это поиск по строке
                $search = $app->getUserStateFromRequest($this->context.'.filter.search', 'filter_search');

$this->setState('filter.search', $search);

//Это опубликован или нет

    $state = $app->getUserStateFromRequest($this->context.'.filter.state', 'filter_published', '', 'string');

$this->setState('filter.state', $state);

 //Это по категории

        $kat = $app->getUserStateFromRequest($this->context.'.filter_category_id', 'filter_category_id');

$this->setState('filter.kat', $kat);

  

 

// Load the parameters.

$params = JComponentHelper::getParams('com_katalog');

$this->setState('params', $params);

 

// List state information.

parent::populateState('a.id', 'asc');

}

    

    protected function getStoreId($id = '')

{

// Compile the store id.

  

        $id .= ':'.$this->getState('filter.search');

$id.= ':'.$this->getState('filter.kat');

$id.= ':'.$this->getState('filter.state');

 

 

 

return parent::getStoreId($id);

}

    protected function getListQuery()

{

 

$db= $this->getDbo();

$query= $db->getQuery(true);

 

//тут перечисляем поля которые выводим из таблицы #__katalog_items

         //Сразу одним запросов выведем все категории через запятую у каждого товара

         //Для этого в перечисление полей добавим такой запрос

         //Сами категории мы будет использовать стандартные joomla  таблица  #__categories

      // (SELECT GROUP_CONCAT(CONCAT_WS(\':\', kat.title)) FROM #__katalog_xref as xref 

         // LEFT JOIN  #__categories AS kat ON xref.catid = kat.id WHER xref.vid=a.id) as kats

 

    $query->select(

"a.*, (SELECT GROUP_CONCAT(CONCAT_WS(\":\", kat.title)) FROM #__katalog_xref as xref 

          LEFT JOIN  #__categories AS kat ON xref.catid = kat.id WHERE xref.vid=a.id) as kats"

);

$query->from('`#__katalog_items` AS a'); 

 

 

 

 

// Filter by search in title

$search = $this->getState('filter.search');

if (!empty($search))

{

if (stripos($search, 'id:') === 0) {

$query->where('a.id = '.(int) substr($search, 3));

}

else

{

$search = $db->Quote('%'.$db->getEscaped($search, true).'%');

$query->where('( a.title LIKE '.$search.')');

}

}

   

   //Так как у нас товар может быть привязан к нескольким категориям сразу

   //то если будет в сортировке выбрана категория нужно в запрос добавить таблицу где содержится привязка к категории

    $kat = $this->getState('filter.kat');

  

  if ($kat)

  {

    $query->join('LEFT','#__katalog_xref AS x ON a.id=x.vid');

        //Это запись аналагична LEFT JOIN #__katalog_xref AS x ON a.id=x.vid

       

        //Это уже сама сортировка по категории

    $query->where('x.catid='.$kat);

    

  }

 

        // Filter by published state.

$published = $this->getState('filter.state');

if (is_numeric($published)) {

$query->where('a.published = '.(int) $published);

}

else if ($published === '') {

$query->where('(a.published IN (0, 1))');

}

        

       

            

            

          

       

$orderCol= $this->state->get('list.ordering','a.id');

$orderDirn= $this->state->get('list.direction','asc');

        

       

$query->order($orderCol.' '.$orderDirn);

 

//echo nl2br(str_replace('#__', 'jos_', $query->__toString()));

        

return $query;

}

}

?>

 

Содержимое файла product.php в папке models (форма товара)

<?php

 

// No direct access.

defined('_JEXEC') or die;

 

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

 

 

class KatalogModelProduct extends JModelAdmin

{

  protected $option = 'com_katalog';

protected $text_prefix= 'com_katalog';

 

protected function canDelete($record)

{

  

$user = JFactory::getUser();

 

    

        return $user->authorise('core.delete', 'com_wine.product.'.(int) $record->id);

}

    

    protected function prepareTable(&$table)

{

jimport('joomla.filter.output');

$date = JFactory::getDate();

$user = JFactory::getUser();

 

$table->title= htmlspecialchars_decode($table->title, ENT_QUOTES);

$table->alias= JApplication::stringURLSafe($table->alias);

if (empty($table->alias)) {

$table->alias = JApplication::stringURLSafe($table->title);

}

}

protected function canEditState($record)

{

  return parent::canEditState($record);

 

}

public function getTable($type = 'Product', $prefix = 'Table', $config = array())

{

return JTable::getInstance($type, $prefix, $config);

}

 

public function getForm($data = array(), $loadData = true) {

$app= JFactory::getApplication();

$form = $this->loadForm('com_katalog.products', 'product', array('control' => 'jform', 'load_data' => $loadData));

if (empty($form)) {

return false;

}

return $form;

}

protected function loadFormData()

// Check the session for previously entered form data.

$data = JFactory::getApplication()->getUserState('com_katalog.edit.product.data', array());

 

if (empty($data)) {

$data = $this->getItem();

}

 

return $data;

}

    public function save($data)

{

     $params = JComponentHelper::getParams('com_katalog');

      

if (parent::save($data)) {

 

                $id = $data['id'];

                if (empty($id)) 

                 {

$this->_db->setQuery('SELECT MAX(id) FROM #__katalog_items');

$id = $this->_db->loadResult();

                 }

  

                 }

               

                katalogHelper::save_xref($id);    

return true;

}

 

    protected function getReorderConditions($table)

{

$condition = array();

//$condition[] = 'catid= '.(int) $table->catid;

return $condition;

}

}

Покупка готового скрипта

joomla 3