phpactiverecordyii2after-save

Yii2 how to resave the modal in afterSave


I have a model ProductOffer inside of it I use afterSave to generate the coupon.

Right now the status is null and in aftersave I want to update it.

public function afterSave($insert, $changedAttributes) {
    if (floatval($this->offer) >= floatval($this->product->threshold_price)) {
        $coupon = false;
        $createCoupon = "";
        $ctr = 1;
        while ($coupon == false) {
            $createCoupon = $this->createCoupon(
                "Offer for " . $this->customer_name . ' #' . $this->id, 
                $this->product->sale_price - $this->offer,
                $this->product_id
            );

            if ($createCoupon || $ctr > 3) {
                $coupon = true;
            }

            $ctr++;
        }

        $this->status = self::STATUS_ACCEPTED_COUPON_GENERATED;
        $this->coupon_code = $createCoupon->code;

        // todo this
        // echo "Accepted automatically then send email to customer as the same time to merchant email";
    } else {
        $this->status = self::STATUS_REJECTED;
    }

    return parent::afterSave($insert, $changedAttributes);
}

So here at afterSave I want to update the status of record and save the coupon code.

What I wan't to do is simply like this.

public function afterSave($insert, $changedAttributes) {

    // So basically I want to update the status in afterSave
    $this->status = "What ever value rejected or accepted it depends of the outcome of generating coupon";
    $this->coupon = "AddTheCoupon";

    // Save or Update
    $this->save();

    return parent::afterSave($insert, $changedAttributes);
}

But It seems not working for me and if you going to analyze it, it seems to do endless updating of the data since every save() it will pass through the afterSave().

Is there other way to do it?

Thanks!


Solution

  • You should use the updateAttributes method, which skips all the events.

    See reference updateAttributes(['some_field']).

    /** After record is saved
      */
    public function afterSave($insert, $changedAttributes)
    {
         parent::afterSave($insert, $changedAttributes);
         
         $this->some_field = 'new_value';
         $this->updateAttributes(['some_field']);
    
    }