yii framework where method isn’t saving properly

I am using Yii framework and I am creating a register page for the user. In order for a user to create an account, they need to enter in a ticket code. A widow form pops up and they fill out the ticket code, it ajax validates it properly and stores it as a session variable. The popup window closes and allows the user to fill out the rest of the form and submit it. The form should then validate the information, create the user, reasign the ticket’s user_ID to the new user_ID, and load the page /ticket/mytickets.

what happens, the ticket is confirmed that it exists, saves it into the session, the user is created, the ticket reassign method gets called, the ticket is never reassigned, and the page reloads. When I echo out the page on the reload, it shows the correct information for the user_ID, and the ticket_ID.

Any hints would help for debugging this would be helpful. Thank you

//controler
public function actionRegister()
{

    $model=new User;
    $valid = false;
    //check to see if valid
    if(isset($_POST['User'])){
        $valid = $model->checkValid();
    }
    if($valid)
    {
        $model->attributes=$_POST['User'];
        $user_ID = $model->ID;
        if($model->save()){
            //save ticket to user
            $reassigned = Ticket::model()->reassign_with_IDs($_SESSION['ticket_ID'],$user_ID);
            if($reassigned){
                unset($_SESSION['ticket_ID']);
                //redirect to mytickets
                $this->redirect(array('/ticket/mytickets'));
            }
        }
    }

    $this->render('register',array(
        'model'=>$model,
    ));

}


//model
public static function reassign_with_IDs($ticket_ID,$user_ID){
    $ticket = Ticket::model()->findByPK($ticket_ID);
    $ticket->user_ID = $user_ID;
    if($ticket->save()){
        return true;
    }
    else{
        return false;
    }
}

Answer

$model->ID is only set after $model is saved. Therefore your code should read:

if($valid)
{
    $model->attributes=$_POST['User'];
    if($model->save()){
        //save ticket to user
        $user_ID = $model->ID;
        $reassigned = Ticket::model()->reassign_with_IDs($_SESSION['ticket_ID'], $user_ID);

You can however get rid of the reassign_with_IDs function and the unnecessary variable user_ID and just explicitly set the ticket using:

$reassigned = Ticket::model()->updateByPk($_SESSION['ticket_ID'], ['user_ID'=>$model->ID]);

Leave a Reply

Your email address will not be published. Required fields are marked *