-
Notifications
You must be signed in to change notification settings - Fork 0
/
yii2.txt
397 lines (317 loc) · 11.1 KB
/
yii2.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
==============================================================================
Author: Martin von Wysiecki <wysiecki@gmail.com>
==============================================================================
Tricks - Yii2
INSTALLATION OF advanced template:
composer global require "fxp/composer-asset-plugin:~1.1.1"
composer create-project --prefer-dist yiisoft/yii2-app-advanced yii-application
php ./init
./yii migrate
STANDARD VALUES
//whole logged user
$user = \Yii::$app->user->identity;
//id of logged user
$userId = \Yii::$app->user->identity->id
REQUESTS:
$request = \Yii::$app->request;
$name = $request->post('name');
$get = $request->get();
Grid
'enableSorting' => false
-- edit action column
'class' => 'yii\grid\ActionColumn',
'template'=>'{view} {update} {delete}',
'urlCreator' => function($action, $model, $key, $index) {
-- add custom dropdown {active non active}
add field to rules() in query model in section 'safe'
ex. [['active', ...], 'safe'],
add andFilterWhere
ex. ->andFilterWhere(['like', 'active', $this->active])
'filter'=>array('1'=>'Active','0'=>'Not Active'),
add custom format
ex. 'format' => 'state',
-- add custom sorting for custom fileds, add in query model, method search()
before $query->load();
$dataProvider->sort->attributes['companyId'] = [
'asc' => ['company_name' => SORT_ASC],
'desc' => ['company_name' => SORT_DESC],
];
-- add custom related text field
in query model:
add filed name [public $testName]
add to rules safe [['testanme'],'safe']
add search method:
$query->joinWith(['relTable'])
$query->andFilterWhere('like', 'table.filed', $this->testName)
in gridView attribute 'testName'
-- gen translation files
./yii message/extract @common/config/i18n.php
GRID STYLE
[
'attribute' => 'id',
'headerOptions' => ['style' => 'width:40px'],
'format' => 'raw',
],
HTML Dropdown
use yii\helpers\ArrayHelper;
<?= Html::dropDownList('framework_id', null, ArrayHelper::map(Framework::find()->all(), 'id', 'name'),[
'onchange'=>'',
'prompt'=>'-Choose a Category-',
'class'=>'yourclass',
]) ?>
HTML hidden input
echo Html::hiddenInput('name', $value);
DB
$db = \Yii::$app->getDb();
$db->pdo->setAttribute(\PDO::MYSQL_ATTR_USE_BUFFERED_QUERY,true);
$cmd = $db->createCommand('
SET FOREIGN_KEY_CHECKS=0;
TRUNCATE TABLE door;
SET FOREIGN_KEY_CHECKS=1;
');
$cmd->execute();
JSON
SELECT id, data2->'$.dupa' browser FROM qms_files WHERE data2->>'$.dupa' > 0
$data = Members::find()
->select(['concat(first_name,last_name) as value', 'first_name as label','id as id'])
->asArray()
->all();
CUSTOM FIELDS TO MODELS
public $country_id;
public function rules() {
return ArrayHelper::merge( [ [['country_id'], 'integer']], parent::rules() );
}
OR LIKE Search
$query->andFilterWhere([
'or',
['like', 'profiles.first_name', $this->userFullName],
['like', 'profiles.last_name', $this->userFullName],
]);
JOIN, SORT over two realated tables
$query->joinWith(['reviewJournal','reviewJournal.country']);
$dataProvider->sort->attributes['country_id'] = [
'asc' => ['country.name' => SORT_ASC],
'desc' => ['country.name' => SORT_DESC],
];
DEFAULT SORT ORDER
$dataProvider = new ActiveDataProvider([
'query' => $query,
'sort'=> ['defaultOrder' => ['company_name'=>SORT_ASC]]
]);
$dataProvider->pagination=false;
$dataProvider->sort->defaultOrder = ['created_at' => SORT_DESC];
ARRAY DATAPROVIDER
use yii\data\ArrayDataProvider;
$dataProvider = new ArrayDataProvider([
'allModels' => $data,
'sort' => [
'attributes' => ['company', 'month', 'year'],
],
'pagination' => [
'pageSize' => 10,
],
]);
Relations and other stuff:
http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#joining-with-relations
DEBUG
$model->validate();
var_dump($model->getErrors());
\Kint::dump($data);
TIMESTAMP
use yii\behaviors\TimestampBehavior;
use yii\db\Expression;
$db = new Expression('NOW()');
SAVE ARRAY TO DB
$model->attributes = $values;
$model->save();
PARAMS
Yii::$app->params['range-step-uwert']
PJAX
[http://blog.neattutorials.com/yii2-pjax-tutorial/]
$.pjax.reload('#jebudup', {url: '/test/dupa', type: "POST", data: {dupsko: 'moje'}});
FORM
<?= Html::textInput('allSearch', ''); ?>
echo Html::textInput('allSearch',null,['id'=>'docSearch']);
FORMAT FIELDS:
'created:dateTime',
echo Yii::$app->formatter->asDate('now', 'yyyy-MM-dd');
DROPDOWN (concate date)
<?= $form->field($model, 'department_id')->widget(\kartik\widgets\Select2::classname(), [
'data' => \yii\helpers\ArrayHelper::map(\common\models\Department::find()->orderBy('id')->all(), 'id', 'concate'),
'options' => ['placeholder' => Yii::t('app', 'Choose Department')],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
Model:
public function getConcate(){
return $this->company->name.' - '.$this->name;
}
ENUM
<?php echo $form->field($translateModel, 'language')->dropDownList(
common\models\FrameworkTranslations::optslanguage()
); ?>
DATE_RANGE_FILTER
cols:
[
'attribute' => 'created',
'format'=>'date',
'filterType'=> \kartik\grid\GridView::FILTER_DATE_RANGE,
'filterWidgetOptions' => [
'presetDropdown' => true,
'pluginOptions' => [
'format' => 'YYYY-MM-DD',
'locale' => [
'format' => 'DD-MM-YYYY',
],
'opens'=>'left',
] ,
'pluginEvents' => [
"apply.daterangepicker" => "function() { apply_filter('date') }",
]
],
]
model search:
if(isset($this->created) && $this->created!=''){
$date_explode = explode(" - ", $this->created);
$date1 = trim($date_explode[0]);
$date2= trim($date_explode[1]);
// echo'<br><br><br><br><br><br><br><br><br><br><br><br><br>';
// var_dump($this->created);
// var_dump($date1);
// var_dump($date2);
$a = new \DateTime($date1);
$b = new \DateTime($date2);
// echo $a->getTimestamp();
$date1 = date( 'Y-m-d', $a->getTimestamp());
$date2 = date( 'Y-m-d', $b->getTimestamp());
$query->andFilterWhere(['between', 'created', $date1,$date2]);
}
Masked input fields
http://demos.krajee.com/masked-input
RENDER FROM EVERYWHERE
return \Yii::$app->controller->renderPartial('@common/partial/_benefitContent'.$export['ver'],$export['data']);
DB
NOT NULL ->andWhere(['not', ['City' => null]])
Create migration
./yii migrate/create <name>
SUBQUERY
$subQuery = UserToDepartment::getUsersForDepartment();
$query->andFilterWhere(['not in', 'user.id', $subQuery]);
SUBQUERY in SELECT
$query->select([
'journal.*',
new Expression(
"(SELECT IF(ema = 1,CONCAT(name, ' - EMA'),name) FROM mlm_base WHERE id = mlm_to_journal.mlm_id) as mlm_name"
),
new Expression(
"(SELECT id FROM mlm_base WHERE id = mlm_to_journal.mlm_id) as mlm_id"
),
new Expression(
"(SELECT ema FROM mlm_base WHERE id = mlm_to_journal.mlm_id) as mlm_ema"
)
]
);
DEBUG
\Kint::dump($data);
KARTIK
DATECONTROL
echo $form->field($model, 'contract_from')->widget(DatePicker::className(), [
'options' => [
'class' => 'form-control',
'dateFormat' => 'php:d-m-Y',
'saveFormat' => 'php:U'
],
]);
$dateControlWidgetOpts = [
'type' => DateControl::FORMAT_DATETIME,
'saveFormat' => 'php:U',
'displayFormat' => 'php:d-m-Y',
'widgetOptions' => [
'pluginOptions' => [
'minView' => 2,
'autoclose' => true,
]
]
];?>
<?= $form->field($model, 'available_from')->widget(DateControl::className(), $dateControlWidgetOpts)->label('Available From*'); ?>
JAVASCRIPT in View
use yii\web\View;
$this->registerJs($js2, View::POS_HEAD);
JS
'onclick' => "$('.wrap').showLoading();",
'onclick' => "$('.wrap').hideLoading();",
MODAL
close button
<span class="btn btn-default" data-dismiss="modal" aria-label="Close">Cancel</span>
Modal::begin([
'headerOptions' => ['id' => 'modalHeader'],
'id' => 'note-modal',
'size' => 'modal-lg',
'clientOptions' => [
'backdrop' => 'static', // nie zamyka
'keyboard' => FALSE,
]
]);
echo "<div id='modalContent'></div>";
yii\bootstrap\Modal::end();
AJAX
$("#my_form").submit(function(e) {
e.preventDefault(); // avoid to execute the actual submit of the form.
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data)
{
var form_data = {cid : $cid, countryId : $countryId};
loadAjax('/simply-indexing/list', '#pjax-simply-content', form_data);
$('#simplyDocument').modal('hide');
$('.modal-backdrop').remove();
$('#modalContentSimply').html('');
}
});
return false;
});
FORM CHECK, save on changes
<?php
$js = <<<JS
var originalForm = '';
$(function(){
originalForm = $($('#Journal')[0].elements).serialize();
});
$('#Journal').on('beforeValidate', function (e) {
var newForm = $($('#Journal')[0].elements).serialize();
if(originalForm != newForm) {
var check = confirm('FORM CHANGES DETECTED. Ready to save?');
if (check == true) {
return true;
} else {
$('.wrap').hideLoading();
return false;
}
} else {
location.href = '/journal/index';
return false;
}
});
JS;
$this->registerJs($js);
BROWSER LOCAL STORAGE
set
window.localStorage.setItem('cuurl', hash);
get
var hash = window.localStorage.getItem('cuurl')
SORT ARRAY MULTI BY key name
array_multisort(array_column($array, 'name'), SORT_ASC, $array);
- na początku
'filterInputOptions' => [
'class' => 'form-control',
'prompt' => Yii::$app->params['activeForm.prompt'],
],
SAFETY:
common/components/ReportComponent.php
REPORTS MERGE:
common/models/Report.php:650