Свойство OctoberCMS Reset ReportWidget (ов)

Я хотел бы сбросить свойства моего ReportWidget одним из двух способов:

1) При обновлении страницы, содержащей виджет отчета

или же

2) Когда определенные свойства изменены

Мой ReportWidget имеет 3 свойства: год, квартал, месяц

По умолчанию я отображаю информацию за текущий год. Если пользователь меняет год, а затем, возможно, указывает квартал или месяц для этого года, отчет отображается соответствующим образом.

Теперь, когда они возвращаются на страницу, эти настройки сохраняются. То, что я хотел бы сделать, это сбросить свойства к их настройкам по умолчанию, когда страница перезагружается или обновляется.

Кроме того, если пользователь меняется из года в год, другие свойства должны быть сброшены.

Я попытался решить эту проблему с помощью этого кода:

public function defineProperties() {
    return [
        'year' => [
            'title' => 'Year',
            'default' => $this->getDefaultYear(),
            'group' => 'Date',
            'type' => 'dropdown',
            'options' => $this->getYearOptions(),
        ],
        'quarter' => [
            'title' => 'Quarter',
            'type' => 'dropdown',
            'group' => 'Date',
            'options' => $this->getQuarterOptions(),
            'depends' => ['month']
        ],
        'month' => [
            'title' => 'Month',
            'type' => 'dropdown',
            'group' => 'Date',
            'options' => $this->getMonthOptions(),
            'depends' => ['year']
        ]
    ];
}

public function getYearOptions() {

    $query = User::all();

    $years = [];

    foreach($query as $user) {
        $year = date('Y', strtotime($user->created_at));

        $years[$year] = $year;
    }

    $years = array_unique($years);

    return $years;

}

public function getQuarterOptions() {

    $monthCode = Request::input('month'); // Load the year property value from POST

    $yearCode = Request::input('year');

    if ($yearCode && $monthCode) {
        return;
    }

    if ($yearCode) {

        return [
            1 => '1st',
            2 => '2nd',
            3 => '3rd',
            4 => '4th'
        ];
    }
}

public function getMonthOptions() {

    $yearCode = Request::input('year'); // Load the year property value from POST

    if ($yearCode) {
        return;
    }

    $months = [];

    for ($m=1; $m<=12; $m++) {

        $month = date('m', mktime(0,0,0,$m, 1, date('Y')));

        $months[$month] = date('M', mktime(0,0,0,$m, 1, date('Y')));

    }

    return $months;
}

Итак, что здесь происходит, так это то, что если год изменяется, он вызывает функцию getMonthOptions(), которая прослушивает ответ, и если он ловит год, он ничего не возвращает. Теперь это работает, но, очевидно, мой список месяцев не содержит месяцев. Затем я должен закрыть окно свойств и снова открыть его, чтобы перечислить месяцы.

Есть какие-нибудь идеи о том, как я могу реализовать эту функциональность? Спасибо.

1 ответ

Хм, я переписал ваш компонент и здесь, кажется, работает

в init() мы можем сбросить все значения по умолчанию, как мы хотели, после pageload пользователь может выбрать согласно его требованию и использованию виджета post requests values рассчитывать вещи и работать в соответствии с этим. но теперь снова, когда пользователь refresh page значение будет установлено по умолчанию с init() и расчет сделан на значения по умолчанию как no post values так ли это,

Попробуй это,

<?php
namespace October\Demo\ReportWidgets;

use Backend\Classes\ReportWidgetBase;
use RainLab\User\Models\User;
use Request;

class TestWidget extends ReportWidgetBase
{

    public function defineProperties() {
        return [
            'year' => [
                'title' => 'Year',
                'default' => $this->getDefaultYear(),
                'group' => 'Date',
                'type' => 'dropdown',
                'options' => $this->getYearOptions(),
            ],
            'month' => [
                'title' => 'Month',
                'type' => 'dropdown',
                'group' => 'Date',
                'options' => $this->getMonthOptions(),
                'depends' => ['year']
            ],
            'quarter' => [
                'title' => 'Quarter',
                'type' => 'dropdown',
                'group' => 'Date',
                'options' => $this->getQuarterOptions(),
                'depends' => ['month']
            ],
        ];
    }

    public function init() {

        // it will set default values on every refresh
        // we will not use $this->setProperties() as it will set
        // multiple props at single time but it will remove column size etc props as well so
        $this->setProperty('year' , $this->getDefaultYear());
        $this->setProperty('month' , '01');
        $this->setProperty('quarter' , '1st');
    }

    public function getDefaultYear() {
        // may be dynamic current year (I become sloppy here and hard coded)
        return '2018'; 
    }

    public function getYearOptions() {

        $query = User::all();

        $years = [];

        foreach($query as $user) {
            $year = date('Y', strtotime($user->created_at));

            $years[$year] = $year;
        }

        $years = array_unique($years);

        // hard-coded for testing as i don't have users so
        // $years = ['2014', '2015', '2017', '2018', '2019'];
        // $years = array_combine($years, $years);
        return $years;

    }


    public function getMonthOptions() {


        // Load the year property value from POST
        $yearCode = Request::input('year');

        // PRIORITY is user choise if he choose something this 
        // condition will be false and we dont use default property     
        // if he dosn't choose means condition true we can use default value 
        // (so it should be page refresh)
        if(!$yearCode) {

            // so if page is refreshed we use default value
            // which we set in init() method
            $yearCode = $this->property('year');
        }


        // based on $yearCode Calulate -> month
        $months = [];
        for ($m=1; $m<=12; $m++) {
            $month = date('m', mktime(0,0,0,$m, 1, date('Y')));
            $months[$month] = date('M', mktime(0,0,0,$m, 1, date('Y')));
        }
        return $months;
    }

    public function getQuarterOptions() {

        // Load the month and year property value from POST
        $monthCode = Request::input('month');
        $yearCode = Request::input('year');

        // PRIORITY is user choise if he choose something this 
        // condition will be false and we dont use default property     
        // if he dosn't choose means condition true we can use default value 
        // (so it should be page refresh)
        if (!$yearCode && !$monthCode) {

            // so if page is refreshed we use default value
            // which we set in init() method
            $yearCode = $this->property('year');
            $monthCode = $this->property('month');
        }


        // now based on $yearCode and $month code calulate -> quarter
        if ($yearCode) {
            return [
                1 => '1st',
                2 => '2nd',
                3 => '3rd',
                4 => '4th'
            ];
        }
    }

    public function render()
    {
        return $this->makePartial('widget');
    }
}

если у вас возникли проблемы, пожалуйста, прокомментируйте.

Другие вопросы по тегам