I'm a Yii and php newbie, I'm trying to make a page based on the default index page (with CListView) generated by Yii tutorial website. The gii generated my model and CRUD w/ controllers and index page has almost 100 pages, and all I want to do is:
to add a textfield and a button to specify a condition to the result by 'controller/index' view.
Eg I want to add a filter 'year' so I added a form just above the CListView:
<?php $this->beginWidget('CActiveForm', array('id'=>'fromid')); ?>
<?php echo CHtml::textField('year');?>
<?php echo CHtml::submitButton('search',array('submit'=>'index.php?r=mycontroller/index')); ?>
<?php $this->endWidget(); ?>
So that by clicking the button it will have a submit action w/ textfield value from id 'year' posted. And I catch the action in controller like this: (in mycontroller)
public function actionIndex()
{
if(isset($_POST['year']))
{
$y = (int)$_POST['year'];
$dataProvider=new CActiveDataProvider('Model',array('criteria'=>array('condition'=>'date='.$y);
$this->render('index',array('dataProvider'=>$dataProvider));
}
else
{
$dataProvider=new CActiveDataProvider('Model');
$this->render('index',array('dataProvider'=>$dataProvider));
}
}
The code above just works fine. I entered a year and clicked button, the age refreshed and result filtered. But the problem is, if the result is being paginated into several pages (like 2 pages), and I click the next page button, the filtered result is gone! , the result went back to the 100 pages again. I'm really out of idea how this is happening.
the Clistview is very simple here I didn't add any extra property:
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
)); ?>
So what's wrong with my code?
You're using $_POST, the $_POST['year']
data is lost when you're navigating to the next page, since you're not posting it to page 2, 3 etc.
You can do two things:
$_POST['year']
in a session, so the next page 'knows' what year it has to use $_POST['year']
use $_GET['year']
. When you navigate to page 2, the $_GET['year']
is available in the url on the next page. The last one is the easiest one i think, and that's how i usually use it.
IF you use the get method, change the CActiveForm line to this:
<?php $this->beginWidget('CActiveForm', array(
'id'=>'fromid',
'method' => 'get'
)); ?>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.