RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题 / 1156049
Accepted
Dmitriy
Dmitriy
Asked:2020-07-22 21:56:35 +0000 UTC2020-07-22 21:56:35 +0000 UTC 2020-07-22 21:56:35 +0000 UTC

为什么 $model->save() 不起作用 yii2

  • 772

控制器

$companyObj = new Company();
           
$city = City::findOne(['name' => $post["CabinetRegistrationForm"]["city_name"]]);
            
$companyObj->name = $post["CabinetRegistrationForm"]["company_name"];
$companyObj->activity = 1;
$companyObj->district_id = $city->district_id;
$companyObj->region_id = $city->region_id;
$companyObj->municipality_id = $city->municipality_id;
$companyObj->city_id = $city->id;
$companyObj->address = $post["CabinetRegistrationForm"]["address"];
$companyObj->inn = $post["CabinetRegistrationForm"]["inn"];
$companyObj->approved = 0;
$companyObj->head_fio = $post["CabinetRegistrationForm"]["head_fio"];
$companyObj->phone = $post["CabinetRegistrationForm"]["phone"];
           
$companyObj->save();

模型

namespace common\models;

use mdm\admin\models\AuthItem;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveQuery;
use yii\db\ActiveRecord;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\web\IdentityInterface;

/**
 * This is the model class for table "company".
 *
 * @property int $id
 * @property string $name
 * @property string $org_form
 * @property string $activity
 * @property int $district_id
 * @property int $region_id
 * @property int $municipality_id
 * @property int $city_id
 * @property string $address
 * @property string $inn
 * @property int $approved
 * @property string $head_fio
 * @property string $phone
 * @property string $email
 * @property string $site
 *
 * @property DistrictModel $district
 * @property Municipality $municipality
 * @property City $city
 * @property User[] $users
 * @property SchoolClass[] $classes
 */
class Company extends \common\components\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return 'company';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['name', 'org_form', 'activity'], 'required'],
            [['district_id', 'region_id', 'municipality_id', 'city_id', 'approved'], 'integer'],
            [['address'], 'string'],
            [['name', 'org_form', 'activity', 'inn', 'head_fio', 'email', 'site', 'presentation_url'], 'string', 'max' => 255],
            [['phone'], 'string', 'max' => 50],
            [['district_id'], 'exist', 'skipOnError' => true, 'targetClass' => DistrictModel::className(), 'targetAttribute' => ['district_id' => 'id']],
            [['municipality_id'], 'exist', 'skipOnError' => true, 'targetClass' => Municipality::className(), 'targetAttribute' => ['municipality_id' => 'id']],
            [['presentation_url'], 'trim'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => Yii::t('app', 'ID'),
            'name' => Yii::t('app', 'Name'),
            'org_form' => Yii::t('app', 'Org Form'),
            'activity' => Yii::t('app', 'Activity'),
            'district_id' => Yii::t('app', 'District ID'),
            'region_id' => Yii::t('app', 'Region ID'),
            'municipality_id' => Yii::t('app', 'Municipality ID'),
            'city_id' => Yii::t('app', 'City ID'),
            'address' => Yii::t('app', 'Address'),
            'inn' => Yii::t('app', 'Inn'),
            'approved' => Yii::t('app', 'Approved'),
            'head_fio' => Yii::t('app', 'Head Fio'),
            'phone' => Yii::t('app', 'Phone'),
            'email' => Yii::t('app', 'Email'),
            'site' => Yii::t('app', 'Site'),
            'presentation_url' => Yii::t('app', 'Presentation Url'),
        ];
    }

看法

<?php $form = ActiveForm::begin(['id' => 'form-signup']); ?>

<div class="hidden">
<?= $form->field($model, 'role')->textInput() ?>
</div>
                
<?= $form->field($model, 'second_name')->textInput() ?>
<?= $form->field($model, 'name')->textInput() ?>
<?= $form->field($model, 'last_name')->input('last_name') ?>      
<?= $form->field($model, 'email')->input('email') ?>
<?= $form->field($model, 'inn')->widget(SuggestionsWidget::class, [
      'token' => '*******************',
                    
]) ?>
               
                
<?php if ($model->role == RoleModel::ROLE_RESEARCH_COORDINATOR_OO): ?>                  
<?= $form->field($model, 'company_name')->textarea(); ?>
<?= $form->field($model, 'city_name')->hiddenInput()->label(false); ?>
<?= $form->field($model, 'address')->hiddenInput()->label(false); ?>
<?= $form->field($model, 'head_fio')->hiddenInput()->label(false); ?>
<?= $form->field($model, 'phone')->hiddenInput()->label(false); ?>
<?php endif; ?>
..........

一切似乎都是正确的,没有显示错误,$companyObj->errors- 一个空数组,但它$companyObj->save返回 false。数据库中没有新行。请帮帮我。

php
  • 1 1 个回答
  • 10 Views

1 个回答

  • Voted
  1. Best Answer
    Михаил Динов
    2020-07-31T17:51:10Z2020-07-31T17:51:10Z

    你看,当你调用save()方法的时候,首先按照你在rules()中描述的规则对模型进行验证,如果一切正常,模型就飞到了数据库中。这意味着仍然存在验证错误。调用$companyObj->validate()方法,然后看看$companyObj->getErrors()是什么,会有错误,我保证)))

    顺便说一句,保存时可以禁用验证,$companyObj->save(false)

    我会重写控制器:

            $model = new Company();
    
            if ($model->load(Yii::$app->request->post()) && $model->save()) {
                return $this->redirect(['view', 'id' => $model->id]);
            }
    
            return $this->render('update', [
                'model' => $model,
            ]);
    

    从控制器到模型的部分将被丢弃:

        /**
         * @inheritDoc
         */
        public function beforeValidate(): bool
        {
            $post = Yii::$app->request->post();
    
            $city = City::findOne(['name' => $post["CabinetRegistrationForm"]["city_name"]]);
    
            $this->activity = 1;
            $this->district_id = $city->district_id;
            $this->region_id = $city->region_id;
            $this->municipality_id = $city->municipality_id;
            $this->city_id = $city->id;
            $this->approved = 0;
    
            return parent::beforeValidate();
        }
    

    虽然这是你的基于表单数据的城市搜索,但xs不知何故是愚蠢的......封装也很难)拿它并替换你想要的数据)

    请记住,在 rules() 中,您只描述表单中的那些字段。具有 3 个字段的表单,在 rules() 3 个字段中,您描述,否则所有其他属性都可以替换为任何属性))))

    以及如何正确地将数据从 POST 写入模型?

    $model->load(Yii::$app->request->post()):

    • 从 post 将数据加载到模型中
    • 值将仅分配给 rules() 中描述的那些属性,其他所有内容都将被忽略。
    • 至于hiddenInput()包,xs,对我来说,它们应该被分配在模型的后台某处,但由于我已经这样做了,你需要在它们上面写额外的验证器,这样你就确定会有不可替代。
    • 1

相关问题

  • mysqli 类的对象无法转换为字符串

  • 您的系统中缺少 ext-http *,您的系统中缺少 ext-mysql_xdevapi *

  • 如何从csv中删除bom?

  • 当我按下 Enter 键时,如何让 PhpStorm 的 Emmet 插件触发,就像 VS Code 一样?

  • 注释在 Symfony5 中不起作用

  • 搜索最近的地理位置点

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    如何从列表中打印最大元素(str 类型)的长度?

    • 2 个回答
  • Marko Smith

    如何在 PyQT5 中清除 QFrame 的内容

    • 1 个回答
  • Marko Smith

    如何将具有特定字符的字符串拆分为两个不同的列表?

    • 2 个回答
  • Marko Smith

    导航栏活动元素

    • 1 个回答
  • Marko Smith

    是否可以将文本放入数组中?[关闭]

    • 1 个回答
  • Marko Smith

    如何一次用多个分隔符拆分字符串?

    • 1 个回答
  • Marko Smith

    如何通过 ClassPath 创建 InputStream?

    • 2 个回答
  • Marko Smith

    在一个查询中连接多个表

    • 1 个回答
  • Marko Smith

    对列表列表中的所有值求和

    • 3 个回答
  • Marko Smith

    如何对齐 string.Format 中的列?

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5