Quantcast
Channel: Joomla! Forum - community, help and support
Viewing all articles
Browse latest Browse all 1386

Joomla! 5.x Coding • Re: Filter by categories and category title in the list of items

$
0
0
I fixed my filter by category, but have some another issue.
At first, latest code for file WorkersModel.php:

Code:

<?phpnamespace VPJoomla\Component\Workers\Administrator\Model;use Joomla\CMS\Factory;use Joomla\CMS\MVC\Model\ListModel;use Joomla\CMS\Table\Table;use Joomla\Database\ParameterType;use Joomla\Utilities\ArrayHelper;defined('_JEXEC') or exit();class WorkersModel extends ListModel {/** * Конструктор. * @param   array  $config  Массив с конфигурационными параметрами. */public function __construct($config = []){// Добавляем валидные поля для фильтров и сортировки.if (empty($config['filter_fields'])) {$config['filter_fields'] = array(            'id', 'a.id',            'name', 'a.name','catid', 'a.catid', 'category_title','alias', 'a.alias','country', 'a.country','city', 'a.city','sex', 'a.sex','availability', 'a.availability',            'ordering', 'a.ordering',            'state', 'a.state',            'created', 'a.created',            'modified', 'a.modified'        );}parent::__construct($config);}/**     * Method to get a list of items.     *     * @return  mixed   An array of data items on success, false on failure.     */    public function getItems()    {        $items = parent::getItems();         return $items;    }/** * Метод для построения SQL запроса для загрузки списка данных. * @return  string  SQL запрос. */protected function getListQuery(): string{$db    = $this->getDatabase();$query = $db->getQuery(true);$query->select($this->getState('list.select',[$db->quoteName('a.id'),$db->quoteName('a.name'),$db->quoteName('a.catid'),$db->quoteName('a.alias'),$db->quoteName('a.country'),$db->quoteName('a.city'),$db->quoteName('a.sex'),$db->quoteName('a.availability'),$db->quoteName('a.state'),$db->quoteName('a.created'),$db->quoteName('a.modified'),$db->quoteName('a.ordering'),]))->select($db->quoteName('c.title', 'category_title'))->from($db->quoteName('#__workers', 'a'))->join('LEFT', $db->quoteName('#__categories', 'c'), $db->quoteName('c.id') . ' = ' . $db->quoteName('a.catid'));        // Фильтр по состоянию полученному из запроса        $published = (string) $this->getState('filter.published');        if (is_numeric($published))        {            $query->where($db->quoteName('a.state') . ' = '.$published);        }        elseif ($published === '')        {            $query->where('(' . $db->quoteName('a.state') . ' = 0 OR ' . $db->quoteName('a.state') . ' = 1)');        }// Фильтр по категории$categoryId = $this->getState('filter.category_id');if (!empty($categoryId)) {// Check if $categoryId is an arrayif (is_array($categoryId)) {// Convert array to string$categoryId = implode(',', $categoryId);}// Log the category ID being passed to the methoderror_log('Category ID: ' . $categoryId);$query->where($db->quoteName('a.catid') . ' IN (' . $categoryId . ')');// Log the SQL queryerror_log('SQL query: ' . $query);}// Filter by country$country = $this->getState('filter.country');if (!empty($country)) {$query->where($db->quoteName('a.country') . ' = ' . $db->quote($country));}//Фильтр поиска по полу$sex = (int) $this->getState('filter.sex');if ($sex) {$query->where($db->quoteName('a.sex') . ' = ' . $db->quote($sex));}//Фильтр поиска по доступности$availability = (string) $this->getState('filter.availability');if (\in_array($availability, ['0','1'])) {$availability = (int) $availability;$query->where($db->quoteName('a.availability') . ' = :availability')->bind(':availability', $featured, ParameterType::INTEGER);}         // Фильтр поиска по названию.        $search = $this->getState('filter.search');         if (!empty($search))        {            $search = $db->quote('%' . str_replace(' ', '%', $db->escape(trim($search), true) . '%'));            $query->where('(a.name LIKE ' . $search . ')');        }// Добавляем сортировку.$orderCol  = $this->state->get('list.ordering', 'id');$orderDirn = $this->state->get('list.direction', 'desc');$query->order($db->escape($orderCol . ' ' . $orderDirn));return $query;}protected function populateState($ordering = 'a.id', $direction = 'desc'){    $app = Factory::getApplication();    $input = $app->input;    $search = $this->getUserStateFromRequest($this->context . '.filter.search', 'filter_search');    $this->setState('filter.search', $search);    $published = $this->getUserStateFromRequest($this->context . '.filter.published', 'filter_published', '');    $this->setState('filter.published', $published);$country = $this->getUserStateFromRequest($this->context . '.filter.country', 'filter_country', '');$this->setState('filter.country', $country);$sex = $this->getUserStateFromRequest($this->context . '.filter.sex', 'filter_sex', '');$this->setState('filter.sex', $sex);$availability = $this->getUserStateFromRequest($this->context . '.filter.availability', 'filter_availability', '');$this->setState('filter.availability', $availability);    // Set the default ordering and direction if not already set    parent::populateState($ordering, $direction);}protected function getStoreId($id = ''): string{// Compile the store id.$id .= ':' . $this->getState('filter.search');$id .= ':' . serialize($this->getState('filter.category_id'));$id .= ':' . $this->getState('filter.country');$id .= ':' . $this->getState('filter.sex');$id .= ':' . $this->getState('filter.availability');return parent::getStoreId($id);}/* Prepare a faqcontentiten record for saving in the database */protected function prepareTable($table): void    {// Set ordering to the last item if not setif (empty($table->ordering)){$db = $this->getDatabase();$query = $db->getQuery(true)->select('MAX(ordering)')->from('#__workers');$db->setQuery($query);$max = $db->loadResult();$table->ordering = $max + 1;}}    /**     * Method to change the published state of one or more records.     *     * @param array    &$pks   A list of the primary keys to change.     * @param integer $value  The value of the published state.     *     * @return  boolean  True on success.     *     * @since   4.0.0     */    public function publish(array &$pks, int $value = 1) {        if (empty($pks)) {            return false; // No records to update        }        $db = $this->getDatabase();        // Sanitize the value        $value = (int) $value;        try {            $query = $db->getQuery(true)                ->update($db->quoteName('#__workers'))                ->set($db->quoteName('state') . ' = ' . $value)                ->whereIn($db->quoteName('id'), $pks);            $db->setQuery($query);            $db->execute();            return true;        } catch (\Exception $e) {            return false;        }    }    /**     * Method to change the published state of one or more records to unpublished.     *     * @param array &$pks A list of the primary keys to change.     *     * @return  boolean  True on success.     */    public function unpublish(array &$pks) {        return $this->publish($pks, 0);    }    /**     * Method to change the published state of one or more records to archived.     *     * @param array &$pks A list of the primary keys to change.     *     * @return  boolean  True on success.     */    public function archive(array &$pks) {        return $this->publish($pks, 2);    }    /**     * Method to change the published state of one or more records to trashed.     *     * @param array &$pks A list of the primary keys to change.     *     * @return  boolean  True on success.     */    public function trash(array &$pks) {        return $this->publish($pks, -2);    }}
After each filter the panel with filters just hiding, but at the clean Joomla 5.1 there is no. Why? Some JS error maybe? But in my component no one JS file.

Statistics: Posted by zeus07 — Tue Apr 30, 2024 9:25 am



Viewing all articles
Browse latest Browse all 1386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>