Yii Framework Forum: beforeSave() edit the record before saving - Yii Framework Forum

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

beforeSave() edit the record before saving Rate Topic: -----

#1 User is offline   Final13 

  • Newbie
  • Yii
  • Group: Members
  • Posts: 1
  • Joined: 19-October 17

Posted 19 October 2017 - 09:59 AM

data in the birthday field is entered manually and i need to save the last 4 characters from the 10 entered characters to the database, but i can not edit the record before saving. Please help!!
class SignupForm extends Model
{

    public $username;
    public $email;
    public $password;
    public $birthday;
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['username', 'trim'],
            ['username', 'required'],
            ['username', 'unique', 'targetClass' => '\app\models\User', 'message' => 'This username has already been taken.'],
            ['username', 'string', 'min' => 2, 'max' => 255],
            ['email', 'trim'],
            ['email', 'required'],
            ['email', 'email'],
            ['email', 'string', 'max' => 255],
            ['email', 'unique', 'targetClass' => '\app\models\User', 'message' => 'This email address has already been taken.'],
//            ['password', 'required'],
//            ['password', 'string', 'min' => 3],
            ['birthday', 'required'],
            ['birthday', 'string', 'min' => 10, 'max' => 10]
        ];
    }

    /**
     * Signs user up.
     *
     * @return User|null the saved model or null if saving fails
     */
    public function signup()
    {

        if (!$this->validate()) {
            return null;
        }

        $user = new User();
        $user->username = $this->username;
        $user->email = $this->email;
        $user->setPassword($this->birthday);
        $user->generateAuthKey();
        return $user->save() ? $user : null;
    }

    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $this->birthday = substr('$birthday', 6,4);
            return true;
        } else {
            return false;
        }
    }


}

0

#2 User is offline   alrazi 

  • Elite Member
  • Yii
  • Group: Moderators
  • Posts: 1,398
  • Joined: 08-August 12
  • Location:Durban, South Africa

Posted 19 October 2017 - 11:42 AM

should not this be like so

 public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            $this->birthday = substr($this->birthday, 6,4);
            return true;
        } else {
            return false;
        }
    }

1

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users