Jump to content

Dodanie własnego pola CMS page


tasilvar

Recommended Posts

Witam serdecznie, 

Planuję dodać do sekcji 'Strony CMS' nowe pole w charakterze zwykłego inputa tekstowego. Przeniosłem kontroler i klasę do folderu override i zmodyfikowałem je na potrzeby wyświetlania dodatkowego inputa jednak kiedy próbuję nadpisać go o wprowadzoną wartość debugger krzyczy mi że nie znalazł w tabeli ps_cms mojego pola, czy nie powinien on automatycznie go dodać gdy w klasie CMS dodaję nową włąściwość ? Proszę o wskazówki. Dla ścisłości w backendzie samo pole mi się wyświetla, problem jest z zachowaniem dla niego wartości. 

Pliki edytowane, 

classes\CMS.php

controllers\admin\AdminCMSController.php

Link to comment
Share on other sites

Plik AdminCMSController.php

<?php
/**
 * 2007-2017 PrestaShop
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * https://opensource.org/licenses/OSL-3.0
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to [email protected] so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 * @author    PrestaShop SA <[email protected]>
 * @copyright 2007-2017 PrestaShop SA
 * @license   https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
 * International Registered Trademark & Property of PrestaShop SA
 */

/**
 * @property CMS $object
 */
class AdminCmsControllerCore extends AdminController
{
    protected $category;

    public $id_cms_category;

    protected $position_identifier = 'id_cms';

    public function __construct()
    {
        $this->bootstrap = true;
        $this->table = 'cms';
        $this->list_id = 'cms';
        $this->className = 'CMS';
        $this->lang = true;
        $this->addRowAction('edit');
        $this->addRowAction('delete');
        $this->_orderBy = 'position';

        parent::__construct();

        $this->bulk_actions = array(
            'delete' => array(
                'text' => $this->trans('Delete selected', array(), 'Admin.Actions'),
                'confirm' => $this->trans('Delete selected items?', array(), 'Admin.Notifications.Warning'),
                'icon' => 'icon-trash'
            )
        );
        $this->fields_list = array(
            'id_cms' => array('title' => $this->trans('ID', array(), 'Admin.Global'), 'align' => 'center', 'class' => 'fixed-width-xs'),
            'link_rewrite' => array('title' => $this->trans('URL', array(), 'Admin.Global')),
            'feature_image' => array('title' => $this->l('Feature image'), 'width' => 'auto'),
            'meta_title' => array('title' => $this->trans('Title', array(), 'Admin.Global'), 'filter_key' => 'b!meta_title'),
            'position' => array('title' => $this->trans('Position', array(), 'Admin.Global'),'filter_key' => 'position', 'align' => 'center', 'class' => 'fixed-width-sm', 'position' => 'position'),
            'active' => array('title' => $this->trans('Displayed', array(), 'Admin.Global'), 'align' => 'center', 'active' => 'status', 'class' => 'fixed-width-sm', 'type' => 'bool', 'orderby' => false)
        );

        // The controller can't be call directly
        // In this case, AdminCmsContentController::getCurrentCMSCategory() is null
        if (!AdminCmsContentController::getCurrentCMSCategory()) {
            $this->redirect_after = '?controller=AdminCmsContent&token='.Tools::getAdminTokenLite('AdminCmsContent');
            $this->redirect();
        }

        $this->_category = AdminCmsContentController::getCurrentCMSCategory();
        $this->tpl_list_vars['icon'] = 'icon-folder-close';
        $this->tpl_list_vars['title'] = $this->trans('Pages in category "%name%"', array('%name%' => $this->_category->name[Context::getContext()->employee->id_lang]), 'Admin.Design.Feature');
        $this->_join = '
		LEFT JOIN `'._DB_PREFIX_.'cms_category` c ON (c.`id_cms_category` = a.`id_cms_category`)';
        $this->_select = 'a.position ';
        $this->_where = ' AND c.id_cms_category = '.(int)$this->_category->id;
    }

    public function getTabSlug()
    {
        return 'ROLE_MOD_TAB_ADMINCMSCONTENT_';
    }

    public function initPageHeaderToolbar()
    {
        $this->page_header_toolbar_btn['save-and-preview'] = array(
            'href' => '#',
            'desc' => $this->trans('Save and preview', array(), 'Admin.Actions')
        );
        $this->page_header_toolbar_btn['save-and-stay'] = array(
            'short' => $this->trans('Save and stay', array(), 'Admin.Actions'),
            'href' => '#',
            'desc' => $this->trans('Save and stay', array(), 'Admin.Actions'),
        );

        return parent::initPageHeaderToolbar();
    }

    public function renderForm()
    {
        if (!$this->loadObject(true)) {
            return;
        }

        if (Validate::isLoadedObject($this->object)) {
            $this->display = 'edit';
        } else {
            $this->display = 'add';
        }

        $this->initToolbar();
        $this->initPageHeaderToolbar();

        $categories = CMSCategory::getCategories($this->context->language->id, false);
        $html_categories = CMSCategory::recurseCMSCategory($categories, $categories[0][1], 1, $this->getFieldValue($this->object, 'id_cms_category'), 1);

        $this->fields_form = array(
            'tinymce' => true,
            'legend' => array(
                'title' => $this->l('Page'),
                'icon' => 'icon-folder-close'
            ),
            'input' => array(
                // custom template
                array(
                    'type' => 'select_category',
                    'label' => $this->trans('Page Category', array(), 'Admin.Design.Feature'),
                    'name' => 'id_cms_category',
                    'options' => array(
                        'html' => $html_categories,
                    ),
                ),
                array(
                    'type' => 'text',
                    'label' => $this->trans('Meta title', array(), 'Admin.Global'),
                    'name' => 'meta_title',
                    'id' => 'name', // for copyMeta2friendlyURL compatibility
                    'lang' => true,
                    'required' => true,
                    'class' => 'copyMeta2friendlyURL',
                    'hint' => $this->trans('Invalid characters:', array(), 'Admin.Notifications.Info').' &lt;&gt;;=#{}'
                ),
                array(
                    'type' => 'text',
                    'label' => $this->trans('Meta description', array(), 'Admin.Global'),
                    'name' => 'meta_description',
                    'lang' => true,
                    'hint' => $this->trans('Invalid characters:', array(), 'Admin.Notifications.Info').' &lt;&gt;;=#{}'
                ),
                // ------------------- New field -------------------------------
                array(
                    'type' => 'text',
                    'label' => $this->trans('Feature image', array(), 'Admin.Global'),
                    'name' => 'feature_image',
                    'lang' => false,
                    'hint' => $this->trans('Invalid characters:', array(), 'Admin.Notifications.Info').' &lt;&gt;;=#{}'
                ),
                // ------------------- New field -------------------------------
                array(
                    'type' => 'tags',
                    'label' => $this->trans('Meta keywords', array(), 'Admin.Global'),
                    'name' => 'meta_keywords',
                    'lang' => true,
                    'hint' => array(
                        $this->trans('To add "tags" click in the field, write something, and then press "Enter."', array(), 'Admin.Design.Help'),
                        $this->trans('Invalid characters:', array(), 'Admin.Notifications.Info').' &lt;&gt;;=#{}'
                    )
                ),
                array(
                    'type' => 'text',
                    'label' => $this->trans('Friendly URL', array(), 'Admin.Global'),
                    'name' => 'link_rewrite',
                    'required' => true,
                    'lang' => true,
                    'hint' => $this->trans('Only letters and the hyphen (-) character are allowed.', array(), 'Admin.Design.Feature')
                ),
                array(
                    'type' => 'textarea',
                    'label' => $this->trans('Page content', array(), 'Admin.Design.Feature'),
                    'name' => 'content',
                    'autoload_rte' => true,
                    'lang' => true,
                    'rows' => 5,
                    'cols' => 40,
                    'hint' => $this->trans('Invalid characters:', array(), 'Admin.Notifications.Info').' <>;=#{}'
                ),
                array(
                    'type' => 'switch',
                    'label' => $this->trans('Indexation by search engines', array(), 'Admin.Design.Feature'),
                    'name' => 'indexation',
                    'required' => false,
                    'class' => 't',
                    'is_bool' => true,
                    'values' => array(
                        array(
                            'id' => 'indexation_on',
                            'value' => 1,
                            'label' => $this->trans('Enabled', array(), 'Admin.Global')
                        ),
                        array(
                            'id' => 'indexation_off',
                            'value' => 0,
                            'label' => $this->trans('Disabled', array(), 'Admin.Global')
                        )
                    ),
                ),
                array(
                    'type' => 'switch',
                    'label' => $this->trans('Displayed', array(), 'Admin.Global'),
                    'name' => 'active',
                    'required' => false,
                    'is_bool' => true,
                    'values' => array(
                        array(
                            'id' => 'active_on',
                            'value' => 1,
                            'label' => $this->trans('Enabled', array(), 'Admin.Global')
                        ),
                        array(
                            'id' => 'active_off',
                            'value' => 0,
                            'label' => $this->trans('Disabled', array(), 'Admin.Global')
                        )
                    ),
                ),
            ),
            'submit' => array(
                'title' => $this->trans('Save', array(), 'Admin.Actions'),
            ),
            'buttons' => array(
                'save_and_preview' => array(
                    'name' => 'viewcms',
                    'type' => 'submit',
                    'title' => $this->trans('Save and preview', array(), 'Admin.Actions'),
                    'class' => 'btn btn-default pull-right',
                    'icon' => 'process-icon-preview'
                )
            )
        );

        if (Shop::isFeatureActive()) {
            $this->fields_form['input'][] = array(
                'type' => 'shop',
                'label' => $this->trans('Shop association', array(), 'Admin.Global'),
                'name' => 'checkBoxShopAsso',
            );
        }

        if (Validate::isLoadedObject($this->object)) {
            $this->context->smarty->assign('url_prev', $this->getPreviewUrl($this->object));
        }

        $this->tpl_form_vars = array(
            'active' => $this->object->active,
            'PS_ALLOW_ACCENTED_CHARS_URL', (int)Configuration::get('PS_ALLOW_ACCENTED_CHARS_URL')
        );
        return parent::renderForm();
    }

    public function renderList()
    {
        $this->_group = 'GROUP BY a.`id_cms`';
        //self::$currentIndex = self::$currentIndex.'&cms';
        $this->position_group_identifier = (int)$this->id_cms_category;

        $this->toolbar_title = $this->trans('Pages in this category', array(), 'Admin.Design.Feature');
        $this->toolbar_btn['new'] = array(
            'href' => self::$currentIndex.'&add'.$this->table.'&id_cms_category='.(int)$this->id_cms_category.'&token='.$this->token,
            'desc' => $this->trans('Add new', array(), 'Admin.Actions')
        );

        return parent::renderList();
    }

    public function displayList($token = null)
    {
        /* Display list header (filtering, pagination and column names) */
        $this->displayListHeader($token);
        if (!count($this->_list)) {
            echo '<tr><td class="center" colspan="'.(count($this->fields_list) + 2).'">'.$this->trans('No items found', array(), 'Admin.Design.Notification').'</td></tr>';
        }

        /* Show the content of the table */
        $this->displayListContent($token);

        /* Close list table and submit button */
        $this->displayListFooter($token);
    }

    public function postProcess()
    {
        if (Tools::isSubmit('viewcms') && ($id_cms = (int)Tools::getValue('id_cms'))) {
            parent::postProcess();
            if (($cms = new CMS($id_cms, $this->context->language->id)) && Validate::isLoadedObject($cms)) {
                Tools::redirectAdmin(self::$currentIndex.'&id_cms='.$id_cms.'&conf=4&updatecms&token='.Tools::getAdminTokenLite('AdminCmsContent').'&url_preview=1');
            }
        } elseif (Tools::isSubmit('deletecms')) {
            if (Tools::getValue('id_cms') == Configuration::get('PS_CONDITIONS_CMS_ID')) {
                Configuration::updateValue('PS_CONDITIONS', 0);
                Configuration::updateValue('PS_CONDITIONS_CMS_ID', 0);
            }
            $cms = new CMS((int)Tools::getValue('id_cms'));
            $cms->cleanPositions($cms->id_cms_category);
            if (!$cms->delete()) {
                $this->errors[] = $this->trans('An error occurred while deleting the object.', array(), 'Admin.Notifications.Error')
                    .' <b>'.$this->table.' ('.Db::getInstance()->getMsgError().')</b>';
            } else {
                Tools::redirectAdmin(self::$currentIndex.'&id_cms_category='.$cms->id_cms_category.'&conf=1&token='.Tools::getAdminTokenLite('AdminCmsContent'));
            }
        } elseif (Tools::getValue('submitDel'.$this->table)) {
            // Delete multiple objects
            if ($this->access('delete')) {
                if (Tools::isSubmit($this->table.'Box')) {
                    $cms = new CMS();
                    $result = true;
                    $result = $cms->deleteSelection(Tools::getValue($this->table.'Box'));
                    if ($result) {
                        $cms->cleanPositions((int)Tools::getValue('id_cms_category'));
                        $token = Tools::getAdminTokenLite('AdminCmsContent');
                        Tools::redirectAdmin(self::$currentIndex.'&conf=2&token='.$token.'&id_cms_category='.(int)Tools::getValue('id_cms_category'));
                    }
                    $this->errors[] = $this->trans('An error occurred while deleting this selection.', array(), 'Admin.Notifications.Error');
                } else {
                    $this->errors[] = $this->trans('You must select at least one element to delete.', array(), 'Admin.Notifications.Error');
                }
            } else {
                $this->errors[] = $this->trans('You do not have permission to delete this.', array(), 'Admin.Notifications.Error');
            }
        } elseif (Tools::isSubmit('submitAddcms') || Tools::isSubmit('submitAddcmsAndPreview')) {
            parent::validateRules();
            if (count($this->errors)) {
                return false;
            }
            if (!$id_cms = (int)Tools::getValue('id_cms')) {
                $cms = new CMS();
                $this->copyFromPost($cms, 'cms');
                if (!$cms->add()) {
                    $this->errors[] = $this->trans('An error occurred while creating an object.', array(), 'Admin.Notifications.Error').' <b>'.$this->table.' ('.Db::getInstance()->getMsgError().')</b>';
                } else {
                    $this->updateAssoShop($cms->id);
                }
            } else {
                $cms = new CMS($id_cms);
                $this->copyFromPost($cms, 'cms');
                if (!$cms->update()) {
                    $this->errors[] = $this->trans('An error occurred while updating an object.', array(), 'Admin.Notifications.Error').' <b>'.$this->table.' ('.Db::getInstance()->getMsgError().')</b>';
                } else {
                    $this->updateAssoShop($cms->id);
                }
            }
            if (Tools::isSubmit('view'.$this->table)) {
                Tools::redirectAdmin(self::$currentIndex.'&id_cms='.$cms->id.'&conf=4&updatecms&token='.Tools::getAdminTokenLite('AdminCmsContent').'&url_preview=1');
            } elseif (Tools::isSubmit('submitAdd'.$this->table.'AndStay')) {
                Tools::redirectAdmin(self::$currentIndex.'&'.$this->identifier.'='.$cms->id.'&conf=4&update'.$this->table.'&token='.Tools::getAdminTokenLite('AdminCmsContent'));
            } else {
                Tools::redirectAdmin(self::$currentIndex.'&id_cms_category='.$cms->id_cms_category.'&conf=4&token='.Tools::getAdminTokenLite('AdminCmsContent'));
            }
        } elseif (Tools::isSubmit('way') && Tools::isSubmit('id_cms') && (Tools::isSubmit('position'))) {
            /** @var CMS $object */
            if (!$this->access('edit')) {
                $this->errors[] = $this->trans('You do not have permission to edit this.', array(), 'Admin.Notifications.Error');
            } elseif (!Validate::isLoadedObject($object = $this->loadObject())) {
                $this->errors[] = $this->trans('An error occurred while updating the status for an object.', array(), 'Admin.Notifications.Error')
                    .' <b>'.$this->table.'</b> '.$this->trans('(cannot load object)', array(), 'Admin.Notifications.Error');
            } elseif (!$object->updatePosition((int)Tools::getValue('way'), (int)Tools::getValue('position'))) {
                $this->errors[] = $this->trans('Failed to update the position.', array(), 'Admin.Notifications.Error');
            } else {
                Tools::redirectAdmin(self::$currentIndex.'&'.$this->table.'Orderby=position&'.$this->table.'Orderway=asc&conf=4&id_cms_category='.(int)$object->id_cms_category.'&token='.Tools::getAdminTokenLite('AdminCmsContent'));
            }
        } elseif (Tools::isSubmit('statuscms') && Tools::isSubmit($this->identifier)) {
            // Change object status (active, inactive)
            if ($this->access('edit')) {
                if (Validate::isLoadedObject($object = $this->loadObject())) {
                    /** @var CMS $object */
                    if ($object->toggleStatus()) {
                        Tools::redirectAdmin(self::$currentIndex.'&conf=5&id_cms_category='.(int)$object->id_cms_category.'&token='.Tools::getValue('token'));
                    } else {
                        $this->errors[] = $this->trans('An error occurred while updating the status.', array(), 'Admin.Notifications.Error');
                    }
                } else {
                    $this->errors[] = $this->trans('An error occurred while updating the status for an object.', array(), 'Admin.Notifications.Error')
                        .' <b>'.$this->table.'</b> '.$this->trans('(cannot load object)', array(), 'Admin.Notifications.Error');
                }
            } else {
                $this->errors[] = $this->trans('You do not have permission to edit this.', array(), 'Admin.Notifications.Error');
            }
        } elseif (Tools::isSubmit('submitBulkdeletecms')) {
            // Delete multiple CMS content
            if ($this->access('delete')) {
                $this->action = 'bulkdelete';
                $this->boxes = Tools::getValue($this->table.'Box');
                if (is_array($this->boxes) && array_key_exists(0, $this->boxes)) {
                    $firstCms = new CMS((int)$this->boxes[0]);
                    $id_cms_category = (int)$firstCms->id_cms_category;
                    if (!$res = parent::postProcess(true)) {
                        return $res;
                    }
                    Tools::redirectAdmin(self::$currentIndex.'&conf=2&token='.Tools::getAdminTokenLite('AdminCmsContent').'&id_cms_category='.$id_cms_category);
                }
            } else {
                $this->errors[] = $this->trans('You do not have permission to delete this.', array(), 'Admin.Notifications.Error');
            }
        } else {
            parent::postProcess(true);
        }
    }

    public function getPreviewUrl(CMS $cms)
    {
        $preview_url = $this->context->link->getCMSLink($cms, null, null, $this->context->language->id);
        if (!$cms->active) {
            $params = http_build_query(array(
                'adtoken' => Tools::getAdminTokenLite('AdminCmsContent'),
                'ad' => basename(_PS_ADMIN_DIR_),
                'id_employee' => (int)$this->context->employee->id
                )
            );
            $preview_url .= (strpos($preview_url, '?') === false ? '?' : '&').$params;
        }

        return $preview_url;
    }
}

A tutaj klasa CMS.php

 

<?php
/**
 * 2007-2017 PrestaShop
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Open Software License (OSL 3.0)
 * that is bundled with this package in the file LICENSE.txt.
 * It is also available through the world-wide-web at this URL:
 * https://opensource.org/licenses/OSL-3.0
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to [email protected] so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade PrestaShop to newer
 * versions in the future. If you wish to customize PrestaShop for your
 * needs please refer to http://www.prestashop.com for more information.
 *
 * @author    PrestaShop SA <[email protected]>
 * @copyright 2007-2017 PrestaShop SA
 * @license   https://opensource.org/licenses/OSL-3.0 Open Software License (OSL 3.0)
 * International Registered Trademark & Property of PrestaShop SA
 */

/**
 * Class CMSCore
 */
class CMSCore extends ObjectModel
{
    /** @var string Name */
    public $id;
    public $id_cms;
    public $meta_title;
    public $meta_description;
    public $meta_keywords;
    public $content;
    public $link_rewrite;
    public $id_cms_category;
    public $position;
    public $indexation;
    public $active;
    
    // ---------------- New field --------------------------------
    public $feature_image;

    /**
     * @see ObjectModel::$definition
     */
    public static $definition = array(
        'table' => 'cms',
        'primary' => 'id_cms',
        'multilang' => true,
        'multilang_shop' => true,
        'fields' => array(
            'id_cms_category' =>    array('type' => self::TYPE_INT, 'validate' => 'isUnsignedInt'),
            'position' =>            array('type' => self::TYPE_INT),
            'indexation' =>         array('type' => self::TYPE_BOOL),
            'active' =>            array('type' => self::TYPE_BOOL),
            // -------------- New field -----------------------------------
            
             'feature_image' =>    array('type' => self::TYPE_STRING),
            
            // -------------- New field -----------------------------------
            
            //            'myDate' =>   array('type' => self::TYPE_DATE, 'validate' => 'isDate' ),
            
            /* Lang fields */
            'meta_description' =>    array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'size' => 255),
            'meta_keywords' =>        array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'size' => 255),
            'meta_title' =>            array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isGenericName', 'required' => true, 'size' => 128),
            'link_rewrite' =>        array('type' => self::TYPE_STRING, 'lang' => true, 'validate' => 'isLinkRewrite', 'required' => true, 'size' => 128),
            'content' =>            array('type' => self::TYPE_HTML, 'lang' => true, 'validate' => 'isCleanHtml', 'size' => 3999999999999),
        ),
    );

    protected $webserviceParameters = array(
        'objectNodeName' => 'content',
        'objectsNodeName' => 'content_management_system',
    );

    /**
     * Adds current CMS as a new Object to the database
     *
     * @param bool $autoDate    Automatically set `date_upd` and `date_add` columns
     * @param bool $nullValues Whether we want to use NULL values instead of empty quotes values
     *
     * @return bool Indicates whether the CMS has been successfully added
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public function add($autoDate = true, $nullValues = false)
    {
        $this->position = CMS::getLastPosition((int) $this->id_cms_category);
        return parent::add($autoDate, true);
    }

    /**
     * Updates the current CMS in the database
     *
     * @param bool $nullValues Whether we want to use NULL values instead of empty quotes values
     *
     * @return bool Indicates whether the CMS has been successfully updated
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public function update($nullValues = false)
    {
        if (parent::update($nullValues)) {
            return $this->cleanPositions($this->id_cms_category);
        }

        return false;
    }

    /**
     * Deletes current CMS from the database
     *
     * @return bool True if delete was successful
     * @throws PrestaShopException
     */
    public function delete()
    {
        if (parent::delete()) {
            return $this->cleanPositions($this->id_cms_category);
        }

        return false;
    }

    /**
     * Get links
     *
     * @param int       $idLang Language ID
     * @param null      $selection
     * @param bool      $active
     * @param Link|null $link
     *
     * @return array
     */
    public static function getLinks($idLang, $selection = null, $active = true, Link $link = null)
    {
        if (!$link) {
            $link = Context::getContext()->link;
        }
        $result = Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
		SELECT c.id_cms, cl.link_rewrite, cl.meta_title
		FROM '._DB_PREFIX_.'cms c
		LEFT JOIN '._DB_PREFIX_.'cms_lang cl ON (c.id_cms = cl.id_cms AND cl.id_lang = '.(int) $idLang.')
		'.Shop::addSqlAssociation('cms', 'c').'
		WHERE 1
		'.(($selection !== null) ? ' AND c.id_cms IN ('.implode(',', array_map('intval', $selection)).')' : '').
        ($active ? ' AND c.`active` = 1 ' : '').
        'GROUP BY c.id_cms
		ORDER BY c.`position`');

        $links = array();
        if ($result) {
            foreach ($result as $row) {
                $row['link'] = $link->getCMSLink((int) $row['id_cms'], $row['link_rewrite']);
                $links[] = $row;
            }
        }

        return $links;
    }

    /**
     * @param null $idLang
     * @param bool $idBlock
     * @param bool $active
     *
     * @return array|false|mysqli_result|null|PDOStatement|resource
     */
    public static function listCms($idLang = null, $idBlock = false, $active = true)
    {
        if (empty($idLang)) {
            $idLang = (int) Configuration::get('PS_LANG_DEFAULT');
        }

        return Db::getInstance(_PS_USE_SQL_SLAVE_)->executeS('
		SELECT c.id_cms, l.meta_title
		FROM  '._DB_PREFIX_.'cms c
		JOIN '._DB_PREFIX_.'cms_lang l ON (c.id_cms = l.id_cms)
		'.Shop::addSqlAssociation('cms', 'c').'
		'.(($idBlock) ? 'JOIN '._DB_PREFIX_.'block_cms b ON (c.id_cms = b.id_cms)' : '').'
		WHERE l.id_lang = '.(int) $idLang.(($idBlock) ? ' AND b.id_block = '.(int) $idBlock : '').($active ? ' AND c.`active` = 1 ' : '').'
		GROUP BY c.id_cms
		ORDER BY c.`position`');
    }

    /**
     * @param $way
     * @param $position
     *
     * @return bool
     */
    public function updatePosition($way, $position)
    {
        if (!$res = Db::getInstance()->executeS('
			SELECT cp.`id_cms`, cp.`position`, cp.`id_cms_category`
			FROM `'._DB_PREFIX_.'cms` cp
			WHERE cp.`id_cms_category` = '.(int) $this->id_cms_category.'
			ORDER BY cp.`position` ASC'
        )) {
            return false;
        }

        foreach ($res as $cms) {
            if ((int) $cms['id_cms'] == (int) $this->id) {
                $movedCms = $cms;
            }
        }

        if (!isset($movedCms) || !isset($position)) {
            return false;
        }

        // < and > statements rather than BETWEEN operator
        // since BETWEEN is treated differently according to databases
        return (Db::getInstance()->execute('
			UPDATE `'._DB_PREFIX_.'cms`
			SET `position`= `position` '.($way ? '- 1' : '+ 1').'
			WHERE `position`
			'.($way
                ? '> '.(int) $movedCms['position'].' AND `position` <= '.(int) $position
                : '< '.(int) $movedCms['position'].' AND `position` >= '.(int) $position).'
			AND `id_cms_category`='.(int) $movedCms['id_cms_category'])
        && Db::getInstance()->execute('
			UPDATE `'._DB_PREFIX_.'cms`
			SET `position` = '.(int) $position.'
			WHERE `id_cms` = '.(int) $movedCms['id_cms'].'
			AND `id_cms_category`='.(int) $movedCms['id_cms_category']));
    }

    /**
     * @param $idCategory
     *
     * @return bool
     */
    public static function cleanPositions($idCategory)
    {
        $sql = '
		SELECT `id_cms`
		FROM `'._DB_PREFIX_.'cms`
		WHERE `id_cms_category` = '.(int) $idCategory.'
		ORDER BY `position`';

        $result = Db::getInstance()->executeS($sql);

        for ($i = 0, $total = count($result); $i < $total; ++$i) {
            $sql = 'UPDATE `'._DB_PREFIX_.'cms`
					SET `position` = '.(int) $i.'
					WHERE `id_cms_category` = '.(int) $idCategory.'
						AND `id_cms` = '.(int) $result[$i]['id_cms'];
            Db::getInstance()->execute($sql);
        }

        return true;
    }

    /**
     * @param $idCategory
     *
     * @return false|null|string
     */
    public static function getLastPosition($idCategory)
    {
        $sql = '
		SELECT MAX(position) + 1
		FROM `'._DB_PREFIX_.'cms`
		WHERE `id_cms_category` = '.(int) $idCategory;

        return (Db::getInstance()->getValue($sql));
    }

    /**
     * @param null $idLang
     * @param null $idCmsCategory
     * @param bool $active
     * @param null $idShop
     *
     * @return array|false|mysqli_result|null|PDOStatement|resource
     */
    public static function getCMSPages($idLang = null, $idCmsCategory = null, $active = true, $idShop = null)
    {
        $sql = new DbQuery();
        $sql->select('*');
        $sql->from('cms', 'c');

        if ($idLang) {
            if ($idShop) {
                $sql->innerJoin('cms_lang', 'l', 'c.id_cms = l.id_cms AND l.id_lang = '.(int) $idLang.' AND l.id_shop = '.(int) $idShop);
            } else {
                $sql->innerJoin('cms_lang', 'l', 'c.id_cms = l.id_cms AND l.id_lang = '.(int) $idLang);
            }
        }

        if ($idShop) {
            $sql->innerJoin('cms_shop', 'cs', 'c.id_cms = cs.id_cms AND cs.id_shop = '.(int) $idShop);
        }

        if ($active) {
            $sql->where('c.active = 1');
        }

        if ($idCmsCategory) {
            $sql->where('c.id_cms_category = '.(int) $idCmsCategory);
        }

        $sql->orderBy('position');

        return Db::getInstance()->executeS($sql);
    }

    /**
     * @param $idCms
     *
     * @return array|false|mysqli_result|null|PDOStatement|resource
     */
    public static function getUrlRewriteInformations($idCms)
    {
        $sql = 'SELECT l.`id_lang`, c.`link_rewrite`
				FROM `'._DB_PREFIX_.'cms_lang` AS c
				LEFT JOIN  `'._DB_PREFIX_.'lang` AS l ON c.`id_lang` = l.`id_lang`
				WHERE c.`id_cms` = '.(int) $idCms.'
				AND l.`active` = 1';

        return Db::getInstance()->executeS($sql);
    }

    /**
     * @param int      $idCms
     * @param int|null $idLang
     * @param int|null $idShop
     *
     * @return array|bool|null|object
     */
    public static function getCMSContent($idCms, $idLang = null, $idShop = null)
    {
        if (is_null($idLang)) {
            $idLang = (int) Configuration::get('PS_LANG_DEFAULT');
        }
        if (is_null($idShop)) {
            $idShop = (int) Configuration::get('PS_SHOP_DEFAULT');
        }

        $sql = '
			SELECT `content`
			FROM `'._DB_PREFIX_.'cms_lang`
			WHERE `id_cms` = '.(int) $idCms.' AND `id_lang` = '.(int) $idLang.' AND `id_shop` = '.(int) $idShop;

        return Db::getInstance()->getRow($sql);
    }

    /**
     * Method required for new PrestaShop Core
     *
     * @return string
     *
     * @since 1.7.0
     */
    public static function getRepositoryClassName()
    {
        return '\\PrestaShop\\PrestaShop\\Core\\CMS\\CMSRepository';
    }
}

 

I to tyle oba pliki są w override, i efekt w backendzie prezentuje się jak w załączonym screenie. Przy debuggowaniu pojawia się komunikat o braku pola w bazie danych. Czy nie powinno to "w locie" utworzyć dodatkowego pola w wskazanej tabeli ? 

 

 

Zrzut ekranu 2018-03-25 o 13.34.22.png

Zrzut ekranu 2018-03-25 o 13.32.11.png

 

EDIT:

Temat rozwiązany, ręcznie dodałem pole w bazie danych i gra, jednak wywalało mi się że presta może dodawać z automatu nowe pola do tabel na podstawie zmodyfikowanego modelu w klasie. Jeśli tak się da to proszę tylko o rozwianie moich wątpliwości na przyszłość.

Edited by tasilvar (see edit history)
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...