codefog / contao-haste

Haste is a collection of tools and classes to ease working with Contao
http://codefog.pl/extension/haste.html
MIT License
42 stars 24 forks source link

Relations::filterByRelations() not working within archives (sorting mode:4) #118

Closed fatcrobat closed 6 years ago

fatcrobat commented 6 years ago

The current implementation of Haste\Model\Relations::filterByRelations() does not work with dataContainers with pid like tl_news.

/**
 * Filter records by relations set in custom filter
 * @param \DataContainer $dc in BE
 */
public function filterByRelations($dc)
{
    if (empty(static::$arrFilterableFields)) {
        return;
    }

    $arrIds = is_array($GLOBALS['TL_DCA'][$dc->table]['list']['sorting']['root']) ? $GLOBALS['TL_DCA'][$dc->table]['list']['sorting']['root'] : [];
    $blnFilter = false;
    $session = \Session::getInstance()->getData();

    foreach (array_keys(static::$arrFilterableFields) as $field) {
        if (isset($session['filter'][$dc->table][$field])) {
            $blnFilter = true;
            $ids = Model::getReferenceValues($dc->table, $field, $session['filter'][$dc->table][$field]);
            $arrIds = empty($arrIds) ? $ids : array_intersect($arrIds, $ids);
        }
    }

    if ($blnFilter) {
        $GLOBALS['TL_DCA'][$dc->table]['list']['sorting']['root'] = empty($arrIds) ? [0] : array_unique($arrIds);
    }
}

The reason for this error is, that contao stores the pid concatenated with the table in the $session['filter']. E.g. tl_news_4 (tl_news with pid 4).

The following fix handles archives (tested with contao 4.4.8 and haste 4.17.7)

/**
 * Filter records by relations set in custom filter
 * @param \DataContainer $dc in BE
 */
public function filterByRelations($dc)
{
    if (empty(static::$arrFilterableFields)) {
        return;
    }

    $arrIds    = is_array($GLOBALS['TL_DCA'][$dc->table]['list']['sorting']['root']) ? $GLOBALS['TL_DCA'][$dc->table]['list']['sorting']['root'] : [];
    $blnFilter = false;
    $session   = \Session::getInstance()->getData();

    foreach (array_keys(static::$arrFilterableFields) as $field) {
        if (!is_array($session['filter'])) {
            continue;
        }

        foreach ($session['filter'] as $table => $fields) {
            if(!is_array($fields)){
                continue;
            }

            if (isset($fields[$field])) {
                $blnFilter = true;
                $ids       = Model::getReferenceValues($dc->table, $field, $fields[$field]);
                $arrIds    = empty($arrIds) ? $ids : array_intersect($arrIds, $ids);
            }
        }
    }

    if ($blnFilter) {
        $GLOBALS['TL_DCA'][$dc->table]['list']['sorting']['root'] = empty($arrIds) ? [0] : array_unique($arrIds);
    }
}
qzminski commented 6 years ago

Fixed in 460423d.