Yii2.0 技巧总结
View部分
1. 使用ActiveField中的hint生成提示文字
<?= $form->field($model, 'freightAddedFee')->textInput()->hint('大于0的整數') ?>?2. 文本框添加placeholder屬性,其實這個本來就是html5帶的屬性。
<?= $form->field($model, 'mobile', $input_class)->textInput(['maxlength' => 60,'placeholder' => '11位數字']) ?>3. ?用activeForm生成的元素不讓出現label
<?= $form->field($model, 'skuType1')->textInput()->label(false) ?>4. 使用GridView,如果數據庫中保存的是圖片地址,在前臺顯示成圖片可以使用format,并添加圖片樣式
['label' => '頭像','format' => ['image',['class' => 'thumbnail_image']],'value' => 'avatarUrl',],?
Controller 部分
1. 跳轉回上次的地址
return $this->redirect(Yii::$app->request->referrer);?
Model 部分
1. 通過中間表關聯查詢
public function getVendorNickName(){return $this->hasOne(User::className(), ['id' => 'userId']) ->viaTable(BaseVendor::tableName(), ['id' => 'vendorId']); }參見:http://www.yiiframework.com/doc-2.0/guide-db-active-record.html#relations-with-junction-table
2. 查詢語句使用join時為表起別名。起別名可以防止沖突,因為有時候會join一張表兩次。
下面的例子為user表起了u1的別名
$query->joinWith(['vendorNickName' => function ($q) {$q->where('u1.nickname LIKE "%' . $this->vendorNickName . '%"')->from(User::tableName().' u1');}]);生成的SQL類似:
SELECT `za_order`.* FROM `za_order` LEFT JOIN `za_user_vendor` ON `za_order`.`vendorId` = `za_user_vendor`.`id` LEFT JOIN `za_user` `u1` ON `za_user_vendor`.`userId` = `u1`.`id` WHERE u1.nickname LIKE "%一號微店%"?
?配置和components
1. 1分鐘配置站點出錯自動發告警郵件功能。
我們知道站點出錯時,Yii2會記錄日志 可能會在存放在 \frontend\runtime\logs,Yii2 自帶swiftmailer。我們可以通過配置修改Log的target。指定是以文本存儲本地還是發送郵件。
具體見下面的代碼。你需要修改郵箱相關配置信息。
更多信息見 文檔
'components' => ['user' => [//.....],'log' => ['traceLevel' => YII_DEBUG ? 3 : 0,'targets' => [['class' => 'yii\log\FileTarget','levels' => ['error', 'warning'],], ['class' => 'yii\log\EmailTarget','levels' => ['error'],//'categories' => ['yii\db\*'],'message' => ['from' => ['no_reply@qq.com'],'to' => ['xx@qq.com'],'subject' => basename(dirname(__DIR__)) .' errors in XX site',],'categories' => ['yii\db\*', 'yii\web\HttpException:*'] // 只處理數據庫和請求導致的錯誤
'except' => ['yii\web\HttpException:404'], // 排除404,不然的話你會發現你的郵箱里全塞滿了這些郵件 ],],],'mailer' => ['class' => 'yii\swiftmailer\Mailer',// viewPath 不使用'viewPath' => '',// send all mails to a file by default. You have to set// 'useFileTransport' to false and configure a transport// for the mailer to send real emails.'useFileTransport' => false,'transport' => ['class' => 'Swift_SmtpTransport','host' => 'smtp.qq.com','username' => 'xxx@qq.com','password' => 'your_password','port' => '465','encryption' => 'ssl',],],
?
參考:http://www.kkh86.com/it/yii2-adv/guide-base-modify-jquery.html
?
?
轉載于:https://www.cnblogs.com/mafeifan/p/4205527.html
總結
以上是生活随笔為你收集整理的Yii2.0 技巧总结的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: (转载)WebSphere MQ安装过程
- 下一篇: GDOI2015 解题报告