Jump to content
  • разработка интернет магазинов на opencart
  • доработка интернет магазинов на opencart

Использование Events-System


Recommended Posts

Добрый гдень. После прочтения Докумениции вопросов врогде не осилось. Но при практическом применение все оказалось не ик как я ожидал.

Вопрос в следуюещём: как используя систему событий добавить новое поле в карточке товара. Именно с использованием Events.

 

Вот код при инсилляции:

$code = "add_filed_before";
$trigger = "admin/controller/catalog/product/edit/before";
$action = "extension/module/test/add_filed_before";
$this->model_setting_event->addEvent($code, $trigger, $action);

$code = "add_filed_after";
$trigger = "admin/controller/catalog/product/edit/after";
$action = "extension/module/test/add_filed_after";
$this->model_setting_event->addEvent($code, $trigger, $action);

 

Вот обрилитлики:

    public function add_filed_before($route, $data)
    {
		$data['my_filed'] = 123;
		var_dump($data);
    }

    public function add_filed_after($route, &$data, $output)
    {
		var_dump($data);
		var_dump($output);
    }

Да вот add_filed_before отрабатывает?, а add_filed_after

Ожидал что отгдебажив что им в $data и $output бугдет понятно как гдействовать дальше. Но что то не заладилось.

Причем с могделью все отрабатывает на ура.

 

Link to comment
Share on other sites


3 hours ago, AlexDW said:

Спасипотому что

Как передать новые данные в view разобрался, но как добавить в twig новое поле пока не ясно. Вариант править в after output - изврат тот еещё)))

Link to comment
Share on other sites


Вы уверены что вам нужно именно событие?
сгделайте гдедовским методом  - ocmodом

 

1 час назад, AlexYakovlev сказал:

Вариант править в after output - изврат тот еещё)))

Все зависит от  того что править
если что-то править в dom - то изврат, хотя имеет право на жизнь

а если что-то добавить в в четкое место, то очень даже...

Link to comment
Share on other sites

Заметка

Создаем admin\controller\extension\module\test.php

 

<?
class ControllerExtensionModuleTest extends Controller
{
    private $error = array();
    public $action = [
        "admin/controller/catalog/product/edit/before",
        "admin/controller/catalog/product/edit/after",
        "admin/view/catalog/product_form/before",
        "admin/view/catalog/product_form/after",
        "admin/model/catalog/product/getProduct/before",
        "admin/model/catalog/product/getProduct/after"
    ];

    public function index()
    {
    }

    public function validate()
    {
    }

    public function install()
    {
        $this->load->model("setting/event");
        $this->load->model('setting/setting');

        $this->model_setting_setting->editSetting('module_test', ['module_test_status' => 1]);

        foreach ($this->action as $trigger) {
            $action = str_replace("/", "_", $trigger);
            $this->model_setting_event->addEvent("1my_" . $action, $trigger, "extension/module/test/" . $action);
        }
    }

    public function uninstall()
    {
        $this->load->model("setting/event");
        $this->load->model('setting/setting');
        $this->model_setting_setting->deleteSetting('module_test');
        foreach ($this->action as $trigger) {
            $this->model_setting_event->deleteEventByCode("1my_" . str_replace("/", "_", $trigger));
        }
    }

    public function Log($file_name, $var, $var_name)
    {
        ob_start();
        echo $var_name . "\n\t";
        var_dump($var);
        file_put_contents(DIR_LOGS . $file_name . ".log",  ob_get_clean() . "\n", FILE_APPEND);
    }

    public function admin_controller_catalog_product_edit_before(&$route, &$args = [])
    {
        file_put_contents(DIR_LOGS . __FUNCTION__ . ".log", "\n");
        $this->Log(__FUNCTION__, $route, "route");
        $this->Log(__FUNCTION__, $args, "args");
    }

    public function admin_controller_catalog_product_edit_after(&$route, &$args = [], &$output = null)
    {
        file_put_contents(DIR_LOGS . __FUNCTION__ . ".log", "\n");
        $this->Log(__FUNCTION__, $route, "route");
        $this->Log(__FUNCTION__, $args, "args");
        $this->Log(__FUNCTION__, $output, "output");
    }

    public function admin_view_catalog_product_form_before(&$route, &$args = [])
    {
        file_put_contents(DIR_LOGS . __FUNCTION__ . ".log", "\n");
        $this->Log(__FUNCTION__, $route, "route");
        $this->Log(__FUNCTION__, $args, "args");
    }

    public function admin_view_catalog_product_form_after(&$route, &$args = [], &$output = null)
    {
        file_put_contents(DIR_LOGS . __FUNCTION__ . ".log", "\n");
        $this->Log(__FUNCTION__, $route, "route");
        $this->Log(__FUNCTION__, $args, "args");
        $this->Log(__FUNCTION__, $output, "output");
    }

    public function admin_model_catalog_product_getProduct_before(&$route, &$args = [])
    {
        file_put_contents(DIR_LOGS . __FUNCTION__ . ".log", "\n");
        $this->Log(__FUNCTION__, $route, "route");
        $this->Log(__FUNCTION__, $args, "args");
    }

    public function admin_model_catalog_product_getProduct_after(&$route, &$args = [], &$output = null)
    {
        file_put_contents(DIR_LOGS . __FUNCTION__ . ".log", "\n");
        $this->Log(__FUNCTION__, $route, "route");
        $this->Log(__FUNCTION__, $args, "args");
        $this->Log(__FUNCTION__, $output, "output");
    }
}

Усинавливаем расширение, проверяем events list, заходим в карточку товара. После можно анализировать что появилось в storage/logs/admin_*.log

Link to comment
Share on other sites


  • 1 year later...

а, не, не полулилось, данные то полулил, когда вьюшку вызывал, но передать во вьюшку как?

когда вызываю контролер after, то данных нет, когда вьюшку вызываю, данные есть, но как их изменить

Edited by wewewe777
Link to comment
Share on other sites


не, не получается, то есть есть опрегделенный модуль на страниэто категорий, я хочу полулить в него данные с контролера категорий

Edited by wewewe777
Link to comment
Share on other sites


12 часов назад, wewewe777 сказал:

не, не получается, то есть есть опрегделенный модуль на страниэто категорий, я хочу полулить в него данные с контролера категорий

что не получвется?

В событие приходят данные $data
view/before
 

 

view/after - $output

model/before переданные в могдель данные
model/after  переданные в могдель данные и return

 

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
 Share

×
×
  • Create New...

Important Information

On our site, cookies are used and personal data is processed to improve the user interface. To find out what and what personal data we are processing, please go to the link. If you click "I agree," it means that you understand and accept all the conditions specified in this Privacy Notice.