How to use widget kartik select2 with ajax & templates in yii2 - php

I want to display more than 1 information when searching, so I use select2 ajax & templates. It use json. I change the url and I make function on my controller. But I have a problem. It can not show anything. What's the problem? This is my code:
view
$formatJs = <<< 'JS'
var formatProduct = function (product) {
if (product.loading) {
return product.text;
}
var markup =
'<div class="row">' +
'<div class="col-sm-5">' +
'<b style="margin-left:5px">' + product.name + '</b>' +
'</div>' +
'<div class="col-sm-3"><i class="fa fa-code-fork"></i> ' + product.ean_no + '</div>' +
'<div class="col-sm-3"><i class="fa fa-star"></i> ' + product.desc + '</div>' +
'</div>';
return '<div style="overflow:hidden;">' + markup + '</div>';
};
var formatProductSelection = function (product) {
return product.name || product.text;
}
JS;
// Register the formatting script
$this->registerJs($formatJs, \yii\web\View::POS_HEAD);
// script to parse the results into the format expected by Select2
$resultsJs = <<< JS
function (data, params) {
params.page = params.page || 1;
return {
// Change `data.items` to `data.results`.
// `results` is the key that you have been selected on
// `actionJsonlist`.
results: data.results
};
}
JS;
Select2
echo Select2::widget([
'name' => 'kv-repo-template',
'value' => '14719648',
'initValueText' => 'kartik-v/yii2-widgets',
'options' => ['placeholder' => 'Search for a repo ...'],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 1,
'ajax' => [
'url' => Url::to(['/bom/product/productlist']),
'dataType' => 'json',
'delay' => 250,
'data' => new JsExpression('function(params) { return {q:params.term, page: params.page}; }'),
'processResults' => new JsExpression($resultsJs),
'cache' => true
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('formatProduct'),
'templateSelection' => new JsExpression('formatProductSelection'),
],
]);
controller
public function actionProductlist($search = NULL, $code = NULL)
{
header('Content-type: application/json');
$clean['more'] = false;
$query = new \yii\db\Query;
if(!is_Null($search))
{
$mainQuery = $query->select('code, name, description, volume')
->from('product');
$command = $mainQuery->createCommand();
$rows = $command->queryAll();
$clean['results'] = array_values($rows);
}
else
{
if(!is_null($code))
{
$clean['results'] = ['ean_no'=> $code, 'name' => Product::find($code)->nama,
'description' => Product::find($code)->description, 'volume' => Product::find($code)->volume];
}else
{
$clean['results'] = ['ean_no' => 123, 'name' => 'None found', 'description' => 'None found', 'volume' => 'None found'];
}
}
echo \yii\helpers\Json::encode($clean);
exit();
}
on mozilla when i open the inspect element console. there is an error message like this :
TypeError: data.slice is not a function
S2

Try to remove
'processResults' => new JsExpression($resultsJs),

Related

Rows not found, Codeiginiter Show Index

I'm new with Codeigniter. I got error on my code using Codeigniter. My index doesn't show the row of my datatable, even my datatable had data in it. Anyone can find my error or typo text on my code? Please help me :(.
btw I have 2 controllers.
Here's my first controller (modules->api->controller->Tower.php)
defined('BASEPATH') OR exit('No direct script access allowed');
require_once APPPATH . '/core/MY_Auth.php';
require 'vendor/autoload.php';
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
class Tower extends MY_Auth
{
protected $ruleMsg;
function __construct()
{
parent::__construct();
$this->load->model('Model_tower');
$this->load->library('Pagingmeta');
$this->load->library('Validate');
$this->ruleMsg = '%s must be filled';
}
public function index_get($id = '') {
if (!empty($id)) {
return $this->get_detail($id);
}
$keyword = $this->get('search', true);
$except = $this->get('excepth', true);
$type = $this->get('type', true)??'list';
$page = $this->get('page', true)??1;
$limit = $this->get('limit', true)??10;
$data = $this->Model_tower->get_list($keyword, $this->role, $this->regional, $page, $limit);
$this->response([
'message' => 'Get tower success',
'data' => $data['data'],
'meta' => $this->pagingmeta->get_meta($data['total'], $limit, $page)
], REST_Controller::HTTP_OK);
}
private function get_detail($id) {
$data = $this->Model_tower->get_detail($id);
if (empty($data)) {
return $this->response([
'message' => 'Data not found'
], REST_Controller::HTTP_BAD_REQUEST);
}
if ($this->regional != $data->regional && $this->role != 'ADMN' && $id != $this->userId) {
return $this->response([
'message' => "You didn't have right to access this data"
], REST_Controller::HTTP_BAD_REQUEST);
}
if ($this->role == 'ADMN') {
$data->is_editable = true;
}
return $this->response([
'message' => 'Get tower success',
'data' => $data
], REST_Controller::HTTP_OK);
}
public function tower_post() {
$this->validate_role();
$rules = $this->rules_post($this->post(null, true));
$params = $this->validate->validation($this->post(null, true), $rules);
if (!$params['status']) {
$this->response([
'message' => $params['errors'][0]
], REST_Controller::HTTP_BAD_REQUEST);
}
$params = $params['data'];
if ($this->Model_tower->validate_site_id($params['site_id'])) {
$this->response([
'message' => 'Site ID already exist'
], REST_Controller::HTTP_BAD_REQUEST);
}
$id = $this->Model_tower->tower_action($params, $this->userId);
$this->response([
'message' => 'Create tower success',
'data' => $id
], REST_Controller::HTTP_CREATED);
}
public function tower_put($id = '') {
$this->validate_role();
$rules = $this->rules_post($this->put(null, true));
$params = $this->validate->validation($this->put(null, true), $rules);
if (!$params['status']) {
$this->response([
'message' => $params['errors'][0]
], REST_Controller::HTTP_BAD_REQUEST);
}
$params = $params['data'];
if ($this->Model_tower->validate_site_id($params['site_id'], $id)) {
$this->response([
'message' => 'Site ID already exist'
], REST_Controller::HTTP_BAD_REQUEST);
}
$this->Model_tower->tower_action($params, $this->userId, $id);
$this->response([
'message' => 'Update tower success',
'data' => $id
], REST_Controller::HTTP_OK);
}
public function upload_post() {
$this->validate_role();
$this->load->library('Uuid');
$spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($_FILES['data']['tmp_name']);
$sheet = $spreadsheet->getActiveSheet();
// Store data from the activeSheet to the varibale in the form of Array
$data = array_values($sheet->toArray(null,true,true,true));
$oldData = $this->Model_tower->get_all_data();
$oldData = array_column($oldData, 'site_id');
$insertData = [];
$now = date('Y-m-d H:i:s');
foreach($data as $index => $d) {
if ($index == 0) {
continue;
}
$code = $this->uuid->generate();
$type = '';
$regional = '';
$inputedType = $d['D'];
if ($inputedType == 'MTEL') {
$type = 'mtel';
} else {
$type = 'reseller';
}
$inputedRegional = $d['G'];
if ($inputedRegional == 'Jawa Timur') {
$regional = 'JATIM';
} else if ($inputedRegional == 'Jawa Tengah') {
$regional = 'JATENG';
} else {
$regional = 'BALNUS';
}
if (empty($d['A']) || empty($d['B']) || in_array($d['A'], $oldData)) {
break;
}
$insertData[] = [
'site_id' => $d['A'],
'project_id' => $d['B'],
'site_name' => $d['C'],
'type' => $type,
'company' => $d['E'],
'address' => $d['F'],
'regional_code' => $regional,
'active_status' => 1,
'created_at' => $now,
'updated_at' => $now,
'code' => $code,
'created_by' => $this->userId,
'updated_by' => $this->userId
];
}
if (!empty($insertData)) {
$this->Model_tower->insert_batch($insertData);
}
$this->response([
'message' => 'Bulk insert success',
], REST_Controller::HTTP_CREATED);
}
private function validate_role() {
if ($this->role != 'ADMN') {
return $this->response([
'message' => "You didn't have right to access this action"
], REST_Controller::HTTP_BAD_REQUEST);
}
}
private function rules_post() {
return [
[
'field' => 'site_id',
'label' => 'Site id',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'project_id',
'label' => 'Project id',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'name',
'label' => 'Name',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'type',
'label' => 'Type',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'regional',
'label' => 'Regional',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'address',
'label' => 'Address',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'company',
'label' => 'Company',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
[
'field' => 'status',
'label' => 'Status',
'rules' => 'required',
'errors' => ['required' => $this->ruleMsg]
],
];
}
}
and this is my second Controller (Controllers->Tower.php)
defined('BASEPATH') OR exit('No direct script access allowed');
require_once APPPATH . '/core/MY_Cont.php';
class Tower extends MY_Cont
{
public function __construct()
{
parent::__construct();
}
public function index() {
$opts = array(
'content_only' => false,
'parent_menu' => 'tower',
'child_menu' => 'List Tower',
'nav_target' => 'tower_list',
);
$this->view('tower/index', $opts);
}
public function detail($code = null) {
if (empty($code)) {
$this->render_invalid();
}
$fetch_detail = $this->get_data_tower($code);
if ($fetch_detail['code'] !== 200) {
$this->render_invalid();
}
$opts = array(
'content_only' => false,
'parent_menu' => 'tower',
'child_menu' => 'Tower Detail',
'tower' => $fetch_detail['response']->data,
'nav_target' => 'tower_list',
);
$this->view('tower/detail', $opts);
}
public function new() {
$regional = $this->get_regional();
$opts = array(
'content_only' => false,
'parent_menu' => 'tower',
'child_menu' => 'Add New Tower',
'list_region' => $regional['response']->data,
'nav_target' => 'tower_new',
);
$this->view('tower/new', $opts);
}
public function bulk() {
$opts = array(
'content_only' => false,
'parent_menu' => 'tower',
'child_menu' => 'Upload Tower',
'nav_target' => 'tower_bulk',
);
$this->view('tower/bulk', $opts);
}
public function edit($code = null) {
if (empty($code)) {
$this->render_invalid();
}
$fetch_detail = $this->get_data_tower($code);
if ($fetch_detail['code'] !== 200) {
$this->render_invalid();
}
$regional = $this->get_regional();
$opts = array(
'content_only' => false,
'parent_menu' => 'tower',
'child_menu' => 'Edit Tower Detail',
'tower' => $fetch_detail['response']->data,
'list_region' => $regional['response']->data,
'nav_target' => 'tower_list',
);
$this->view('tower/edit', $opts);
}
private function render_invalid() {
header('HTTP/1.0 404');
$opts = array(
'content_only' => true,
'cfg_mainclass' => 'fullpage',
'private_routing' => false,
);
$this->view('layouts/404', $opts);
exit();
}
private function get_data_tower($id = '') {
if (empty($id)) {
$curl = curl_init(base_url() . 'api/tower');
} else {
$curl = curl_init(base_url() . 'api/tower/' . $id);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: ' . $this->session->userdata('usertoken'),
));
$result = json_decode(curl_exec($curl));
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
return array(
'code' => $httpcode,
'response' => $result,
);
}
private function get_regional() {
$curl = curl_init(base_url() . 'api/master/regional');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
'Authorization: ' . $this->session->userdata('usertoken'),
));
$result = json_decode(curl_exec($curl));
$httpcode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
$response = array(
'code' => $httpcode,
'response' => $result,
);
return $response;
}
}
and this is my index.php
<div class="container-fluid">
<div class="row">
<div class="col-12">
<div class="mainpanel">
<div class="mainpanel-header">
<div class="row align-items-end">
<div class="col-9">
<h3>List Tower</h3>
<h5>Click on tower to view detail</h5>
</div>
<div class="col text-right">
<a href="{{ base_url }}tower/new" class="panel-cta">
Add new tower
</a>
</div>
</div>
</div>
<form method="post" action="" id="form-filter-data" autocomplete="off">
<div class="digi-tablefilter">
<div class="filter-inputholder">
<label>Search</label>
<input type="text" name="search" placeholder="Search keyword" id="filter-search" />
</div>
<div class="filter-inputholder">
<input type="submit" value="Apply filter" />
</div>
</div>
</form>
<span class="table-information" id="t-info"></span>
<div class="digi-tableholder">
<table>
<thead>
<tr>
<th>Name</th>
<th>Project ID</th>
<th>Site ID</th>
<th>Regional</th>
<th>Company</th>
</tr>
</thead>
<tbody id="tower-table-value"></tbody>
</table>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div id="test-pag"></div>
</div>
</div>
</div>
</section>
<script>
$(document).ready(function() {
const payload = {
page: 1,
limit: 10,
search: '',
}
fetchListData(payload);
});
function fetchListData(payload) {
var apiURL = "{{ api_server ~ 'tower' }}";
var userToken = getUserToken();
$.ajax({
url: apiURL,
type: "GET",
data: payload,
headers: {
Authorization: userToken,
},
success: function(response) {
const { data, message, meta } = response;
buildDataTable(data, meta);
},
error: function(response) {
const { responseJSON } = response;
addNotification({
type: 'error',
title: 'Fetching data tower gagal',
message: responseJSON.message,
});
return;
}
});
}
function buildDataTable(data, metadata) {
const target = document.getElementById("tower-table-value");
const txtResult = document.getElementById("t-info");
$("#tower-table-value").empty();
target.innerHTML = "";
txtResult.innerHTML = "";
if (data.length == 0) {
buildEmptyRows();
return;
}
$.each(data, function(idx, item) {
const { id, name, project_id, site_id, regional, company } = item;
const tr = document.createElement('tr');
const nameHolder = document.createElement('td');
const projectHolder = document.createElement('td');
const siteHolder = document.createElement('td');
const regionalHolder = document.createElement('td');
const companyHolder = document.createElement('td');
nameHolder.innerHTML = name;
projectHolder.innerHTML = project_id;
siteHolder.innerHTML = site_id;
regionalHolder.innerHTML = regional;
companyHolder.innerHTML = company;
tr.appendChild(nameHolder);
tr.appendChild(projectHolder);
tr.appendChild(siteHolder);
tr.appendChild(regionalHolder);
tr.appendChild(companyHolder);
tr.onclick = function(e) {
window.location.href = `{{ base_url }}tower/detail/${item.id}`;
}
target.appendChild(tr);
});
var $resultText = `Showing result with keyword <strong>${$("#filter-search").val() == '' ? '-' : $("#filter-search").val()}</strong> ${metadata.total} row(s) found.`;
txtResult.innerHTML = $resultText;
if (metadata.last_page > 1) {
buildPagination(metadata);
} else {
hideLoader();
}
}
function buildEmptyRows() {
const target = document.getElementById("tower-table-value");
const txtResult = document.getElementById("t-info");
var $resultText = `Showing result with keyword <strong>${$("#filter-search").val() == '' ? '-' : $("#filter-search").val()}</strong> • 0 row(s) found.`;
txtResult.innerHTML = $resultText;
const tr = document.createElement('tr');
const td = document.createElement('td');
td.colspan = 5;
td.innerHTML = 'No Rows Found.';
tr.appendChild(td);
target.appendChild(tr);
hideLoader();
}
function buildPagination(metadata) {
const { from, to, last_page, current_page, per_page, total } = metadata;
$("#test-pag").pagination({
items: total,
itemsOnPage: per_page,
currentPage: current_page,
onPageClick: function(pageNumber, event) {
event.preventDefault();
const payload = {
page: pageNumber,
limit: per_page,
search: '',
}
fetchListData(payload);
}
});
}
$("#form-filter-data").submit(function(e) {
e.preventDefault();
const $payload = {
page: 1,
limit: 10,
search: $("#filter-search").val()
}
fetchListData($payload);
})
</script>
I'll very thankful if u can solve my problem :D

Ajax live edit is not wotking and got an 500 (Internal Server Error)?

i'm trying to modify a product but when i click the button a got that 500 (Internal Server Error)
this is ajax method
$(document).ready(function(){
fetch_customer_data();
$(document).on('click', '#btnModify', function(){
var name = $('#Name2').text();
var title = $('#Title2').text();
var mainPrice = $('#MainPrice2').text();
var discount = $('#DiscountPrice2').text();
var StockQ = $('#StockQuantity2').text();
var Desc = $('#Discription2').text();
var Features = $('#Features2').text();
var id = $("#id2").text();
if(name != ' ')
{
$.ajax({
url:"/Product/Update",
method:"POST",
data:{name:name, title:title , name:name , mainPrice:mainPrice , discount:discount ,StockQ:StockQ , Desc:Desc , Features:Features, id:id, _token:_token},
success:function(data)
{
fetch_customer_data();
}
});
}
else
{
alert('Something went wrong');
}
});
and this is the edit function
public function edit(Request $request)
{
if($request->ajax())
{
$data = array([
'Name' => $request->name,
'Title' => $request->title,
'MainPrice' => $request->mainPrice,
'DiscountPrice' => $request->discount,
'StockQuantity' => $request->StockQ,
'Discription' => $request->Desc,
'Features' => $request->Features
]
);
DB::table('products')
->where('id', $request->id)
->update($data);
echo '<div class="alert alert-success">Data Updated</div>';
}
}
Route :
Route::post('/Product/Update', [ProductsController::class, 'edit']);
Try this:
$data = array(
'Name' => $request->name,
'Title' => $request->title,
'MainPrice' => $request->mainPrice,
'DiscountPrice' => $request->discount,
'StockQuantity' => $request->StockQ,
'Discription' => $request->Desc,
'Features' => $request->Features
)
because you are using multi dimensional array instead of 2d array
maybe this will helpful

Yii2- Unable to upload image

I am working on yii2. In one of my view, I am trying to upload an image. But I am unable to upload it.
Model
class MeterAcceptanceHeader extends \yii\db\ActiveRecord
{
public static $status_titles =[
0 => 'Prepared',
1 => 'Created',
2 => 'Printed',
3 => 'Canceled',
];
/**
* #inheritdoc
*/
public static function tableName()
{
return 'meter_acceptance_header';
}
/**
* #inheritdoc
*/
public function rules()
{
return [
[['sub_div', 'prepared_by'], 'required'],
[['prepared_by', 'updated_by'], 'integer'],
[['prepared_at', 'updated_at'], 'safe'],
[['sub_div', 'meter_type', 'status'], 'string', 'max' => 100],
[['images'], 'string', 'max' => 255],
[['images'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png,jpg,pdf', 'maxFiles' => 4],
[['sub_div'], 'exist', 'skipOnError' => true, 'targetClass' => SurveyHescoSubdivision::className(), 'targetAttribute' => ['sub_div' => 'sub_div_code']],
[['prepared_by'], 'exist', 'skipOnError' => true, 'targetClass' => User::className(), 'targetAttribute' => ['prepared_by' => 'id']],
];
}
/**
* #inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'sub_div' => 'Sub Div',
'meter_type' => 'Meter Type',
'prepared_by' => 'Prepared By',
'prepared_at' => 'Prepared At',
'updated_at' => 'Updated At',
'status' => 'Status',
'updated_by' => 'Updated By',
'images' => 'Document Snap',
];
}
/**
* #return \yii\db\ActiveQuery
*/
public function getMeterAcceptanceDetails()
{
return $this->hasMany(MeterAcceptanceDetails::className(), ['accpt_id' => 'id']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getSubDiv()
{
return $this->hasOne(SurveyHescoSubdivision::className(), ['sub_div_code' => 'sub_div']);
}
/**
* #return \yii\db\ActiveQuery
*/
public function getPrepared()
{
return $this->hasOne(User::className(), ['id' => 'prepared_by']);
}
}
MeterAcceptanceHeader Table
MeterAcceptanceImages Table
There is a form1 in which user is prompt to select from the dropdown.
Form1 View
<div class="meter-acceptance-header-form">
<?php $model->status = common\models\MeterAcceptanceHeader::$status_titles[0]; ?>
<?php $form = ActiveForm::begin(['id'=>'acceptance-form','options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'sub_div')->dropDownList([''=>'Please Select'] + \common\models\SurveyHescoSubdivision::toArrayList()) ?>
<?= $form->field($model, 'meter_type')->dropDownList([''=>'Please Select','Single-Phase' => 'Single-Phase', '3-Phase' => '3-Phase', 'L.T.TOU' => 'L.T.TOU']) ?>
<?= $form->field($model, 'status')->textInput(['maxlength' => true,'readonly' => true]) ?>
<div class="form-group">
<a class="btn btn-default" onclick="window.history.back()" href="javascript:;"><i
class="fa fa-close"></i>
Cancel</a>
<a class="<?= $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary' ?>" onclick="
$('#acceptance-form').submit();" href="javascript:">
<?= $model->isNewRecord ? 'Create' : 'Update' ?></a>
</div>
<?php ActiveForm::end(); ?>
After clicking on Create button the user is prompt to the second form in which a user will upload an image.
Below is my code for the controller from which I am trying to upload it.
public function actionSetpdf($id)
{
$model = $this->findModel($id);
$m = 0;
$accpt_id = $model->id;
$meter_type = $model->meter_type;
$ogp_sub_div = $model->sub_div;
$images=[];
$ic=0;
$files_uploaded = false;
if(Yii::$app->request->isAjax && Yii::$app->request->post())
{
$data = explode(',',$_POST['data']);
foreach($data as $value)
{
$m = new MeterAcceptanceDetails;
$m -> load(Yii::$app->request->post());
$m->accpt_id = $accpt_id;
$m->meter_type = $meter_type;
$m->created_at = date('Y-m-d H:i:s');
$m->created_by = Yii::$app->user->id;
$m->meter_id = $value;
$m->meter_msn = \common\models\Meters::idTomsn($value);
$m->flag = 1;// 1 means created
$m->ogp_sub_div = $ogp_sub_div;
if($m->save())
{
// Here the upload image code starts
if($ic==0)
{
$model->images = UploadedFile::getInstances($model, 'images');
foreach ($model->images as $file)
{
if (file_exists($file->tempName))
{
$img_s = new MeterAcceptanceImages;
$file_name = rand(0, 1000) . time().date('his') . '.' . $file->extension;
$file->saveAs('uploads/meter_acceptance/' . $file_name);
$img_s->file_path = $file_name;
$img_s->accpt_id = $accpt_id;
if ($img_s->save()) {
$images[] = $img_s;
} else {
print_r($img_s->getErrors());
}
}
}
}else{
foreach($images as $image){
$img_s = new MeterAcceptanceImages;
$img_s->file_path = $image->file_path;
$img_s->accpt_id = $accpt_id;
$img_s->save();
}
}
$model->status = MeterAcceptanceHeader::$status_titles[1];
$model->update();
}
else{
$this->renderAjax('viewcreated');
}
}
}
else{
$this->renderAjax('viewcreated');
}
return $this->redirect(Url::toRoute(['meteracceptanceheader/viewsetpdf','id' => $model->id,'model' => $this->findModel($id)]));
}
Form2 View
<div class="map-meters-form" id="doc">
<?php $form = ActiveForm::begin(['id' => 'map-form', 'enableClientValidation' => true, 'enableAjaxValidation' => false,
'options' => ['enctype' => 'multipart/form-data']]) ?>
<section class="content">
<div class="box">
<div id="chk" class="box-body">
<?php Pjax::begin(); ?>
<?= DetailView::widget([
'model' => $model,
'attributes' => [
[
'label'=>'Serial #',
'value' => function($d)
{
return $d->id;
}
],
[
'label' => 'Meter Type',
'value' => function ($d) {
if(is_object($d))
return $d->meter_type;
return ' - ';
},
],
'sub_div',
[
'label' => 'Sub Division Name',
'value' => function ($d) {
if(is_object($d))
return $d->subDiv->name;
return '-';
},
],
[
'label' => 'Prepared By',
'value' => function ($d) {
if(is_object($d))
return $d->prepared->name;
},
],
'prepared_at',
'status',
],
]) ?>
<br>
<div class="pre-scrollable">
<?= GridView::widget([
'dataProvider' => $dataProvider,
//'ajaxUpdate' => true,
'filterModel' => false,
//'id'=>'gv',
'columns' => [
['class' => 'yii\grid\SerialColumn'],
['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d) {
return ['value' => $d['meter_id']];
}],
'Meter_Serial_Number',
'Meter_Type',
'Sub_Division_Code',
'Sub_Division_Name',
],
]); ?>
</div>
<?php Pjax::end(); ?>
<?= $form->field($model, 'images[]')->fileInput(['multiple' => true, 'accept' => 'image/*'])?>
<br>
<form>
<p>
Submit
<br/>
</p>
</form>
</div>
</div>
</section>
<?php ActiveForm::end(); ?>
</div>
<?php
$url = Url::toRoute(['/meteracceptanceheader/setpdf','id'=>$model->id]);
$script = <<< JS
$(document).ready(function () {
$(document).on('pjax:end', function() {
$("#chk").find("input:checkbox").prop("checked", true);
});
$("#chk").find("input:checkbox").prop("checked", true);
$('#myid').on('click',function(e) {
e.preventDefault();
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!=="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
$.ajax({
url: '$url',
type: 'POST',
dataType: 'json',
data: {data:strValue},
success: function(data) {
alert(data);
}
});
})
});
JS;
$this->registerJs($script, \yii\web\View::POS_END);
?>
This will allow selecting an image. Now when I try to click submit button I am getting below error
PHP Notice 'yii\base\ErrorException' with message 'Undefined offset: 0'
in
E:\xampp\htdocs\inventory-web\vendor\yiisoft\yii2\db\Command.php:330
By debugging the controller code I found that the error comes at foreach ($model->images as $file) as print_r($model->images) return Array() empty.
By doing print_r($model) I got
common\models\MeterAcceptanceHeader Object ( [_attributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 1 [sub_div] => 37111 [meter_type] => L.T.TOU [prepared_by] => 12 [prepared_at] => 2018-08-20 12:41:27 [updated_at] => [status] => Prepared [updated_by] => [images] => Array ( ) ) [_oldAttributes:yii\db\BaseActiveRecord:private] => Array ( [id] => 1 [sub_div] => 37111 [meter_type] => L.T.TOU [prepared_by] => 12 [prepared_at] => 2018-08-20 12:41:27 [updated_at] => [status] => Prepared [updated_by] => [images] => ) [_related:yii\db\BaseActiveRecord:private] => Array ( ) [_errors:yii\base\Model:private] => [_validators:yii\base\Model:private] => [_scenario:yii\base\Model:private] => default [_events:yii\base\Component:private] => Array ( ) [_behaviors:yii\base\Component:private] => Array ( ) )
I have used the same process in other modules as well and it works properly.
How can I get rid of this problem?
Update 1
<?php
use yii\helpers\Html;
use yii\grid\GridView;
use yii\helpers\Url;
use app\models\User;
use yii\widgets\DetailView;
use yii\widgets\ActiveForm;
use yii\widgets\Pjax;
use kartik\select2\Select2;
use kartik\file\FileInput;
/* #var $this yii\web\View */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = $model->id;
$this->title = 'Meter Acceptance Form';
$this->params['breadcrumbs'][] = $this->title;
?>
<section class="content-header">
<h1>Meter Acceptance</h1>
</section>
<div class="map-meters-form" id="doc">
<section class="content">
<div class="box">
<div id="chk" class="box-body">
<?php Pjax::begin(); ?>
<?=
DetailView::widget([
'model' => $model,
'attributes' => [
[
'label' => 'Serial #',
'value' => function($d){
return $d->id;
}
],
[
'label' => 'Meter Type',
'value' => function ($d){
if( is_object($d) )
return $d->meter_type;
return ' - ';
},
],
'sub_div',
[
'label' => 'Sub Division Name',
'value' => function ($d){
if( is_object($d) )
return $d->subDiv->name;
return '-';
},
],
[
'label' => 'Prepared By',
'value' => function ($d){
if( is_object($d) )
return $d->prepared->name;
},
],
'prepared_at',
'status',
],
])
?>
<br>
<div class="pre-scrollable">
<?=
GridView::widget([
'dataProvider' => $dataProvider,
//'ajaxUpdate' => true,
'filterModel' => false,
//'id'=>'gv',
'columns' => [
['class' => 'yii\grid\SerialColumn'],
['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d){
return ['value' => $d['meter_id']];
}],
'Meter_Serial_Number',
'Meter_Type',
'Sub_Division_Code',
'Sub_Division_Name',
],
]);
?>
</div>
<?php Pjax::end(); ?>
<?php
$form = ActiveForm::begin(['id' => 'map-form', 'enableClientValidation' => true, 'enableAjaxValidation' => false,
'options' => ['enctype' => 'multipart/form-data']])
?>
<?=$form->field($model, 'images[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>
<br>
<p>
Submit
<br/>
</p>
<?php ActiveForm::end(); ?>
</div>
</div>
</section>
</div>
<?php
$url = Url::toRoute(['/meteracceptanceheader/setpdf','id'=>$model->id]);
$script = <<< JS
$(document).ready(function () {
$(document).on('pjax:end', function() {
$("#chk").find("input:checkbox").prop("checked", true);
});
$("#chk").find("input:checkbox").prop("checked", true);
$('#myid').on('click',function(e) {
e.preventDefault();
//START Append form data
var data = new FormData();
var files= $('input[name="MeterAcceptanceHeader[images][]"]')[0].files;
//append files
$.each(files,function(index,file){
data.append("MeterAcceptanceHeader[images][]",file,file.name);
});
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!=="")
{
strValue = strValue + " , " + this.value;
}
else
strValue = this.value;
});
//alert(strValue);
//append your query string to the form data too
data.append('data',strValue);
//END append form data
$.ajax({
url: '$url',
type: 'POST',
dataType: 'json',
contentType: false,
processData: false,
data: {data:strValue},
success: function(data) {
alert(data);
}
});
})
});
JS;
$this->registerJs($script, \yii\web\View::POS_END);
?>
Any help would be highly appreciated.
What looks like that you are trying to submit an image via Ajax call when you click on submit button in the step 2 for image upload as you are binding the click to the #myid which is the anchor button
Submit
And if you are trying to send the image via ajax you need to use the FormData interface.
The FormData interface provides a way to easily construct a set of
key/value pairs representing form fields and their values, which can
then be easily sent using the XMLHttpRequest.send() method. It uses
the same format a form would use if the encoding type were set to
"multipart/form-data".
But before I address how to do it, you need to look into some other issues related to Form2 view.
You are nesting the 2 forms which is technically wrong and you can't do that see Why.
Above all why are you creating a separate form for the submit button?
see this line on top
<?php $form = ActiveForm::begin(['id' => 'map-form', 'enableClientValidation' => true, 'enableAjaxValidation' => false,
'options' => ['enctype' => 'multipart/form-data']]) ?>
This is where your first form starts and the file input field
<?= $form->field($model, 'images[]')->fileInput(['multiple' => true, 'accept' => 'image/*'])?>
is inside this form, and on the very next line you have the anchor button that i mentioned above in the start but you are wrapping it inside a separate form and that too before you close the ActiveForm
<form>
<p>
Submit
<br/>
</p>
</form>
instead you are closing the ActiveForm after this form by calling <?php ActiveForm::end(); ?>. As you have seen in the previous question that you faced weird behavior with the filter inputs for the GridVew as you were wrapping the GridView inside the form, and you are repeating that same mistake here too and also nesting 2 forms within.
What i will advise you to do first
Remove the form that you are creating just for the anchor button, as you wont be needing it if you want to submit the image via ajax by clicking on the anchor just keep the anchor inside the main ActiveForm. And Move the ActiveForm::begin() just before the fileInput() and after the Pjax::end().
With that said you should now user FormData to upload the image via ajax and to do so you have to add these options contentType: false and processData: false inside your ajax call and use FormData.append() to append the input files to the FormData.
So your javascript for the click function will look like this, i assume the model used for the image upload is MeterAcceptanceImages
$('#myid').on('click',function(e) {
event.preventDefault();
//START Append form data
let data = new FormData();
let files= $("input[name='MeterAcceptanceImages[images][]']")[0].files;
//append files
$.each(files,function(index,file){
data.append('MeterAcceptanceImages[images][]',file,file.name);
});
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!==""){
strValue = strValue + " , " + this.value;
}else{
strValue = this.value;
}
});
//append your query string to the form data too
data.append('data',strValue);
//END append form data
$.ajax({
url: '$url',
type: 'POST',
dataType: 'json',
contentType: false,
processData: false,
data: data,
success: function(data) {
alert(data);
}
});
});
So overall your view Form2.php should look like below
<div class="map-meters-form" id="doc">
<section class="content">
<div class="box">
<div id="chk" class="box-body">
<?php Pjax::begin(); ?>
<?=
DetailView::widget([
'model' => $model,
'attributes' => [
[
'label' => 'Serial #',
'value' => function($d){
return $d->id;
}
],
[
'label' => 'Meter Type',
'value' => function ($d){
if( is_object($d) )
return $d->meter_type;
return ' - ';
},
],
'sub_div',
[
'label' => 'Sub Division Name',
'value' => function ($d){
if( is_object($d) )
return $d->subDiv->name;
return '-';
},
],
[
'label' => 'Prepared By',
'value' => function ($d){
if( is_object($d) )
return $d->prepared->name;
},
],
'prepared_at',
'status',
],
])
?>
<br>
<div class="pre-scrollable">
<?=
GridView::widget([
'dataProvider' => $dataProvider,
//'ajaxUpdate' => true,
'filterModel' => false,
//'id'=>'gv',
'columns' => [
['class' => 'yii\grid\SerialColumn'],
['class' => 'yii\grid\CheckboxColumn', 'checkboxOptions' => function($d){
return ['value' => $d['meter_id']];
}],
'Meter_Serial_Number',
'Meter_Type',
'Sub_Division_Code',
'Sub_Division_Name',
],
]);
?>
</div>
<?php Pjax::end(); ?>
<?php
$form = ActiveForm::begin(['id' => 'map-form', 'enableClientValidation' => true, 'enableAjaxValidation' => false,
'options' => ['enctype' => 'multipart/form-data']])
?>
<?=$form->field($model, 'images[]')->fileInput(['multiple' => true, 'accept' => 'image/*']) ?>
<br>
<p>
Submit
<br/>
</p>
<?php ActiveForm::end(); ?>
</div>
</div>
</section>
</div>
<?php
$url = Url::toRoute(['/meteracceptanceheader/setpdf', 'id' => $model->id]);
$script = <<< JS
$(document).ready(function () {
$(document).on('pjax:end', function() {
$("#chk").find("input:checkbox").prop("checked", true);
});
$("#chk").find("input:checkbox").prop("checked", true);
$('#myid').on('click',function(e) {
event.preventDefault();
//START Append form data
let data = new FormData();
let files= $("input[name='MeterAcceptanceImages[images][]']")[0].files;
//append files
$.each(files,function(index,file){
data.append('MeterAcceptanceImages[images][]',file,file.name);
});
var strValue = "";
$('input[name="selection[]"]:checked').each(function() {
if(strValue!==""){
strValue = strValue + " , " + this.value;
}else{
strValue = this.value;
}
});
//append your query string to the form data too
data.append('data',strValue);
//END append form data
$.ajax({
url: '$url',
type: 'POST',
dataType: 'json',
contentType: false,
processData: false,
data: data,
success: function(data) {
alert(data);
}
});
});
});
JS;
$this->registerJs($script, \yii\web\View::POS_END);
?>
Now if you try to print_r(UploadedFile::getInstances('images')) should show you all the images you selected and submitted to upload. To troubleshoot in case of errors while uploading of the ajax call you can see my answer i posted previously related to ajax file uploads.

Can't find value in select2 ajax loading in yii2

I use select2 ajax loading. I get the code from this link: http://demos.krajee.com/widget-details/select2. When I enter words into field, it display all data/value, but it can't automatic select data/value according to words that I enter into field. So, my select2 always select the first data/value and display all value. What's the problem? These are the codes:
_form.php
$url = Url::to(['/paket/jsonlist']);
$cityDesc = empty($model->no_induk) ? '' : Penerima::findOne($model->no_induk)->nama;
echo $form->field($model, 'no_induk')->widget(Select2::classname(), [
'initValueText' => $cityDesc, // set the initial display text
'options' => ['placeholder' => 'Search for a city ...'],
'pluginOptions' => [
'allowClear' => true,
'minimumInputLength' => 1,
'language' => [
'errorLoading' => new JsExpression("function () { return 'Waiting for results...'; }"),
],
'ajax' => [
'url' => $url,
'dataType' => 'json',
'data' => new JsExpression('function(params) { return {q:params.term}; }')
],
'escapeMarkup' => new JsExpression('function (markup) { return markup; }'),
'templateResult' => new JsExpression('function(no_induk) { return no_induk.text; }'),
'templateSelection' => new JsExpression('function (no_induk) { return no_induk.id; }'),
],
]);
my controller:
public function actionJsonlist($q = NULL, $id = NULL)
{
\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$out = ['results' => ['id' => '', 'text' => '']];
if(!is_null($q))
{
$query = new \yii\db\Query;
$mainQuery = $query->select('no_induk AS id, nama AS text')
->from('penerima')
->limit(20);
$command = $mainQuery->createCommand();
$data = $command->queryAll();
$out['results'] = array_values($data);
}
elseif ($id > NULL)
{
$out['results'] = ['id' => $id, 'text' => \frontend\models\Penerima::find($id)->nama];
}
return $out;
}
Could be you use the attribute name and not the vars
echo $form->field($model, 'no_induk')->widget(Select2::classname(), [
'initValueText' =>'cityDesc', // set the initial display text
or
echo $form->field($model, 'no_induk')->widget(Select2::classname(), [
'initValueText' =>$model->cityDesc, // set the initial display text

Arguments from Controller passed to View was not fetched in php

Im Using
PHP language , yii-1.1.13 framework and MySQL DB.
Views code of Main Page.
<?php
/**
* The view for the trip schedules page.
* #uses ManageTripSchedulesForm $model
* #uses VoyageServiceClassInfo $voyageServiceClassInfo
* #uses LocationInfo $locationInfo
* #uses PierInfo $pierInfo
* #uses VesselInfo $vesselInfo
* #uses ServiceClassInfo $serviceClassInfo
* #uses FareSetInfo $fareSetInfo
* #uses SearchTripsForm $searchTripsForm
* #uses FerryOperatorInfo $ferryOperatorInfo
* #uses ManageTripSchedulesFilterForm $filterForm
*/
$this->setPageTitle(SystemConstants::SITE_NAME . ' - Trip Schedules');
$baseUrl = Yii::app()->getBaseUrl();
$cs = Yii::app()->getClientScript();
// --- POS_HEAD
// a plug-in used in manageTripSchedules.js
$cs->registerScriptFile($baseUrl . '/js/jquery.blockUI.js', CClientScript::POS_HEAD);
// for this view
$cs->registerCssFile($baseUrl . '/css/manageTripSchedules.css');
$cs->registerScriptFile($baseUrl . '/js/manageTripSchedules.js', CClientScript::POS_HEAD);
$this->endWidget('zii.widgets.jui.CJuiDialog');
/**
* Maintenance Dialog widget
*/
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'dialog',
'options' => array(
'title' => 'Trip Schedules',
'autoOpen' => false,
'modal' => true,
'resizable' => false,
'width' => 600,
'dialogClass' => 'tripschedules-dialog-class',
'show'=>array(
'effect'=>'drop',
'duration'=>500,
),
'hide'=>array(
'effect'=>'drop',
'duration'=>500,
),
),
));
/**
* Render the maintenance dialog view.
*/
echo $this->renderPartial('manageTripSchedulesDialog', array(
'model' => $model,
'ferryOperatorInfo' => $ferryOperatorInfo,
'locationInfo' => $locationInfo,
'pierInfo' => $pierInfo,
'vesselInfo' => $vesselInfo,
'serviceClassInfo' => $serviceClassInfo,
'fareSetInfo' => $fareSetInfo
));
$this->endWidget('zii.widgets.jui.CJuiDialog');
<div id="grid-container" class="grid-div">
<?php
$pageSize = 10;
$helper = new TripSchedulesGridHelper($this);
$this->widget('zii.widgets.grid.CGridView', array(
'id' => 'tripschedules-grid',
'dataProvider' => $voyageServiceClassInfo->searchTripSchedules(Yii::app()->user->ferry_operator_id, $filterForm, $pageSize),
'emptyText' => 'No data found.',
'selectableRows' => 0,
'template' => '{items}{pager}', // to remove summary header
'pager' => array(
'header' => '', // to remove 'Go to page:'
),
'cssFile' => $baseUrl . '/css/manageTripSchedulesGrid.css',
'columns' => array(
array(
'name' => 'id',
'value' => '$data->voyage_service_class_id',
'headerHtmlOptions' => array('style' => 'display:none'),
'htmlOptions' => array('style' => 'display:none'),
),
'voyage.ferry_operator.name::Operator',
array(
'name' => 'Origin',
'value' => array($helper, 'formatOriginTerminal'),
),
array(
'name' => 'Destination',
'value' => array($helper, 'formatDestinationTerminal'),
),
array(
'name' => 'DepartureTime',
'header' => 'Departure',
'value' => array($helper, 'formatDepartureDate'),
),
array(
'name' => 'ArrivalTime',
'header' => 'Arrival',
'value' => array($helper, 'formatArrivalDate'),
),
array(
'name' => 'TripHrs',
'header' => 'Trip Hrs',
'value' => array($helper, 'formatTripDuration'),
),
'voyage.vessel.name::Vessel',
'service_class.name::Service Class',
'fare_set.fare_type::Fare Set',
array(
'class' => 'CButtonColumn',
'template'=>'{update}{delete1}',
'buttons'=>array(
'update' => array(
'label'=>'Edit',
'imageUrl'=>Yii::app()->baseUrl.'/images/gridview/update.png',
'url'=>'"#"',
'click'=>'function(){updateTripScheduleJs($(this).parent().parent().children(":nth-child(1)").text());}',
),
'delete1' => array(
'label'=>'Delete',
'imageUrl'=>Yii::app()->baseUrl.'/images/gridview/delete.png',
'url'=>'"#"',
'click'=>'function(){deleteTripScheduleJs($(this).parent().parent().children(":nth-child(1)").text());}',
),
),
),
),
));
?>
</div>
Views code of Add/Edit Dialog.
<?php
echo $form->dropDownList($model, 'service_class_id',
$serviceClassInfo->getAllServiceClassesForSelection2($model->ferry_operator_id,
$this->_ferryOperatorId , true, 'Select class'),
array(
'id' => 'service_class_id',
'class' => 'selectbox',
'ajax' => array(
'type'=>'POST',
'url'=>CController::createUrl('loadFareSet'),
'update'=>'#fare_set_id',
'data'=>array('service_class_id'=>'js:this.value'),
))
);
?>
In my Controller, below is my code.
<?php
class SiteController extends Controller
{
public $_ferryOperatorId;
public function actionRetrieveTripSchedule() {
$voyageServiceClassInfo = new VoyageServiceClassInfo;
if (isset($_POST['id']))
{
if (Yii::app()->request->isAjaxRequest)
{
$voyageServiceClassInfo = VoyageServiceClassInfo::model()->with('voyage')->findByPk($_POST['id']);
if ($voyageServiceClassInfo != null)
{
$this->_ferryOperatorId = '3';
$_json = array(
array('name'=>'voyage_service_class_id', 'value'=>$voyageServiceClassInfo->voyage_service_class_id),
array('name'=>'ferry_operator_id', 'value'=>$voyageServiceClassInfo->voyage->ferry_operator_id),
array('name'=>'origin_location_id', 'value'=>$voyageServiceClassInfo->voyage->origin_location_id),
array('name'=>'origin_pier_id', 'value'=>$voyageServiceClassInfo->voyage->origin_pier_id),
array('name'=>'destination_location_id', 'value'=>$voyageServiceClassInfo->voyage->destination_location_id),
array('name'=>'destination_pier_id', 'value'=>$voyageServiceClassInfo->voyage->destination_pier_id),
array('name'=>'departure_date', 'value'=>$voyageServiceClassInfo->voyage->departure_date),
array('name'=>'departure_time', 'value'=>$voyageServiceClassInfo->voyage->departure_time),
array('name'=>'arrival_date', 'value'=>$voyageServiceClassInfo->voyage->arrival_date),
array('name'=>'arrival_time', 'value'=>$voyageServiceClassInfo->voyage->arrival_time),
array('name'=>'vessel_id', 'value'=>$voyageServiceClassInfo->voyage->vessel_id),
array('name'=>'service_class_id', 'value'=>$voyageServiceClassInfo->service_class_id),
array('name'=>'fare_set_id', 'value'=>$voyageServiceClassInfo->fare_set_id),
);
echo CJSON::encode(array(
'status'=>'success',
'messages'=>"Target data is retrieved normally.",
'val'=>$_json,
));
}
else
{
echo CJSON::encode(array(
'status'=>'failure',
'messages'=>"Target data can not be retrieved from server.",
'val'=>$_json,
));
}
}
}
}
}
Models code of Service class drop down lists.
public function getAllServiceClassesForSelection2(
$operatorId = null, $operatorIdEdit = null, $addInstructionRow = false, $instruction = null)
{
$serviceClassArray = array();
if ($addInstructionRow) {
if ($instruction == null) {
$instruction = 'Select a ServiceClass';
}
$serviceClassArray += array('' => $instruction);
}
$criteria = new CDbCriteria;
$criteria->select = 'service_class_id, name';
if ($operatorId != null || $operatorId != '')
{
$criteria->condition = 'ferry_operator_id = ' . $operatorId;
}
if ($operatorIdEdit != null || $operatorIdEdit != '' && $model->operation_mode == AdminGeneralHelper::OPERATION_MODE_UPDATE)
{
$criteria->condition = 'ferry_operator_id = ' . $operatorIdEdit;
}
$criteria->order = 'name';
$servceClassInfos = $this->findAll($criteria);
foreach ($servceClassInfos as $servceClassInfo) {
$serviceClassArray += array(
$servceClassInfo->service_class_id => $servceClassInfo->name,
);
}
return $serviceClassArray;
}
In my JS file, below is my code.
function updateTripScheduleJs(id) {
// Get target data via controller and set values to fields of dialog.
$.blockUI({
message: "Loading data...",
});
$("#dialog-msg").html(""); // clear the message area of dialog
// Ajax request
$.ajax({
url: 'retrieveTripSchedule',
type: 'POST',
datatype: 'json',
data: $.parseJSON('{"id": '+id+'}'),
timeout: 20000,
beforeSend: function(){
},
success: function(data){
$.unblockUI();
var res = eval('(' + data + ')');
if (res.status == 'success'){
for (var idx in res.val){
if (res.val[idx].name == 'departure_time' || res.val[idx].name == 'arrival_time'){
$('#'+res.val[idx].name).attr('value',formatAMPM(res.val[idx].value));
} else {
$('#'+res.val[idx].name).attr('value',res.val[idx].value);
}
}
$("#operation_mode").attr('value','U'); // Set update mode
$(".submit-button").attr('value','Update Trip Schedule'); // Set submit button label
$(".update-only-div").css('display','block'); // Show columns for update
$(".create-only-div").css('display','none'); // Hide columns for update
$("#dialog").dialog("open");
} else {
alert("Trip Schedule does not exist. It may be deleted by other user");
$.fn.yiiGridView.update('tripschedules-grid'); // Refresh the list of service class.
}
},
error: function(){
$.unblockUI();
alert("Ajax Communication Error. Please contact system administrator.");
}
}
);
}
Below is the scenario:
I clicked the pencil icon, dialog will show. It will load all the
details depend on the selected row. This is correct.
It will load all the details. This is correct.
No. of values in Drop down lists for service class is wrong.
My expected output of service class is only 4 (based on DB) but in actual, all service class was displayed.
I found out that $this->_ferryOperatorId = '3' from controller that was used in views
($serviceClassInfo->getAllServiceClassesForSelection2($model->ferry_operator_id,
$this->_ferryOperatorId , true, 'Select class'))
has no value.
In my models code, if the ferryOperatorId = null, it will display all the
service class.
My question is what is the correct code for me to get the value of $this->_ferryOperatorId from controller
then used the value in views.
:(
Please help me to solve this.

Categories