Yii Json to Array dropdownlist - php

I have a json like this:
{"response":{"count":7,"list":[{"kdTeacher":"001","nmTeacher":"Eulis Irma"},{"kdTeacher":"002","nmTeacher":"Ni Wayan"},{"kdTeacher":"003","nmTeacher":"Dwi Widi"}]},"metaData":{"message":"OK","code":200}}
I want the teacher name and the teacher code display in dropdownlist.
In my controller like this:
$model=new Teacher;
$paises = file_get_contents(Yii::getPathOfAlias('webroot.assets') .
DIRECTORY_SEPARATOR . "teacher.json");
$jsondecode = CJSON::decode($paises, true);
$temp = array();
foreach ($jsondecode as $key => $value) {
$temp[] = $value;
}
$this->render('techer', array(
'data'=>$temp,
'model'=>$model,
));
}
and in view
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->dropDownList($model,'nama',CHtml::listData($data,'kodeTeacher','nmTeacher')); ?>
<?php echo $form->error($model,'name'); ?>
</div>
id

Problem is that you can't get teacher data, because you use wrong data for foreach loop. Teacher code and name are stored at ['response']['list'] index of decoded json. Take a look:
$model=new Teacher;
$paises = file_get_contents(Yii::getPathOfAlias('webroot.assets') .
DIRECTORY_SEPARATOR . "teacher.json");
$decodedJson = json_decode($paises, true);
$temp = array();
//check if list of teachers is available
if(isset($decodedJson['response']) && isset($decodedJson['response']['list']))
{
//use foreach on ['response']['list'] index - here are teachers data stored
foreach($decodedJson['response']['list'] as $teacher)
$temp[$teacher['kdTeacher']] = $teacher['nmTeacher'];
}
$this->render('techer', array(
'data'=>$temp,
'model'=>$model,
));
Working example of get teachers data from JSON: CLICK!!!
And in view (now you don't need to use CHtml::listData method):
<div class="row">
<?php echo $form->labelEx($model,'name'); ?>
<?php echo $form->dropDownList($model,'nama',$data); ?>
<?php echo $form->error($model,'name'); ?>
</div>

Related

ACF Checkbox Output Sorted and Styled

I have the following code:
<?php $allCheckbox = get_field('sensor_types'); //Checked value from backend
$field_key = "field_60e546d470762"; //Get value using key
$post_id = get_the_ID();
$field = get_field_object($field_key, $post_id);?>
<?php foreach($field['choices'] as $lab => $val){
if(in_array($val, $allCheckbox)){
$enable = 'Yes';
} else {
$enable = 'No';
}?>
<div class="ct-div-block d-data-block c-columns-2-3">
<div class="ct-div-block"><?php echo $val; ?></div>
<div class="ct-div-block"><?php echo $enable ?></div>
</div>
<div class="d-seperator"></div>
<?php } ?>
I want to sort out the output to alphabetical order but as there is two output $val and $enable I am at confusion as to how i can use the Sort Function to solve this issue. The sort is dependent on $enable that is the ones with yes will come first then the ones with no

Can't update data using Mysql and Codeigniter

i want to update my array data from table monitordata, but the data wont update i dont know where's the problem. there's no error in this code too :(
this is my controller
public function ubah($id) {
$data_lama = $this->monitor_m->get($id);
$this->data->tglmonitor = $data_lama->tglmonitor;
$this->data->detail = $this->monitor_m->get_record(array('monitor_data.idMonitor'=>$id),true);
$this->template->set_judul('SMIB | Monitoring')
->render('monitor_edit',$this->data);
}
public function ubahku($id) {
$id = $this->input->post('idMonitor_data');
if($this->input->post('idinven')!=NULL){
$idMonitor = $this->input->post('idMonitor');
$kondisi = $this->input->post('kondisi');
$nobrg = $this->input->post('nobrg');
$keterangan = $this->input->post('keterangan');
$kdinven = $this->input->post('kdinven');
$idinven = $_POST['idinven'];
for($i = 0; $i < count($idinven); $i++){
$data_detail = array(
'idMonitor' => $this->input->post('idMonitor'),
'idinven'=> $idinven[$i],
'kdinven'=> $kdinven[$i],
'nobrg'=> $nobrg[$i],
'kondisi'=> $kondisi[$i],
'keterangan' => $keterangan[$i]);
//print_r($data_detail);
$where = array('idMonitor_data' => $id);
$this->monitordata_m->update_by($where,$data_detail);
}
} redirect('monitorcoba');
}
This is my model monitordata_m
class Monitordata_m extends MY_Model {
public function __construct(){
parent::__construct();
parent::set_table('monitor_data','idMonitor_data');
}
This is MY_Model model i put in core folder.
public function update_by($where = array(), $data = array()) {
$this->db->where($where);
if ($this->db->update($this->table,$data)){
return true;
}
return false;
}
And this is my view
<?php echo form_open(site_url("monitorcoba/ubahku"),'data-ajax="false"'); ?>
<input data-theme="e" style="float: right;" data-mini="true" data-inline="false" data-icon="check" data-iconpos="right" value="Simpan" type="submit" />
<div data-role="collapsible-set" data-mini="true">
<?php foreach ($detail as $items): ?>
<div data-role="collapsible">
<?php echo form_hidden('idMonitor_data', $items['idMonitor_data'] ); ?>
<?php echo form_hidden('idMonitor', $items['idMonitor'] ); ?>
<h4><?php echo '[ '.$items['kdinven'].' ] '.$items['namabrg'] ?> </h4>
<?php echo form_hidden('kdinven', $items['kdinven'] ); ?>
<?php echo form_hidden('idinven', $items['idinven'] ); ?>
<div data-role="controlgroup">
<?php echo form_label ('Kondisi : ');
echo " <select name='kondisi' data-mini='true'>
<option value=".$items['kondisi'].">".$items['kondisi']."</option>
<option value=''>--Pilih--</option>
<option value='Baik'>Baik</option>
<option value='Rusak'>Rusak</option>
<option value='Hilang'>Hilang</option>";
echo "</select>";
echo form_input('keterangan',#$keterangan,'placeholder="Masukan Keterangan Tambahan"','class="input-text"');
?>
<?php echo form_close(); ?>
even if i use update_by it doesnt work. it's been 2 weeks and i have no clue :( i've tried all of the answer that i found in google but still.. so please help me.
This is the DATABASE result and POST_DATA for method ubahku
You have defined a method named update_by, but you are calling $this->monitordata_m->update($id,$data_detail);. Definitely it should not work. please call $this->monitordata_m->update_by($id,$data_detail); from your controller & check what will happen.
Firstly, Please correction $this->monitordata_m->update($id,$data_detail); to $this->monitordata_m->update_by($id,$data_detail); because your function name is update_by in your monitordata_m model.
Secondly, in your monitordata_m model update_by function have 2 param like $where = array() $data = array(), $where is a array but you calling in controller only $id. Your $id is not array. $where is like that $where = array('id' => $id) //id is where field name from db table
So, ubahku($id) method in your controller call $where in update_by function:
$where = array('id' => $id); // 'id' means "where field name"
$this->monitordata_m->update_by($where,$data_detail);
So, thank you so much for everyone who answer my question. so the problem was when i update the data, system only detect "kondisi[]" and "keterangan[]" as an array because i use this "[]" for both of it, so i just have to add "[]" in the end of every name in html form / views. so system will detect every input as an array. i hope you understand what i'm saying, sorry for my bad english. thank you this case is closed :)

Dependent dropdown for country and state in yii 1.13

I had created two database tables as,
Country
State
In Country table i had countryid & cname field. In State table i had state_id, state_name & country_cid.
Now i need to make a dependent dropdown i.e. when i select country dropdown box, then the particular state for that country should be displayed. I had done below coding. But it displays only country and not displays state.
This is in views/sample/register.php file.
<div class="row">
<?php echo $form->labelEx($model,'countryid');
$opts = CHtml::listData(Country::model()->findAll(),'countryid','cname');
echo $form->dropDownList($model,'country_id',$opts,
array(
'prompt'=>'Select Country',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('SampleController/dynamicSubcategory'),
array('coountry_id'=>'js:this.value'),
'dataType' => 'JSON',
'success'=>'js:function(data)'
. '{'
. 'var html="<option value=>-----Select city-----</option>";'
. '$.each(data,function(i,obj)'
. '{'
. 'html+="<option value=\'"+obj.id+"\'>"+obj.name+"</option>";'
. '});'
. '$("#state_id").html(html);'
. '}'
)));
echo $form->error($model,'country_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'state_id');
echo CHtml::dropDownList('state_id','', array());
echo $form->error($model,'state_id'); ?>
</div>
This is in controllers/SampleController.php file
public function actiondynamicSubcategory()
{
$countryId=$_POST['coountry_id'];
$criteria=new CDbCriteria();
$criteria->select=array('state_id,state_name');
$criteria->condition='country_cid='.$countryId;
$criteria->order='state_name';
$cityAry= State::model()->findAll($criteria);
$ary=array();
foreach($cityAry as $i=>$obj)
{
$ary[$i]['state_id']=$obj->id;
$ary[$i]['state_name']=$obj->name;
}
echo json_encode($ary);
}
I had created Country model & State model. I had analyzed many sites. But i can't get right. Please anybody help.
You can try below code which I have used in one of my projects -
**Code in the view file :**
<?php $arrOptionsCountry = array('prompt'=>'Select Country','ajax'=> array('type'=>'POST','url' => ApplicationConfig::getURL('', 'site','SearchValueStates'),'update'=>'#Airports_state','beforeSend'=>'stateLoading'));
echo $form->dropDownList($model,'country',$arrCountryList,$arrOptionsCountry,array('class'=>'span11 customDropdown1_select'));
$arrOptionsState = array('prompt'=>'Select State','ajax'=> array('type'=>'POST','url' => ApplicationConfig::getURL('', 'site', 'SearchValueCities'),'update'=>'#station_name','beforeSend'=>'cityLoading'));
echo $form->dropDownList($model,'state',$arrStatesList,$arrOptionsState);
echo $form->dropDownList($model,'city',$arrCityList);
?>
**Site Controller :**
public function actionSearchValueStates()
{
$arrParam =array();
if(isset($_POST['Airports']['country']))
{
$Term = $_POST['Airports']['country'] ;
$case = "STATE-LIST";
$prompt = "Select State";
$arrParam['id'] = isset($Term)?$Term:null ;
$data = States::getList($case,$arrParam);
$data = CHtml::listData($data,'id','name');
echo CHtml::tag('option',array('value'=>''),$prompt,true);
foreach($data as $value=>$name)
{
echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name));
}
}
Yii::app()->end();
}
I got the answer for my question.
This is in views/sample/register.php file
<div class="row">
<?php echo $form->labelEx($model,'country');
$opts = CHtml::listData(Country::model()->findAll(),'countryid','cname');
echo $form->dropDownList($model,'country_id',$opts,
array(
'prompt'=>'Select Country',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('Sample/dynamicSubcategory'),
'update'=>'#state_name',
'data'=>array('country_id'=>'js:this.value'),
)));
echo $form->error($model,'country_id'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'state_id');
echo CHtml::dropDownList('state_name','', array(), array(
'prompt'=>'Select State'
));
echo $form->error($model,'state_id'); ?>
</div>
This is in controllers/SampleController.php file
public function actiondynamicSubcategory()
{
$data=State::model()->findAll('country_cid=:countryid',
array(':countryid'=>(int) $_POST['country_id']));
$data=CHtml::listData($data,'state_id','state_name');
echo "<option value=''>Select State</option>";
foreach($data as $value=>$state_name)
echo CHtml::tag('option', array('value'=>$value),CHtml::encode($state_name),true);
}
This code works fine for dependent dropdown in yii

Yii, Looping form fields for Tabular Input

I am using the Yii Framework 1.1.17, and have generated three models:
Question, AnswerOption and Response.
The relationships:
Table: Question (list of questions)
id
text
Table: AnswerOption (list of possible answers, associated with question)
id
question_id
text
Table: Response (question and selected answer collector)
id
question_id
answer_option_id
text
I am trying to create a form, and admittedly collect answers for all possible questions.
File: ResponseController
public function actionCreate()
{
// load all questions and with it the possible answer Options
$questions = Question::model()->findAll();
// get number of questions
$count = Question::Model()->count();
$model = array();
$i = 1;
while ($i <= $count) {
$model[] = Response::model();
$i++;
}
if (isset($_POST['Response'])) {
//
}
$this->render('create', array(
'model' => $model,
'questions' => $questions,
));
}
This is the area that I am having trouble with:
File: response/_form
<?php foreach($questions as $i=>$question): ?>
<?php echo CHtml::activehiddenField($question,"[$i]id"); ?> <?php echo $question['text']; ?>
<?php $options = CHtml::listData($question->answerOptions, 'id', 'text');?>
<?php echo CHtml::activeDropDownList(AnswerOption::model(), "[$i]text", $options, array('empty' => 'Select answer...')); ?>
<?php endforeach; ?>
I may have populated my questions and possible answers, but I need to validate and save the results in $model.
It seems like I cannot find a way to efficiently work this out. Can someone please guide me?
I managed to resolve my "loop" problem by:
File: response/_form
<?php $questions = Question::model()->findAll(); ?>
<?php foreach ($questions as $j=>$question): ?>
<div class="row">
<?php echo $form->labelEx($model["$j"], "[$j]question_id"); ?>
<?php echo $form->hiddenField($model["$j"], "[$j]question_id", array('value' => $question["id"])); ?>
<?php echo $question['text']; ?>
</div>
<div class="row">
<?php $options = CHtml::listData($question->answerOptions, 'id', 'text');?>
<?php echo $form->labelEx($model["$j"], "[$j]answer_option_id"); ?>
<?php echo $form->dropDownList($model["$j"], "[$j]answer_option_id", $options, array('empty' => 'Select answer...')); ?>
</div>
<?php endforeach; ?>
Hopefully, this would come in handy for someone, someday.

Foreach loop shows only few items

I'm working with CodeIgniter.
I need to get some data from database with a foreach loop.
I have 4 items in the database, but the loop retrieve only two of them (the items with id 2 and 4).
This is the code in the for the foreach in the controller:
$this->load->model('home_model');
$data['query']=$this->home_model->get_films($limit);
if ($data['query']) {
$data['main_content'] = 'home';
$data['film'] = array();
foreach($data['query'] as $film_info) {
$data['film'] = array(
'id' => $film_info->id,
'poster_src' => $film_info->film_poster_src,
'title' => $film_info->film_name,
'year' => $film_info->film_year,
'genre_id' => $film_info->genre_id,
);
$this->db->select('*');
$this->db->from('genres');
$this->db->where('id', $film_info->genre_id);
$query1 = $this->db->get();
$genre_info = $query1->row();
$data['genre_name'] = $genre_info->genre_name;
$this->db->select('*');
$this->db->from('votes');
$this->db->where('film_id', $film_info->id);
$this->db->where('vote', '1');
$query2 = $this->db->get();
$data['votes_count'] = $query2->num_rows();
}
$this->load->view('template', $data);
This is the code in the model:
<?php
class Home_model extends CI_Model
{
function get_films($limit)
{
$query = $this->db->get('films', $limit, $this->uri->segment(2));
return $query->result();
}
}
And this is the code in the view:
<div class="col-sm-6 col-md-4">
<div class="thumbnail">
<img src="<?php echo $film['poster_src'] ?>" alt="Film poster">
<div class="caption">
<h3><?php echo $film['title'] ?></h3>
<p>Year: <?php echo $film['year'] ?></p>
<p>Genre: <?php echo $genre_name ?></p>
<p>Votes: <?php echo $votes_count ?></p>
<p>Watch Add to bookmarks</p>
</div>
</div>
</div>
If I put the foreach code in the view, it works properly.
I am not 100% sure so don't vote if false just make me aware i will try another way if possible.in foreach loop try to put the data in another array like this
$new_array[] = $the_result_value_you want
then you will be able to use $new_array outside the loop

Categories