0
votes

I have an item, the goal is when user create an item I will prompt for email address within save item I will check to see if user already exist if not I will go ahead and create new user with bunch of default values, in the background and if user want to activate then user could comeback and complete profile. How can i do that in model. It seem the only way to save is to pass in array how can i do that with object parameters.

App::uses('User', 'Model');
class Item extends AppModel{
   public function save($data = null, $validate = true, $fieldList = array()) {
   $user = User::getUserbyEmail($data['Item']['email_address']);
   if($user){
      $user = new User();
      $user->firstName = "Bob";
      $user->save();  /// this save does not work
   }
   //get user Id and call parent save
   .........
}

class User extends AppModel {
   public $firtName;
   private $created;
   private $status = 0; //0 is in active
   $private $password;

   public function  __construct($id = false, $table = null, $ds = null) {
     parent::__construct($id, $table, $ds);
     $this->created = date("Y-m-d H:i:s");
     $this->setPassword($password);
  }

  public function setPassword($value){
     $this->password = mysecret_algorithm(standard_password);
  } 

 ..bunch of setter and getter here

}

I am using cakephp and I don't want to do this in controller because I have item add feature at multiple place it would be nice to do in model then every controller just invoke $this->Item->save();

1

1 Answers

1
votes

In your code, what is the purpose of User::getUserbyEmail?

As for saving the user, try this:

class Item extends AppModel{
   public function save($data = null, $validate = true, $fieldList = array()) {
       $user = User::getUserbyEmail($data['Item']['email_address']);
       if (!$user){
           $user = new User(); // EDIT: forgot this part
           $user->create();
           $user->set($userData);
           $user->save();  /// this save does not work
       }
   }
   //get user Id and call parent save
   .........
}

$userData in the above should be an associative array where the array keys are the name of fields in your users database table:

$userData = array(
    'firstname' => 'Bob'
);

Note that your code must pass validation in this case.