1

I need to overwrite \Magento\Widget\Model\ResourceModel\Widget\Instance _afterSave method to save another page_group field in the database.

/**
 * Perform actions after object save
 *
 * @param \Magento\Widget\Model\Widget\Instance $object
 * @return $this
 */
protected function _afterSave(AbstractModel $object)
{
    $pageTable = $this->getTable('widget_instance_page');
    $pageLayoutTable = $this->getTable('widget_instance_page_layout');
    $connection = $this->getConnection();

    $select = $connection->select()->from($pageTable, 'page_id')->where('instance_id = ?', (int)$object->getId());
    $pageIds = $connection->fetchCol($select);

    $removePageIds = array_diff($pageIds, $object->getData('page_group_ids'));

    if (is_array($pageIds) && count($pageIds) > 0) {
        $inCond = $connection->prepareSqlCondition('page_id', ['in' => $pageIds]);

        $select = $connection->select()->from($pageLayoutTable, 'layout_update_id')->where($inCond);
        $removeLayoutUpdateIds = $connection->fetchCol($select);

        $connection->delete($pageLayoutTable, $inCond);
        $this->_deleteLayoutUpdates($removeLayoutUpdateIds);
    }

    $this->_deleteWidgetInstancePages($removePageIds);

    foreach ($object->getData('page_groups') as $pageGroup) {
        $pageLayoutUpdateIds = $this->_saveLayoutUpdates($object, $pageGroup);
        $data = [
            'page_group' => $pageGroup['group'],
            'layout_handle' => $pageGroup['layout_handle'],
            'block_reference' => $pageGroup['block_reference'],
            'page_for' => $pageGroup['for'],
            'entities' => $pageGroup['entities'],
            'page_template' => $pageGroup['template'],
            'action_buttons' => $pageGroup['action_buttons'],
        ];
        $pageId = $pageGroup['page_id'];
        if (in_array($pageGroup['page_id'], $pageIds)) {
            $connection->update($pageTable, $data, ['page_id = ?' => (int)$pageId]);
        } else {
            $connection->insert($pageTable, array_merge(['instance_id' => $object->getId()], $data));
            $pageId = $connection->lastInsertId($pageTable);
        }
        foreach ($pageLayoutUpdateIds as $layoutUpdateId) {
            $connection->insert(
                $pageLayoutTable,
                ['page_id' => $pageId, 'layout_update_id' => $layoutUpdateId]
            );
        }
    }

    return parent::_afterSave($object);
}

Is there any way that i am missing to overwrite this method without using a preference and copy the whole class content in my module? (the whole class because there is the call to parent::_afterSave() so i have to extend from parent - \Magento\Framework\Model\ResourceModel\Db\AbstractDb to avoid hard-coding of parent class)

Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.