[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1403
  • Last Modified:

Yii framework

Hi,
I have just started to learn about yii framework. I'm having particular difficulty connecting the dots when it comes to models, modules and controllers.

I have managed to create these pages that work:
from ads table
' ads' folder, AdsController.php  
to create a url:    yii.dev/index.php/ads

AND
from agency table
' agency' folder, AgencyController.php
to create a url:    yii.dev/index.php/agency

However, I am confused as to how I can display specified ads and agency records on the home page

i.e. agency and ads records in two separate sections
on this page yii.dev/index.php

Before in basic php I would include files  ie. include('agency.php');  include('ads.php');

Basically how can I add two (or more) separate table displays on one page.

Hope that is clear.

Thanks
0
mmguide
Asked:
mmguide
  • 7
  • 6
1 Solution
 
ansudhindraCommented:
I think in your default controller for (index.php) in the default action (or whatever you name it) you have create objects of the models and then use it. below is one example
public function actionHome(){
$ads = new Ads;
$dataProvider1 = $ads->getHomePageList();

$agnecy = new Agency;
$dataProvider2 = $agency->getHomePageList();
			
$this->render('home',array(
'agency'=>$dataProvider2,
'ads'=>$dataProvider1,
));
}

Open in new window

where Ads, and Agnecy are the models in the model folder corresponding to a particular table(s).
and in the view page you will have 2 seperate arrays one for ads and another for agency. You can use foreach loop over these arrays to display it in the view file.
0
 
mmguideAuthor Commented:
Thanks. Though I'm a little confused about  the getHomePageList();

If my home page is 'index' instead of 'home' should this change as well.

Currently I get errors.

Sorry if this may seem obvious but I'm still struggling with the through logic of yii
0
 
ansudhindraCommented:
getHomePageList is the function which returns data from database. This function should be implemented in the model.
in the code you are instantiating the model and then calling the function.

Your home page may be the index, but what the action you specify?
if you specify as "index" then you should rename the function in the controller class as
public class actionIndex()

and $this->render('home'... 'home' here is the name of the view file in the view (view directory), if you have index.php in the view directory, then it should be render('index'..
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
mmguideAuthor Commented:
Ok so
getHomePageList() should be a function in both models:    Ads.php  and  Agency.php ?


Could you give an example what the model should look like because I have this for Ads.php :

class Ads extends CActiveRecord
{
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Ads 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 'ads';
	}

	/**
	 * @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(
			//database array
),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array(
//database array 
),
		);
	}

	/**
	 * @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(
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			//labels array
		);
	}

	/**
	 * 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.

		$criteria=new CDbCriteria;

		$criteria->compare('ID',$this->ID);
		$criteria->compare('memID',$this->memID);
		//etc...

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
}

Open in new window

0
 
ansudhindraCommented:
Model class is the one which actually represents your database table as a class (ORM) (in simple terms), it can contain business logic as well.

in the rules() function you have to declare the table columns with their type, whether they are required or optional, which format user input should be.

Attribute labels function is to define the names for the columns to display in the forms.

below is the code form one of my proj. class called Bills that has 7 columns.

<?php
	class Bills extends CActiveRecord{
		
		public static function model($className=__CLASS__){
			return parent::model($className);
		}
		
		public function tableName(){
			return 't_bills';
		}
		
		public function rules(){
			// NOTE: you should only define rules for those attributes that
			// will receive user inputs.
			return array(
				array('billDate, billType, isPaid', 'required'),
				array('billDate, payByDate', 'type', 'type' => 'date', 'message' => '{attribute}: is not a date!', 'dateFormat' => 'yyyy-MM-dd'),
				// The following rule is used by search().
				// Please remove those attributes that should not be searched.
				array('id, billDate, payByDate, billType, billAmount, isPaid, comments', 'safe', 'on'=>'search'),
			);
		}
		
		public function attributeLabels(){
			return array(
				'id' => 'ID',
				'billDate' => 'Bill Date',
				'billType' => 'Bill Type',
				'billAmount' => 'Bill Amount',
				'payByDate' => 'Pay By Date',
				'isPaid' => 'Is Paid?',
				'comments' => 'Comments',
			);
		}
		
		public function search(){
			// Warning: Please modify the following code to remove attributes that
			// should not be searched.
	
			$criteria=new CDbCriteria;
	
			$criteria->compare('id',$this->id);
			$criteria->compare('billDate',$this->billDate,true);
			$criteria->compare('billType',$this->billType,true);
			$criteria->compare('billAmount',$this->billAmount,true);
			$criteria->compare('isPaid',$this->isPaid,true);
			$criteria->compare('comments',$this->comments,true);
				
			return new CActiveDataProvider($this, array(
				'criteria'=>$criteria,
			));
		}
		
		public function relations(){
	        return array(
	        
	        );
	    }
	    
	    public function beforeSave(){
			return parent::beforeSave();
		}
		
		public function getHomePageList(){
    		$sql = "select q.d, d.description" .
					" from (" .
						" select curdate() d" .
						" union" .
						" select date_sub(curdate(), INTERVAL 1 DAY) d" .
						" union" .
						" select date_sub(curdate(), INTERVAL 2 DAY) d" .
						/*" union" .
						" select date_sub(curdate(), INTERVAL 3 DAY) d" .
						" union" .
						" select date_sub(curdate(), INTERVAL 4 DAY) d" .*/
					" ) q left join t_diary d on d.diarydate = q.d";
			$sql = Yii::app()->db->createCommand($sql)->queryAll();
			return $sql;
		}
		
		public function getAccountDDValues(){
			//logic here
		}
	}
?>

Open in new window

0
 
mmguideAuthor Commented:
Thanks. I think I have managed to get the search going by calling search() from the models (is this correct?)
 but outputting doesn't work.

foreach ($dataProvider1 as $key => $value) { echo $value;}

Undefined variable: dataProvider1


Could you clarify this please.
0
 
ansudhindraCommented:
its in the view right?

if you copied my code (in the first post), then it should be
for ads
foreach($ads as $key => $value) { echo $value["column_name"]; }
and for agency
foreach($agency as $key => $value) { echo $value["column_name"]; }


column_name is the name of the column you specified in the select query in the getHomePageList() function (from model class).
0
 
mmguideAuthor Commented:
Ok, I have used your method from the example but still have an issue with output. Do you have example of this?  Your help is much appreciated.
0
 
ansudhindraCommented:
I dont have it live...  may be if you have send me the link.. we will sort it out.
0
 
ansudhindraCommented:
what error you are getting? post the code as zip file so that i can help you..
0
 
mmguideAuthor Commented:
Just wondered how you outputted the $dataprovider1.

I tried
foreach ($dataProvider1 as $key => $value) { echo $value;}

but the error was:
Undefined variable: dataProvider1

yii-1.1.12/htdocs/protected/views/site/index.php(12)

01
02 <?php
03 /* @var $this SiteController */
04
05 //$this->pageTitle=Yii::app()->name;
06 ?>
07
08 <h1><i><?php echo CHtml::encode(Yii::app()->name); ?></i></h1>
09
10 <?php
11
12 foreach ($dataProvider2 as $key => $value) { echo $value;}
13 /*$this->widget('zii.widgets.CListView', array(
14     'dataProvider1'=>$dataProvider1,
15     'itemView'=>'_view',
16 ));*/
17 ?>
18 <p>You have successfully created your Yii application.</p>
19
20 <p>You may change the content of this page by modifying the following two files:</p>
21 <ul>
22     <li>View file: <code><?php echo __FILE__; ?></code></li>
23     <li>Layout file: <code><?php echo $this->getLayoutFile('main'); ?></code></li>
24 </ul>

Stack Trace
#0       
+
 /yii-1.1.12/framework/web/CBaseController.php(127): require("/yii-1.1.12/htdocs/protected/views/site/...")
#1       
+
 /yii-1.1.12/framework/web/CBaseController.php(96): CBaseController->renderInternal("/yii-1.1.12/htdocs/protected/views/site/...", array("agency" => array(array("aID" => "3"), array("aID" => "4"), array("aID" => "5"), array("aID" => "6"), ...), "ads" => array(array("ID" => "9"), array("ID" => "10"), array("ID" => "13"), array("ID" => "14"), ...)), true)
#2       
+
/yii-1.1.12/framework/web/CController.php(870): CBaseController->renderFile("/Users/yii-1.1.12/htdocs/protected/views/site/...", array("agency" => array(array("aID" => "3"), array("aID" => "4"), array("aID" => "5"), array("aID" => "6"), ...), "ads" => array(array("ID" => "9"), array("ID" => "10"), array("ID" => "13"), array("ID" => "14"), ...)), true)
#3       
+
 /yii-1.1.12/framework/web/CController.php(783): CController->renderPartial("index", array("agency" => array(array("aID" => "3"), array("aID" => "4"), array("aID" => "5"), array("aID" => "6"), ...), "ads" => array(array("ID" => "9"), array("ID" => "10"), array("ID" => "13"), array("ID" => "14"), ...)), true)
#4       

/yii-1.1.12/htdocs/protected/controllers/SiteController.php(44): CController->render("index", array("agency" => array(array("aID" => "3"), array("aID" => "4"), array("aID" => "5"), array("aID" => "6"), ...), "ads" => array(array("ID" => "9"), array("ID" => "10"), array("ID" => "13"), array("ID" => "14"), ...)))

39         $dataProvider2 = $agency->getHomePageList();;
40                    
41         $this->render('index',array(
42         'agency'=>$dataProvider2,
43         'ads'=>$dataProvider1,
44         ));
45     }
46                                            
47
48     /**
49      * This is the action to handle external exceptions.

#5       
+
 /yii-1.1.12/framework/web/actions/CInlineAction.php(50): SiteController->actionIndex()
#6       
+
/yii-1.1.12/framework/web/CController.php(309): CInlineAction->runWithParams(array())
#7       
+
/yii-1.1.12/framework/web/CController.php(287): CController->runAction(CInlineAction)
#8       
+
/yii-1.1.12/framework/web/CController.php(266): CController->runActionWithFilters(CInlineAction, array())
#9       
+
/yii-1.1.12/framework/web/CWebApplication.php(283): CController->run("")
#10       
+
/yii-1.1.12/framework/web/CWebApplication.php(142): CWebApplication->runController("")
#11       
+
 /yii-1.1.12/framework/base/CApplication.php(162): CWebApplication->processRequest()
#12       

 /yii-1.1.12/htdocs/index.php(13): CApplication->run()

08 defined('YII_DEBUG') or define('YII_DEBUG',true);
09 // specify how many levels of call stack should be shown in each log message
10 defined('YII_TRACE_LEVEL') or define('YII_TRACE_LEVEL',3);
11
12 require_once($yii);
13 Yii::createWebApplication($config)->run();
0
 
ansudhindraCommented:
as earlier said,..

replace line number 12 which says
foreach ($dataProvider2 as $key => $value) { echo $value;}

with the below line
foreach ($agency as $key => $value) { echo $value['column_name'];}

Note: $dataprovide2 is the variable in controller but when it invokes the view it passes this as agency variable (whatever you specify in the left side in the assignment operator). In your case view has two array variable with the name "$ads" and "$agency" and not "$dataprovider1" and "$dataprocider2".
0
 
mmguideAuthor Commented:
Apologies for my stupidity. Thank you very much for your patience.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 7
  • 6
Tackle projects and never again get stuck behind a technical roadblock.
Join Now