1

I've recently been introduced to the concept of Saving the model that I've updated. In this case, I have created a function called incrementPayList which takes in the id of a list and the increments it by one.

This is the code for the function in the paylist model

public function incrementPayList($id) 
{
    $results = Recipient::model()->findAll(array("condition"=>"list_id = $id"));
    $count = count ( $results );
    $this->num_indv = $count + 1;         
}

Now in the recipient controller, I am calling this function. The recipient holds all of the individuals who are connected to a certain payList

 */
public function actionCreate($id)
{
    $model=new Recipient;
    // Uncomment the following line if AJAX validation is needed
    // $this->performAjaxValidation($model);

    if(isset($_POST['Recipient']))
    {
        $model->attributes=$_POST['Recipient'];

        Paylist::model()->incrementPayList($id);
        if($model->save())
        {
            $this->redirect(array('view','id'=>$model->id));
        }
    }

    $this->render('create',array(
        'model'=>$model,
        'id'=>$id
    ));
}

I know that the $count returns the correct number - but it is not saving that count in the field num_indv. I have an inkling that this is because I am not saving the new PayList model. However, how/where should I do this? Should I do it inside the function itself? Or should I do it in the controller? But, if I do it in the controller, I can't simply use $model->save() because it is not the same model.

Haim Evgi
  • 123,187
  • 45
  • 217
  • 223
Stephen
  • 2,360
  • 2
  • 18
  • 23

2 Answers2

1

The reason it isn't working is that you aren't running incrementPayList on the Paylist instance $model but on the Recipient singleton (see Difference between static class and singleton pattern? and Best practice on PHP singleton classes for more information).

Your code should read:

$model->attributes=$_POST['Recipient'];
$model->incrementPayList($id);
if($model->save())
    {

Also use CActiveRecord::count() instead of findAll followed by count($results) since you only need the number and not the items themselves.

Community
  • 1
  • 1
topher
  • 14,790
  • 7
  • 54
  • 70
  • How would $model->incrementPayList($id); work if $model is a formed as a new Recipient model. Are you saying that I should house incrementPayList in the recipient model then? – Stephen Jul 14 '14 at 13:15
  • Correct me if I'm wrong but `incrementPayList` sets the `num_indv` for a single record. Each `CActiveRecord` represents a record therefore it should be called from `$model` and not `Recipient::model()` – topher Jul 14 '14 at 19:44
0

you can save like this

$modelPaylist = new Paylist;

    if(modelPaylist->save())....
Arslan Butt
  • 775
  • 1
  • 8
  • 20