D
D
dikium2016-09-29 13:58:51
Yii
dikium, 2016-09-29 13:58:51

How to make the ActiveRecord::load() method work in Yii2?

Hello! I have a question: I'm using Yii2 and I'm trying to do a trivial save of data from a form to a database using ActiveRecord like this:

$order = new Order();
if($order->load(Yii::$app->request->post()) && $order->validate())
{
  $order->save(false);

  $this->redirect(['orders']);
}

The Order model itself looks like this:
class Order extends ActiveRecord
{
    const STATUS_NEW = 'na_utv';
    const STATUS_DOIT = 'na_isp';
    const STATUS_DONE = 'ready';
    const STATUS_DECLINE = 'declined';

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

  public function rules()
  {
    return [
      [['status', 'consume_type',  /*'comment',*/ 'count', 'cost'], 'required', 'message' => 'Это поле должно быть заполнено'],

      ['technic_id', 'match', 'pattern' => '/null.*/', 'not' => true, 'message' => 'В поле "обслуживаемая техника" нужно выбрать принтер, а не подразделение'],

      ['user_fio', 'required', 'message' => "Введите ФИО заказчика"]
    ];
  }


  public function attributeLabels()
  {
    return [
      'technic_id' => 'Обслуживаемая техника',
      'status' => 'Статус заказа',
      'consume_type' => 'Тип расходного материала',
      'count' => 'Количество',
      'user_fio' => "ФИО заказчика",
      'comment' => 'Комментарий к заказу',
      'cost' => 'Стоимость расходного материала'
    ];
  }
}

The problem is that the ticket creation function generates a database error: General error: 1364 Field 'comment' doesn't have a default
value for some reason, the $order-save() function does not see the comment field in the model, although the corresponding column is in the database.
The situation changes if you add a rule for the comment field in the rules() method - this makes the save() method work as it should. However, this field is optional and I don't want to put it in the rules() method because there simply aren't any rules for the field. What do i do? I read that the ActiveRecord object receives a list of table columns from the database and makes similar properties, but is it really necessary to specify all the database columns in the rules () method?

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
M
Maxim Fedorov, 2016-09-29
@dikium

if you load data into the model using the load method, then only those attributes that are considered safe will be loaded, and specifically in your case, all the attributes that are specified in the rules. You can solve this problem by assigning the safe validator to the Comment attribute.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question