I have two tables: 1. STUDENT- fields are- (studentid,studentname,batch)
2. BATCH- fields are- (batchid,batchname)
I want to populate a dropdown list from the field "batchname" ( from the table "BATCH") and have the batchname selected based on the field-"batch" (from the table "Student")
My controller -
function update($id){
$this->load->model('mod_studentprofile');
$data['query']= $this->mod_studentprofile->student_get($id); //to retrieve information from the table "STUDENT"
$data['query']= $this->mod_studentprofile->batch_get();
$data['main_content']='update_studentprofile';
$this->load->view('includes/template',$data);
}
My model -
function batch_get()
{
$query = $this->db->get('batch');
return $query->result();
}
Now, I cannot figure out how to populate the dropdown in the "View". Would you please kindly help me with this?
Thanks in Advance.
You need to put the options you want displayed in the drop down into an array, like so
$options = array(
'red' => 'Red',
'green' => 'Green',
'blue' => 'Blue',
);
// The params here are:
// 'color' => name of the drop down
// '$options' => options for the drop down
// 'red' => the selected value of the drop down
echo form_dropdown('color', $options, 'red');
What I would do is create a function in my model, say $model->dropdown_options() and use that to get the rows from the database and put them into an array.
See Jamie Rumbelow's 'MY_Model' class, he has a method that does exactly what you're describing.
https://github.com/jamierumbelow/codeigniter-base-model/blob/master/core/MY_Model.php
Related
How to populate a select dropdown in cakephp3 from a database table.
Currently Cakephp produces an array (list of options) which is numeric indexed.
The option values should have id of database records (should not be the numeric keys generated by Cakephp)
Departments(table) is a taxonomy to classify events.
Events(table) which should store department based list of events.
A event may belongs to many departments. How do I achieve this?
EventsController.php
<?php $department_results = $connection->execute('SELECT departmentname FROM department')->fetchAll('assoc'); // list of departments
$this->set('departmentvalues', $department_results );
Events: add.ctp
<?php echo $this->Form->input('department', array('label' => false,
'div' => false,
'type' => 'select',
'multiple'=>'checkbox',
'legend' => 'false',
'options' => $departmentvalues,
'empty' => 'Please select a Department'
));
Objective:
A select dropdown with values from database, option values should be id of the database record
Expected result:
<select name="department"><option value="2">Maths</option><option value="4">Physics</option></select>
Issue:
cakephp generates numeric indexed array of options.
<select name="department"><option value="0">Maths</option><option value="1">Physics</option></select>
You should really use the CakePHP standard for querying your models, instead of raw SQL, especially in the case of a simple list.
Something like the below should do what you need:
$department_results = $this->Departments->find('list')
->hydrate(false)
->fields(['id','departmentname'])
->toArray();
$this->set('departmentvalues', $department_results);
Note that you will need to include the fields as you have named your column departmentname. By default, a find('list') should return id and name fields.
Another option is to set the displayField this way :
`class DepartmentsTable extends Table {
public function initialize(array $config) {
parent::initialize($config);
$this->displayField('departmentname');
}
}`
In the controller you may just call the method find('list') this way :
$departments= TableRegistry::get("Departments");
$departmentvalues=$departments->find('list')
->hydrate(false)
->toArray();
$this->set('departmentvalues', $department_results);
I'm using version 1.1.14 of yii.
My VIEW file has
<?php echo $form->dropDownList($model,'estado', CHtml::listData(Estado::model()->findAll(), 'id', 'estado')); ?>
I have a model called Estado which was generated from a table with only 2 fields ID as PK and estado where I have my data. Which has 3 rows Active, Inactive, Prospecting.
So far the code only shows the last row of that table, ignoring the first 2.
What am I doing wrong?
for the dropdown list you can pass a normal array :
$data = array(
'number1',
'number2',
'number3',
);
or an array with key => value
$data = array(
7 => 'number7',
2 =>'number2',
4 =>'number4',
);
Chtml::listData() will only help you make that array avalable for the function
however if you need to make a combination of models ( or arrays) you have to do that manually using array concatenation functions such as CMap::mergeArray()
echo Form::select(
'campaign_user_id',
User::find(1)->profile->lists('first_name', 'id'),
Input::get('campaign_user_id', $campaign->user_id),
array(
"placeholder" => "US",
'class' => 'form-control',
'disabled' => 'disabled'
)
)
The code above is used to build a Dropdown selection list. It fetches a list of Users from the database. On line 3 you can see User::find(1)->profile->lists('first_name', 'id')
It is getting the first_name column, I need to somehow get first and last name columns though and combine them in this list. So that list value is still user ID and Full name is shown.
Any idea how to make this work with 2 DB columns first_name and last_name? Or another method to reach my end goal?
// In your model
class User extends Eloquent
{
public function getFullNameAttribute()
{
return $this->attributes['first_name'] . ' ' . $this->attributes['last_name'];
}
}
then grab like so:
User::find(1)->profile->lists('full_name', 'id');
OR
User::find(1)->profile->select(DB::raw('concat (first_name," ",last_name) as full_name,id'))->lists('full_name', 'id');
I prefer the first one :)
I need to show two dependent drop-down lists in my page. If we select an item from first drop-down list, based on the item which we selected, it should filter the entries in the second drop-down list, then I need to perform a search using the value in the second drop-down list. But the thing is that the values come from the table to show in the first drop-down list is not an active record of it. Can anyone help on this?
Currently I have that second drop-down list in place and it can perform a search based on the selected value. Now what I need to do is place a drop-down list above this and filter the items based on the first drop-down list.
Edit
1st table - client_id, client_name - items in the first drop-down list should show client names
2nd table - program_id, client_id, program_name -
3rd table - ad_id, program_id, ad_name - the second drop-down list should show ad_names filtered by using client_id.
Finally I did that, here is it.
In my controller,
public function actionDynamicDropdownList()
{
if($_POST['client_id'] > '0') {
$result = Yii::app()->db->createCommand()->select('program_id, program_name')->from('program')->where('client_id='.$_POST['client_id'].'')->order('program_name')->queryAll();
$this->render('admin', array(
'result' => $result,
));
}
}
public function actionDynamicProgramsList()
{
if($_POST['program_id'] > '0') {
$results = Yii::app()->db->createCommand()->select('ad_id, ad_name')->from('ads')->where('program_id='.$_POST['program_id'].'')->order('ad_name')->queryAll();
$this->render('admin', array(
'results' => $results,
));
}
}
and in my view, I have added
<?php
$data = Yii::app()->db->createCommand()->select('client_id, client_name')->from('client')->order('client_name')->queryAll();
echo CHtml::dropDownList('client_id', '',CHtml::listData($data,'client_id','client_name'), array(
'empty'=>'- Select Client Name -',
'ajax'=> array(
'type'=>'POST',
'url'=>Yii::app()->baseUrl.'/index.php?r=page/dynamicDropdownList',
'update'=>'#program_id')));
//empty since it will be filled by the above dropdown
echo CHtml::dropDownList('program_id','', CHtml::listData($result,'program_id','program_name'), array(
'empty'=>'- Select Program Name - ',
'onchange'=>'alert(this.value);',
'ajax'=> array(
'type'=>'POST',
'url'=>Yii::app()->baseUrl.'/index.php?r=page/dynamicProgramsList',
'update'=>'#ad_id')));
//empty since it will be filled by the above dropdown
echo CHtml::dropDownList('ad_id','', CHtml::listData($results,'ad_id','ad_name'), array(
'empty'=>'- Select Ad Name - ',
));
?>
I have enum function in some of the rows and was wondering how we could fetch this in Cake to view it as select box?
Below is the function example:
enum('Uusi hakija','Jatkohakemus','40+','60+','Työyhteisöhanke','Mieshanke','Urheiluseurahanke')
The proper "Cake" way of doing this would be to use the Array Datasource from the official datasources plugin.
You setup a model for your enum data and assign all the normal relationships. To set the data set the records property in your model like so:
public $records = array(
array('id' => '1', 'name' => 'stuff'),
array('id' => '2')
);
$enumList = enum('Your', 'stuff', 'goes', 'here');
$vars = explode('.', $enumList);
$this->Form->select('Model.field_name', $vars);
Very simple but should work. Your option names would be 0, 1, 2, etc.
Check out CakePHP's FormHelper and the select input.