Call To A Member Function Saveas() On A Non-Object

Hi All

This is my Controller content upload file function :




public function actionCreate()

	{

		$model=new Articles;


		// Uncomment the following line if AJAX validation is needed

		// $this->performAjaxValidation($model);


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

		{

			

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

            

           $model->user_id=Yii::app()->user->id;

           $model->active=0;

           

		   

            $model->image=CUploadedFile::getInstance($model,'image'); 

       

       

       /// create new image name 

            $newname = rand(1,987699) . '-' . $model->image;


            

            $model->image=$newname;

            

        ///    

        	if($model->save())

                $model->image->saveAs('postimages/'.$model->image);

				$this->redirect(array('view','id'=>$model->article_id));

		}


		$this->render('create',array(

			'model'=>$model,

		));

	}




Error message :





Fatal error: Call to a member function saveAs() on a non-object in H:\xampp\htdocs\cms\protected\controllers\ArticleController.php on line 93




thanks in advance

You have dropped the image object by this line:


            $model->image=$newname;

So $model->image is just a string now. You have to use two different attributes, image and imagePath for instance

Edit: or like this




    //$newname = rand(1,987699) . '-' . $model->image;


    //$model->image=$newname;

            

    if($model->save())

        $model->image->saveAs('postimages/'.rand(1,987699) . '-' .$model->image);

Thank you Mr. bennouna but file not upload now :(




	if($model->save())

                $model->image->saveAs('postimages/'.rand(1,987699). '-' .$model->image);

				$this->redirect(array('view','id'=>$model->article_id));

		}



Well you have to specify full path (real absolute path, not relative one, and not url) to your image folder. So it should be something like


$model->image->saveAs('/real/path/to/postimages/'.rand(1,987699). '-' .$model->image);

Mr.bennouna

I’ts work but i need to insert the image name into database before save()

So I used :

[b] $model->image=$newname;

[/b]

So how I can fix it ?

Thanks in advance .

Use another attribute different from ‘image’ as your upload field?

Thank you so much MR. bennouna to help me .

I’m having the same problem!


  public function actionCreate() {

        $model = new Comida;

        $comidaAdicionais = array();

        $comidaSabor = array();

        $imagemcomida = new ImagemComida();

        

        if (isset($_POST['Comida'],$_POST['ImagemComida'])) {

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

            $imagemcomida->attributes = $_POST['ImagemComida'];

            

            if ($model->save()) {

                $imagemcomida->id_comida = $model->id;

                if (!is_array(@$_POST['ComidaSabor']['id_sabor'])) {

                    $_POST['ComidaSabor']['id_sabor'] = array();

                }


                $comidaSabor = $_POST['ComidaSabor']['id_sabor'];


                foreach ($comidaSabor as $id_sa) {

                    $modelRelacao = new ComidaSabor;

                    $modelRelacao->id_comida = $model->id;

                    $modelRelacao->id_sabor = $id_sa;

                    $modelRelacao->save();

                }


                if (!is_array(@$_POST['ComidaAdicionais']['id_adicional'])) {

                    $_POST['ComidaAdicionais']['id_adicional'] = array();

                }


                $comidaAdicionais = $_POST['ComidaAdicionais']['id_adicional'];


                foreach ($comidaAdicionais as $id_ad) {

                    $modelRelacao = new ComidaAdicionais;

                    $modelRelacao->id_comida = $model->id;

                    $modelRelacao->id_adicional = $id_ad;

                    $modelRelacao->save();

                }

                    $rnd = rand(0, 9999);  // generate random number between 0-9999

                    

                    $uploadedFile = CUploadedFile::getInstance($imagemcomida, 'imagem');

                    $fileName = "{$rnd}-{$uploadedFile}";  // random number + file name

                    $imagemcomida->imagem = $fileName;

                    

                   

                    if ($imagemcomida->save()) {

                        if (is_dir(Yii::app()->basePath . '/../images/comida/' . Yii::app()->user->id)) {

                            $uploadedFile->saveAs(Yii::app()->basePath . '/../images/comida/' . Yii::app()->user->id . '/' . $fileName);  // image will uplode to rootDirectory/banner/

                        } else {

                            mkdir(Yii::app()->basePath . '/../images/comida/' . Yii::app()->user->id, 0700);

                            $uploadedFile->saveAs(Yii::app()->basePath . '/../images/comida/' . Yii::app()->user->id . '/' . $fileName);  // image will uplode to rootDirectory/banner/

                        }

                    } else {

                        $this->redirect(array('index'));

                    }

                } 

                


                $this->redirect(array('view', 'id' => $model->id));

            } else {

                //erro ao salvar no banco

            }

        


        $this->render('create', array(

            'model' => $model, 'comidaSabor' => $comidaSabor, 'comidaAdicionais' => $comidaAdicionais, 'imagemcomida' => $imagemcomida

        ));

    } 

I have a table with 3 variables, id, id_comida, image and the image name referring to. this saving in the database but not this saving in the correct folder!

problem solved, only missed by $ filename, true);

same problem here, I have just add this line in my cactive-form

‘htmlOptions’=>array(‘enctype’=>‘multipart/form-data’),

Hi You can also try this

for e.g


if(($_FILES['Coupon']['name']['image']==''))

				{

					Yii::app()->user->setFlash('error', Yii::t("messages","Please Upload a One of Them Images"));

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

					Yii::app()->end();

				}else{

					$path	= 	YiiBase::getPathOfAlias('webroot');

					$url ='http://'.$_SERVER['HTTP_HOST']. Yii::app()->baseUrl;

					$model->image=$_FILES['Coupon']['name']['image'];

					$model->image = CUploadedFile::getInstance($model, 'image');

					$model->image->saveAs($path.'/upload/coupon/'.$model->image);

					$image_path=$url.'/upload/coupon/'.$model->image;

					$model->image_url=$image_path;


				}

I have same Problem…

My view part is :

<div class="row">

	&lt;?php echo &#036;form-&gt;labelEx(&#036;model,'product_picture'); ?&gt;


	&lt;?php echo CHtml::activeFileField(&#036;model,'product_picture'); ?&gt;


	&lt;?php echo &#036;form-&gt;error(&#036;model,'product_picture'); ?&gt;


&lt;/div&gt; 

My Model part is :

public function rules()

{


	// NOTE: you should only define rules for those attributes that


	// will receive user inputs.


	return array(


		array('product_name, product_category, product_picture, product_buy_rate, product_sale_rate, product_description, product_stock_status, product_avail_stock', 'required'),


		array('product_buy_rate, product_sale_rate, product_avail_stock', 'numerical', 'integerOnly'=&gt;true),


		array('product_name', 'length', 'max'=&gt;30),


		[size=&quot;5&quot;][b]array('product_picture', 'file', 'types'=&gt;'jpg, gif, png', 'allowEmpty' =&gt; true,),[/b][/size]


		array('product_category ','length', 'max'=&gt;100),


		array('product_description', 'length', 'max'=&gt;300),


		array('product_stock_status', 'length', 'max'=&gt;10),


		// The following rule is used by search().


		// @todo Please remove those attributes that should not be searched.


		array('product_id, product_name, product_category, product_picture, product_buy_rate, product_sale_rate, product_description, product_stock_status, product_avail_stock', 'safe', 'on'=&gt;'search'),


	);


}

[u]

My Controller part is :[/u]

public function actionCreate()


{


	&#036;model=new Product;





	// Uncomment the following line if AJAX validation is needed


	// &#036;this-&gt;performAjaxValidation(&#036;model);





	if(isset(&#036;_POST['Product']))


	{


		&#036;model-&gt;attributes=&#036;_POST['Product'];





		//&#036;rnd = rand(0,9999);


		&#036;uploadedFile = CUploadedFile::getInstance(&#036;model,'product_picture');


        &#036;fileName =date(time()). '-' . &#036;model-&gt;product_picture;


        &#036;model-&gt;product_picture = &#036;fileName;


		if(&#036;model-&gt;save()){


		    &#036;uploadpath = Yii::app()-&gt;theme-&gt;basePath.'/adminpanel/Upload/'.&#036;fileName;


		    &#036;uploadedFile-&gt;saveAs(&#036;uploadpath);


			&#036;this-&gt;redirect(array('view','id'=&gt;&#036;model-&gt;product_id));


			}


	}





	&#036;this-&gt;render('create',array(


		'model'=&gt;&#036;model,


	));


}

I goe some error :

fatal error call to a member function save as() on a non-object

Plz help