How to post result from controller to view in yii - php

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));
}

Related

How to load selected values in multiple-dropdown in update view in yii?

I am new in yii. I have problem with fetching selected values in dropdown when updating the record.
I have dropdown with multiple selection of user's email.
When adding it is working fine, it allows me to select multiple values and can insert selected value's ids comma separated in database. But the problem is when i want to update the record it displays only 1 selected record.
Here is my code:
in my View file:
<div class="controls">
<?php echo $form->dropDownList($model, 'uid', $allUsers, array('class' => 'select2-me input-sel_large', 'multiple' => 'true', 'options' => array('' => array('selected' => true)))); ?>
<?php echo $form->error($model, 'uid') ?>
</div>
in my Controller file:
$model = new User;
$allUsers = $model->getAllUsers();
in my Model file:
public function getAllUsers() {
$arr = Yii::app()->db->createCommand()
->select('userEmail,pkUserID')
->from('tbl_user')
->queryAll();
$users = array();
if (is_array($arr)) {
foreach ($arr as $value) {
$users[$value['pkUserID']] = $value['userEmail'];
}
}
return $users;
}
Can anyone help?
Example. Hope this help you.
class YourForm extends CFormModel
{
public $uid = array(); // selected pkUserID's
}
//in action
$yourForm = new YourForm();
$yourForm->uid = array(1,2,3); // for example selected users with pk 1,2,3
$this->render('your_view', array('yourForm'=>$yourForm));
//view
/** #var CActiveForm $form */
/** #var YourForm $yourForm */
echo $form->dropDownList(
$yourForm,
'uid',
CHtml::listData(User::model()->findAll(array('order' => 'userEmail ASC')), 'pkUserID', 'userEmail'),
array('empty' => '', 'multiple'=>true))
)

Basic edit operation in yii

I have used CgridView which list all the data from my table 'Jobs',also have an edit and delete for each row.Which has been implemeted using prebuilt template in yii.I tried few things,but it not working.My first aim is to display that particular row data in edit form.
My codes are as follows:
The model corresponding is,UpdateJob.php.
/*Model*/
public function edit() {
$criteria = new CDbCriteria;
$criteria->compare('id', 'Admin', true);
return new CActiveDataProvider('viewjob', array(
// 'criteria' => $criteria,
'sort'=>array(
'defaultOrder'=>'key_skills ASC',
),
));
}
/*Contoller*/
public function actionUpdateJob()
{
if(isset($_GET['id'])) //Is it the right way //
{
$id=$_GET['id'];
}
$model = new UpdateJob('edit');
$params = array('model' => $model,'id' => $id
);
$this->render('update', $params);
}
/*VIEW*/ Have just tried to show the data as follows.
<div class="row">
<?php echo $form->labelEx($model,'Company Name'); ?>
<?php echo $form->textField($model,'posted_by'); ?>
<?php echo $form->error($model,'posted_by'); ?>
</div>
Thats it..
How to just display the row of a particular id. For the time being I don't want to update it. Please Help
this will be done through js
$(gridID).yiiGridView('getSelection') should be your start
read http://www.yiiframework.com/doc/api/1.1/CGridView

Editing a specific record in yii

I have a view section in my project,and using CGridView to list all the data from table,also have an edit and delete option within the grid to edit and delete specific row.
I am stuck with the edit section.I am working on how to get a specific row data dispalyed in editjob.php,I have done a few things,but no use.My codes are as follows,
In my view job section using CgridView,
'buttons' =>array('update'=>array(
'label'=>'edit',
'url'=>'Yii::app()->controller->createUrl("UpdateJob",array("id"=>$data["id"]))',
))
In Model UpdateJob:
public function edit()
{
$criteria=new CDbCriteria;
$criteria->find('id','Admin',true);
return new CActiveDataProvider('viewjob', array(
'criteria'=>$criteria,
// 'sort'=>array(
// 'defaultOrder'=>'key_skills ASC',
// ),
));
in controller:
public function actionUpdateJob()
{
if(isset($_GET['id']))
{
$id=$_GET['id'];
}
$model = new UpdateJob('edit');
$params = array('model' => $model,'id' => $id //passing the id like this
);
$this->render('update', $params);
}
And finaly in view written something like ,but showing error
<div class="row">
<?php echo $form->labelEx($model,'Company Name'); ?>
<?php echo Chtml::textField('posted_by',UpdateJob::model()->FindByPk($model->id)->posted_by); ?>
<?php echo $form->error($model,'posted_by'); ?>
</div>
am I on right track.
Youre loading a fresh model instead of fetching an existing one. Replace this line:
$model = new UpdateJob('edit');
By this line:
$model = UpdateJob::model()->findByPk($id);
To save the data you do this:
if(isset($_POST['UpdateJob'])) {
$model->scenario='edit';
$model->attributes=$_POST['UpdateJob'];
if($model->save())
$this->redirect(array('admin');
}

How to customize dataProvider using CListView in Yii

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,
));

how to save search result of CGridView to another model?

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;

Categories