【问题标题】:yii2 updating tabular set of data is not workingyii2更新表格数据集不起作用
【发布时间】:2016-01-17 16:34:23
【问题描述】:

http://www.yiiframework.com/doc-2.0/guide-input-tabular-input.html#collecting-tabular-input

我根据上面的链接工作,但我的数据没有更新到数据库中

我的表结构是

设置

id、名称、值

我的控制器 SettingsController.php

 <?php

 namespace backend\controllers;

 use Yii;
 use yii\base\Model;
 use yii\web\Controller;
 use backend\models\Setting;

class SettingsController extends Controller
{


public function actionIndex()
{
    $settings = Setting::find()->indexBy('id')->all();

    if (Model::loadMultiple($settings, Yii::$app->request->post()) && Model::validateMultiple($settings)) {
        foreach ($settings as $setting) {
            $setting->save(false);
        }
        return $this->redirect('update');
    }

    return $this->render('update', ['settings' => $settings]);
  }
}

我的模型是 Setting.php

<?php
namespace backend\models;
use Yii;
class Setting extends \yii\db\ActiveRecord
{

  public static function tableName()
  {
     return 'setting';
  }

}

视图在设置--update.php

<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
$form = ActiveForm::begin();
 foreach ($settings as $index => $setting) {
      echo $form->field($setting, "[$index]value")->label($setting->name);
 }
 ?>
<div class="form-group">
    <?= Html::submitButton('Update', ['class' => 'btn btn-primary']) ?>
</div>
<?php
ActiveForm::end();

我的问题是更新的数据没有保存。但我没有收到任何错误。

【问题讨论】:

    标签: yii2 yii2-advanced-app


    【解决方案1】:

    您的Setting 模型中没有任何规则或安全属性,则此模型的值不可用..

    尝试在规则中为您的模型添加保存属性列表..

    public function rules()
    {
       return [
           [['field1', 'field2',,,,'fieldn'], 'safe'],
       ];
    }
    

    【讨论】:

    • 谢谢你..现在它的工作..我添加了安全的名称和值..我们可以添加规则,例如名称是否是电子邮件,然后验证相应的值字段
    • 是的。如果您添加规则,则不需要对规则中的字段进行安全规范。并且您可以使用验证规则电子邮件添加名称,请参阅 yii2 上的验证指南yiiframework.com/doc-2.0/guide-input-validation.html
    猜你喜欢
    • 2015-02-26
    • 2017-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多