Zainab
Zainab

Reputation: 15

Yii2 prevent TimestampBehavior

I am creating a custom Identity interface without created_at property. I got an error :

"name": "Unknown Property",
"message": "Setting unknown property: api\\common\\models\\User::created_at",

I tried to comment the TimestampBehavior, but I got the following error:

 "name": "PHP Warning",
 "message": "Invalid argument supplied for foreach()",

I want to know where is the problem.

Model class:

class User extends ActiveRecord implements IdentityInterface
{
public static function tableName()
{
    return '{{%user}}';
}

public function behaviors()
{
    // return [
    //     TimestampBehavior::className(),
    // ];
}

/**
 * @inheritdoc
 */
public function rules()
{
    return [
        [['purpose'], 'required'],
        [['status'], 'integer'],

    ];
}

}

for the rest controller the action is

           public function actionLogin(){
                . 
                . 
                .

                $api_user = new User();
                $api_user->purpose="app";
                $api_user->status=User::STATUS_ACTIVE;
                if($api_user->save()){
                    $success = true;

                }
            }

Upvotes: 0

Views: 1382

Answers (4)

Hassan Raza
Hassan Raza

Reputation: 679

This will automatically resolve the issue. BlameableBehavior and TimestampBehavior

// Include these on the start
use yii\behaviors\BlameableBehavior;
use yii\behaviors\TimestampBehavior;
use Carbon\Carbon;

// Paste this function inside the class.

/**
     * @return array
     */
    public function behaviors()
    {
        return [
            'blameable' => [
                'class'              => BlameableBehavior::className(),
                'createdByAttribute' => 'created_by',
                'updatedByAttribute' => 'updated_by',
            ],
            'timestamp' => [
                'class' => TimestampBehavior::className(),
                'createdAtAttribute' => 'created_at',
                'updatedAtAttribute' => 'updated_at',
                'value' => Carbon::now(),
            ],
        ];
    }

NOTE: If you are not using updated_at or updated_by then remove it form the above code

Upvotes: 1

user206
user206

Reputation: 1105

Example: Rename and prevent time recording or remove properties. Also change the value

Rename or delete properties or change value.

public function behaviors()
{
  return [
    [
        'class' => \yii\behaviors\TimestampBehavior::className(),
        'createdAtAttribute' => 'created_at',
        // 'createdAtAttribute' => 'c_time', //Change the name of the field
        'updatedAtAttribute' => false, //false if you do not want to record the creation time.
        // 'value' => new Expression('NOW()'), // Change the value
    ],
  ];
}

Or

      'class' => \yii\behaviors\TimestampBehavior::className(),
      'attributes' => [
          \yii\db\ActiveRecord::EVENT_BEFORE_INSERT => ['created_at'],
          // \yii\db\ActiveRecord::EVENT_BEFORE_UPDATE => [],
      ],

$createdAtAttribute: The attribute that will receive timestamp value Set this property to false if you do not want to record the creation time.

$attributes: List of attributes that are to be automatically filled with the value specified via $value. The array keys are the ActiveRecord events upon which the attributes are to be updated, and the array values are the corresponding attribute(s) to be updated. You can use a string to represent a single attribute, or an array to represent a list of attributes. For example,

[
    ActiveRecord::EVENT_BEFORE_INSERT => ['attribute1', 'attribute2'],
    ActiveRecord::EVENT_BEFORE_UPDATE => 'attribute2',
]

Upvotes: 0

Michal Hynčica
Michal Hynčica

Reputation: 6144

You were getting following warning because you've completely removed the return in the behaviors() method.

"name": "PHP Warning",

"message": "Invalid argument supplied for foreach()",

The behaviors method must return an array. If you don't want to use any behavior your behaviors() method should return empty array like this:

public function behaviors()
{
    return [];
}

This is also default implementation of behaviors() method in yii\base\Component so if you don't need to use any behavior you can simply remove the behaviors() method from your model.

Attaching TimestampBehavior to your model when you are not using it means that you add unnecessary overhead.

Upvotes: 0

ttrasn
ttrasn

Reputation: 4826

change your Behavior in your model to:

public function behaviors()

{

    return [

        'timestamp' => [

            'class' => 'yii\behaviors\TimestampBehavior',

            'attributes' => [

                ActiveRecord::EVENT_BEFORE_INSERT => ['updated_at'],

                ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],

            ],

            'value' => new Expression('NOW()'),

        ],           

    ];

 }

if you haven't updated_at also delete it from attributes.

Upvotes: 0

Related Questions