Jump to content
Larry Ullman's Book Forums

How To Use $_Session Variables To Update Form Data


Jonathon
 Share

Recommended Posts

Hi,

 

I've been playing with forms. I've used some sample data and have just been updating them. I plan to have a login system (surprising I know!) so only a user can add content. One of my fields is a user_id FK field. I noticed when it came to updating it populates the user_id input field and asks for a value ( because i put it in my rules) for this.

 

But I was looking into my model and controller and I wasn't sure how you'd go about setting an attribute  through a $_SESSION. I suspect that when I make the login system i'l;l set a $_SESSION['user_type'] and $_SESSION['user_id']  value and then planned to just confirm the existence of these and use them for insert/updating records.

 

But in Yii, I was a bit lost as to how to do this  :wacko:

  • Upvote 1
Link to comment
Share on other sites

Well it's not so much setting the variables.

 

It's how to use them to update/create a record, for instance to controller code for updating is:

 

 
    public function actionUpdate($id)
    {
        $model=$this->loadModel($id);
 
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
 
        if(isset($_POST['Item']))
        {
            $model->attributes=$_POST['Item'];
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }
 
        $this->render('update',array(
            'model'=>$model,
        ));
    }
 

 

But how do you use a value that doesn't come from a form in the updating process?

 

On a total side note. I was so shocked at how little coding was needed to populate a form and update it. Because other than fix a few inputs into select boxes. I. Did. Nothing. This actually stresses me out, like it can't be that easy. Or is that a classic primer to "Yes It Is"?

Link to comment
Share on other sites

Ok,

 

I have been looking at the framework code, it appears that you can do it with  $model->setAttribute('user_id', 1); (I haven't done logging in yet, so that's why I haven't used the $_SESSION vairables). So I just hard coded the user_id           

 

 

 

 
public function actionUpdate($id)
    {
        $model=$this->loadModel($id);
 
        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);
 
        if(isset($_POST['Item']))
        {
            $model->attributes=$_POST['Item'];
            $model->setAttribute('user_id', 1);            
 
            if($model->save())
                $this->redirect(array('view','id'=>$model->id));
        }
 
        $this->render('update',array(
            'model'=>$model,
        ));
    }
Link to comment
Share on other sites

Hello Jonathon, please check out my thread

 

http://www.larryullman.com/forums/index.php?/topic/1491-my-project-diary/page-3  (POST #52)

 

You need to setup a login system, basically by overriding the original login system Yii have started you off with.

 

It means overriding UserIdentity and doing some work in the loginform.php which is in models.

 

You do not need to add user_id to a session as it can be fetched by this:

 

$this->user_id = Yii::app()->user->getId();

 

If you are adding attributes to a model its a simple as this

 

public function actionCreate()
	{
		$uploaded = false;
		// Set the image upload directory
		$imageDirectory = Yii::getPathOfAlias('webroot.images.item');
		// Set the image thumbnail upload directory
		$imageThumbnailDirectory = Yii::getPathOfAlias('webroot.images.item.thumbnail');
		
		// Load models required for item listing form
		$modelItem = new Item('item-listing-form');
		$modelImage = new Image;
		$modelShipping = new Shipping('item-listing-form');
		$modelShippingHasService = new ShippingHasService('item-listing-form');
		$modelLocalPickup = new LocalPickup('item-listing-form');
		$modelReturns = new Returns('item-listing-form');
		
		if(isset($_POST['Item'], $_POST['Image'], $_POST['Image'], $_POST['Shipping'], $_POST['ShippingHasService'], $_POST['LocalPickup'], $_POST['Returns']))
		{
			$modelItem->attributes = $_POST['Item'];
			$modelImage->attributes = $_POST['Image'];
			$imageFile = CUploadedFile::getInstance($modelImage,'image');
			$modelShipping->attributes = $_POST['Shipping'];
			$modelShippingHasService->attributes = $_POST['ShippingHasService'];
			$modelLocalPickup->attributes = $_POST['LocalPickup'];
			$modelReturns->attributes = $_POST['Returns'];
			
			$modelItem->validate();
			$modelImage->validate();
			$modelShipping->validate();
			$modelShippingHasService->validate();
			$modelLocalPickup->validate();
			$modelReturns->validate();

			$transaction = Yii::app()->db->beginTransaction();
			
			if($modelItem->save())
			{
				$modelImage->item_id = $modelItem->id;
				// Save image and also change the name of the image to the item id
				$imageFileName = $modelItem->id;
				$imageFile->saveAs($imageDirectory.DIRECTORY_SEPARATOR.$imageFileName);	
				
				if($modelImage->save())
				{
					$modelShipping->item_id = $modelItem->id;
				
					if($modelShipping->save())
					{
						$modelShippingHasService->shipping_id = $modelShipping->id;
					
						if($modelShippingHasService->save())
						{
							$modelLocalPickup->item_id = $modelItem->id;
						
							if($modelLocalPickup->save())
							{
								$modelReturns->item_id = $modelItem->id;
						
								if($modelReturns->save())	
								{
									$transaction->commit();
									$this->redirect(array('view','id'=>$modelItem->id));			
								}
								else
									$transaction->rollBack(); 
							}
							else
								$transaction->rollBack(); 
						}
						else
							$transaction->rollBack(); 
					}
					else
						$transaction->rollBack(); 
				}
				else
					$transaction->rollBack(); 
			}
			else
				$transaction->rollBack(); 
		}

		$this->render('create',array(
			'modelItem'=>$modelItem, 
			'modelImage'=>$modelImage, 
			'uploaded' => $uploaded, 
			'modelReturns'=>$modelReturns, 
			'modelShipping'=>$modelShipping, 
			'modelShippingHasService'=>$modelShippingHasService, 
			'modelLocalPickup'=>$modelLocalPickup,
		));
	}

Please ignore my image upload stuff now, i have to come back to this later on and do it up with some nice js and php. But this is what i done. Exceptions i was going to add in a little later on i don't to make it too complicated when i am trying to figure things out. There are also about another 8 models i have to add to this form but i just want to get my site following if you know what i mean.

 

I hope this will give you a rough idea of how this works until. This is the best i can do right now until i can see Larry's way of doing this, if he does stuff better i will change all my stuff.

Link to comment
Share on other sites

I really need to fix some classes in my own project. This looks pretty compared to some I my code. That's the bad part about laziness, haha! :D

 

You do some really serious nesting here. Hope you never have to debug that method. I find that the most simple thing to do when introducing exceptions is to twist the logic around. I usually twist it like this:

try {
    if ( ! $modelItem->save() )
    {
       throw new Exception("Huston?..."):
    }
    // More tests....

    // All tests passed. do shit.
    $transaction->commit();
    $this->redirect(array('view','id'=>$modelItem->id));
} catch ( Exception $e)
{
    $transaction->rollback();
}

 

Do you do it similarly, or what's your plan? I enjoy your work log btw.

  • Upvote 1
Link to comment
Share on other sites

Hello gents,

 

It was an interesting read Edward - Thank you.

 

I will take on authentication when Larry's next update comes through. The main thing for me in this was just how you use a Yii session value in an attribute, rather than a user input. So

$model->setAttribute
was a nice little find.  :)
  • Upvote 2
Link to comment
Share on other sites

I really need to fix some classes in my own project. This looks pretty compared to some I my code. That's the bad part about laziness, haha! :D

 

You do some really serious nesting here. Hope you never have to debug that method. I find that the most simple thing to do when introducing exceptions is to twist the logic around. I usually twist it like this:

try {
    if ( ! $modelItem->save() )
    {
       throw new Exception("Huston?..."):
    }
    // More tests....

    // All tests passed. do shit.
    $transaction->commit();
    $this->redirect(array('view','id'=>$modelItem->id));
} catch ( Exception $e)
{
    $transaction->rollback();
}


 

That was the method i doing it i was aware of try and catch and throwing the exceptions. I will be honest with you i am struggling more with the planning for my site than the coding. Its very difficult there being so many database's etc, i always miss stuff out from the tables, then have to come back and redo them, following editing models and editing crud etc. It also difficult to plan out classes at this point, i really need to kind of hard code some stuff to start of with then see what is repeating in each controller/methods etc then pull out the code. The problem is i don't have a second opinion here, and the type of planning i am doing is not the kind of questions to put up on the forum, i know if someone asked what i wanted to ask i would not bother to answer. Its all a bit complicated, but i guess the only way is to take a break for a while like Larry said come back and see if it gets better.

Link to comment
Share on other sites

 Share

×
×
  • Create New...