DropDownList effects a ClistView in Yii - php

I am still very new to this Yii framework, and I would like assistance with this code. I currently manage to get a dropdownlist dependent on another dropdownlist but I can't seem to get the dropdownlist to effect what gets displayed in the ClistView.
profile Controller
/* add a team message submitted by the coach of the team */
public function actionAddTeamMessage($id)
{
/* check if team and message aren't null */
if(isset($_POST['teamId']['addTeamMessage']))
{
try
{
/* creates a new message */
$teamModel = new TeamMessage;
$teamModel->teamId = $_POST['teamId'];
$teamModel->content = $_POST['addTeamMessage'];
$teamModel->sendTime = new CDbExpression('NOW()');
$teamModel->save();
}
catch(Exception $e)
{
echo "Unable to save.";
}
}
/* render the profile page for the current user */
$user=User::model()->findByPk($id);
$this->render('profile', array(
'model' => $user));
}
/* will handle functionality for the user dropdownlist ajax
* under contructions
*/
public function actionDisplayMessage()
{
$data = TeamMessage::model()->findAll('teamId=:teamId', array(
':teamId'=>(int) $_POST['teamId']
)
);
$data=CHtml::listData($data,'id', 'content');
echo "<option value=''>Select Message</option>";
foreach($data as $value=>$content)
echo CHtml::tag('option', array('value'=>$value),CHtml::encode($content),true);
//TODO still being tested.
/* for ClistView still debugging */
/*$dataProvider=new CActiveDataProvider('Player', array(
'criteria'=>array(
'condition'=>'teamId=:teamId',
)));*/
}
View Profile
<!-- Would allow user to access specific team messages and control how much gets display.
still under construction. -->
<div class="row">
<?php
echo CHtml::dropDownList("teamId", 'id', Chtml::listData($model->memberOfTeams, 'id', 'teamName'),array(
'empty'=>'Select Team',
'ajax'=>array(
'type'=>'POST', // request type
'url'=>CController::createUrl('DisplayMessage'),
'update'=>'#teamMessages', // selector to update
'data'=>array('teamId'=>'js:this.value'),
)
)
);
?>
<?php
echo CHtml::dropDownList('teamMessages','',array(),array('empty'=>'Select Message'));
/*$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_viewTeamMessage',
'id'=>'ajaxListView',
));*/
?>
</div>
As you can see in the cListView. I was debating on creating a _viewTeamMessage which will display the team message + sendtime. But I realize, I wouldn't be able to pass a dataprovider without re rendering the page, and i am trying to avoid heading into that direction.

You could pull your Team messges out into a partial view and then just use a render partial to render just the messages into your page usig Ajax. If the partial view is named _teamMessages.php it would look something like this (untested):
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_viewTeamMessage',
'id'=>'ajaxListView',
));
Then you modify your profile view to look like:
<!-- Would allow user to access specific team messages and control how much gets display.
still under construction. -->
<div class="row">
<?php
echo CHtml::dropDownList("teamId", 'id', Chtml::listData($model->memberOfTeams, 'id', 'teamName'),array(
'empty'=>'Select Team',
'ajax'=>array(
'type'=>'POST', // request type
'url'=>CController::createUrl('DisplayMessage'),
'update'=>'.team-messages', // selector to update
'data'=>array('teamId'=>'js:this.value'),
)
)
);
?>
<div class="team-messages">
<?php
$this->renderPartial('_teamMessages',
array('dataProvider'=>$dataProvider))
?>
</div>
</div>
Then finally you change your controller to something like this:
public function actionDisplayMessage()
{
/* REMOVE
$data = TeamMessage::model()->findAll('teamId=:teamId', array(
':teamId'=>(int) $_POST['teamId']
)
);
$data=CHtml::listData($data,'id', 'content');
echo "<option value=''>Select Message</option>";
foreach($data as $value=>$content)
echo CHtml::tag('option', array('value'=>$value),CHtml::encode($content),true);
*/
// still being tested.
$dataProvider=new CActiveDataProvider('Player', array(
'criteria'=>array(
'condition'=>'teamId=(int) $_POST['teamId']',
)));
$this->renderPartial('_teamMessages', array('dataProvider'=>$dataProvider);
}
this should just cause the message widget to be recreated instead of the whole page.

Related

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

CakePHP. Multiple Forms per page

I have website with few short News , to every News we can write a comment via Form. And there my problem occur.
When i fill my fields in one form, after pressing button, all forms are reloading without saving, and every field in every form must be filled out so they're treated like a one part how to avoid it ?
Additional info ( Info is my main modal with news, it's joined with Com modal)
index.ctp Form
<br><h5>Add comment:</h5><br>
<?php echo $this->Form->create('Com'); ?>
<?php echo $this->Form->input(__('mail',true),array('class'=>'form-control')); ?>
<?php echo $this->Form->input(__('body',true),array('class'=>'form-control')); ?>
<?php $this->request->data['ip'] = $this->request->clientIp(); ?>
<?php $this->request->data['info_id'] = $info['Info']['id']; ?>
<?php echo $this->Form->submit(__('Add comment',true),array('class'=>'btn btn-info')); ?>
<?php $this->Form->end(); ?>
controller ComsController.php
public function add()
{
if($this->request->is('post'))
{
$this->Infos_com->create();
$this->request->data['Infos_com']['ip'] = $this->request->clientIp();
$this->request->data['Infos_com']['id_infos'] = $number;
if($this->Infos_com->save($this->request->data))
{
$this->Session->setFlash(__('Comment is waiting for moderating',true),array('class'=>'alert alert-info'));
return $this->redirect(array('controller'=>'Infos','action'=>'index'));
}
$this->Session->setFlash(__('Niepowodzenie dodania komentarza',true),array('class'=>'alert alert-info'));
return TRUE;
}}
and Model Com.php, i comment lines to avoid neccesity of filling every field in forms
class Com extends AppModel
{
public $belongsTo = array('Info');
/*public $validate = array(
'mail'=>array(
'requierd'=>array(
'rule'=>array('notEmpty'),
'message'=>'Write your email'
)
),
'body'=>array(
'required'=>array(
'rule'=>array('notEmpty'),
'messages'=>'Write smth'
)
)
); */
}
I don't think you can access $this->request->data in a view (the data should be entered with a form, it was not submitted). You should use hidden fields to pass arguments like IP od id... Example:
echo $this->Form->input('Infos_com.client_id', array(
'type' => 'hidden',
'value' => $value
));
If you have multiple forms, it would be useful to separate their fields. For example:
echo $this->Form->input('Infos_com.' . $news_id . '.body', array('label' => __('body')));
This way you will get an array like:
$this->request->data['Infos_com'][$news_id]['body'].
And then you can make your logic in the model.

Yii Dependent-dropdown code not working

I am trying to setup a new application using the Yii framework that requires a dependent dropdown, so that when a user selects the jobSkillArea, the options for the next dropdown, jobSkillSpecialty, gets loaded using the built-in jQuery methods. I have copied and modified the code from things I found here and the Yii forums, but I am getting nothing, not even in Chrome's javascript console. Can anyone look at this and see where I've gone wrong? Thanks.
Here is the code in my view for the two dropdowns:
<div class="row">
<?php echo $form->labelEx($model,'jobSkillArea'); ?>
<?php
$list = array();
$list = CHtml::listData(validJobSkillAreas::model()->findAll(), 'JobSkillArea', 'JobSkillArea');
echo $form->dropDownList($model, 'jobSkillArea', $list,
array('prompt'=>'--Select Skill Area--'),
array(
'ajax'=>array(
'type'=>'POST',
'data'=>array('jobSkillArea'=>'js:this.value'),
'url'=>CController::createUrl('NewConsFormController/getSkillSpecialty'),
'update'=>'#'.CHtml::activeId($model,'jobSkillSpecialty')
)
)
);
?>
<?php echo $form->error($model,'jobSkillArea'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'jobSkillSpecialty'); ?>
<?php
$list = array();
$list = CHtml::listData(validJobSkillSpecialties::model()->findAll(),'jobSkillSpecialty','jobSkillSpecialty');
echo $form->dropDownList($model, 'jobSkillSpecialty', array(), array('prompt'=>'--Select Skill Specialty--'));
?>
<?php echo $form->error($model,'jobSkillSpecialty'); ?>
</div>
Then below is the code called by the first dropdown from my controller. The first find is to get the ID that links the parent with the child since I am not storing the KeyValue in the end product. The rest is as it came from the forums.
public function actionGetSkillSpecialty() {
$areaID = ValidJobSkillAreas::model()->find('JobSkillArea=:SkillArea',
array(':SkillArea'=>'$_POST[$jobSkillArea]'));
$data=ValidJobSkillSpecialties::model()->findAll('SkillAreaId=:SkillAreaId',
array(':SkillAreaId'=>$areaID->ID));
$list=array();
$list=CHtml::listData($data,'jobSkillSpecialty','jobSkillSpecialty');
echo "<option value=''>--Select Skill Specialty--</option>";
foreach($list as $value=>$jobSkillSpecialty) {
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($jobSkillSpecialty),true);
}
}
The view is a partial render within the _form view because that was the only way I could get the accordion widget to work with the fields I have. This is the accordion code that calls the jobDetails section that contains the two dropdown selection boxes.
<div id="accordion">
<?php
$this->widget('zii.widgets.jui.CJuiAccordion', array(
'panels'=>array(
'Job Details'=>$this->renderPartial('_partial_jobdetails',array('model'=>$model,'this'=>$this,'form'=>$form),true,false),
'Consultant Details'=>$this->renderPartial('_partial_consdetails',array('model'=>$model,'this'=>$this,'form'=>$form),true,false),
'Client Details'=>$this->renderPartial('_partial_clientdetails',array('model'=>$model,'this'=>$this,'form'=>$form),true,false),
'Internal Info'=>$this->renderPartial('_partial_internaldetails',array('model'=>$model,'this'=>$this,'form'=>$form),true,false),
'Form Requirements'=>$this->renderPartial('_partial_formsdetails',array('model'=>$model,'this'=>$this,'form'=>$form),true,false),
'JPMC Details'=>$this->renderPartial('_partial_jpmcdetails',array('model'=>$model,'this'=>$this,'form'=>$form),true,false),
),
// additional javascript options for the accordion plugin
'options'=>array(
'collapsible'=>true,
'active'=>false,
'autoHeight'=>false,
'heightStyle'=>'content',
),
'htmlOptions'=>array(
// HTML options you may need
),
));
?>
</div>
Please try the following code
View
<?php
echo CHtml::dropDownList('region_id','',
CHtml::listData($courses, 'course_id', 'course_name'),
array(
'prompt'=>'Select Region',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('loadcities'),
'update'=>'#city_name',
'data'=>array('region'=>'js:this.value'),
)));
echo CHtml::dropDownList('city_name','', array(), array('prompt'=>'Select City'),
);
?>
=================================================
controller function
public function actionLoadcities()
{
$data=City::model()->findAll('course='.$_POST['region'],
array(':region'=>(int) $_POST['region']));
$data=CHtml::listData($data,'city_id','city_name');
echo "<option value=''>Select City</option>";
foreach($data as $value=>$city_name)
echo CHtml::tag('option', array('value'=>$value),CHtml::encode($city_name),true);
}

Bulid Ajax in Yii

I need to understand how to build Ajax request in Yii. I searched on the Yii website and found the following article :
http://www.yiiframework.com/wiki/24/
I wrote the code and I tested it on my localhost ? but for some reason it did not work.
For a first attempt I only wanted to do something simple. I wanted to print the result of another action on my page by using Ajax. The text that I want to be displayed is 'Hi'.
This is how mu code looks like for that action:
view/index
<?php
/* #var $this CurrentController */
$this->breadcrumbs=array(
'Current'=>array('/current'),
'index',
);
?>
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'users-index-form',
'enableAjaxValidation'=>true,
)); ?>
<?php
echo CHtml::dropDownList('country_id','', array(1=>'USA',2=>'France',3=>'Japan'),
array(
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('currentController/dynamiccities'), //url to call.
//Style: CController::createUrl('currentController/methodToCall')
'update'=>'#city_id', //selector to update
//'data'=>'js:javascript statement'
//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());
?>
<?php $this->endWidget(); ?>
</div><!-- form -->
Controller
<?php
class CurrentController extends Controller
{
public function accessRules()
{
return array(
array('allow', // allow authenticated user to perform 'create' and 'update' actions
'actions'=>array('create','update','dynamiccities'),
'users'=>array('#'),
),
);
}
public $country_id;
public function actionIndex()
{
$this->render('index');
}
public function actionDynamiccities() /// Called Ajax
{
echo CHtml::tag('option',
array('value'=>'2'),CHtml::encode('Text'),true);
}
}
Unfortunately I'm not getting the desired result. What I get is:
drowpdown list contains country array.
another drowpdown list but empty ?!
How should I fix my example code so it would work? Can anyone see what I am doing wrong?
echo CHtml::dropDownList('city_id','', array());
use id as
echo CHtml::dropDownList('city_id','', array('id'=>'city_id'));

Categories