CActiveProvider and model

How to get the model by CActiveProvider?

i have this in CGridView :


'footer' =>$encomendaLinhasProvider->model()->renderTableFooter()

but i get:

CActiveDataProvider and its behaviors do not have a method or closure named "model".

As far as I know, CDataProvider is meant to fetch data from ActiveRecords.

It uses ActiveRecord::findAll method for this purpose.

It can not invoke ActiveRecord::model() method in an instance of CDataProvider.

Where you have declared the method renderTableFooter?

In the model.

Well check here the reference to model() property CACtiveDataProvider

It is not static method model() as declared in ActiveRecord.

It is an instance of AR added as a property to CActiveDataProvider.

If $dataProvider is an instance of CActiveDataProvider,

It can be used in the following way,




//someMethod is method declared in in your AR class.

$dataProvider->model->someMethod();


$dataProvider->model->findByPk(1)



In your case, the following may work.




'footer' =>$encomendaLinhasProvider->model->renderTableFooter()



thank you


$this->widget('zii.widgets.grid.CGridView', array(

    'id' => 'encomenda-linha',

    'dataProvider' => $encomendaLinhasProvider,

    'htmlOptions' => array('style' => 'padding:0'),

    'columns' => array('ritmo.artist',

        'ritmo.title',

        array(

            'header' => Yii::t('app', 'Price'),

            'name' => 'ritmo.price',

            'htmlOptions' => array('style' => 'width:10px;'),

            'value' => '$data->ritmo->price." €"'

        ),

        array(

            'class' => 'CButtonColumn',

            'template' => '{delete}',

            'buttons' => array(

                'delete' => array(

                    

                    'url' => 'Yii::app()->createUrl("encomenda/deletelinha",array("id"=>$data->idencomenda_linha))',

                    'imageUrl' => Yii::app()->request->baseUrl . '/images/cross.png',

                    

            )),

            'deleteConfirmation'=>Yii::t('app','Are you sure you want to delete the style?'),

        ),

		array(

            'header' => Yii::t('app', 'Totals'),

            'name' => 'ritmo.price',

			'type'=>'raw',

            'footer' =>$encomendaLinhasProvider->model->renderTableFooter()

        ),


    )

));

Now i need to pass a parameter to the function renderTableFooter that is a value column of the CGridView.How to do that?

Dear ZipZap,

I really struggle to comprehend what you are intending.

(It seems that it is highly professional stuff).

I think you want to put something like lowest price or highest price of whole lot items.

If you pass $data as parameter to the renderTableFooter method, you may work on

individual row or object.

If you pass $encomendaLinhasProvider as a parameter, you may get all the instances.




//inside the active record.

public function renderTableFooter($dataProvider)

{

  $datas=$dataProvider->getData();

  foreach($datas as $data)

   {

     //do something on $data;

   }

    

}



encomenda is the purchase model and encomendalinha the purchase product lines.What i am trying to do is is to display the total amount of the purchase in the footer that i have in the encomenda model.To do that i have this function in encomendalinha model:


public function renderTableFooter($total){

               

		echo "<div style=\"float:right;\"><table style=\"background-color: #5E747B;\"><tr><td>";

		echo $total;

		echo "</td>        

        </tr>

        <tr>

            <td>";

		echo "<td><?php echo Yii::t('app', 'PayPal Fee (if aplicable) :') ?></td>

            <td style=\"text-align: right;\">";

		echo number_format($total+($total* 3.4 / 100) + 0.35, 2, ',', ' ') . " €";

		echo "</td>        

        </tr>


			</table>

		</div>";

		

    }

Now and following your advice i pass the totalValue that is a attribute of the encomenda model but i get the string and not the value in the function:


'footer' =>$encomendaLinhasProvider->model->renderTableFooter('$data->enc->totalValue')

My advice is to remove the quotes.

It should be like




'footer' =>$encomendaLinhasProvider->model->renderTableFooter($data->enc->totalValue);



If you still find problem, try the following.




public function renderTableFooter($data){


                $total=$data->enc->totalValue;

                echo "<div style=\"float:right;\"><table style=\"background-color: #5E747B;\"><tr><td>";

                echo $total;

                echo "</td>        

        </tr>

        <tr>

            <td>";

                echo "<td><?php echo Yii::t('app', 'PayPal Fee (if aplicable) :') ?></td>

            <td style=\"text-align: right;\">";

                echo number_format($total+($total* 3.4 / 100) + 0.35, 2, ',', ' ') . " €";

                echo "</td>        

        </tr>


                        </table>

                </div>";

                

    }



Now call the method.




'footer' =>$encomendaLinhasProvider->model->renderTableFooter($data);



Undefined variable: data

zipzap buddy can you do gist for your controller, model, and view


<?php


/**

 * This is the model class for table "encomenda_linha".

 *

 * The followings are the available columns in table 'encomenda_linha':

 * @property integer $idencomenda_linha

 * @property integer $style

 * @property integer $encomenda

 *

 * The followings are the available model relations:

 * @property Encomenda $encomenda0

 * @property Ritmo $style0

 */

class EncomendaLinha extends CActiveRecord

{

    public $artist;	//why do you have to declare this two attribute if these are declared on

    public $title;      // relation 'ritmo' 

	/**

	 * Returns the static model of the specified AR class.

	 * @param string $className active record class name.

	 * @return EncomendaLinha the static model class

	 */

	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}


	/**

	 * @return string the associated database table name

	 */

	public function tableName()

	{

		return 'encomenda_linha';

	}


	/**

	 * @return array validation rules for model attributes.

	 */

	public function rules()

	{

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

		// will receive user inputs.

		return array(

			array('encomenda', 'required'),

			array('style, encomenda', 'numerical', 'integerOnly'=>true),

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

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

			array('idencomenda_linha, style, encomenda,artist,title', 'safe', 'on'=>'search'),

		);

	}


	/**

	 * @return array relational rules.

	 */

	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

			'enc' => array(self::BELONGS_TO, 'Encomenda', 'encomenda'),

			'ritmo' => array(self::BELONGS_TO, 'Ritmo', 'style'),

		);

	}

        

        public function afterDelete(){

            Yii::import('application.modules.admin.models.*');

            parent::afterDelete();

            $enc=Encomenda::model()->findByPk($this->encomenda);

            if ($enc->quantity==1){

                $enc->delete();

            }

            else

            {

            $enc->quantity--;

            $enc->totalValue=$enc->totalValue-$this->ritmo->price;

            $enc->save();

            }

        }


	/**

	 * @return array customized attribute labels (name=>label)

	 */

	public function attributeLabels()

	{

		return array(

			'idencomenda_linha' => 'Idencomenda Linha',

			'style' => Yii::t('app','Style'),

			'encomenda' => 'Encomenda',

		);

	}


	/**

	 * Retrieves a list of models based on the current search/filter conditions.

	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.

	 */

	public function search()

	{

		// Warning: Please modify the following code to remove attributes that

		// should not be searched.

                Yii::import('application.modules.admin.models.*');

		$criteria=new CDbCriteria;

                $criteria->with = array( 'encomenda','ritmo' );	

		$criteria->compare('idencomenda_linha',$this->idencomenda_linha);

		$criteria->compare('style',$this->style);

		$criteria->compare('encomenda',$this->encomenda);

                $criteria->compare('ritmo.artist',$this->artist,true);   

		$criteria->compare('ritmo.title',$this->title,true);

                

		return new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

		));

	}

	

	public function renderTableFooter($total){

               

		echo "<div style=\"float:right;\"><table style=\"background-color: #5E747B;\"><tr><td>";

		echo $total;

		echo "</td>        

        </tr>

        <tr>

            <td>";

		echo "<td><?php echo Yii::t('app', 'PayPal Fee (if aplicable) :') ?></td>

            <td style=\"text-align: right;\">";

		echo number_format($total+($total* 3.4 / 100) + 0.35, 2, ',', ' ') . " €";

		echo "</td>        

        </tr>


			</table>

		</div>";

		

    }

        

        

}


<?php


class EncomendaController extends Controller

{

	/**

	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning

	 * using two-column layout. See 'protected/views/layouts/column2.php'.

	 */

	public $layout='//layouts/column2';


	/**

	 * @return array action filters

	 */

	public function filters()

	{

		return array(

			'accessControl', // perform access control for CRUD operations

		);

	}

        

         private function preencheCarrinho(){

            $encomendaLinhasProvider = new CActiveDataProvider('EncomendaLinha', array(

                    'criteria' => array(

                        'condition' => 'encomenda=:encomenda',

                        'params' => array(':encomenda' => $_SESSION['encomenda']),

                       

                    ),

                    'pagination' => array(

                        'pageSize' => 10,

                    ),

                ));

            

            return $encomendaLinhasProvider;

        }

       

        public function init() {

        $app = Yii::app();

        if (isset($app->session['lg'])) {

                $app->language = $app->session['lg'];

        }

}





	/**

	 * Specifies the access control rules.

	 * This method is used by the 'accessControl' filter.

	 * @return array access control rules

	 */

	public function accessRules()

	{

		return array(

			

			array('allow', 

				'actions'=>array('admin','create','update','index','delete','language','view'),

				'users'=>array('admin'),

			),

                    

            array('allow', 

				'actions'=>array('deletelinha','index'),

				'users'=>array('@'),

			),

			

			array('deny',  // deny all users

				'users'=>array('*'),

			),

		);

	}


	/**

	 * Displays a particular model.

	 * @param integer $id the ID of the model to be displayed

	 */

	public function actionView($id)

	{

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

			'model'=>$this->loadEncomendaLinha($id),

		));

	}


	/**

	 * Creates a new model.

	 * If creation is successful, the browser will be redirected to the 'view' page.

	 */

	public function actionCreate()

	{

		$model=new Encomenda;

                  


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

		{

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

			if($model->save())

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

		}


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

			'model'=>$model,

		));

	}


	

	/**

	 * Deletes a particular model.

	 * If deletion is successful, the browser will be redirected to the 'admin' page.

	 * @param integer $id the ID of the model to be deleted

	 */

	public function actionDelete($id)

	{

		if(Yii::app()->request->isPostRequest)

		{

			// we only allow deletion via POST request

			$this->loadModel($id)->delete();

                        

                        


			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser

			if(!isset($_GET['ajax']))

                        {

                           $this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : 

                                    array('admin'));

		 

                        }

				}

		else

			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

	}

        

        public function actionDeleteLinha($id)

	{

		if(Yii::app()->request->isPostRequest)

		{

			// we only allow deletion via POST request

			$enclinha=EncomendaLinha::model()->findByPk($id);

                    

                       $enclinha->delete();

                       

		       $this->renderPartial('_carrinho',array('encomendaLinhasProvider'=>$this->preencheCarrinho()));

		}

		else

			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');

	}


        public function actionLanguage() {

        $app = Yii::app();

        if (isset($_GET['lg'])) {

                $app->session['lg'] = $_GET['lg'];

        }

        $this->redirect('admin');

}

       

	/**

	 * Lists all models.

	 */

	public function actionIndex()

	{

		if (!isset(Yii::app()->session['encomenda']))

                {

                    $this->redirect(Yii::app()->homeUrl);

                }

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

			

                        'encomendaLinhasProvider'=>$this->preencheCarrinho()

		));

	}


	/**

	 * Manages all models.

	 */

	public function actionAdmin()

	{

		$model=new Encomenda('search');

		$model->unsetAttributes();  // clear any default values

		if(isset($_GET['Encomenda']))

			$model->attributes=$_GET['Encomenda'];


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

			'model'=>$model,

		));

	}


	/**

	 * Returns the data model based on the primary key given in the GET variable.

	 * If the data model is not found, an HTTP exception will be raised.

	 * @param integer the ID of the model to be loaded

	 */

	public function loadModel($id)

	{

		$model=Encomenda::model()->findByPk($id);

		if($model===null)

			throw new CHttpException(404,'The requested page does not exist.');

		return $model;

	}

        

        public function loadEncomendaLinha($id)

	{

                

		$model=EncomendaLinha::model()->findByAttributes(array('encomenda'=>$id));

		if($model===null)

			throw new CHttpException(404,'The requested page does not exist.');

		return $model;

	}


	/**

	 * Performs the AJAX validation.

	 * @param CModel the model to be validated

	 */

	protected function performAjaxValidation($model)

	{

		if(isset($_POST['ajax']) && $_POST['ajax']==='encomenda-form')

		{

			echo CActiveForm::validate($model);

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

		}

	}

        

        

}




<?php


/**

 * This is the model class for table "encomenda".

 *

 * The followings are the available columns in table 'encomenda':

 * @property integer $idencomenda

 * @property string $createDate

 * @property string $totalValue

 * @property integer $customer

 * @property string $quantity

 * @property integer $confirmed

 * @property integer $confirmed

 *

 * The followings are the available model relations:

 * @property User $cliente

 * @property EncomendaLinha[] $encomendaLinhas

 */

class Encomenda extends CActiveRecord

{

   


	/**

	 * Returns the static model of the specified AR class.

	 * @param string $className active record class name.

	 * @return Encomenda the static model class

	 */

	public static function model($className=__CLASS__)

	{

		return parent::model($className);

	}


	/**

	 * @return string the associated database table name

	 */

	public function tableName()

	{

		return 'encomenda';

	}


	/**

	 * @return array validation rules for model attributes.

	 */

	public function rules()

	{

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

		// will receive user inputs.

		return array(

			array('quantity', 'required'),

			array('customer, confirmed', 'numerical', 'integerOnly'=>true),

			array('totalValue, quantity', 'length', 'max'=>10),

			array('createDate', 'safe'),

			array('idencomenda, createDate, totalValue, 

                            quantity, confirmed,paid,nome', 'safe', 'on'=>'search'),

		);

	}


	/**

	 * @return array relational rules.

	 */

	public function relations()

	{

		// NOTE: you may need to adjust the relation name and the related

		// class name for the relations automatically generated below.

		return array(

			'cliente' => array(self::BELONGS_TO, 'User', 'customer'),

			'encomendaLinhas' => array(self::HAS_MANY, 'EncomendaLinha', 'encomenda'),

		);

	}


	/**

	 * @return array customized attribute labels (name=>label)

	 */

	public function attributeLabels()

	{

		return array(

			'idencomenda' => Yii::t('app','Idencomenda'),

			'createDate' => Yii::t('app','Create Date'),

			'totalValue' => Yii::t('app','Total Value'),

			'customer' => Yii::t('app','Customer'),

			'quantity' => Yii::t('app','Quantity'),

			'confirmed' => Yii::t('app','Confirmed'),

                        'paid' => Yii::t('app','Paid'),

		);

	}

        

        public function afterDelete(){

            parent::afterDelete();

            Yii::app()->session->add('encomenda', null);

        }


	/**

	 * Retrieves a list of models based on the current search/filter conditions.

	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.

	 */

	public function search()

	{

		// Warning: Please modify the following code to remove attributes that

		// should not be searched.

                Yii::import('application.modules.admin.models.*');

		$criteria=new CDbCriteria;

                $alias = $this->getTableAlias(true);

                $criteria->with=array('cliente');

		$criteria->compare('idencomenda',$this->idencomenda);

		$criteria->compare($alias.'.createDate',$this->createDate,true);

		$criteria->compare('totalValue',$this->totalValue,true);

		$criteria->compare('quantity',$this->quantity,true);

                $criteria->compare('cliente',$this->cliente,true);

                $criteria->order=$alias.'.createDate DESC';

		return new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

		));

	}

}

index view


<h1><?php echo Yii::t('app', 'Shopping Cart'); ?></h1>

<div style="height:60px;">

    <div style="width: 230px; float: left;">

        <h3><?php

echo CHtml::link(CHtml::image(Yii::app()->request->baseUrl . '/images/previous.png'), Yii::app()->createUrl('site/index'));

echo ' ' . Yii::t('app', 'Continue Choosing...');

?></h3></div>

    <div style="width:230px;float:right;text-align: end;">

        <h3>

<?php

    echo Yii::t('app', 'CheckOut') . ' ';

    echo CHtml::link(CHtml::image(Yii::app()->request->baseUrl . '/images/cart.png', 'cart', array('width' => '24px', 'height' => '24px')), Yii::app()->createUrl('site/finalizar'));

?>

        </h3>

    </div>

</div>

<br>

<?php

$this->renderPartial('_carrinho', 

        array('encomendaLinhasProvider' => $encomendaLinhasProvider));

?>

<br>




<h4><?php echo Yii::t('app', 'Information about the payment') ?></h4>

<p><?php echo Yii::t('app', 'After Checkout, you must choose the method of payment that are available:') ?></p>

<p><?php echo Yii::t('app', '1-If you are in Portugal, you can choose Bank Transfer,please use this NIB :0010 0000 44384560001 53') ?><br>

    <?php echo Yii::t('app', '2-Other countries please use this paypal account: zipzapduo@gmail.com (with this option you have to pay the aditional paypal fees)') ?></p>

carrinho partial view


<script type="text/javascript">

    $(function(){

      

        $('.summary').remove();

    });

</script>

<?php

Yii::import('application.modules.admin.models.Ritmo');


$this->widget('zii.widgets.grid.CGridView', array(

    'id' => 'encomenda-linha',

    'dataProvider' => $encomendaLinhasProvider,

    'htmlOptions' => array('style' => 'padding:0'),

    'columns' => array('ritmo.artist',

        'ritmo.title',

        array(

            'header' => Yii::t('app', 'Price'),

            'name' => 'ritmo.price',

            'htmlOptions' => array('style' => 'width:10px;'),

            'value' => '$data->ritmo->price." €"'

        ),

        array(

            'class' => 'CButtonColumn',

            'template' => '{delete}',

            'buttons' => array(

                'delete' => array(

                    

                    'url' => 'Yii::app()->createUrl("encomenda/deletelinha",array("id"=>$data->idencomenda_linha))',

                    'imageUrl' => Yii::app()->request->baseUrl . '/images/cross.png',

                    

            )),

            'deleteConfirmation'=>Yii::t('app','Are you sure you want to delete the style?'),

        ),

		array(

            'header' => Yii::t('app', 'Totals'),

            'name' => 'ritmo.price',

			'type'=>'raw',

            'footer' =>$encomendaLinhasProvider->model->renderTableFooter($data->enc->totalValue)

        ),


    )

));





?>




Sorry friend,

Running out of options.

Try the following,




//SINGLE QUOTE THE ARRAY VALUE.$data may be passed to the function.

//MODIFY THE METHOD ACCORDINGLY


'footer' =>'$encomendaLinhasProvider->model->renderTableFooter($data->enc->totalValue)';


//OR


'footer' =>'$encomendaLinhasProvider->model->renderTableFooter($data)';




If nothing works…

Forget about the method renderTableFooter or pass the contents inside the method as

a string with single quotes and proper escaping.