Порядок вывода данных в таблице GridView по дате создания YI

Обсуждения, заметки, статьи о фреймворке

Модераторы: Xpycm, Koduc

Правила форума
ВНИМАНИЕ! Форум не является средством гарантированной поддержки клиентов и пользователей. Поэтому на быстрый ответ тут рассчитывать не нужно, как и на ответ вообще. Сотрудники отвечают по мере своих возможностей.

На форуме действует ограничение в 3 сообщения / сутки.
Если Вы хотите сказать "спасибо", то воспользуйтесь функцией "Повысить репутацию" - зелёная иконка "плюс" под ником ответившего.

Порядок вывода данных в таблице GridView по дате создания YI

Сообщение vac9p » 20 дек 2020, 12:53

Есть сайт с CMS реализованной на yii2. В панели администратора есть раздел "клиенты", со списком клиентов и возможность редактирования каждого клиента. Данные об аккаунтах клиентов имеют дату создания и сейчас по дефолту сначала выводятся старые клиенты. Так вот, к вопросу - подскажите пожалуйста как изменить порядок вывода записей, таким образом, чтобы сначала выводились не старые клиенты, а новые? ps. таблица выводится с помощью виджета GridView.

Код: Выделить всё

 <?= GridView::widget([
            
'id' => 'customers',
            
'tableOptions' => [
                
'class' => 'table table-bordered table-hover table-striped',
            ],
            
'options'          => ['class' => 'table-responsive grid-view'],
            
'dataProvider' => $dataProvider,
            
'filterModel' => $searchModel,
            
'columns' => [
                
'first_name',
                
'last_name',
                
'email',
                
'source',
                
'adsCount',
                [
                 
'attribute'=>'created_at',
                 
'filter'=>  DatePicker::widget(
                     [
                        
'model' => $searchModel,
                        
'attribute' => 'created_at',
                        
'options'=>[
                            
'class'=>'form-control',
                            ],
                        
'dateFormat' => 'yyyy-MM-dd',
                     ]
                 )
                ],
                [
                 
'attribute'=>'status',
                 
'value'=> function($model) {
                     return 
t('app',ucfirst(html_encode($model->status)));
                 },
                 
'filter' => Html::activeDropDownList($searchModel'status', [ 'active' => t('app','Active'), 'inactive' => t('app','Inactive') ],['class'=>'form-control','prompt' => 'All'])
                ],
                [
                    
'class' => 'yii\grid\ActionColumn',
                    
'contentOptions' => [
                        
'class'=>'table-actions',
                        
'id' => 'table-action-customer'
                    
],
                    
'template' => '{activation} {activate} {deactivate} {impersonate} {view} {update} {delete}',
                    
'buttons'  => [
                        
'activation' => function ($url$model) {
                            return (
$model->status === \app\models\Customer::STATUS_INACTIVE && $model->activation_key != null) ? Html::a(
                                
'<span class="fa fa-envelope-o"></span>',
                                
$url,
                                [
                                    
'data-content'      => t('app''Resend the activation email.'),
                                    
'data-container'    => 'body',
                                    
'data-toggle'       => 'popover',
                                    
'data-trigger'      => 'hover',
                                    
'data-placement'    => 'top',
                                    
'data-pjax'         => '0',
                                    
'data-confirm'      => t('app''Are you sure you want to resend the activation email for this customer?'),
                                    
'style'             => 'margin-right: 7px'
                                
]
                            ) : 
'';
                        },
                        
'activate' => function ($url$model) {
                            return (
$model->status === \app\models\Customer::STATUS_INACTIVE || $model->status === \app\models\Customer::STATUS_DEACTIVATED) ? Html::a(
                                
'<span class="fa fa-check"></span>',
                                
$url,
                                [
                                    
'data-content'      => t('app''Set active'),
                                    
'data-container'    => 'body',
                                    
'data-toggle'       => 'popover',
                                    
'data-trigger'      => 'hover',
                                    
'data-placement'    => 'top',
                                    
'data-confirm'      => t('app''Are you sure you want to activate this customer?'),
                                    
'style'             => 'margin-right: 6px'
                                
]
                            ) : 
'';
                        },
                        
'deactivate' => function ($url$model) {
                            return 
$model->status === \app\models\Customer::STATUS_ACTIVE Html::a(
                                
'<span class="fa fa-times"></span>',
                                
$url,
                                [
                                    
'data-content'      => t('app''Set deactivated'),
                                    
'data-container'    => 'body',
                                    
'data-toggle'       => 'popover',
                                    
'data-trigger'      => 'hover',
                                    
'data-placement'    => 'top',
                                    
'data-pjax'         => '0',
                                    
'data-confirm'      => t('app''Are you sure you want to deactivate this customer?'),
                                    
'style'             => 'margin-right: 9px'
                                
]
                            ) : 
'';
                        },
                        
'impersonate' => function ($url$model) {
                            return 
Html::a(
                                
'<i class="fa fa-random"></i>',
                                
url(['/admin/customers/impersonate''id' => $model->customer_id]),
                                [
                                    
'data-content'      => t('app''Impersonate this customer account on frontend'),
                                    
'data-container'    => 'body',
                                    
'data-toggle'       => 'popover',
                                    
'data-trigger'      => 'hover',
                                    
'data-placement'    => 'top',
                                    
'data-pjax' => '0',
                                    
'style'     => 'margin-right: 5px'
                                
]
                            );
                        },
                    ],
                ],
            ],
        ]); 
?>

vac9p
Незнакомец
 
Сообщения: 1
Зарегистрирован: 20 дек 2020, 12:51
Очки репутации: 0

Re: Порядок вывода данных в таблице GridView по дате создани

Сообщение andipas » 21 дек 2020, 10:38

При создании $dataProvider используйте defaultOrder с сортировкой по нужному атрибуту.

Пример:
Код: Выделить всё

$dataProvider 
= new CActiveDataProvider('customers', array(
    'sort'=>array(
        'defaultOrder'=>'id DESC',
    ),
));

$dataProvider = new ActiveDataProvider([
    'query' => $query,
    'sort' => ['defaultOrder'=>'topic_order asc']
]);


https://stackoverflow.com/questions/229 ... lt-sorting
Часто задаваемые вопросы. Для правки файлов notepad++, netbeans, phpStorm. Для правки CSS firebug.
Аватара пользователя
andipas
Разработчик
Разработчик
 
Сообщения: 695
Зарегистрирован: 28 дек 2011, 22:37
Очки репутации: 30

If You Find Yourself Creating a 10-Field Form for a Standard

Сообщение jakiasultana8038 » 06 авг 2022, 14:30

Chances are filling it out will not outweigh the value received on that ebook. What you need to do friction can come in many different forms, but one of the most common problems tends to be with how forms are structured and organized. First, make sure you consider the value of the offer; is it a webinar, one ebook, a downloadable pillar page? Then, brainstorm the value and benefits the offer(s) will bring your users. You can then use this value to begin formulating how many fields, and what types, to show your user. One ideal strategy when deciding this is to go a field or two less than the value, rather than trying to match it. This technique can impress your users if they recognize they don't need to do as much on their end to receive your offer, leading to more conversions. Above all, make it easy for your users to figure out what they need to do, and don’t hit them with barriers that lead their expectations astray.

Examples shopify has managed to slim down their form to one field making it appear easy and less time-consuming. You just have to enter your email address to begin the process. There isn’t even a credit card field that eliminates the concern of having to put some form of payment upfront before even trying the product. Shopify-1 kyle rush led an interesting obamacare online campaign, where they tested one full donation form vs. The same one that sequentially went through each question, but was ultimately the same length. The outcome was a 5% increase in conversion rate on it since users felt visually less overwhelmed when business email list looking at the form. Obamacare conversion rate.jpg sometimes it all comes back to visual impact. If you chunk out the action in small bites so it's easy for visitors to complete, they may be more willing to do it. 6) videos, videos, videos if you’re not using videos on your landing page.

Изображение

You are missing out on a valuable way of creating comfort and trust. You can give the information on the page more context and even add a voice or visuals to aid the message. Companies that use video in their content marketing show a 66% higher average website conversion rate. In fact, videos are so important for landing pages they are one of the selling 7. What you need to do the most important things you need to do with your landing page video are to answer these questions: what's the solution you're providing? Why does the visitor need this solution? What's going to happen next? Badda bing, badda boom. It’s as simple as that. If you’re effectively answering these questions with your video, you’re exponentially increasing your chances of making a conversion. Examples partnermd, a stellar impact client, does it currently. Right off the bat, charleen hits the viewer with the common pain points of the normal healthcare experience.
jakiasultana8038
Незнакомец
 
Сообщения: 1
Зарегистрирован: 06 авг 2022, 13:59
Очки репутации: 0


Вернуться в Yii фреймворк

Кто сейчас на конференции

Сейчас этот форум просматривают: нет зарегистрированных пользователей и гости: 6

cron