I have a dynamically loaded dropdownlist called type_id, and I would like that when I select a value in that dropdownlist, my description textarea field would be updated with a value.
form
echo $form->field($model, 'type_id')->dropDownList(ArrayHelper::map($types,'id','name'),['prompt'=>'Selecione a Área',
'onchange' => '???']);
<?= $form->field($model, 'description')->textarea(['rows' => 8]) ?>
This value will be obtained dynamically through the query:
Controller
public function actionScript($id)
{
$types = Type::find()
->where(['id' => $id])
->One();
return $type->script;
}
That is, in textarea field I want to show the respective script column to the selected id in type_id dropdonw.
type table
TABLE `mod_helpdesk_type` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`priority` int(1) NOT NULL DEFAULT '0',
`script` text NOT NULL,
`active` int(11) NOT NULL,
PRIMARY KEY (`id`)
);
It will help you
echo $form->field($model, 'type_id')->dropDownList(ArrayHelper::map($types,'id','name'),['prompt'=>'Selecione a Área',
['class' => 'your_class', 'id' => 'your_id']
'onchange' => '???']);
<?= $form->field($model, 'description')->textarea(['rows' => 8,'id'=>'textArea']) ?>
$('#your_id').change(function(){
$('#textArea').val('testing');
})
try onchange ajax event
echo $form->field($model, 'type_id')->dropDownList(ArrayHelper::map($types,'id','name'),[
'prompt'=>'Selecione a Área',
'onchange' => '
$.get( "yourControllerName/script&id="+$(this).val(), function( data ) {
$( "#yourTextAreaIdElement" ).val( data );
});
'
]);
and better prevent if request has an ids passed into actionScript
public function actionScript($id)
{
$script = '';
if(!empty($id)) {
$types = Type::find()
->where(['id' => $id])
->one();
if(!empty($types)) {
$script = $types->script;
}
}
return $script;
}
Like that?
$('#<?php echo Html::getInputId($model, 'type_id'); ?>').change(function () {
var val = $(this).val();
$.ajax({
url: '<?php echo Url::to('script'); ?>',
type: 'get',
data: {id: val},
success: function (data) {
$('#<?php echo Html::getInputId($model, 'description'); ?>').val(data);
}
});
});
Related
I'm Trying to create a bar chart using Highcharts for my Codeigniter project
Created Controller, View & Model with relevant Routes
tbl_demo_viewer table:
CREATE TABLE IF NOT EXISTS `tbl_demo_viewer` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`numberofview` int(11) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
tbl_demo_click table:
CREATE TABLE IF NOT EXISTS `tbl_demo_click` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`numberofclick` int(12) NOT NULL,
`created_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ;
application/config/database.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
$active_group = 'default';
$query_builder = TRUE;
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'root',
'password' => 'root',
'database' => 'h_sole',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
application/config/routes.php
$route['default_controller'] = 'welcome';
$route['404_override'] = '';
$route['translate_uri_dashes'] = FALSE;
$route['my-chart'] = "Chart";
application/controllers/Chart.php
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Chart extends FZ_Controller {
public function __construct() {
parent::__construct();
$this->load->model('Chart_model');
}
public function createChart()
{
$this->data['click'] = $this->Chart_model->getClick();
$this->data['viewer'] = $this->Chart_model->getViewer();
$bc = array(array('link' => base_url(), 'page' => 'Home'), array('link' => '#', 'page' => 'Demo'));
$meta = array('page_title' => 'Demo', 'bc' => $bc);
$this->render('my_chart', $meta, $this->data);
}
}
application/models/Chart_model.php
<?php
class Chart_model extends CI_Model {
function __construct() {
parent::__construct();
}
public function getViewer() {
$this->db->set_dbprefix('');
$this->db->select('SUM(numberofview) as count');
$this->db->from('tbl_demo_viewer');
$this->db->group_by('tbl_demo_viewer.created_at');
$this->db->order_by('tbl_demo_viewer.created_at');
$q = $this->db->get();
}
public function getClick() {
$this->db->set_dbprefix('');
$this->db->select('SUM(numberofclick) as count');
$this->db->from('tbl_demo_click');
$this->db->group_by('tbl_demo_click.created_at');
$this->db->order_by('tbl_demo_click.created_at');
$q = $this->db->get();
}
}
application/views/my_chart.php
<!DOCTYPE html>
<html>
<head>
<title>HighChart</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
</head>
<body>
<script type="text/javascript">
$(function () {
var data_click = <?php echo $click; ?>;
var data_viewer = <?php echo $viewer; ?>;
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Yearly Website Ratio'
},
xAxis: {
categories: ['2013','2014','2015', '2016']
},
yAxis: {
title: {
text: 'Rate'
}
},
series: [{
name: 'Click',
data: data_click
}, {
name: 'View',
data: data_viewer
}]
});
});
</script>
<div class="container">
<br/>
<h2 class="text-center">Codeigniter 3 - Highcharts mysql json example</h2>
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Chart Example</div>
<div class="panel-body">
<div id="container"></div>
</div>
</div>
</div>
</div>
</div>
</body>
</html>
No error fired. But did not created the desired chart. I can not understand what I am going wrong. Can anyone help me ?
I've a field called employee_name and depending on this field value I want to autofill another field employee_id. I've searched and I found this answer and tried implementing this on my form but I'm getting Error in ajax request. The jquery code in my form is
$('#emp').focusout(function() {
empName = this.value;
if ( empName != '' || empName != null ) {
$('#depcustomer-employee_name').val(empName);
}
$.ajax({
url: '".yii\helpers\Url::toRoute("deposit/employeeid")."',
dataType: 'json',
method: 'GET',
data: {name: $(this).val()},
success: function (data, textStatus, jqXHR) {
$('#depcustomer-employee_id').val(data.id);
},
beforeSend: function (xhr) {
alert('loading!');
},
error: function (jqXHR, textStatus, errorThrown) {
console.log('An error occured!');
alert('Error in ajax request');
}
});
});
My Controller name is Deposit and my controller code is
public function actionEmployeeid($name){
$model= app\modules\settings\models\DepEmployee::findOne(['employee_name'=>$name]);
return \yii\helpers\Json::encode([
'id'=>$model->employee_id
]);
What could be the possible reason that my ajax code is not working?
My form is quite big. Here's the part of the employee field entry
<div class="row">
<div class="col-md-6">
<?= $form->field($model, 'employee_id')->textInput(['maxlength' => true]) ?>
</div>
<div class="col-md-6">
<label for='emp'>Employee Name</label>
<?= Html::activeHiddenInput($model, 'employee_name')?>
<?php
echo AutoComplete::widget([
'name' => 'employee_name',
'id' => 'emp',
'clientOptions' => [
'source' => $dataEmp,
'autoFill'=>true,
'minLength'=>'2',
'select' => new JsExpression("function( event, ui ) {
$('#depcustomer-name').val(ui.item.id);
}")
],
]);
?>
</div>
</div>
According to your autocomplete data you already have employee_id. So no need to make ajax request to get employee id.
DepEmployee Model
public static function getEmpData()
{
$dataEmp = DepEmployee::find()
->select(['employee_name as value', 'employee_name as label','employee_id as id'])
->asArray()
->all();
return $dataEmp;
}
_form
<?= AutoComplete::widget([
'name' => 'employee_name',
'id' => 'emp',
'clientOptions' => [
'source' => DepEmployee::getEmpData(),
'autoFill'=>true,
'minLength'=>'2',
'select' => new JsExpression("function( event, ui ) {
$('#depcustomer-name').val(ui.item.id);
$('#depcustomer-employee_id').val(ui.item.id);
}")
],
]);?>
What i should do if i was at your place:
Here the view:
<?= $form->field($model, 'employeeName')->textInput([
// I use onfocusout instead of focusout
'onfocusout' => '
$.post("generateemployeeid?name="+$(this).val(), function(data) {
$("#employee_id_container").html(data);
});
',
]) ?>
<div id="employee_id_container"></div> // <- I will autofill here
Now here is the function who will fill the ID input: (should be in your controller)
public function actionGenerateemployeeid($name) {
$employeeModel = DepEmployee::find()
->where(['employee_name' => $name])
->one();
if($employeeModel !== NULL) {
echo 'Employee ID: <input type="text" name="EmployeeID" value="'.$employeeModel->employee_id.'" readonly><br>';
}
else {
// error 404
}
}
Resume: the jquery function take the employee name and send to the controller who will look for the employee ID in the database. Then send an input text with default value (employee ID) as response and load this input in the form.
I have resource regarding dropDownList onchange event, but when I select my dropdownlist that is nothing happen and dint show any error message.
This is my dropdownlist in view:
<?= $form->field($model, 'pro_id')
->dropDownList($pro_option, // options
['prompt'=>'...'] , // options
['onchange' => '$.post("'.Yii::$app->urlManager->createUrl(["transaction/price"]).'"+$(this).val(), function( data ) {
$("#transactionform-r_price").html( data );
})']);?>
<?= $form->field($model, 'r_price')->textInput(['readonly' => true]) ?>
This is my controller(TransactionController.php) actionPrice:
public function actionPrice($id)
{
$price = 123;
return $price;
}
Please correct your syntax like this.
<?= $form->field($model, 'pro_id')->dropDownList($pro_option, [
'prompt' => '---Select Value---',
'onchange'=>'$.get( "'.Url::toRoute(['transaction/price']).'", { id : $(this).val() })
.done(function(data) {
$( "#'.Html::getInputId($model, 'r_price').'").html(data);
});'
]) ?>
Here my problem is i have a form . In that i have dependent dropdown.
for example if i select company name it automatically selects the dependent company email and company phone number. This is working perfectly while creating. but the problem is while am updating the same form, the dependent value getting reset. so that makes me to select the company name for every time but i don't to be like that. once if i select the value while creating the value shouldn't change while updating also.
_form.php
<?= $form->field($model, 'employee_id')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Employeedetails::find()->all(),'id','employeecode'),
'language' => 'en',
'options' => [
'placeholder' => 'Select a employeecode ...',
'onchange' => '
$.post( "index.php?r=employeedetails/lists2&id='.'"+$(this).val().split("-")[0], function( data ) {
$( "select#claimprocess-claim_for" ).html( data );
}),
$.post( "index.php?r=employeedetails/lists3&id='.'"+$(this).val().split("-")[0], function( data ) {
$( "select#claimprocess-email" ).html( data );
}),
$.post( "index.php?r=employeedetails/lists1&id='.'"+$(this).val(), function( data ) {
$( "select#claimprocess-employee_name" ).html( data );
});',
],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
This is Controller code
controller.php
public function actionLists($id)
{
$countEmployeedetails = Employeedetails::find()
->where(['company_id' => $id])
->count();
$employeedetails = Employeedetails::find()
->where(['company_id' => $id])
->all();
if($countEmployeedetails>0){
foreach($employeedetails as $employee){
echo "<option value='".$employee->id."'>".$employee->employeecode."</option>";
}
}
else{
echo "<option>-</option>";
}
}
public function actionLists1($id)
{
$countEmployeedetails = Employeedetails::find()
->where(['id' => $id])
->count();
$employeedetails = Employeedetails::find()
->where(['id' => $id])
->all();
if($countEmployeedetails >= 0)
{
foreach($employeedetails as $employee)
{
echo "<option value='".$employee->id."'>".$employee->name."</option>";
}
}
else{
echo "<option>-</option>";
}
}
public function actionLists2($id)
{
$countEmployeedetails = Employeedetails::find()
->where(['id' => $id])
->count();
$employeedetails = Employeedetails::find()
->where(['id' => $id])
->all();
if($countEmployeedetails >= 0)
{
foreach($employeedetails as $employee)
{
// $arr["id"] . '-' . $arr['designation']
echo "<option value='".$employee->id. '-' .$employee->name. "'>".$employee->RelationName."</option>";
}
}
else{
echo "<option>-</option>";
}
}
Finally i found answer, actually mistake was mine, because here am using getting records based on company_id but here i have used approvaldetails table id so that is the mistake, after i changed it to company_id, now its working good
public function actionLists2($id)
{
$countEmployeedetails = Employeedetails::find()
->where(['company_id' => $id])
->count();
$employeedetails = Employeedetails::find()
->where(['company_id' => $id])
->all();
if($countEmployeedetails >= 0)
{
foreach($employeedetails as $employee)
{
// $arr["id"] . '-' . $arr['designation']
echo "<option value='".$employee->id. '-' .$employee->name. "'>".$employee->RelationName."</option>";
}
}
else{
echo "<option>-</option>";
}
}
I have create a action comment like this:
public function actionComment($id)
{
$text = CommentModel::find($id)->where(true)->all();
if (isset($_POST['name'])) {
$text = new CommentModel();
$text->name=$_POST['name'];
$text->comment=$_POST['comment'];
$text->i_post=$_POST['id_post'];
$text->save();
$this->redirect('comment',array('id'=>$text->id));
}
return $this->render('comment',array("text"=>$text));
}
and comment view is:
<h2>List of all comments:</h2>
<?php
foreach($text as $text[0]){
echo "name"." ".":"." ".$text[0]->name."<br>" ;
echo "comment"." ".":"." ".$text[0]->comment."<br>";
?>
my comment model is:
public function attributeLabels()
{
return [
'id' => 'ID',
'name' => 'Name',
'comment' => 'Comment',
'id-post' => 'Id Post',
];
}
how should i define id_pst in my project to each post has sepecific comment??