How to customize dataProvider using CListView in Yii - php

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

Related

Yii, Update CGridView dataprovider based on AJAX result

I'm not sure that I am going about this the right way but here goes.
I have a dropdown list, when I change the values of this list I wish to update the dataprovider of a CGridView via Ajax.
dropDownList
<?php echo $form->dropDownList(
$model,
'assigned_to',
CHtml::listData(Users::model()->findAll(), 'id', 'username'),
array(
'empty' => 'Please Select',
'ajax' => array(
'type'=>'POST',
'url'=>Yii::app()->createUrl('CrmCalendar/Create', array('id'=>$model->model_id,'modelId'=>$model->model, 'updateGrid'=>1)),
'dataType' => 'json',
'success'=>'function(data)
{
alert(data);
$.fn.yiiGridView.update("user-activites-grid", {
data: data
});
}',
),
)
); ?>
CGridView Widget
<?php $this::widget('zii.widgets.grid.CGridView', array(
'id'=>'user-activites-grid',
'ajaxUpdate' => true,
'dataProvider'=>$model->dpUserActivities(),
));
?>
Controller Action
public function actiongetUserActivitesUpdate($id, $modelId)
{
$model=new CrmCalendar;
$model->model = $modelId;
$model->model_id = $id;
if(isset($_GET['updateGrid']))
{
$model->attributes=$_POST['CrmCalendar'];
$newDp = $model->dpUserActivities();
echo serialize($newDp);
}
}
dpUserActivities
public function dpUserActivities($size=20)
{
$date = DateTime::createFromFormat('d/m/Y H:i:s', $this->StartTime);
$date = $date->format('Y-m-d');
$dataProvider=new CActiveDataProvider($this, array(
'criteria'=>array('condition'=>'assigned_to=:assigned_to AND DATE(StartTime) = :date', 'params'=>array(':assigned_to'=>$this->assigned_to, ':date'=>$date),),
'pagination'=>array('pageSize'=>$size,),
'sort'=>array('defaultOrder'=>'Starttime ASC',),
));
return $dataProvider;
}
What I am trying to achieve is that when the drop down for assigned to is changed then the the value is stored back into the $model and the dpUserActivites is re run with the new data and then the CGridView is updated.
Sorry if this makes no sense.
Let me know if you need any more information
Regards.

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 can i get relation data by CActiverecord in yii?

I have 2 tables. tables have relation (HAS_MANY)
table1: user(id,name)
table2:address(id,userId,address)
user can has some address
I define relation in moles: user.php and address.php
user.php
'address' => array(self::HAS_MANY, 'address', 'userId'),
address.php
'user' => array(self::BELONGS_TO, 'user', 'userId'),
when i write
$dataProvider = new CActiveDataProvider('user')
i get only record of user table but i want to get records two table i want to get name,array(address) For each user , how can do it?
UserController.php
public function actionIndex() {
$dataProvider = new CActiveDataProvider('User');
$this->render('index', array(
'dataProvider' => $dataProvider,
));
}
index.php
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
)); ?>
_view.php
<b><?php echo $data->name)); ?>: <?php $data->address->address; ?>:</b>
In indexaction function, change the dataprovider code as below.
$dataProvider = new CActiveDataProvider('User','criteria'=>array(
'with'=>array(
'address'
),
'together'=>true,
));
You can get the data from address table using $data->address->address_table_field_name in your view file.
Here address is relation name defined in your user model file.
You don't need to use CActiveDataProvider, rather use the model directly.
Give it a try
foreach( User::model()->findAll() as $user ) {
$address = $user->address;
foreach( $address as $a ) {
}
}
try using
$model= User::model()->with('address')->findAll();
Note:- address in with('address') is the relation Name.
Eg:-
To get User records try this
foreach($model as $record)
{
echo $record->id . $record->name;
}
To get address records try this
foreach($model as $record)
{
foreach($record->address as $myaddress)
{
echo $myaddress->id . $myaddress->userId . $myaddress->address;
}
}

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