can't change yii CCheckboxColumn value - php

I made a small app: there is a lost of users , I check those who I want , click a button and a certain message is being sent to their emails.
I'm using yii's checkbox column and ajax in order to send the users' emails to the action in the controller.
Now, in order to be able to debug this app , I set the destination address to mine , and the users' emails in the message variable.
The app works! BUT , I get the users' ids instead of their emails.
Checkbox column sends the model's id by default , but one can change it with 'name' or 'value' , HOWERVER , for some reason both those lines simply doesn't work.
I'm sitting on this for four days , I wrote another ajax , but I'm still gettin the id.
I'd be vey gladful if anyone can help me. Here's the code:
The gridview:
<?php $this->widget('zii.widgets.grid.CGridView', array(
'id'=>'test-person-grid',
'dataProvider'=>$model->search(),
'filter'=>$model,
'columns'=>array(
'id',
'name',
'email',
array(
'id'=>'col',
'class'=>'CCheckBoxColumn',
'selectableRows'=>'2',
'value'=>'$data->email',
),
array(
'class'=>'CButtonColumn',
),
),
)); ?>
The ajax:
<?php
Yii::app()->clientScript->registerScript('send','
$("#sender").click(function(){
var checked=$("#test-person-grid").yiiGridView("getChecked","col");
var count=checked.length;
if(count>0 && confirm(" do you want to send "+count+" message? "))
{
$.ajax({
data:{checked:checked},
url:"'.CHtml::normalizeUrl(array('testPerson/sender')).'",
success:function(data){$("#test-person-grid").yiiGridView("update",{});},
});
}
});
');
?>
The controller action:
public function actionSender()
{
if(Yii::app()->request->getIsAjaxRequest())
{
$checkedMails=$_GET['checked'];
foreach($checkedMails as $message)
{
mail('mark#gmail.com', 'Test mail', $message);
}
}
}

You have the userID so I would do a findByPK on in the controller.
This question on the YII forum is the same and the answer given by the staff is the same.
http://www.yiiframework.com/forum/index.php/topic/48235-fnyiigridviewgetchecked-returns-empty-values/

Thanks! Finally it works.
I used only one foreach , and under it I used the findByPk like this:
$checkedIds=$_GET['checked'];
foreach($checkedIds as $id)
{
$message=TestPerson::model()->findByPk($id)->email;
mail('mark#gmail.com', 'Test mail', $message);
}
Cheers,
Mark.

Related

Yii: ID getting overwritten on load

I need help with tracing this web application. I'm very new to Yii, and I'm trying to dissect an existing app to understand it better. I'm trying to create an edit function, which video tutorials lead me to believe has the exact same process as an add function [save()], except you specify the ID to be overwritten (and I very well could be wrong about this).
Near as I can tell, the following files are in play:
views/forum/view.php
views/forum/_commentform.php
views/forum/_comments.php
controllers/ForumController.php
models/Forum.php
models/Comment.php
I can't really change much of the existing, though I can add my own. It starts with view.php, where much of the stuff is displayed. At the bottom of it is this:
<?php
$this->widget('zii.widgets.CListView',
array('dataProvider'=>$dataProvider, 'itemView'=>'_comments', 'summaryText'=>'',));
?>
_comments.php displays all the usual elements of a comment, like say, from Facebook. There's an edit button there that I made, code here:
<?php echo CHtml::link(CHtml::encode('Edit'),array('forum/editcomment','reply'=>$data->id,'topic'=>$data->content_id)); ?>
That edit button gets the ID of the current comment from the database. Near as the application logs can tell me, this does work.
That calls this particular function in ForumController.php:
public function actionEditComment() {
if(isset($_GET['reply'])) {
$comment=Comment::model()->findByAttributes(array('id'=>$_GET['reply']));
$topic=Forum::model()->findByAttributes(array('id'=>$comment->content_id));
$this->renderPartial('_commentform', array('forum'=>$topic, 'model'=>$comment, 'view'=>'view',));
}
}
Next is the _commentform.php. Nothing much, just a textbox, though it does check if an ID is present; if it is, it is editing an existing comment, otherwise, it is creating a new one. A submit button also changes from Reply to Update, depending on the value of isNewRecord.
EDIT: There's also a CActiveForm, in case that of any help. Might have something to do with routing?
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'comment-form',
'action'=>Yii::app()->createUrl('forum/view/id/'.$forum->id),
'enableAjaxValidation'=>false,
)); ?>
<?php
if ($view == 'view') {
echo CHtml::submitButton($model->isNewRecord ? 'Reply' : 'Update', array('id'=>'comment'.$model->id));
}?>
Again, confirmed via application logs, the ID of the comment is being passed through, albeit as id => comment<commentID>. Then this is where things get hazy. I assume the flow goes back to ForumController.php, where, per my logging, the ID is lost.
Here's the parts of the ForumController.php that I deem responsible:
public function actionView() {
$post=$this->loadModel();
$comment=$this->newComment($post);
$viewcount=$post->view_count+1;
$post->view_count=$viewcount;
$post->save();
$this->render('view',array('model'=>$post, 'dataProvider'=>$dataProvider,));
}
private $_model;
public function loadModel() {
if($this->_model===null) {
if(isset($_GET['id'])) {
$this->_model=Forum::model()->findByPk($_GET['id'], $condition);
}
if($this->_model===null)
throw new CHttpException(404,'The requested page does not exist.');
}
return $this->_model;
}
protected function newComment($post) {
$comment=new Comment;
if(isset($_POST['Comment'])) {
$comment->attributes=$_POST['Comment'];
$post->addComment($comment);
}
return $comment;
}
Interestingly, if I write out $comment from newComment() out to the log, it does print out the edited comment (i.e., it prints out "john cena" if I edited the existing comment "who is champ?"), but $comment->id yields a null, which I assume is why instead of updating, the edited comment is saved as a new one.
As for the models, Forum.php and Comment.php strangely point to the same database table, because for some reason they decided to put Forums and Comments into one table. Forum.php also contains the actual addComment function (a placement I find weird), though by the time the flow gets there, the Comment ID is of course null, though the edited comment itself is there.
Where did I go wrong? Did I miss anything?
EDIT: Here's the attributes and rules for the Comment model:
public function attributeLabels() {
return array(
'id' => 'ID',
'node_type' => 'Node Type',
'party_id' => 'Party',
'category' => 'Category',
'title' => 'Title',
'content' => 'Content',
'date_created' => 'Create Time',
'date_modified' => 'Update Time',
'status' => 'Status',);
}
public function rules()
{
/* combine parent and own rules */
$parentRules = parent::rules();
$myRules = array(
array('node_type_id', 'default', 'value'=>'7'), /* set type to Person */
array('node_type_id', 'in', 'range'=>array('7')), /* allow only Person type */
array('party_id, date_created, date_modified, status', 'numerical', 'integerOnly'=>true),
array('category, title, content', 'safe'),
);
/* you want to apply parent rules last, delete them here if necessary */
return array_merge($myRules);
}
Could you post Comment class defenition here?
I think you don't have rule for "id" in Comment::rules(),
When rule for attribute is not defined attribute will be unsafe and you can't set it value by $comment->attributes, or you can change you code to something like:
if(isset($_POST['Comment']) && isset($_POST['Comment']['id'])) {
$comment = Comment::model()->findByPk($_POST['Comment']['id']);
$comment->attributes=$_POST['Comment'];
$post->addComment($comment);
}

is it possible to display content from cgridview to dropdown in yii?

I have modified my model so that the data displayed in cgridview is unique per user, depending on the account type...
However I need to create a form from another model where I could get the data from the cgridview via dropdown...
I used this code at first...
<?php
$this->widget('ext.select2.ESelect2',array(
'model'=>$model,
'attribute'=>'pr_id',
'data'=>$model->searchPatient(),//function to provide data
// or
//'data'=>CHtml::listData(PatientRecord::model()->findAll(), 'id', 'first_name')
);
?>
but it returns all of the contents of the PatientRecord model, I tried using a condition before planning to retrieve the contents from the cgridview...
$doctor= Yii::app()->user->id;
CHtml::listData(PatientRecord::model()->findAll( array(
'condition'=>'doctor_id=:doctor_id',
'params' => array(':doctor_id' => $doctor)
)
);), 'id', 'first_name')
it didn't have an error but it didn't display anything on the dropdown either...
any suggestions?
I think the problem is with a ; and ) in your model code, try this:
$doctor= Yii::app()->user->id;
CHtml::listData(PatientRecord::model()->findAll( array(
'condition'=>'doctor_id=:doctor_id',
'params' => array(':doctor_id' => $doctor)
)
), 'id', 'first_name');
You should always enable error logging in local environment, this will help you find any errors in your code. Here is a link on how to enable error logging.
Hope that helps :)

Yii - How To Display User's Own Uploaded Data In CGridView?

everyone I am working on a project that allow user do upload and download data. I want to show only a user's own uploaded data in CGridView.
Here's my relation table
I have tried to edit my page --> views/file/myUploads.php
<?php
$isMine=Yii::app()->user->id; // I have tried this
if($isMine){
$this->widget('zii.widgets.CGridView',array(
'id'=>'file-grid',
'dataProvider'=>$model->search(),
//'filter'=>$model,
'columns'=>array(
'name'
'description',
'category'
'uploader'
'upload_date',
array(
'header'=>'Actions',
'class'=>'bootstrap.widgets.TbButtonColumn',
'template'=>'{delete}', //'visible'=> (Yii::app()->user->getLevel()==1),
'deleteConfirmation'=>"js: 'Are you want to delete '+$(this).parent().parent().children(':first-child').text()+ '?'",
'buttons'=>array(
'delete' => array(
'visible'=> '$data->pengunggah==Yii::app()->user->id',
),
)
),
),
)); }
?>
I have tried that codes above but the page still display all data, not user's own data.
I have tried to edit myUpload function in FileController.php too
public function actionMyUpload()
{
$isMine=Yii::app()->user->id; // I have tried this
if($isMine){
$model=new File('search');
$model->unsetAttributes(); // clear any default values
if(isset($_GET['File']))
$model->attributes=$_GET['File'];
$this->render('myUpload',array(
'model'=>$model,
));
}
}
But still display all data.
Can anyone help me? Thanks a lot.
Revert all your changes back, Open Your Model Class File ie "File.php" and add this line in your search() function:
$criteria=new CDbCriteria;
// Simply add this line
$criteria->addCondition('id_user='.Yii::app()->user->id);

Yii CArrayDataProvider Keyfield As Button Id In CGridView

My issue is two-fold. First, I'm unable to correctly set the keyField for CArrayDataProvider, all I'm getting back is a string instead of a value. Second, I'm trying to use the keyField inside of CArrayDataProvider to set an id on the button in each row inside of CGridView. The reason I want to do this is so that I can pass the id value onward to an ajax function (if there's a better way to do this in Yii, I'm all ears). Any help would be much appreciated, thanks in advance!
I also posted this question once on Yii's forums. I normally wouldn't repost, but I have had a hard time getting answers there, as opposed to stack overflow, you guys are the best! Here's the link to my original post if anyone is interested.
Here is how I'm building the array that I'm using as my RAW data:
foreach ($items as $item) {
$tableRow = array("id"=>$item["Id"], "Organization"=>$item["Organization"], "Roles"=>$item["Roles"]);
$return_items[] = $tableRow;
}
Here is the CArrayDataProvider setup I'm using. I noticed that 'keyField' is not being given the id value, just the string 'id':
$dataProvider=new CArrayDataProvider($return_items, array(
'keyField'=>'id',
'sort'=>array(
'attributes'=>array(
'Organization',
'Roles',
),
),
'pagination'=>array(
'pageSize'=>10,
),
));
Lastly, here is the CGridView I'm trying to setup in the view. All that appears on the button is the id tag, but no value:
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$authItems,
'columns'=>array(
'Organization',
'Roles',
array('name'=>'',
'type'=>'raw',
'htmlOptions'=>array('id'=>'id'),
'value'=>'CHtml::button("Edit Roles", array("data-toggle"=>"modal", "data-target"=>"#roles-modal"))'),
),
));
Try passing it via CHtml::button which you have already applied. E.g.
'value'=>'CHtml::button("Edit Roles", array(
"id"=>$data["id"],
"data-toggle"=>"modal",
"data-target"=>"#roles-modal"
))'),

How to filter the rows of a gridview in yii using radio buttons

I used the below code to create two radio buttons(approved messages and rejected messages) in Yii framework
<?php echo CHtml::activeRadioButtonList($model, 'Approved', array('Approved Messages', 'Rejected Messages'), array('labelOptions'=>array('style'=>'display:inline'),'separator'=>'')) ?>
Now I have to filter and display all the rows in CGridView of the table where column 'approved' has value=1 when I click on "approved messages" radio button and all the rows in CGridView of the table where column 'Approved' has value=0 when I click on "rejected messages" radio button. How can I do this
I used a drop down for this, the values are Yes and No. Just translate the approved column into text using the following code:
array(
'name' => 'approved',
'value' => '($data->approved ? "Yes" : "No")',
'filter' = >CHtml::dropDownList('Approved', '',
array(
' '=>'All',
'1'=>'On',
'0'=>'Off',
)
),
)
This link is where I got this info: http://www.yiiframework.com/forum/index.php/topic/30694-cgridview-filter-dropdown-from-array/
I googled using cgridview filter example
Alright, lets put in the radio buttons instead of all the dropdowns haha.
I assume you have your view set up something like this:
// view/index.php (or similar)
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$model->search(),
'filter'=>Message::model(),
'columns'=>
[
'id',
'username',
'email:email',
'approved'=>[
'name'=>'approved',
'filter'=>$this->approvedFilter(),
// I like moving stuff like this out of the way.
// But maybe it's smarter to put it in your model instead?
]
]
));
Next for the controller.
// MessageController.php (or similar)
public function actionIndex()
{
$model = Message::model();
// All we need to do is to assign the incoming value to the model we are using...
if ( isset( $_GET['Message']['Approved'] )){
$model->approved = $_GET['Message']['Approved'];
}
$this->render('index', ['model'=>$model]);
}
// Oh yeah the filter. I just copied your code.
public function approvedFilter(){
return CHtml::activeRadioButtonList(
Message::model(), 'approved', array(0,1),
array(
'labelOptions'=>array('style'=>'display:inline'),
'separator'=>''
)
);
}
This code has been tested, but I made some last minute changes, so sorry if it blows up!
And I still think a simple 'approved:boolean' is much cleaner. ;)

Categories