Yii2 Dependant drop down not working when we open update page.My depend drop down value came from database. When I create entry It works Very well with the condition. but I when go for Update then Pre selectect value does not show. i.e. Which I save while creating. This is my _form.php
$arrCountry = \yii\helpers\ArrayHelper::map($modelCountry, 'country_id', 'country');
echo $form->field($model, 'country_id')->dropDownList($arrCountry,
['prompt'=>'-Choose a country-',
'onchange'=>'
$.post( "'.Yii::$app->urlManager->createUrl('country/lists?id=').'"+$(this).val(), function( data ) {
$( "select#city_name" ).html( data );
});
']);
$dataPost=\yii\helpers\ArrayHelper::map(City::find()->asArray()->all(), 'city_id', 'city_name');
// print_r($dataPost);die;
echo $form->field($model, 'city_id')
->dropDownList(
$dataPost,
['id'=>'city_name']
);
2.Controller
public function actionLists($id)
{
$countCity =City::find()
->where(['city_id' => $id,'status'=>'not assign'])
->count();
$arrCity = City::find()
->where(['city_id' => $id,'status'=>'not assign'])
->orderBy('city_id DESC')
->all();
if($countCity>0){
foreach($arrCity as $arrCity){
echo "<option value='".$arrCity->city_id."'>".$arrCity->city_name."</option>";
}
}
else{
echo "<option>-</option>";
}
}
Related
I have dropDownList in my view ( data from db) :
use yii\widgets\ActiveForm;
\app\assets\HelloAsset::register($this);
$form = ActiveForm::begin();
$users=\app\models\User::find()->all();
$items=\yii\helpers\ArrayHelper::map($users,'id','username');
echo $form->field($model, 'username')->dropDownList($items);
echo \yii\bootstrap\Html::submitButton('Send');
ActiveForm::end();
I want to get data from 'username' in my controller:
$model=new Data();
if ($model->load(\Yii::$app->request->post())){
echo 'it is status:'.$model->username;
}else {
return $this->render('simple', ['model' => $model]);
}
But data is null.
How I must get data in right?
Please, help me solve this problem.
I created a Dependent drop-down now i want to fetch these values on update page. How can i do ?
I created 2 drop-down - 1st Client and 2nd Staff
on update page i got the value of client but i did not get the value of staff (Because it is dependent drop-down)
Form
<?php
//First drop-down
echo $form->field($model, 'client')->dropDownList($Client,
['prompt'=>'-Select Client-',
'onchange'=>'
$.post
(
"'.urldecode(
Yii::$app->urlManager->createUrl
('leads/lists&id=')).'"+$(this).val(), function( data )
{
$( "select#staff_id" ).html( data );
});
']); ?>
// depend dropdown
<?php echo $form->field($model, 'staff')
->dropDownList
(
['prompt'=>'-Choose a Sub Category-'],
['id'=>'staff_id','value'=>$Staff]
);
?>
Controller
public function actionLists($id)
{
$sql = "select * from staff where client='$id' ";
//exit;
$models = Staff::findBySql($sql)->asArray()->all();
//echo "<pre>";print_r($model);exit;
if(sizeof($models) >0){
echo "<option>-Choose a Sub Category-</option>";
foreach($models as $model){
echo "<option value='".$model['id']."'>".$model['fname']."</option>";
}
}
else{
echo "<option>-Choose a Sub Category-</option><option></option>";
}
}
first add $modelsStaff variable to your create and update actions like below:
<?
public function actionCreate()
{
$modelsStaff=null;
$model = new model();
if ($model->load(Yii::$app->request->post()) && $model->save())
{
return $this->redirect(['view', 'id' => $model->id]);
}
else
{
return $this->render('create', [ 'model' => $model,'modelsStaff'=>$modelsStaff]);
}
}
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save())
{
return $this->redirect(['view', 'id' => $model->id]);
}
else
{
$sql = "select * from staff where client='$model->client'";
$modelsStaff = Staff::findBySql($sql)->asArray()->all();
return $this->render('update', [ 'model' => $model,'modelsStaff'=>$modelsStaff]);
}
}
?>
In your update action find all staff using $model->client and get all staff under this client and update your view like this
<?php
//First drop-down
echo $form->field($model, 'client')->dropDownList($Client,
['prompt'=>'-Select Client-',
'onchange'=>'
$.post
(
"'.urldecode(
Yii::$app->urlManager->createUrl
('leads/lists?id=')).'"+$(this).val(), function( data ) //<---
{
$( "select#staff_id" ).html( data );
});
']); ?>
// depend dropdown
<?php echo $form->field($model, 'staff')->dropDownList
($modelsStaff,
['prompt'=>'-Choose a Sub Category-'],
['id'=>'staff_id','value'=>$Staff]
);
?>
You have to create separate function in your controller (like an example):
public function actionLists($id)
{
$posts = \common\models\Post::find()
->where(['category_id' => $id])
->orderBy('id DESC')
->all();
if (!empty($posts)) {
$option = '<option>-Select Option-</option>';
foreach($posts as $post) {
$options .= "<option value='".$post->id."'>".$post->title."</option>";
}
return $options;
} else {
return "<option>-</option>";
}
}
and in view file (example):
use yii\helpers\ArrayHelper;
$dataCategory=ArrayHelper::map(\common\models\Category::find()->asArray()->all(), 'id', 'name');
echo $form->field($model, 'category_id')->dropDownList($dataCategory,
['prompt'=>'-Choose a Category-',
'onchange'=>'
$.post( "'.Yii::$app->urlManager->createUrl('post/lists?id=').'"+$(this).val(), function( data ) {
$( "select#title" ).html( data );
});
']);
$dataPost=ArrayHelper::map(\common\models\Post::find()->asArray()->all(), 'id', 'title');
echo $form->field($model, 'title')
->dropDownList(
$dataPost,
['id'=>'title']
);
This is from Yii docs: https://www.yiiframework.com/wiki/723/creating-a-dependent-dropdown-from-scratch-in-yii2
Since this is my first question, do tell me if i miss anything..
I have 3 dropdown menu which are dependant..
1st dropdown is to select table names which will automatically update 2nd dropdown menu which will list attributes names based on the selected table name.. this are successfully implemented..
in 2nd dropdown menu, after selecting the attributes names, user will need to click on the submit button.. when submitting, it will update 2nd dropdown menu to exclude the previously selected attribute names, and will send the selected attribute names to the 3rd dropdown menu..
Updating the 2nd dropdown menu to exclude the previously selected attributes are successfully implemented..
But updating the 3rd dropdown menu are no success..
Do guide me where I'm missing.. I'm still new with Yii so pls be patient with me ok =D
Codes on the controller:
public function actionLoadColumn()
{
$getCol = array();
$col = array();
$getTblNm[] = $_POST['tableNm'];
if(isset($_POST['columnDD'])){
$getCol[]=$_POST['columnDD'];
}
foreach($getCol as $getColKey=>$getColVal){
foreach($getColVal as $getColKey1=>$getColVal1){
$col[]=$getColVal1;
}
}
$getAttr = array();
foreach($getTblNm as $tblKey=> $tbl){
foreach( $tbl as $data){
$model1 = new $data;
$getColumn = $model1->attributes;
foreach($getColumn as $key=>$val){
$getAttr[]=$key;
}
$getAttr = array_combine($getAttr, $getAttr);
unset($getAttr['created_by'],$getAttr['created_at'],$getAttr['updated_by'],$getAttr['updated_at']);
foreach($col as $colKey=>$colVal){
unset($getAttr[$colVal]);
}
}
}
//var_dump($getAttr);
foreach($getAttr as $value=>$city_name)
echo CHtml::tag('option', array('value'=>$value),CHtml::encode($city_name),true);
var_dump($col);
if(isset($_POST['columnDD'])){
echo CHtml::dropDownList('selCol','', $col,//CHTML::listData($getTNm,'tableNm','tableNm'),
array(
'multiple'=>'multiple',
'size'=>15,
//'prompt'=>'SELECT TABLES',
'ajax' => array(
'type'=>'POST',
//'url'=>CController::createUrl('loadcolumn'),
//'update'=>'#columnDD',
//'data'=>array('tableNm'=>'js:this.value'),
)
)
);
}
//foreach($col as $cVal=>$cKey)
// echo CHtml::tag('option', array('value'=>$cVal, 'update'=>'selCol'),CHtml::encode($cKey),true);
}
codes on the view:
<div class="form">
<?php $form=$this->beginWidget('CActiveForm', array(
'id'=>'base-company-reg-form',
'enableAjaxValidation'=>false,
));
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx----START----xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
echo '<table><tr><td>1. Select tables</td><td></td><td>2. Select columns</td><td></td><td>3. Arrange columns</td></tr><tr><td>';
echo CHtml::dropDownList('tableNm[]','', $getTNm,//CHTML::listData($getTNm,'tableNm','tableNm'),
array(
'multiple'=>'multiple',
'size'=>15,
//'prompt'=>'SELECT TABLES',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('loadcolumn'),
'update'=>'#columnDD',
//'data'=>array('tableNm'=>'js:this.value'),
)
)
);
echo '</td><td>';
echo'=';
echo '</td><td>';
echo CHtml::dropDownList('columnDD[]','', array(), array('multiple'=>'multiple', 'size'=>'15'));
echo '</td><td>';
echo CHtml::ajaxSubmitButton('>>>',Yii::app()->createUrl('baseCentre/loadcolumn'),
array(
'type'=>'POST',
'update'=>'#columnDD',
)
);
echo '</td><td>';
//echo CHtml::dropDownList('selCol[]','', array(), array('multiple'=>'multiple', 'size'=>'15'));
echo '</td></tr></table>';
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx----END----xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
?>
<?php
$this->endWidget();
?>
</div>
I am using dependant dropdownlist for get value for subject dropdown when select value from 'Grade' dropdown. It is working fine. But the problem is when there are only one value in grade dropdown the subject dropdown is not updated.
this is my code:-
Grade DropDown----------
($data is consist of grade)
<?php echo CHtml::dropDownList('myDropDown1','',$data,array(
'id'=>'gr',
'empty' => '(Select Grade)',
'style'=>'width:200px',
'ajax' =>
array(
'type'=>'POST', //request type
'url'=>CController::createUrl('sub'), //action to call
'update'=>'#cls', // which HTML element to update
)
)); ?>
Subject Dropdown (which depend on grade dropdown)------------
<?php echo CHtml::label('Subject',''); ?>
<?php echo CHtml::dropDownList('myDropDown3','',array(),array(
'id'=>'sub',
'prompt'=> 'Please select a class', 'style'=>'width:150px',
'style'=>'width:200px',
)); ?>
<?php //echo $form->error($model,'sub_id'); ?>
In controller-------------------
public function actionClass()
{
$grd = $_POST['myDropDown1'];
$c_id = TbClass::model()->findAll('id=:id',
array(':id'=>$grd,));
$data3 = CHtml::listData($c_id,'id','grade');
$grd2 = array_shift($data3);
$sub1 = TbClass::model()->findAll('grade=:grade',
array(
':grade'=>$grd2,
));
$data4 = CHtml::listData($sub1,'id','class');
foreach($data4 as $value=>$name)
{
echo CHtml::tag('option',
array('value'=>$value),CHtml::encode($name),true);
}
}
This code is working fine. Problem is when grade has only one value in the dropdown , cannot update the subject dropdown.
I think your problem is in array_shift,
have you checked the value of $grd2 ?
I'm newbie in codeigniter and still learning. Anyone can help for sample in basic view, add, update, delete operation and queries in codeigniter will gladly appreciated.
Just a simple one like creating addressbook for newbie.
thanks,
best regards
Some sample queries in Codeigniter
class Names extends Model {
function addRecord($yourname) {
$this->db->set("name", $yourname);
$this->db->insert("names");
return $this->db->_error_number(); // return the error occurred in last query
}
function updateRecord($yourname) {
$this->db->set("name", $yourname);
$this->db->update("names");
}
function deleteRecord($yourname) {
$this->db->where("name", $yourname);
$this->db->delete("names");
}
function selectRecord($yourname) {
$this->db->select("name, name_id");
$this->db->from("names");
$this->db->where("name", $yourname);
$query = $this->db->get();
return $this->db->result();
}
function selectAll() {
$this->db->select("name");
$this->db->from("names");
return $this->db->get();
}
}
More information and more ways for CRUD in codeigniter active record documentation
More about error number over here
A sample controller
class names_controller extends Controller {
function addPerson() {
$this->load->Model("Names");
$name = $this->input->post("name"); // get the data from a form submit
$name = $this->xss->clean();
$error = $this->Names->addRecord($name);
if(!$error) {
$results = $this->Names->selectAll();
$data['names'] = $results->result();
$this->load->view("show_names", $data);
} else {
$this->load->view("error");
}
}
}
More about controllers over here
A sample view - show_names.php
<table>
<tr>
<td>Name</td>
</tr>
<?php foreach($names as $row): ?>
<tr><td><?ph echo $row->name; ?></td></tr>
<?php endforeach; ?>
</table>
More about codeigniter views over here
You can use this as an example
class Crud extends Model {
// selecting records by specifying the column field
function select()
{
// use $this->db->select('*') if you want to select all the records
$this->db->select('title, content, date');
// use $this->db->where('id', 1) if you want to specify what row to be fetched
$q = $this->db->get('mytable');
// to get the result
$data = array();
// for me its better to check if there are records that are fetched
if($q->num_rows() > 0) {
// by doing this it means you are returning array of records
foreach($q->result_array() as $row) {
$data[] = $row;
}
// if your expecting only one record will be fetched from the table
// use $row = $q->row();
// then return $row;
}
return $data;
}
// to add record
function add()
{
$data = array(
'title' => 'My title' ,
'name' => 'My Name' ,
'date' => 'My date'
);
$this->db->insert('mytable', $data);
}
// to update record
function update()
{
$data = array(
'title' => $title,
'name' => $name,
'date' => $date
);
$this->db->where('id', 1);
$this->db->update('mytable', $data);
}
// to delete a record
function delete()
{
$this->db->where('id', 1);
$this->db->delete('mytable');
}
}
Some of this are from codeigniter userguide.
To view the records,
If return data is array of records,
foreach($data as $row)
{
echo $row['title'] . "<br />";
}
If the return data is an object (by using $q->row),
echo $data->title;
This is just a few examples or CRUD in Codeigniter. Visit the codeigniter userguide.