How to save the search results of a model into another model ?
I have this at the view file
<?php
Yii::app()->clientScript->registerScript('search', "
$('.search-button').click(function(){
$('.search-form').toggle();
return false;
});
$('.search-form form').submit(function(){
$.fn.yiiGridView.update('wsrecruitcvhead-grid', {
data: $(this).serialize()
});
return false;
});
");
?>
<?php echo CHtml::link('Advanced Search','#',array('class'=>'search-button')); ?>
<div class="search-form" style="display:none">
<?php $this->renderPartial('_search',array(
'model'=>$model,
)); ?>
</div><!-- search-form -->
<?php echo " | " .CHtml::link('Save Search',array('savesearchresult','r'=>'wsrecruitcvhead/savesearchresult')); ?>
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'wsrecruitcvhead-grid',
'dataProvider'=>$model->search(),
#'filter'=>$model,
'columns'=>array(
#'MemberShipID',
#'ResumeID',
'ResumeTitle',
'ResumeSummaryIntroduction',
'Name',
'DOB',
array(
'class' => 'CButtonColumn',
'viewButtonUrl' => 'Yii::app()->createUrl("wsrecruitcvhead/view",array("id"=>$data["ResumeID"]))',
'template'=>'{view}',
),
),
)); ?>
how will I get the id values of each magnifying glass icon from the search result ?
I have this in my controller
/*
* CV advance search page
*/
public function actionAdvancecvsearch()
{
$model = new Wsrecruitcvhead('search');
$model->unsetAttributes();
if(isset($_GET['Wsrecruitcvhead']))
$model->attributes = $_GET['Wsrecruitcvhead'];
$this->render('advancecvsearch',array(
'model' => $model,
));
}
/*
* save search results
*/
public function actionSavesearchresult()
{
$model = new Wsrecruitsavedsearches;
if(isset($_POST['Wsrecruitcvhead']))
{
$model->MemberShipID = Yii::app()->user->id;
$model->ResumeID = $_POS['Wsrecruitcvhead']['id'];
$model->datesaved = new CDbCriteria(NOW());
if($model->save())
{
$this->redirect(array('savedcvsearches','r'=>'wsrecruitcvhead/savedcvsearches'));
}
else
{
$this->redirect(array('advancecvsearch','r'=>'wsrecruitcvhead/advancecvsearch'));
}
}
}
/*
* render savedcvsearches
*/
public function actionSavedcvsearches()
{
//some code stuff here
$this->render('savedcvsearches');
}
actually I saw an example , but it didn't help
how to save cgridview search results
Set a new Column with a display:none; class and set a hidden field using CHtml.
'columns'=>array(
array=>(
'name'=>'',
'type'=>'raw',
'value'=>"CHtml::hiddenField('resumeIds[]', $data['ResumeID'])",
'htmlOptions'=>array('class'=>'hiddenTrClass')
)
)
The process would be something like
foreach($_POST['resumeIds'] as $id):
//Do Something
endforeach;
Related
I have the following view named 'findreseller.php':
<?php
$countries = CHtml::listData(Country::model()->findAll(), 'id', 'name');
echo CHtml::dropdownlist('find_reseller', '', $countries,
array('ajax'=>array(
'type'=>'POST',
'url'=>Yii::app()->getController()->createAbsoluteUrl('/webcare/reseller/loadAjaxData'),
'update' =>'#data',
)
)
);
?>
<div id="data">
<?php $this->renderPartial('_ajaxContent', array('dataProvider'=>$dataProvider))?>
</div>
_ajaxContent just echoes the result, nothing special there...
The dropdown, as you can see is generated with CHtml because I dont't need a form. I just need an onChange event to do something...
As per the code that follows, in '/webcare/reseller/loadAjaxData' I have:
public function actionLoadAjaxData() {
$country = $_POST['find_reseller'];
//do something...
$dataProvider=new CArrayDataProvider($country_reseller);
$this->render('findreseller', array('dataProvider' => $dataProvider));
}
I can tell that I am missing something, but I am not sure what exactly.
Edit
Modified like this:
<?php
//CHtml::form();
$countries = CHtml::listData(Country::model()->findAll(), 'id', 'name');
echo CHtml::dropdownlist('find_reseller', '', $countries,
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('/webcare/reseller/loadAjaxData'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#city_id', //selector to update
'data'=>'js: $(this).val()',
//leave out the data key to pass all form values through
)
)
);
//empty since it will be filled by the other dropdown
echo CHtml::dropDownList('city_id','', array());
//CHtml::endForm();
?>
<div id="data">
<?php $this->renderPartial('_ajaxContent', array('dataProvider'=>$dataProvider))?>
</div>
And now I get:
http://prntscr.com/42wwx6
And I have the following controller action:
public function actionLoadAjaxData() {
$country = $_POST['country_id'];
...
$dataProvider=new CArrayDataProvider($country_reseller);
$data = User::model()->findAll('country_id=:country_id AND reseller=:reseller',
array(':country_id'=>(int) $_POST['country_id'], ':reseller'=>1));
$data=CHtml::listData($data,'city','city');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
$this->render('action_name', array('dataProvider' => $dataProvider));
}
Edit 2
If I write a die in actionLoadAjaxData(), right at the beginning, the method is loaded fine, the action is ok and the server answers 200.
I am trying to do following things...I have a page which is been used for searching as well as displaying results. I have done the following things, have a controller which is filtering data and I think its working fine till now..., but now have no idea how to display the desired result in my view page.
/*Codes for Controller */
public function actionSearch()
{
$model = new SearchEmployee();
/*Getting Data From Search Form For Processing */
if (isset($_POST['SearchEmployee'])) {
$category = $_POST['SearchEmployee']['category_id'];
$skills = $_POST['SearchEmployee']['skills'];
$experience = $_POST['SearchEmployee']['experience'];
$model = SearchEmployee::model()->find(array(
'select' => array('*'), "condition" => "category_id=$category AND key_skills like '%$skills%' AND experience=$experience",
));
$this->render('search', array('model' => $model));
}
/*Getting Data From Search Form For Processing */
$this->render('search', array('model' => $model));
}
In View: I have done like below, not posting full view, just portion of section where I have to show results.
<div class="view">
<h1>Results </h1>
<div class="view" id="id">
<h1> Records Display </h1>
<h4>Name: <?php echo $model->name; ?></h4>
<h4>Skills: <?php echo $model->experience;?></h4>
<h4>Experience: <?php echo $model->key_skills; ?></h4>
<h5> <?php echo CHtml::submitButton('VIew Details'); ?></h5>
</div>
</div>
I don't know whether I am on right track.
You should try with different word rather then model like modelData etc.
public function actionSearch()
{
$model = new SearchEmployee();
/*Getting Data From Search Form For Processing */
if (isset($_POST['SearchEmployee'])) {
$category = $_POST['SearchEmployee']['category_id'];
$skills = $_POST['SearchEmployee']['skills'];
$experience = $_POST['SearchEmployee']['experience'];
$modelData = SearchEmployee::model()->find(array(
'select' => array('*'), "condition" => "category_id=$category AND key_skills like '%$skills%' AND experience=$experience",
));
$this->render('search', array('model' => $model));
}
/*Getting Data From Search Form For Processing */
$this->render('search', array('modelData' => $modelData));
}
I'm trying to output data into the CListView of the current user only. So far, if I put in the $dataProvider, it only outputs ALL the records from the database.
This is my current code:
$current = Yii::app()->user->id;
$currentid = Yii::app()->db->createCommand("select * from content where id = ". $current)->queryRow();
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider, //This is the original. I tried replacing it
//with $currentid but errors.
'itemView'=>'_view2',
'template'=>'{items}<div>{pager}</div>',
'ajaxUpdate'=>false,
));
From what I understand from the Yii Documentations, $dataProvider stores all the data within the database and places it inside the dataProvider itself and my "_view2" uses that to output all the records.
My Controller codes for the showing/view is as follows:
public function actionView()
{
$post=$this->loadModel();
if(Persons::model()->compare_country(explode("|",$post->country)))
{
$post->view_count = $post->view_count + 1;
Yii::app()->db->createCommand("UPDATE content SET view_count = {$post->view_count} WHERE id = {$post->id}")->execute();
//$post->save();
$comment=$this->newComment($post, 'view');
if (!empty(Yii::app()->session['announcement_message']))
{
Yii::app()->user->setFlash('message',Yii::app()->session['announcement_message']);
Yii::app()->session['announcement_message'] = null;
}
$this->render('view',array(
'model'=>$post,
'comment'=>$comment,
'view'=>'view',
));
}
else
{
$this->redirect(Yii::app()->createAbsoluteUrl('news/index',array('page'=>'1')));
}
}
public function actionShow($id)
{
$post=$this->loadModel($id);
$comment=$this->newComment($post);
$attachments=Attachments::model()->findAllByAttributes(array(
'content_id' => $id,
));
$this->render('show',array(
'model'=>$post,
'comment'=>$comment,
'attachments'=>$attachments
));
}
If you wanted to see my _view2, these are my codes:
<div class="profile-member-post-box announcement" >
<div class="events-post-bodytext profile-member-info">
<?php $person=Persons::model()->findByAttributes(array('party_id'=>$data->party_id));
if ($person->party_id === Yii::app()->user->id)
{
?>
<span><?=CHtml::link($data->title, array('view', 'id'=>$data->id), array('class' => 'titlelink'));?></span>
<?php
$country=Lookup_codes::model()->findByAttributes(array('id'=>$person->country));
$location = empty($country) ? '' : 'of '.$country->name;
$sysUser=User::model()->findByAttributes(array('party_id'=>$data->party_id));
?>
<p>
By: <?php echo CHtml::link($person->getusername(), array('persons/view/id/'.$person->showViewLinkId())); ?>
<span class="date2"> - <?php echo date('M j, Y',strtotime($data->date_created)); ?></span>
</p>
<div>
<?php if(Yii::app()->partyroles->isAdmin() || ((get_access('Announcement','edit') && (Yii::app()->user->id == $data->party_id)) || (get_local_access('sub-admin','edit',$data->id)))):?>
Edit | <?php endif;?> <?php echo (Yii::app()->partyroles->isAdmin() || (get_access('Announcement','delete') && (Yii::app()->user->id == $data->party_id)) || (get_local_access('sub-admin','delete',$data->id))) ? CHtml::link('Delete','#',array('submit'=>array('delete','id'=>$data["id"]),'confirm'=>'Are you sure you want to delete this item?')) : NULL?>
</div>
<?php
}
else
?>
</div>
I just need to be able to fix the view to show records only by the current user.
UPDATE!!------------
I'm going to add my actionIndex here:
public function actionIndex()
{
if(get_access('Announcement','view') || get_access('Announcement','view_local'))
{
$id = Yii::app()->user->id;
$condition = Persons::model()->get_view_condition('Announcement');
$criteria=new CDbCriteria(array(
'condition'=>'1=1 '.$condition,
'order'=>'date_modified DESC',
'with'=>'commentCount',
));
/*
if(isset($_GET['tag']))
$criteria->addSearchCondition('tags',$_GET['tag']);
*/
$items=SystemParameters::model()->findAllByAttributes(array(
'name' => 'blogs_per_page',
));
$dataProvider=new CActiveDataProvider('Announcement', array(
'pagination'=>array(
'pageSize'=>strip_tags($items[0]->value),
),
'criteria'=>$criteria,
));
/* $dataProvider=new CActiveDataProvider('Announcement', array(
'pagination'=>array(
'pageSize'=>5,
),
'criteria'=>$criteria,
));*/
//$dataProvider=Announcement::model()->findAll();
$attachments=Attachments::model()->findAllByAttributes(array(
'content_id' => $id,
));
if (!empty(Yii::app()->session['announcement_message']))
{
Yii::app()->user->setFlash('message',Yii::app()->session['announcement_message']);
Yii::app()->session['announcement_message'] = null;
}
$this->render('index',array(
'dataProvider'=>$dataProvider,
));
}
else
{
$this->redirect(Yii::app()->createAbsoluteUrl('news/index',array('page'=>'1')));
}
}
Your question is very hard to follow... but I'll attempt to answer by giving an example of how to use the CDataProvider and CListView to display all of the Announcements owned by the current logged in User. This assumes the Announcement model's table has a user_id field which contains the id of the User who owns or created it.
First, in your indexAction() in your controller:
// get the logged in user's ID
$userId = Yii::app()->user->id;
// now define the dataprovider, which will do the SQL query for you
$dataProvider = new CActiveDataProvider( // declare a new dataprovider
'Announcement', // declare the type of Model you want to query and display
array( // here we build the SQL 'where' clause
'criteria' => array( // this is just building a CDbCriteria object
'condition' => 'user_id=:id', // look for content with the user_id we pass in
'params' => array(':id' => $userId), // pass in (bind) user's id to the query
//'order'=>'date_modified DESC', // add your sort order if you want?
//'with'=>'commentCount', // join in your commentCount table?
)
)
);
$this->render('index',array( // render the Index view
'dataProvider'=>$dataProvider, // pass in the data provider
));
Then in your index.php view:
// create the CListView and pass in the $dataProvider we created above, in the indexAction
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider, // this is the data provider we just created
'itemView'=>'_view2',
'template'=>'{items}<div>{pager}</div>',
'ajaxUpdate'=>false,
));
I have a variable and I want to update the value in the controller and render a part of the page based on the value.
This works very well in the first time but the variable doesn't get the value, stay with the first. Here my code:
Model:
public function actionCreate()
{
$model=new CadTeste;
$teste=1;
if(isset($_POST['CadTeste']))
{
$model->attributes=$_POST['CadTeste'];
if($model->save())
$this->redirect(array('view','id'=>$model->icd_teste));
}
$this->render('create',array(
'model'=>$model,
'teste'=>$teste,
));
}
Form:
<div id="data">
<?php $this->renderPartial('_ajaxContent', array('teste'=>$teste)); ?>
</div>
<?php
echo CHtml::ajaxSubmitButton('Alterar Num',CController::createUrl('CadTeste/UpdateAjax'),
array('type'=>'POST',
'data' => array('teste'=> $teste),
'update' => '#data'
)
); ?>
The Controler
public function actionUpdateAjax()
{
$teste = $_POST['teste'];
$teste += 10;
$this->renderPartial('_ajaxContent', array('teste'=>$teste), false, true);
}
And the _ajaxContent
<?php echo $teste; ?>
Every time I click on the button I get the value "11" instead of "11, 21, 31, 41".
How can I do that? Should I change the value every time in the controller?
Try Using Sessions . This Works for me
View File
<?php Yii::app()->session['teste']=$teste ?>
<div id='data'>
<?php $this->renderPartial('_ajaxContent', array('teste'=>$teste)); ?>
</div>
<?php
echo CHtml::ajaxSubmitButton('Alterar Num',$this->createUrl('CadTeste/UpdateAjax'),
array('type'=>'POST',
// 'data' => array('teste'=> $teste),
'update' => '#data'
)
); ?>
Your Controller
public function actionUpdateAjax()
{
$teste = Yii::app()->session['teste'];
$teste += 10;
$this->renderPartial('_ajaxContent', array('teste'=>$teste));
unset(Yii::app()->session['teste']);
Yii::app()->session['teste']=$teste;
}
And Your Model As it Is
public function actionCreate()
{
$model=new CadTeste;
$teste=1;
if(isset($_POST['CadTeste']))
{
$model->attributes=$_POST['CadTeste'];
if($model->save())
$this->redirect(array('view','id'=>$model->icd_teste));
}
$this->render('create',array(
'model'=>$model,
'teste'=>$teste,
));
}
Not sure if this is your problem, but renderPartial() does not play well with AJAX. It is a known Yii issue:
http://www.yiiframework.com/forum/index.php/topic/24699-yii-20-ajaxrenderpartial-conflict/
Try using this for the view:
<?php
echo CHtml::ajaxSubmitButton('Alterar Num',CController::createUrl('CadTeste/UpdateAjax',array('teste'=>$teste)),
array('type'=>'POST',
'update' => '#data'
)
); ?>
This for the controller:
public function actionUpdateAjax($teste)
{
$teste += 10;
$this->renderPartial('_ajaxContent', array('teste'=>$teste));
}
This way you can POST to action/ajaxupdate/teste/1
Its called Parameter Binding, the parameter in $teste is populated automatically from the url, if it's not present, it will give you an error. (You could put a default value $teste=1 to make it optional)
Q : How to ajax update the CgridVeiw?
Status : I've done with cookie. but there are a problem. it is when the page upload, the date are always show in from-date and to-date text box. and When reload the page, it doesn't clear out.
This is my view
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'page-form',
'enableAjaxValidation'=>true,
)); ?>
<div style="margin-top:30px;">
<b>From :</b>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'name'=>'from_date', // name of post parameter
//'value'=>Yii::app()->request->cookies['from_date']->value, // value comes from cookie after submittion
'options'=>array(
'showAnim'=>'fold',
'dateFormat'=>'yy-mm-dd',
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?>
<span> </span>
<b>To :</b>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
'name'=>'to_date',
//'value'=>Yii::app()->request->cookies['to_date']->value,
'options'=>array(
'showAnim'=>'fold',
'dateFormat'=>'yy-mm-dd',
),
'htmlOptions'=>array(
'style'=>'height:20px;'
),
));
?>
<span> </span>
<?php echo CHtml::submitButton('Go'); ?>
<?php
echo CHtml::ajaxSubmitButton('Search', CHtml::normalizeUrl(array('index')),
array(
'success'=>'js:'
.'function(){'
.'$.fn.yiiGridView.update("acc-payment-recei-grid", {url:"index"});'
.'}',
),
array('id'=>'go', 'name'=>'go'));
?>
<?php $this->endWidget(); ?>
<p style="float:right;">
New Payment Receive
</p>
</div>
<style>
.items table tr:last-child td:first-child {
-moz-border-radius-bottomleft:10px;
-webkit-border-bottom-left-radius:10px;
border-bottom-left-radius:10px
}
.items table tr:last-child td:last-child {
-moz-border-radius-bottomright:10px;
-webkit-border-bottom-right-radius:10px;
border-bottom-right-radius:10px
}
</style>
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'acc-payment-recei-grid',
'dataProvider'=>$accpaymentrecei->search(),
//'filter'=>$accpaymentrecei,
'columns'=>array(
//'id',
array('name' => 'acc_category_id',
'value'=>'(isset($data->acccategories->name)) ? CHtml::encode($data->acccategories->name) :""',
),
array('name' => 'acc_recei_id',
'header'=> 'Account Received',
//'value'=>'(isset($data->method)) ? CHtml::encode($data->method) :""',
),
array(
'name' => 'date',
'value'=>'($data->date= 0) ? "" : date("d M yy",strtotime($data->date))',
),
array('name' => 'method',
'value'=>'(isset($data->method)) ? CHtml::encode($data->method) :""',
),
array('name' => 'description',
//'value'=>'(isset($data->method)) ? CHtml::encode($data->method) :""',
),
/*
'created_date',
'updated_date',
'file_name',
*/
array(
'class'=>'CButtonColumn',
),
),
));
This is controller
public function actionIndex()
{
$accpaymentrecei=new AccPaymentRecei('search');
$accpaymentrecei->unsetAttributes(); // clear any default values
if(isset($_GET['AccPaymentRecei']))
$accpaymentrecei->attributes=$_GET['AccPaymentRecei'];
$acccategory = AccCategory::model()->findAll();
$arr_method = array('Cash'=>'Cash', 'Cheque'=>'Cheque', 'Credit Card'=>'Credit Card', 'Bank Transfer'=>'Bank Transfer');
$this->from_to_date($accpaymentrecei);
//exit();
$this->render('index',array(
'accpaymentrecei'=>$accpaymentrecei,
'acccategory'=>$acccategory,
'arr_method'=>$arr_method,
));
}
protected function from_to_date($model)
{
unset(Yii::app()->request->cookies['from_date']); // first unset cookie for dates
unset(Yii::app()->request->cookies['to_date']);
//$model=new XyzModel('search'); // your model
$model->unsetAttributes(); // clear any default values
if(!empty($_POST))
{
Yii::app()->request->cookies['from_date'] = new CHttpCookie('from_date', $_POST['from_date']); // define cookie for from_date
Yii::app()->request->cookies['to_date'] = new CHttpCookie('to_date', $_POST['to_date']);
$model->from_date = $_POST['from_date'];
$model->to_date = $_POST['to_date'];
}else{
Yii::app()->request->cookies['from_date'] = new CHttpCookie('from_date', date("Y/m/d"));
Yii::app()->request->cookies['to_date'] = new CHttpCookie('to_date', date("Y/m/d"));
}
}
Code below - it's only example, main principles of solution. First principle: we don't need refresh page (by the submit), we need only refresh CGridView after request.
The solution has a few parts:
We need form with some parameters. In your case - fromDate and toDate. You have this one already. But we don't need any submit element. At all! We will use AJAX.
We need some function for initiate AJAX-request. For example, let's event for this request will be change of parameters *from_date* or *to_date*. This function also must update CGridView after request.
We need action in controller for processing AJAX-request.
Let's begin from part 2. It may be some like this:
Yii::app()->clientScript->registerScript('scriptId',
"var ajaxUpdateTimeout;
var ajaxRequest;
$('**selector_for_parameters_fields**').change(function(){
ajaxRequest = $(this).serialize();
clearTimeout(ajaxUpdateTimeout);
ajaxUpdateTimeout = setTimeout(function () {
$.fn.yiiGridView.update(
// this is the id of the CGridView
'acc-payment-recei-grid',
{data: ajaxRequest}
)
},
// this is the delay
300);
});"
);
Place this code into view. Notes:
$(this).serialize() - key moment. Look for more info
selector_for_parameters_fields - give them ( fromDate and toDate ) some unique
selector
We use some delay (300 ms) for decreasing loading from unnecessary AJAX-requests
Now - about action in Controller
public function actionIndex($fromDate='', $toDate='')
{
$criteria = new CDbCriteria();
if(!empty($fromDate))
$criteria->addSearchCondition('your search condition about fromDate');
if(!empty($toDate))
$criteria->addSearchCondition('your search condition about toDate');
$dataProvider=new CActiveDataProvider('YourModel',
array('criteria' => $criteria,));
$this->render('YourView',array('dataProvider'=>$dataProvider,));
}
It must works, but requires some tuning for concrete conditions.