CActiveRecord save()

1.In my User class, I have this




   array('username, password, email', 'required'),



2.In my SignupForm.php, I have this on purpose




    array('username,password', 'required'),



3.Fill in SignupForm.php, only "username" and "password" is filled in, the field "email" required by User is left out

4.After submit, SignupForm will pass validation (expected)

5.User will pass validation (unexpected, bug?)

6.This will return "true" even the required field "email" is left out:




    if($user->save(true,$_POST['SignupForm'])){



7.This will return "false" as expected since I left out the required field "email"




    $user=new User();

    $user->attributes=$_POST['SignupForm'];

    if($user->save(true)){



I can’t figure out why when I dig in deeper into the stack, spent a day on it to verify it. Please let me know for further clarification.

–Environment–

PHP 5.3.2-1ubuntu4 with Suhosin-Patch (cli) (built: Apr 9 2010 08:18:14)

Copyright © 1997-2009 The PHP Group

Zend Engine v2.3.0, Copyright © 1998-2010 Zend Technologies

with Xdebug v2.1.0rc1, Copyright (c) 2002-2010, by Derick Rethans



---User.php---

class User extends CActiveRecord

{

...


	public function rules()

	{

		return array(

		array('username, password, [b]email[/b]', 'required'),

		array('username, password, email', 'length', 'max'=>128),

		array('id, username, password, email', 'safe', 'on'=>'search'),

		);

	}

...






--SignupForm.php--

class SignupForm extends CFormModel

{

	public $username;

	public $password;

	public $email;


	public function rules()

	{

		return array(

			array('username,password', 'required'),

		);

	}

...	






--SiteController--<unexpected result >

...

		$model=new SignupForm();

		if(isset($_POST['SignupForm']))

		{

			$model->attributes=$_POST['SignupForm'];

			if($model->validate()){

				$user=new User();

				if($user->save(true,$_POST['SignupForm'])){

					print("success");//goes here, unexpectedly

				} else {

					print("fail");

				}

			}

		}

...






--SiteController--<expected result >

...

		$model=new SignupForm();

		if(isset($_POST['SignupForm']))

		{

			$model->attributes=$_POST['SignupForm'];

			if($model->validate()){

				$user=new User();

				$user->attributes=$_POST['SignupForm'];

				if($user->save(true)){

					print("success");

				} else {

					print("fail");//goes here, expected

				}

			}

		}

...



I want to add, even though


 if($user->save(true,$_POST['SignupForm'])){

returns "true" when a required attribute is left out

the attributes were not saved into the DB

I think the second parameter to save() takes a list of attribute names. You’ll have to assign the attribute values before saving.

/Tommy