yii2自动更新时间,根据条件设定指定值,接受多选框的值

た 入场券 2022-09-30 13:46 226阅读 0赞

gii自动生成的_form.php文件中,我们可以根据代码$model->isNewRecord 返回的值,来判断当前是增加还是更新,在form.php文件中,还可以根据它的属性值给字段input框赋予默认值

connect字段为多选框字段,前台传到后台的数据默认是数组格式。该字段对应是让tostring方法处理,先把它的值赋给静态变量$connect,然后在beforeSave中把数组格式化成字符串,在返回,存入数据库。

  1. <?php
  2. namespace backend\models;
  3. use Yii;
  4. use \yii\db\ActiveRecord;
  5. class Newdocument extends ActiveRecord {
  6. public function beforeSave($insert){
  7. if(parent::beforeSave($insert)){
  8. if($this->isNewRecord){
  9. //判断是更新还是插入
  10. $this->connect = implode(',', $this->connect);
  11. $this->create_time = time();
  12. }else{
  13. $this->update_time = time();
  14. $this->connect = implode(',', $this->connect);
  15. }
  16. return true;
  17. }else{
  18. return false;
  19. }
  20. }
  21. /** * @inheritdoc */
  22. public static function tableName() {
  23. return 'document';
  24. }
  25. /** * @inheritdoc */
  26. public function rules() {
  27. return [
  28. [[ 'create_time','update_time'], 'integer'],
  29. ['connect','tostring'],
  30. ];
  31. }
  32. public function tostring(){ //可通过方法单独控制某个字段,也可以直接通过beforesave方法控制
  33. //if($this->isNewRecord){//判断是更新还是插入
  34. //$this->connect = implode(',', $this->connect);
  35. //}else{
  36. // $this->connect = implode(',', $this->connect);
  37. //}
  38. }
  39. }

发表评论

表情:
评论列表 (有 0 条评论,226人围观)

还没有评论,来说两句吧...

相关阅读