How to develop dependant drop down without database - php

I have following code in my controller:
public function getData($property)
{
$data = array(
'type'=>array(
'PC',
'Laptop'
),
'brand'=>array(
'1'=>array(
'ASUS PC',
'DELL PC',
),
'2'=>array(
'ASUS laptop',
'DELL laptop',
),
);
return $data[$property];
}
In my view:
<?= $form->dropDownList($model, 'type',$model->getData('type'), array('class' => 'form-control')) ?>
This code(in the view) returns types.(e.g shows pc and laptop options in the drop down ).
I need to develop dependant drop that will show 'ASUS PC'and 'DELL PC' in the drop down, if user chooses pc option from the the first drop down(type). How can I do it.

1) add two dropdown fields in view page.
<?php echo $form->dropDownList($model, 'type',array('PC'=>'PC','Laptop'=>'Laptops'),
array(
'empty'=>'--Select Product Type---' ,
'ajax' => array(
'type'=>'POST', //request type
'url'=>CController::createUrl('yourcontroller/getData'), //url to call.
'data'=>array('type'=>'js:this.value'),// value to send
'update'=>'#dependent_value', //selector to update
))); ?>
//empty since it will be filled by the other dropdown
<div class="row">
<?php echo CHtml::dropDownList('dependent_value','', array()); ?>
</div>
Controller
public function actionGetData() {
$data = array('type' => array('PC', 'Laptop'), 'brand' => array('1' => array('ASUS PC', 'DELL PC'), '2' => array('ASUS laptop', 'DELL laptop')));
//echo "<pre>";print_r($_POST['type']);die;
if ($_POST['type'] == 'PC') {
$arr = $data['brand'][1];
} elseif ($_POST['type'] == 'Laptop') {
$arr = $data['brand'][2];
} else {
$arr = array();
}
echo CHtml::tag('option', array('value' => $value), CHtml::encode("Select Product Brand--"), true);
foreach ($arr as $value => $name) {
echo CHtml::tag('option', array('value' => $value), CHtml::encode($name), true);
}
}
Note : Make sure to set permission to access this action in accessRules

Related

Get variable from a function in a class

I want to get a variable from a class in a function , the variable has arrays and i want to print all of theme in foreach loop
Here is my code :
class MP {
public function mp_setup_fields() {
$fields_socialmedia = array(
array(
'label' => 'شبکه های اجتماعی',
'id' => '',
'type' => 'hidden',
'section' => 'mp_custom_section',
),
);
}
}
I want get $fields_socialmedia in my home page
class MP {
public function mp_setup_fields() {
$fields_socialmedia = array(
array(
'label' => 'شبکه های اجتماعی',
'id' => '',
'type' => 'hidden',
'section' => 'mp_custom_section',
),
);
return $fields_socialmedia;
}
}
At first create object of your class then call method of object like below
$mp = new MP();
$array = $mp->mp_setup_fields();
foreach ($array as $value){
foreach ($value as $key => $v){
echo $key ."=". $v;
}
}

cakephp2 can't display data from contain

I am developing a web app using cake php 2.
I have an issue while displaying data from 2 tables...
My models :
<?php
class Discipline extends AppModel{
public $hasMany = "Student";
}
?>
<?php
class Student extends AppModel{
public $belongsTo = array(
"Discipline" => array(
"className" => "Discipline",
"foreignKey" => "discipline_id"
)
);
}
?>
Here is my studentscontroller :
<?php
class StudentsController extends AppController{
function admin_index(){
if($this->request->is('put') || $this->request->is('post')){
$student = $this->request->data['Student'];
if($this->Student->save($this->request->data)){
$this->Session->setFlash("L'eleve a bien été modifié","notif");
}
}
$d['student'] = $this->Student->find('all',array(
'contain' => "Discipline"
));
$this->set($d);
}
}
I am trying to display student's data using this view :
<?php
foreach($student as $k => $v){
$v = current($v);
echo "<td>Action</td>";
echo "<td>Label</td>";
echo "<td>".$v['nom']." ".$v['prenom']."</td>";
echo "<td>".$v['sexe']."</td>";
echo "<td>".$v['naissance']."</td>";
echo "<td>".$v['Discipline']['designation']."</td>";
echo "<td>".$v['comite']."</td>";
echo "<td>".$v['classe']."</td>";
echo "<td>".$v['elite']."</td>";
echo "<td>".$v['alerte']."</td>";
echo "<td>".$v['quota1']."</td>";
echo "<td>".$v['quota2']."</td>";
echo "<td>".$v['total']."</td>";
echo "<td>Pris</td>";
echo "<td>Restant</td>";
echo "<td>Supp</td>";
}
?>
But i have an issue on this line :
echo "<td>".$v['Discipline']['designation']."</td>";
It says this error :
notice (8): Undefined index: designation [APP\View\Students\admin_index.ctp, line 47]
I am used to develop on cakephp 3 and I am pretty embarassed with that error.. what to do to display data from Disciplines table from my student view ?
Any idea ? Thx
EDIT: I did a debug on my StudentsController, and I found the data I wanna display :
array(
'student' => array(
(int) 0 => array(
'Student' => array(
'id' => '2',
'prenom' => 'Jean',
'nom' => 'Michel',
'sexe' => '1',
'naissance' => '2015-08-02',
'age' => '12',
'classe' => '1',
'discipline_id' => '1',
'comite' => 'test',
'categorie' => 'test',
'elite' => true,
'alerte' => 'test',
'quota1' => '12',
'quota2' => '12',
'total' => '24',
'note' => 'tete'
),
'Discipline' => array(
**'id' => '1',
'designation' => 'Alpin'**
)
)
)
)
i think you should change the view
Change:
foreach($student as $k => $value){
$v = current($value);
to:
foreach($student as $k => $v){
$v = current($v);
and change:
echo "<td>".$v['Discipline']['designation']."</td>";
to
echo "<td>".$value['Discipline']['designation']."</td>";
You overwrite the variable $v with the first found array, so $v would be $v['Student']
I for myself won't use current to go inside a array for CakePHP, but use $v['Student'] everywhere

How can i use $data->id in the checkBoxHtmlOptions yii

I am using yii cgridview and i want to add alt in the checkboxes. I am successfull to add this but i want to add $data->rem_type i mean variable in this . here is the code i have tried
array(
'name' => 'check',
'id' => 'selectedIds',
'value' => '$data->rem_id',
'class' => 'CCheckBoxColumn',
'selectableRows' => '100',
'checkBoxHtmlOptions'=>array(
'alt'=>'$data->rem_type'),
),
but it producing the html like this
<input alt="{$data->rem_type}" value="12" id="selectedIds_0" type="checkbox" name="selectedIds[]">
If i removed the quotes (i.e 'alt'=>$data->rem_type)) it show me the error Undefined variable: data
can anybody help me ??
Ok, so I haven't tested this but I think you can do it like this:
extend the CCheckBoxColumn to CheckBoxColumn and overwrite the getDataCellContent function:
class CheckBoxColumn extends CCheckBoxColumn {
public function getDataCellContent($row) {
$data = $this->grid->dataProvider->data[$row];
if ($this->value !== null)
$value = $this->evaluateExpression($this->value, array('data' => $data, 'row' => $row));
elseif ($this->name !== null)
$value = CHtml::value($data, $this->name);
else
$value = $this->grid->dataProvider->keys[$row];
$checked = false;
if ($this->checked !== null)
$checked = $this->evaluateExpression($this->checked, array('data' => $data, 'row' => $row));
$options = $this->checkBoxHtmlOptions;
if ($this->disabled !== null)
$options['disabled'] = $this->evaluateExpression($this->disabled, array('data' => $data, 'row' => $row));
if (array_key_exists("alt", $options)) { //checks if you have set an alt
$options['alt'] = $this->evaluateExpression($options['alt'], array('data' => $data, 'row' => $row)); //if you have it will evaluate the expression
}
$name = $options['name'];
unset($options['name']);
$options['value'] = $value;
$options['id'] = $this->id . '_' . $row;
return CHtml::checkBox($name, $checked, $options);
}
}
I have copied most of the code from the original function
And added this part:
if (array_key_exists("alt", $options)) { //checks if you have set an alt
$options['alt'] = $this->evaluateExpression($options['alt'], array('data' =>data, 'row' => $row)); //if you have it will evaluate the expression
}
There is probably a way to do this better, i.e. not copy the code but I'll let you to this.
Save this in your components folder, include it in your config.php.
And use this class in your widget:
array(
'name' => 'check',
'id' => 'selectedIds',
'value' => '$data->rem_id',
'class' => 'CheckBoxColumn',// <-- instead of CCheckBoxColumn
'selectableRows' => '100',
'checkBoxHtmlOptions'=>array(
'alt'=>'$data->rem_type'),
),
Let me know if it works!

how to create dependent drop down list in YII? What is missing in Controller?

How To get Area DropDown/Select-Option by changing the City Option?
Find all Area List by City table primary key.
Condition is City(id) --> area(city_id) then I show that.
Now it's Show only Null when I change city option.
View:
<div class="row">
<?php echo $form->labelEx($model,'city'); ?>
<?php echo $form->dropDownList($model,'city', CHtml::listData(City::model()->findAll(), 'id', 'city'),
array(
'prompt'=>'select',
'ajax' => array(
'type' => 'POST', //My method type
'dataType' => 'JSON',
'url' => CController::createUrl('users/dynamiccities'), //This is my request/ajax URL
'data'=>array(
'city'=>'js:this.value',
),
'success'=>'js:function(data){
$("#Users_area").html(data.areaList);
}' //The functionaliy after success
)
));
?>
<?php echo $form->error($model,'city'); ?>
</div>
<?php echo $form->dropDownList($model, 'area', array(), array('prompt'=>'select')); ?>
Controller:
public function actionDynamiccities(){
$cityId = $_POST['city'];
$areaList = '';
if ($cityId != '') {
$areaList = CHtml::tag('option', array('value' => ''), CHtml::encode("NULL"), true);
} else {
$condition="city_id=".cityId;
$data = Area::model()->findAll(array('condition'=>$condition), 'id');
if($data){
$areaList = CHtml::tag('option', array('value' => ""), "Select", true);
foreach ($data as $d) {
$areaList .= CHtml::tag('option', array('value' => $d->id), CHtml::encode($d->area), true);
}
}else {
$areaList = CHtml::tag('option', array('value' => ''), CHtml::encode("NULL"), true);
}
}
echo CJSON::encode(array(
'areaList' => $areaList,
));
}

How do I echo previously chosen dropdown value in codeigniter?

This code works well in terms of adding new entry with this dropdown category. My problem is, this sets Option1 as the default value to make sure the dropdown is not left unanswered. My question is, how do I echo the previously saved value for dropdown category? I should have it correctly displayed so I can do edit function correctly.
<tr>
<span style="font-size: 10pt" class="label label-info">Category</span><br/>
<? $options = array
(
'1' => 'Option1',
'2' => 'Option2',
'3' => 'Option3',
'4' => 'Option4',
); ?>
<?php echo form_dropdown('category_id', $options, 'Option1');?>
</tr>
I am looking forward to any help.
Have a nice day! :)
EDIT: this works (by the way there are good classes to handle forms with codeigniter out there, where you don't have to use all this code for each field and that manage validation rules etc. in a much more flexible way - keeping the view and controller very simple and moving most of it into models).
<?php $model = array(
array('value' => '1', 'display' => 'Option1'),
array('value' => '2', 'display' => 'Option2'),
array('value' => '3', 'display' => 'Option3'));
echo '<select name="category_id">';
foreach($model as $i) echo '<option '.($this->input->post('category_id') === $i['value'] ? 'selected="selected"' : '').' value="'.$i['value'].'">'.$i['display'].'</option>';
echo '</select>';
?>
in ref from your question : Edit form echoes previously saved data correctly but does not update the form fields
<?php
foreach($model as $row)
{
if($row="" )
{
$selected_category_id = '';
$options = array
(
'1' => 'Option1',
'2' => 'Option2',
'3' => 'Option3',
'4' => 'Option4',
); ?>
<?php echo form_dropdown('category_id', $options, $selected_category_id);?>
}
else
{
$selected_category_id = '$row->(database column name where vale is stored)';
$options = array
(
'1' => 'Option1',
'2' => 'Option2',
'3' => 'Option3',
'4' => 'Option4',
); ?>
<?php echo form_dropdown('category_id', $options, $selected_category_id);?>
}
}

Categories