Dependent dropdown for country and state in yii 1.13 - php

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

Related

How to Fix My Form Didn't Update Data to Database [Codeigniter]

I have a problem with my form. When i input the form and submit, the form didn't save to my database.
In my form showing code transaction, and email customer. And if customer buying product in my website.
I just confirmation the order with click form code transaction.
In form code transaction showing, code transaction and email customer. And me input the logistic name, no. order of logistic to customer tracking their order, and choice the order packet has sending.
But in my problem the form succes save the order packet information "has sending" , but for logistic name and no. order of logistic didn't save.
This is my view.
<div id="<?php echo $row['codetrans'] ?>" class="reveal-modal">
<h3>Detail Order</h3>
<?php echo form_open('order/edit_stats_order');
$codetrans = array(
'name' => 'codetrans',
'class' => 'column',
'size' => '30'
);
$email = array(
'name' => 'email',
'class' => 'column',
'size' => '30'
);
$no_order = array(
'name' => 'no_order',
'class' => 'column',
'size' => '30'
);
$log = array(
'FedEx' => 'FedEx',
'RPX' => 'RPX');
?>
<span>Code :</span>
<?php echo form_input($codetrans,$row['codetrans']) ?><br/>
<span>Email :</span>
<?php echo form_input($email,$row['email']) ?><br/>
<span>Logistic Name :</span><br/>
<?php echo form_dropdown('log', $log,$row['log']); ?><br/><br/>
<span>No. Order :</span>
<?php echo form_input($no_order,$row['no_order']) ?><br/>
<?php $options = array(
'0' => 'Not Sendirng',
'1' => 'Has Sending'); ?><br/>
<?php echo form_dropdown('stats_order', $options,$row['stats_order']); ?><br/>
<?php echo form_hidden('input_hidden_id',$row['codetrans']);?>
<?php echo form_submit('submit', 'Submit', 'class=searchbutton'); ?>
<?php echo form_close();?>
<a class="close-reveal-modal">×</a>
</div>
<?php
}
?>
</ul>
<?php echo anchor('order/stats_order', 'Open All Stats', 'class="btn btn_aS"' ); ?>
</div>
This my controller.
public function edit_stats_order() {
$this->load->model('Order_model');
$codetrans = $this->input->post('codetrans');
$email = $this->input->post('email');
$log = $this->input->post('log');
$no_order = $this->input->post('no_order');
$stats_order = $this->input->post('stats_order');
if($email !='' && $codetrans !='' && $log !='' && $no_order !=''){
$this->Order_model->edit_stats_order($codetrans,$email,$log,$no_order);
redirect('order/main');
}
else{
echo "<script>alert('Check Again!');</script>";
echo "<script>location.href = document.referrer</script>";
}
}
This is my model.
public function edit_stats_order($codetrans,$email,$log,$no_order){
date_default_timezone_set('xxxxx');
$data['email'] = $email;
$data['no_order'] = $no_order;
$data['log'] = $log;
$data['stats_order'] = $stats_order;
$data['date'] = date('Y-m-d');
$this->db->where('codetrans',$codetrans);
$this->db->update('ordering',$data);
}
Why the fault in my code?
Thanks
You are trying to use $stats_order in model function which is not defined in model. So you have to pass $stats_order to model function.
Add one more parameter to the function call for $stats_order in order to pass it to the model.
$this->Order_model->edit_stats_order($codetrans,$email,$log,$no_order,$stats_order);
Also add one more parameter in model function for the same. Change the first line of the function in model to,
public function edit_stats_order($codetrans,$email,$log,$no_order,$stats_order){

Yii Json to Array dropdownlist

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>

Codeigniter - How to create a form with undefined number of input?

So I've been trying to create an 'add' function for a contest table that is also linked to a joining table as the contest has many sport events associated to it (and a sport events will also be included in many contests). I have managed to create it as below, however it is limited to only adding one row into the joining table based on the chosen game in a dropdown.
So now, how do I go about creating the form if I don't know how many sport events there might be? How will the website create another dropdown if one dropdown is used so that more sport events can be selected? Similarly, how does the controller know that there are x amount of dropdowns selected, and hence x amount of rows to be added to the joining table?
I'm sorry if I am using incorrect or ambiguous terms to describe my problem. I have only started learning and creating websites recently.
Thank you.
UPDATE: I may have a solution per the updated codes below. However I am now stuck on the inserting into the database page. For some reason when I click submit, the next page loads but with no error and no rows inserted. Please help :)
View
<h1>Add New Contest</h1>
<?php
echo form_open('contests/add/');
?>
<?php
echo "<br />" "<br />"
echo "Contest Name";
$data = array( 'name' => 'contest_name',
'value' => set_value('contest_name'),
);
echo form_input($data);
echo "<br />" "<br />"
echo "Game";
?>
<div class="field_wrapper">
<div>
<select name="field_name[]">
<option value="" disabled selected>Select Game</option>
<?php
foreach($events_lists->result() as $row) {
$sports_events_id = $row->sports_events_id;
$sports_events_start_date = $row->sports_events_start_date;
$sports_events_start_time = $row->sports_events_start_time;
$home_team_shorthand = $row->home_team_shorthand;
$away_team_shorthand = $row->away_team_shorthand;
?>
<option value="<?php echo $sports_events_id; ?>"><?php echo $home_team_shorthand; ?> v <?php echo $away_team_shorthand; ?> - <?php echo $sports_events_start_date; ?> <?php echo $sports_events_start_time; ?></option>
<?php } ?>
</select>
<img src="add-icon.png"/>
</div>
</div>
<?php
echo "<br />" "<br />"
$data = array( 'value' => 'Add Contest',
'name' => 'submit',
'class' => 'submit-btn',
);
echo form_submit($data);
echo form_close();
?>
Controller
function add()
{
$league_id = $this->uri->segment(3);
$this->load->module('leagues');
$data['leagues_list'] = $this->leagues->get_where($league_id);
foreach ($data['leagues_list']->result() as $row) {
$league_insert_id = $row->id;
$this->load->module('sports_events');
$data['events_lists'] = $this->sports_events->get_events_list($league_insert_id);
}
if ($this->form_validation->run() == FALSE) {
$data['view_file'] = 'add_contest';
$this->load->module('template');
$this->template->cmslayout($data);
} else {
$data1 = array(
'contest_name' => $this->input->post('contest_name')
);
if(isset($_REQUEST['submit'])) {
$data2 = $_REQUEST['field_name'];
}
if ($this->_transactions_new_contest($data1, $data2)) {
return $query;
$this->session->set_flashdata('team_phase_created', 'The team phase has been set');
redirect('/contests/');
}
}
}
Model
function _transactions_new_contest($data1, $data2){
$this->db->trans_start();
$this->db->insert('contests', $data1);
$contest_id = $this->db->query('SELECT contests.id FROM contests ORDER BY contests.id DESC limit 1');
foreach ($contest_id->result() as $row) {
$contest_result_id = $row->id;
foreach($data2 as $value){
$this->db->query('INSERT INTO contests_has_sports_events (contests_id, sports_events_id) VALUES (' . $contest_result_id . ', ' . $value . ')');
} }
$this->db->trans_complete();
}

How to populate the select options from a table in phalcon?

I have a list containing tags with id name and status in a table and in my Model TagsStandard I have this:
const STATUS_APPROVED = 1;
const STATUS_DISABLED= 0;
public $id;
public $name;
public $status;
public static function getAllTag()
{
$tags = TagsStandard::find(array(
"status = 'STATUS_APPROVED'",
"order" => "id"
));
}
So with this I am getting all the tags. Now at Controller in indexAction I have:
$tags = TagsStandard::getAllTag();
if ($tags) {
$this->view->tags = $tags;
$this->view->name = array("name" => $tags->name->toArray());
}
And in the index I have:
<select id='user-skills-input' class="select-chosen" type="text" data-role="tagsinput" value="" multiple>
<?php if(count($tags) > 0): ?>
<?php foreach($tags->items as $idx => $tag):
echo "<option value='" . $tag->id . "'> " . $tag->name . "</option>" ?>
<?php endforeach; ?>
<?php endif; ?>
</select>
The values are not showing up in the options and so can anyone help me with this?
<?php
echo \Phalcon\Tag::select(array(
"user-skills-input",
TagsStandard::find(array(
"status = 'STATUS_APPROVED'",
"order" => "id"
)),
"using" => array("id", "name")
);
Phalcon Tags#select

dependent dropdown box with Yii

i have a countries, states, cities tables , and I need 3 dropdown menus
wherein, if i select a country like e.g United States, the states dropdown menu will automatically show only the states that are under United States, and next, if I select a State like e.g California, the Cities drop down menu will only show off the Cities under California
am currently having problem implementing this in yii. I have this _form file
where these 3 dropdown should be included. I have a partial code, but I can't figure out how to make this work out
this is from the Controller
public function actionDynamicstates()
{
$sql = "SELECT StateName FROM gg_t_worldareasstates ".
"WHERE CountryID = :countryid";
$command = Yii::app()->createCommand($sql);
$command->bindValue(':countryid', $_POST['CountryID'], PDO::PARAM_INT);
$data = $command->execute();
$data = CHtml::listData($data,'StateID','StateName');
foreach($data as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
}
this is from the _form view file
<div class="row">
<?php
$country = new CDbCriteria;
$country->order = 'CountryName ASC';
echo $form->dropDownList($model, 'CountryID',
CHtml::listData
(
Worldareascountries::model()->findAll($country),
'CountryID',
array
(
'ajax' => array
(
'type' => 'POST',
'url' => CController::createUrl('wsmembersdetails/dynamicstates'),
'update' => '#StateID',
)
)
)
);
echo $form->dropDownList('StateID','', array());
?>
</div>
I changed that those codes above into this one
<div class="row">
<?php echo $form->labelEx($model,'Country'); ?>
<?php
$country = new CDbCriteria;
$country->order = 'CountryName ASC';
?>
<?php
echo $form->dropDownList($model,'CountryID',CHtml::listData(Worldareascountries::model()->findAll($country),'CountryID','CountryName'),
array(
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('wsmembersdetails/dynamicstates'),
'update' => "#StateID"
)
)
);
?>
<?php echo $form->error($model,'CountryID'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'State'); ?>
<?php
$state = new CDbCriteria;
$state->order = 'StateName ASC';
?>
<?php
echo $form->dropDownList($model,'StateID',CHtml::listData(Worldareasstates::model()->findAll($state),'StateID','StateName'),
array(
'ajax' => array(
'type' => 'POST',
'url' => CController::createUrl('wsmembersdetails/dynamiccities'),
'update' => '#CityID'
)
)
);
?>
<?php echo $form->error($model,'StateID'); ?>
</div>
<div class="row">
<?php echo $form->labelEx($model,'CityID'); ?>
<?php echo $form->dropDownList($model,'CityID','',array());?>
<?php echo $form->error($model,'CityID'); ?>
change this line
$data = $command->execute();
to
$data = $command->query();
this problem was solved, it's on the yii wiki docs

Categories