I need to call a Javascript function before submitting a form, this function generates 2 values (1 token and 1 hash), so I need to pass these values in 2 hidden fields.
JS Function: FULL/UPDATED
<script type="text/javascript">
//Generates the necessary content
$('#submitForm').click(function() {
PagSeguroBuscaHashCliente(); //Create Hash
PagSeguroBuscaBandeira(); //By field "pagseguro_cartao_numero" return flag card
PagSeguroBuscaToken(); //By 4 digits "pagseguro_cartao_numero" gen token card
setTimeout(function() {
enviarPedido();
}, 3000);
});
function enviarPedido() {
/** TEST GENERATED VALUES **/
alert($('#pagseguro_cliente_hash').val())
alert($('#pagseguro_cartao_token').val())
// var data = {
// hash: $('#pagseguro_cliente_hash').val(),
// token: $('#pagseguro_cartao_token').val()
// };
$('#pagseguro_cliente_hash').val(pagseguro_cliente_hash);
$('#pagseguro_cartao_token').val(pagseguro_cartao_token);
$('#sampleForm').submit();
}
</script>
View form:
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\ArrayHelper;
use app\models\Assinatura;
use CWG\PagSeguro\PagSeguroAssinaturas;
$this->title = 'Assinatura';
$this->params['breadcrumbs'][] = $this->title;
$email = "xxxxxx#hotmail.com";
$token = "xxxxxxx";
// token gerado em 23/04/2020
$sandbox = false;
$pagseguro = new PagSeguroAssinaturas($email, $token, $sandbox);
//Sete apenas TRUE caso queira importa o Jquery também. Caso já possua, não precisa
$js = $pagseguro->preparaCheckoutTransparente(true);
echo $js['completo']; //Importa todos os javascripts necessários
?>
<div class="site-minhaconta">
<h1><?= Html::encode($this->title) ?></h1>
<!-- INICIO FORM -->
<?php $form = ActiveForm::begin([
'method' => 'post',
'id' =>'sampleForm'
])
?>
<div class="panel-body">
<?= $form->field($model, 'pagseguro_cartao_numero')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'pagseguro_cartao_mes')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'pagseguro_cartao_ano')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'pagseguro_cartao_cvv')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'form_nome')->textInput(['maxlength' => true]) ?>
<hr>
<?= $form->field($model, 'form_email')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'form_cpf')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'pagseguro_cliente_hash')->hiddenInput(['id' => 'pagseguro_cliente_hash'])->label(false)?>
<?= $form->field($model, 'pagseguro_cartao_token')->hiddenInput(['id' => 'pagseguro_cartao_token'])->label(false)?>
<div class="form-group">
<?= Html::button('Confirmar Assinatura', ['name'=>'submitForm',
'id' => 'submitForm', 'value'=>'submitForm', 'class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
<!-- FINAL FORM -->
<script type="text/javascript">
//Generates the necessary content
$('#submitForm').click(function() {
PagSeguroBuscaHashCliente(); //Create Hash
PagSeguroBuscaBandeira(); //By field "pagseguro_cartao_numero" return flag card
PagSeguroBuscaToken(); //By 4 digits "pagseguro_cartao_numero" gen token card
setTimeout(function() {
enviarPedido();
}, 3000);
});
function enviarPedido() {
/** TEST GENERATED VALUES **/
alert($('#pagseguro_cliente_hash').val())
alert($('#pagseguro_cartao_token').val())
// var data = {
// hash: $('#pagseguro_cliente_hash').val(),
// token: $('#pagseguro_cartao_token').val()
// };
$('#pagseguro_cliente_hash').val(pagseguro_cliente_hash);
$('#pagseguro_cartao_token').val(pagseguro_cartao_token);
$('#sampleForm').submit();
}
</script>
</div>
Controller Action:
public function actionAssinatura()
{
$model = new \app\models\Assinatura();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->form_email = $_POST['Assinatura']['form_email'];
$model->form_cpf = $_POST['Assinatura']['form_cpf'];
$model->pagseguro_cliente_hash = $_POST['Assinatura']['pagseguro_cliente_hash'];
$model->pagseguro_cartao_token = $_POST['Assinatura']['pagseguro_cartao_token'];
return $this->render('plano_assinatura_process', [
'form_email' => $model->form_email,
'form_cpf' => $model->form_cpf,
'pagseguro_cliente_hash' => $model->pagseguro_cliente_hash,
'pagseguro_cartao_token' => $model->pagseguro_cartao_token,
]);
} else {
return $this->render('plano_assinatura_form', [
'model' => $model,
]);
}
}
Model file
public $pagseguro_cartao_numero;
public $pagseguro_cartao_mes;
public $pagseguro_cartao_ano;
public $pagseguro_cartao_cvv;
public $form_nome;
public $form_email;
public $form_cpf;
public $form_plano;
public $form_codplano;
public $pagseguro_cartao_token;
public $pagseguro_cliente_hash;
public function rules()
{
return [
[[
'pagseguro_cartao_numero',
'pagseguro_cartao_mes',
'pagseguro_cartao_ano',
'pagseguro_cartao_cvv',
'form_nome',
'form_email',
'form_cpf',
'form_plano',
//'form_codplano',
], 'required'],
[['pagseguro_cartao_token', 'pagseguro_cliente_hash'], 'safe'],
];
}
The hidden fields "pagseguro_cliente_hash" and "pagseguro_cliente_token" need to receive the variables js $ ('# pagseguro_cliente_hash'). Val () and $ ('# pagseguro_cartao_token'). Val () respectively.
How do you do that?
Generated JS by Payment gateway (UPDATE 2020-05-09)
<script type="text/javascript" src="https://stc.pagseguro.uol.com.br/pagseguro/api/v2/checkout/pagseguro.directpayment.js"></script><script type="text/javascript">PagSeguroDirectPayment.setSessionId("336d21fd502c41c982c55faf90e1eba9")</script>
<input type='hidden' id='pagseguro_cliente_hash'/>
<script type='text/javascript'>
function PagSeguroBuscaHashCliente() {
PagSeguroDirectPayment.onSenderHashReady(function(response){
if(response.status == 'error') {
console.log(response.message);
return false;
}
$('#pagseguro_cliente_hash').val(response.senderHash); //Hash estará disponível nesta variável.
console.log('Hash Cliente: ' + $('#pagseguro_cliente_hash').val());
});
}
</script>
<input type='hidden' id='pagseguro_cartao_token' />
<script type='text/javascript'>
function PagSeguroBuscaToken() {
PagSeguroDirectPayment.createCardToken({
cardNumber: $('#pagseguro_cartao_numero').val(),
brand: $('#pagseguro_cartao_bandeira').val(),
cvv: $('#pagseguro_cartao_cvv').val(),
expirationMonth: $('#pagseguro_cartao_mes').val(),
expirationYear: $('#pagseguro_cartao_ano').val(),
success: function(response) { console.log('Token: ' + response.card.token); $('#pagseguro_cartao_token').val(response.card.token)},
error: function(response) { console.log(response); },
});
}
</script>
Payment Gateway example form page:
<h2> Campos Obrigatórios </h2>
<p>Número do Cartão</p>
<!-- OBRIGATÓRIO UM CAMPO COM O ID pagseguro_cartao_numero-->
<input type="text" id="pagseguro_cartao_numero" value="4111111111111111"/>
<p>CVV do cartão</p>
<!-- OBRIGATÓRIO UM CAMPO COM O ID pagseguro_cartao_cvv-->
<input type="text" id="pagseguro_cartao_cvv" value="123"/>
<p>Mês de expiração do Cartao</p>
<!-- OBRIGATÓRIO UM CAMPO COM O ID pagseguro_cartao_mes-->
<input type="text" id="pagseguro_cartao_mes" value="12"/>
<p>Ano de Expiração do Cartão</p>
<!-- OBRIGATÓRIO UM CAMPO COM O ID pagseguro_cartao_ano-->
<input type="text" id="pagseguro_cartao_ano" value="2030"/>
<br/>
<button id="botao_comprar">Comprar</button>
<script type="text/javascript">
//Gera os conteúdos necessários
$('#botao_comprar').click(function() {
PagSeguroBuscaHashCliente(); //Cria o Hash identificador do Cliente usado na transição
PagSeguroBuscaBandeira(); //Através do pagseguro_cartao_numero do cartão busca a bandeira
PagSeguroBuscaToken(); //Através dos 4 campos acima gera o Token do cartão
setTimeout(function() {
enviarPedido();
}, 3000);
});
function enviarPedido() {
/** FAÇA O QUE QUISER DAQUI PARA BAIXO **/
alert($('#pagseguro_cliente_hash').val())
alert($('#pagseguro_cartao_token').val())
var data = {
hash: $('#pagseguro_cliente_hash').val(),
token: $('#pagseguro_cartao_token').val()
};
$.post('http://localhost/pagseguro/examples/assinando2.php', data, function(response) {
alert(response);
});
}
</script>
plano_assinatura_form:
<?php $form = ActiveForm::begin([
'method' => 'post',
'id' =>'sampleForm'
])
?>
<div class="panel-body">
<?= $form->field($model, 'pagseguro_cartao_numero')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'pagseguro_cartao_mes')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'pagseguro_cartao_ano')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'pagseguro_cartao_cvv')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'form_nome')->textInput(['maxlength' => true]) ?>
<hr>
<?= $form->field($model, 'form_email')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'form_cpf')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'pagseguro_cliente_hash')->hiddenInput(['id' => 'pagseguro_cliente_hash'])->label(false)?>
<?= $form->field($model, 'pagseguro_cartao_token')->hiddenInput(['id' => 'pagseguro_cartao_token'])->label(false)?>
<div class="form-group">
<?= Html::button('Confirmar Assinatura', ['name'=>'submitForm',
'id' => 'submitForm', 'value'=>'submitForm', 'class' => 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
<!-- FINAL FORM -->
<?php $this->registerJsFile(Yii::$app->request->baseUrl.'/test.js',['depends' => [\yii\web\JqueryAsset::className()]]); ?>
test.js:
$('#submitForm').click(function() {
// PagSeguroBuscaHashCliente(); //Create Hash
// PagSeguroBuscaBandeira(); //By field "pagseguro_cartao_numero"
return flag card
// PagSeguroBuscaToken(); //By 4 digits
"pagseguro_cartao_numero" gen token card
setTimeout(function() {
enviarPedido();
}, 3000);
});
function enviarPedido() {
/** TEST GENERATED VALUES **/
pagseguro_cliente_hash = 'testHash';
pagseguro_cartao_token = 'testToken';
// var data = {
// hash: $('#pagseguro_cliente_hash').val(),
// token: $('#pagseguro_cartao_token').val()
// };
$('#pagseguro_cliente_hash').val(pagseguro_cliente_hash);
$('#pagseguro_cartao_token').val(pagseguro_cartao_token);
alert($('#pagseguro_cliente_hash').val())
alert($('#pagseguro_cartao_token').val())
$('#sampleForm').submit();
}
actionAssinatura:
public function actionAssinatura()
{
$model = new \app\models\Assinatura();
if ($model->load(Yii::$app->request->post()) && $model->validate()) {
$model->form_email = $_POST['Assinatura']['form_email'];
$model->form_cpf = $_POST['Assinatura']['form_cpf'];
$model->pagseguro_cliente_hash = $_POST['Assinatura']['pagseguro_cliente_hash'];
$model->pagseguro_cartao_token = $_POST['Assinatura']['pagseguro_cartao_token'];
return $this->render('plano_assinatura_process', [
'form_email' => $model->form_email,
'form_cpf' => $model->form_cpf,
'pagseguro_cliente_hash' => $model->pagseguro_cliente_hash,
'pagseguro_cartao_token' => $model->pagseguro_cartao_token,
]);
} else {
return $this->render('plano_assinatura_form', [
'model' => $model,
]);
}
}
fetch posted data in assinatura action :
C:\wamp64\www\basic\controllers\SiteController.php:139:
array (size=2)
'_csrf' => string 'C1spbi8HWaBqAO0w5ozFK6KOyKb20j0cRGR_j5t6vEg-FBE-
bXRs8gFZqVSOwp9xyOrl8sHleHUCMQv89CXxeQ==' (length=88)
'Assinatura' =>
array (size=9)
'pagseguro_cartao_numero' => string 'asdfasdf' (length=8)
'pagseguro_cartao_mes' => string 'asdfasdf' (length=8)
'pagseguro_cartao_ano' => string 'asdfasdf' (length=8)
'pagseguro_cartao_cvv' => string 'asdfasdf' (length=8)
'form_nome' => string 'asdfasdf' (length=8)
'form_email' => string 'asdfasdf' (length=8)
'form_cpf' => string 'asdfasdf' (length=8)
'pagseguro_cliente_hash' => string 'testHash' (length=8)
'pagseguro_cartao_token' => string 'testToken' (length=9)
In case of Yii
You should add below form structure using ActiveForm
<?php $form = ActiveForm::begin([
'id'=>'YourFormId'
]) ?>
//input fields and buttons
<?php ActiveForm::end() ?>
Simply add below code to execute your JS before form submitting
$('body').on('beforeSubmit',"#YourFormId",function() {
//javascript code here
});
return false; to stop form submitting
for more details Click Here
Related
I created a dynamic form using wbraganca / yii2-dynamicform to handle requests in my solution. I have couple fields like Item, Qty and Unit. I have a list of items loaded using ArrayHelper and I am using Kartik's Select2 widget to load the data.
_form.php
<?php
use backend\models\Item;
use backend\models\ItemCategory;
use backend\models\ItemUnit;
use backend\models\Jobs;
use common\models\User;
use kartik\depdrop\DepDrop;
use kartik\select2\Select2;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use wbraganca\dynamicform\DynamicFormWidget;
use yii\helpers\Url;
use yii\widgets\Pjax;
/* #var $this yii\web\View */
/* #var $model backend\models\Requests */
/* #var $form yii\widgets\ActiveForm */
$js = '
jQuery(".dynamicform_wrapper").on("afterInsert", function(e, item) {
jQuery(".dynamicform_wrapper .panel-title-address").each(function(index) {
var i = index;
});
});
jQuery(".dynamicform_wrapper").on("afterDelete", function(e) {
jQuery(".dynamicform_wrapper .panel-title-address").each(function(index) {
});
});
';
$this->registerJs($js);
$itemCategory = ItemCategory::find()->where(['cat_status' => 'Active'])->all();
$catData = ArrayHelper::map($itemCategory, 'cat_id', 'cat_name');
if (!Yii::$app->user->identity->isAdmin) {
$modelJobs = Jobs::find()
->joinWith('myJobs')
->where(['ja_user_id' => Yii::$app->user->id, 'ja_status' => 'Active'])
->all();
} else {
$modelJobs = Jobs::find()
->where(['job_status' => 'In Progress'])
->all();
}
$jobs = ArrayHelper::map($modelJobs, 'job_id', function ($modelJobs) {
return $modelJobs->job_no . '-' . $modelJobs->getJobTitle($modelJobs->job_invt_no);
});
if (isset($_GET['cid'])) {
$cat_id = $_GET['cid'];
$subCate = Item::find()->where(['item_category' => $cat_id, 'item_status' => 'Active'])->all();
$invListData = ArrayHelper::map($subCate, 'item_id', 'item_title');
} else {
$cat_id = '';
$invListData = [];
}
if (isset($_GET['job']) && $_GET['job'] != null) {
$job_id = $_GET['job'];
$modelJobs = Jobs::find()->where(['job_id' => $job_id])->one();
$job = $modelJobs->job_no . '-' . $modelJobs->getJobTitle($modelJobs->job_invt_no);
} else {
$job_id = '';
}
$modelUnit = ItemUnit::find()->where(['unit_status' => 'Active'])->all();
$unit = ArrayHelper::map($modelUnit, 'unit_id', function ($modelUnit) {
return $modelUnit->unit_name . '(' . $modelUnit->unit_short_name . ')';
});
?>
<div class="requests-form">
<?php $form = ActiveForm::begin(['id' => 'dynamic-form']); ?>
<?php $form->errorSummary($model); ?>
<div class="row">
<div class="col-md-4">
<?php echo $form->field($model, 'rq_cat_type')->widget(Select2::class, [
'data' => $catData,
'options' => ['placeholder' => '--Select Material Category--', 'value' => $cat_id, 'class' => 'form-control'],
'pluginOptions' => [
'allowClear' => true
],
'pluginEvents' => [
"select2:select" => "function(params) {
console.log($(this).val());
window.history.pushState('', '', '" . Yii::$app->urlManager->createUrl('requests/create?job=' . $job_id . '&cid=') . "'+$(this).val());
window.location.replace('', '', '" . Yii::$app->urlManager->createUrl('requests/create?job=' . $job_id . '&cid=') . "'+$(this).val());
jQuery.pjax.reload({ container: '#loaderPjax', async: false });
}",
],
]);
?>
</div>
<div class="col-md-4">
<?php if (isset($_GET['job']) && $_GET['job'] != null) { ?>
<?= $form->field($model, "rq_job_no")->dropDownList([$job_id => $job], ['value' => $job_id]) ?>
<?php } else { ?>
<?php echo $form->field($model, 'rq_job_no')->widget(Select2::class, [
'data' => $jobs,
'options' => ['placeholder' => '--Select Request Type--', 'class' => 'form-control'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?php } ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'rq_req_date')->widget(\yii\jui\DatePicker::class, [
//'language' => 'ru',
'dateFormat' => 'php:Y-m-d',
'clientOptions' => [
'changeMonth' => true,
'changeYear' => true,
'showButtonPanel' => true,
'yearRange' => '1990:2030',
'minDate' => date('Y-m-d'),
],
'options' => ['class' => 'form-control', 'readOnly' => true, 'placeholder' => 'Enter the Item Required Date'],
]) ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'rq_priority_type')->dropDownList(['Urgent' => 'Urgent', 'Normal' => 'Normal'], ['prompt' => '--Select Priority Type--']) ?>
</div>
<div class="col-md-4">
<?= $form->field($model, 'rq_approval_type')->dropDownList([1 => 'Aramco Approved Vendor Needed', 2 => 'Approved Aramco Submitted Needed', 3 => 'Warranty Certificate to be Collected', 4 => 'Long Lead Material',], ['prompt' => '--Select Type of Approval--']) ?>
</div>
</div>
<!-- code for dynamic form -->
<div class="panel panel-default">
<div class="panel-heading">
<h4><i class="glyphicon glyphicon-envelope"></i> Request Items</h4>
</div>
<?php Pjax::begin(['id' => 'loaderPjax']); ?>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 10, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsAddress[0],
'formId' => 'dynamic-form',
'formFields' => [
'rt_item',
'rt_qty',
'rt_unit',
],
]); ?>
<div class="container-items">
<!-- widgetContainer -->
<?php foreach ($modelsAddress as $i => $modelAddress) { ?>
<div class="item panel panel-default">
<!-- widgetBody -->
<div class="panel-heading">
<h4 class="panel-title pull-left"></h4>
<span class="panel-title-address"></span>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="fa fa-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="fa fa-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (!$modelAddress->isNewRecord) {
echo Html::activeHiddenInput($modelAddress, "[{$i}]rt_id");
}
?>
<div class="row">
<div class="col-md-4">
<?php echo $form->field($modelAddress, "[{$i}]rt_item")->widget(Select2::class, [
'data' => $invListData,
'options' => ['placeholder' => '--Select Request Type--', 'class' => 'reqItem form-control'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelAddress, "[{$i}]rt_qty")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelAddress, "[{$i}]rt_unit")->textInput(['maxlength' => true, 'readOnly' => 'true']) ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php } ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
<?php Pjax::end(); ?>
</div>
<div class="col-md-12">
<?= $form->field($model, 'rq_remarks')->textarea(['rows' => 6]) ?>
</div>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<script>
$(document).on("change", ".reqItem", function() {
var itemVal = $(this).val();
var attrID = $(this).attr("id").replace(/[^0-9.]/g, "");
$.ajax({
"url": "units",
"type": "post",
"data": {
itemID: itemVal
},
success: function(data) {
console.log(data);
console.log(attrID);
$("#reqitems-" + attrID + "-rt_unit").val(data);
},
error: function(errormessage) {
//do something else
alert("not working");
}
});
});
</script>
The form is working perfectly, But I am facing some issues with the new requirement. The updated is to remove the selected value from the list. Which means if I select a value from the dropdown, the list should be updated without the selected value for next index in the dynamic form.
Tried couple of solutions with JQuery and javascript. The goal of requirement is to avoid duplicate entry of same value. Can anyone help me on this?
I am trying to call a API URL using AJAX. I need to validate the response and update the DB, SO I need to return it to the controller.
Is there any way to do that. Here is my view, JS and controller code.
Here is my View Code where I have a separate URL for validation, which is the API URL
View
<?php $form = ActiveForm::begin([
'action' => ['users/renderstep3'],
'validationUrl' => 'API URL',
'options' => [
'class' => 'comment-form'
]
]); ?>
<?= $form->field($paymentmodel, 'customerId')->hiddenInput(['value'=> $userid])->label(false) ?>
<?= $form->field($paymentmodel, 'owner')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
JS
jQuery(document).ready(function($) {
$('body').on('submit', '.comment-form', function(event) {
event.preventDefault(); // stopping submitting
var data = $(this).serializeArray();
data.splice(0,1);
var result = {};
for ( i=0 ; i < data.length ; i++)
{
key = data[i].name.replace("UserPaymentDetails[", "").slice(0,-1);
result[key] = data[i].value;
}
var url = $(this).attr('validationUrl');
$.ajax({
url: url,
type: 'post',
dataType: 'json',
data: JSON.stringify(result)
})
.done(function(response) {
return response;
})
.fail(function() {
console.log("error");
});
});
});
Controller Action
public function actionRenderstep3()
{
$model = new Users();
$detailsmodel = new UserDetails();
$paymentmodel = new UserPaymentDetails();
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$data = Yii::$app->request->post();
print_r($data) ; exit;
}
if ($paymentmodel->load(Yii::$app->request->post()) && $paymentmodel->validate())
{
$paymentmodel->Status = 0;
$paymentmodel->save();
return $this->redirect(['index']);
}
return $this->render('renderstep3', [
'model' => $model,
'detailsmodel' => $detailsmodel,
'paymentmodel' => $paymentmodel,
]); }
Thanks in advance!!
In your controller, you have to change the action like this in order to validate using Ajax. I have edited my answer. Please note that you can delete your custom js code in order to use like this.
// ... The View file
<?php
$form = ActiveForm::begin([
'action' => ['users/renderstep3'],
'enableAjaxValidation' => true,
'validationUrl' => 'API URL',
'options' => [
'class' => 'comment-form'
]
]);
?>
<?= $form->field($paymentmodel, 'customerId')->hiddenInput(['value'=> $userid])->label(false) ?>
<?= $form->field($paymentmodel, 'owner')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>
// ... Controller
public function actionRenderstep3()
{
$model = new Users();
$detailsmodel = new UserDetails();
$paymentmodel = new UserPaymentDetails();
if (Yii::$app->request->isAjax && $paymentmodel->load(Yii::$app->request->post())) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if ($paymentmodel->load(Yii::$app->request->post())) {
$paymentmodel->Status = 0;
$paymentmodel->save(false); // Validate false, because we did the validation before
return $this->redirect(['index']);
}
return $this->render('renderstep3', [
'model' => $model,
'detailsmodel' => $detailsmodel,
'paymentmodel' => $paymentmodel,
]);
}
You can find more information here
https://www.yiiframework.com/doc/guide/2.0/en/input-validation
<?php
$form = ActiveForm::begin([
'action' => ['users/renderstep3'],
'validationUrl' => 'API URL',//ajax validation hit to validationUrl if provide other wise validationUrl is action Url
'options' => [
'class' => 'comment-form'
]
]);
?>
and change some code in js
the below code calls befor form submit
$('body').on('beforeSubmit', '.comment-form', function(event)
In controller
In case of single model validation
if ($paymentmodel->load(Yii::$app->request->post())) {
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return yii\widgets\ActiveForm::validate($model);
}
$paymentmodel->Status = 0;
if ($paymentmodel->save(false)) {
return $this->redirect(['index']);
}
}
In case of multiple model validation
if ($model->load(Yii::$app->request->post())) {
$detailsmodel->load(Yii::$app->request->post());
$paymentmodel->load(Yii::$app->request->post());
if (Yii::$app->request->isAjax) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
$return = yii\widgets\ActiveForm::validate($model);
$return = \yii\helpers\ArrayHelper::merge(yii\widgets\ActiveForm::validate($detailsmodel), $return);
$return = \yii\helpers\ArrayHelper::merge(yii\widgets\ActiveForm::validate($paymentmodel), $return);
return $return;
}
//here is data saving or logic
}
I want to search field in my application. I have penerimaan_table. There are rm_code, quantity, bulan, price fields.
How to show my result like this:
rm_code bulan
k123 7
k123 4
k123 5
When I filter I want just show bulan 7 & 5
k123 7
k123 5
How can I do this?
This is my view:
<?php
use yii\helpers\Html;
use kartik\grid\GridView;
use kartik\export\ExportMenu;
/* #var $this yii\web\View */
/* #var $searchModel backend\models\PenerimaanSearch */
/* #var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Penerimaan Raw Material';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="penerimaan-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Tambah Penerimaan Raw Material', ['create'], ['class' => 'btn btn-success']) ?>
<?= Html::a('Import Penerimaan', ['import'], ['class' => 'btn btn-success']) ?>
</p>
<p><font color="red">Deskripsi Barang yang kosong merupakan Barang Baru!!</p></font>
<?php
echo ExportMenu::widget([
'dataProvider' => $dataProvider,
'columns' => [
// 'id',
'rm_code',
'rmCode.deskripsi_barang',
'saldo_awal',
'quantity',
'bulan',
//'price',
'total'
],
'showPageSummary' => true,
]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
['class' => 'kartik\grid\SerialColumn'],
// 'id',
'rm_code',
'rmCode.deskripsi_barang',
// 'saldo_awal',
'quantity',
'bulan',
[
'attribute' => 'price',
'label' => 'Price',
'footer' => $myAverage,
],
//'price',
[
'label' => 'Total',
'attribute' => 'total',
'pageSummary' => true,
// 'pageSummaryOptions' => ['id_layanan' => 'deskripsi'],
'value' => function ($model) {
if($model)
return $model->total ;
else
return 0;
}
],
['class' => 'kartik\grid\ActionColumn'],
],
'showPageSummary' => true,
]); ?>
<?php echo"Harga Rata-rata Barang adalah:";
$myAverage = 0;
$myTot =0;
$myCnt = 0;
$data = $dataProvider->getModels();
foreach ($data as $key => $value) {
$myTot += $value['price'];
$myCnt++;
}
if ($myCnt>0){
$myAverage = $myTot/$myCnt;
}
echo $myAverage; // your average displayed herre, you can place it wherever you want.
?>
<?php
$this->registerJs("
// 1. Dapatkan handle dari tabel gridview
table = $('div.grid-view > table');
// 2. Hitung kolom tertentu, pada contoh ini menghitung nilai total pada kolom ke 3
var sum = 0;
table.find('tbody').find('tr').each(function() {
sum += parseInt($(this).find('td:nth-child(4)').text());
});
// 3. Tampilkan hasil perhitungan pada tabel baris terakhir kolom ke 3
table.find('tfoot > tr > td:nth-child(4)').text(sum);
");
?>
</div>
Problem 1: the validators
Within your PenerimaanSearch-model remove the integer-validator for the bulan-field. And add two new ones as follows:
public function rules() {
//...
[['bulan'], 'integer', 'when'=>function($model) {
return strpos($model->bulan, '&') === false;
}],
[['bulan'], 'string', 'when'=>function($model) {
return strpos($model->bulan, '&') !== false;
}],
//...
}
This will only validate your field as an integer when no &is present. Otherwise it will use a string validator. The optimal way would be a regex-v& onle, but I'm sure you'll figure out how to do so.
Problem 2: functionality within the Search model
Again in the BulanSearch you can find the search()-method which is responsible for filtering the result by attributes. Remove all operations concerning the bulan-field and instead use the following:
public function search($params)
{
//...
if (!empty($this->bulan)) {
if (strpos($this->bulan, '&') !== false) {
$bulan = $this->bulan;
} else {
//filter with int
$bulan = explode('&', $this->bulan);
}
$this->andFilterWhere(['bulan'=>$bulan]);
}
//...
}
That should do the trick. The andFilterWhere decides itself whether to use an IN-condition (multiple values) or a regular comparison (single value).
This should do the trick! However, tell me if you have problems. I'll be happy to help!
I've added wbraganca dynamic form in yii2. Within this form I'm trying to populate itemid a textbox when productname and batchno - two dropdowns are selected. I'm getting the value but unable to pass it in the textbox. Please help.
My Form looks like -
<div class="bills-form">
<?php $form = ActiveForm::begin([
'id' => 'dynamic-form',
'type' => ActiveForm::TYPE_HORIZONTAL,
'formConfig' => ['labelSpan' => 3, 'deviceSize' => ActiveForm::SIZE_SMALL]
]); ?>
<?= $form->field($model, 'bills_partyname')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Parties::find()->orderBy(['parties_partyname' => SORT_ASC,])->all(),'parties_partyname','partyDetails'),
'language' => 'en',
'options' => ['placeholder' => 'Select Party Name', 'id' => 'partyid'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?= $form->field($model, 'transport')->textInput(['maxlength' => true, 'readOnly'=>true]) ?>
<?= $form->field($model, 'bills_ebillid')->textInput() ?>
<?= $form->field($model, 'bills_year')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Year::find()->orderBy(['yid' => SORT_DESC,])->all(),'year_year','year_year'),
'language' => 'en',
'options' => ['placeholder' => 'Select Year', 'id' => 'yearid'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?= $form->field($model, 'console')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Console::find()->orderBy(['consoleid' => SORT_ASC,])->all(),'console','console'),
'language' => 'en',
'options' => ['placeholder' => 'Select Console','id' => 'consoleid'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?= $form->field($model, 'num')->textInput() ?>
<?= $form->field($model, 'billno')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'billdate')->widget(
DatePicker::className(), [
// inline too, not bad
'inline' => false,
// modify template for custom rendering
//'template' => '<div class="well well-sm" style="background-color: #fff; width:250px">{input}</div>',
'clientOptions' => [
'autoclose' => true,
'todayHighlight' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
<div class="row">
<div class="panel panel-default">
<div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i> Products</h4></div>
<div class="panel-body">
<?php DynamicFormWidget::begin([
'widgetContainer' => 'dynamicform_wrapper', // required: only alphanumeric characters plus "_" [A-Za-z0-9_]
'widgetBody' => '.container-items', // required: css class selector
'widgetItem' => '.item', // required: css class
'limit' => 20, // the maximum times, an element can be cloned (default 999)
'min' => 1, // 0 or 1 (default 1)
'insertButton' => '.add-item', // css class
'deleteButton' => '.remove-item', // css class
'model' => $modelsProductsales[0],
'formId' => 'dynamic-form',
'formFields' => [
'productname',
//'batchno',
'qty',
'free',
'total',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsProductsales as $i => $modelsProductsales): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Products</h3>
<div class="pull-right">
<button type="button" class="add-item btn btn-success btn-xs"><i class="glyphicon glyphicon-plus"></i></button>
<button type="button" class="remove-item btn btn-danger btn-xs"><i class="glyphicon glyphicon-minus"></i></button>
</div>
<div class="clearfix"></div>
</div>
<div class="panel-body">
<?php
// necessary for update action.
if (! $modelsProductsales->isNewRecord) {
echo Html::activeHiddenInput($modelsProductsales, "[{$i}]id");
}
?>
<div class="row">
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($modelsProductsales, "[{$i}]productname")->widget(Select2::classname(), [
'data' => ArrayHelper::map(Productbatch::find()->orderBy(['productname' => SORT_ASC,])->all(),'productname','productname'),
'language' => 'en',
'options' => ['placeholder' => 'Select Productname', 'id' => 'productid'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($modelsProductsales, "[{$i}]qty")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($modelsProductsales, "[{$i}]free")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($modelsProductsales, "[{$i}]total")->textInput(['maxlength' => true]) ?>
</div>
<?= $form->field($modelsProductsales, "[{$i}]itemid")->textInput(['maxlength' => true]) ?>
<?= $form->field($modelsProductsales, "[{$i}]batchno")->widget(DepDrop::classname(), [
'options'=>['id'=>'batchid'],
'pluginOptions'=>[
'depends'=>['productid'],
'placeholder'=>'BatchNo',
'url'=>Url::to(['/invoice/bills/subcat'])
]
]); ?>
<?= $form->field($modelsProductsales, "[{$i}]expdate")->textInput(['maxlength' => true]) ?>
<?= $form->field($modelsProductsales, "[{$i}]mrp")->textInput(['maxlength' => true]) ?>
<?= $form->field($modelsProductsales, "[{$i}]rate")->textInput(['maxlength' => true]) ?>
<?= $form->field($modelsProductsales, "[{$i}]discount")->textInput(['maxlength' => true]) ?>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
</div>
<?= $form->field($model, 'billamount')->textInput() ?>
<?= $form->field($model, 'transport')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
And my javascript code is -
<?php
/* start getting the itemid and expdate */
$script = <<< JS
$(function(){
$('#productid').change(function(){
getItemid();
});
$('#batchid').change(function(){
getItemid();
});
var productid = $(this).val();
var batchid = $(this).val();
var getItemid = function(){
var productid = String($('#productid').val());
var batchid = String($('#batchid').val());
$.get('index.php?r=invoice/bills/get-for-itemid',{ productid : productid, batchid : batchid }, function(data){
//alert(data);
var data = $.parseJSON(data);
var getItemid = data;
$('#dynamic-[{$i}]itemid').val(getItemid["itemid"]);
});
} ;
});
JS;
$this->registerJs($script);
/* end getting the itemid and expdate */
?>
Please see the below screenshot. What I want -
Update
I've checked Yii2-dynamicforms and javascript and updated the 2 form fields(productname,batchno) on which the other are dependent like below -
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($modelsProductsales, "[{$i}]productname")->label(false)->textInput(['onchange' => 'getItemdetails($(this))', 'onkeyup' => 'getItemdetails($(this))'])->widget(Select2::classname(), [
'data' => ArrayHelper::map(Productbatch::find()->orderBy('productname')->all(),'productname','productname'),
'language' => 'en',
'options' => ['placeholder' => 'Select Product','id' => 'prodname'],
'pluginOptions' => [
'allowClear' => true
],
]);
?>
</div>
<div class="col-xs-2 col-sm-2 col-lg-2 nopadding">
<?= $form->field($modelsProductsales, 'batchno')->label(false)->textInput(['onchange' => 'getItemdetails($(this))', 'onkeyup' => 'getItemdetails($(this))'])->widget(DepDrop::classname(), [
'options'=>['id'=>'batchno'],
'pluginOptions'=>[
'depends'=>['prodname'],
'placeholder'=>'Batch No',
'url'=>Url::to(['/invoice/bills/subcat'])
]
]); ?>
But no idea about the javascript part. At present, the javascript looks like below -
<?
/* start getting the itemid */
$script = <<< JS
$(function(){
$('#productsales-{$i}-prodname').change(function(){
getItemid();
});
$('#productsales-{$i}-batchno').change(function(){
getItemid();
});
var prodname = $('#productsales-{$i}-batchno').val();
var batchno = $('#productsales-{$i}-batchno').val();
var getItemid = function(){
var prodname = String($('#productsales-{$i}-prodname').val());
var batchno = String($('#productsales-{$i}-batchno').val());
$.get('index.php?r=invoice/bills/get-for-itemid',{ prodname : productsales-{$i}-prodname, batchno : productsales-{$i}-batchno }, function(data){
alert(data);
//var data = $.parseJSON(data);
//var getItemid = data;
//$('#productsales-{$i}-itemid').val(getItemid["itemid"]);
});
} ;
});
JS;
$this->registerJs($script);
/* end getting the itemid */
?>
Update:Implementing answer of Insaneskull
Form:Just copied from the answer.
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($modelsProductsales, "[{$i}]productname")->widget(Select2::classname(), [
'data' => ArrayHelper::map(Productbatch::find()->orderBy('productname')->all(),'productname','productname'),
'language' => 'en',
'options' => ['placeholder' => 'Select Product', 'onchange' => 'getItemID($(this))'],
'pluginOptions' => [
'allowClear' => true
],
])->label(false);
?>
</div>
<div class="col-xs-2 col-sm-2 col-lg-2 nopadding">
<?= $form->field($modelsProductsales, 'batchno')->widget(DepDrop::classname(), [
'options' => ['onchange' => 'getItemID($(this))'],
'pluginOptions'=>[
'depends'=> [Html::getInputID($modelsProductsales, "[{$index}]productname")],
'placeholder'=>'Batch No',
'url'=>Url::to(['/invoice/bills/subcat'])
]
])->label(false); ?>
</div>
And the JS function registered at the bottom of the form -
<?php
/* start getting the itemid */
$script = <<< JS
function getItemID(item) {
var index = item.attr("id").replace(/[^0-9.]/g, "");
var batch = product = 0;
var id = item.attr("id");
var myString = id.split("-").pop();
if (myString == "productname") {
fetch = index.concat("-batchno");
product = item.val();
batch = $("#productsales-"+fetch+"").val();
} else {
fetch = index.concat("-productname");
batch = item.val();
product = $("#productsales-"+fetch+"").val();
}
$.get('index.php?r=invoice/bills/get-for-itemid',{ prodname : product, batchno : batch }, function(data){
var data = $.parseJSON(data);
var getItemid = data;
itemID = "productsales-".concat(index).concat("-itemid");
$("#"+itemID+"").val(getItemid["itemid"]);
});
}
JS;
$this->registerJs($script);
/* end getting the itemid */
?>
And the error I'm getting -
Data is not getting selected in Select2 widget
Current Javascript
<?php
/* start getting the itemid */
$script = <<< JS
function getItemID(item) {
var index = item.attr("id").replace(/[^0-9.]/g, "");
var batch = product = 0;
var id = item.attr("id");
var myString = id.split("-").pop();
if (myString == "productname") {
fetch = index.concat("-batchno");
product = item.val();
batch = $("#productsales-"+fetch+"").val();
} else {
fetch = index.concat("-productname");
batch = item.val();
product = $("#productsales-"+fetch+"").val();
}
$.get('index.php?r=invoice/bills/get-for-itemid',{ prodname : product, batchno : batch }, function(data){
var data = $.parseJSON(data);
var getItemid = data;
itemID = "productsales-".concat(index).concat("-itemid");
$("#"+itemID+"").val(getItemid["itemid"]);
});
}
JS;
$this->registerJs($script, View::POS_END);
/* end getting the itemid */
?>
error
_form.php
<div class="col-xs-3 col-sm-3 col-lg-3">
<?= $form->field($modelsProductsales, "[{$i}]productname")->widget(Select2::classname(), [
'data' => ArrayHelper::map(Productbatch::find()->orderBy('productname')->all(),'productname','productname'),
'language' => 'en',
'options' => ['placeholder' => 'Select Product', 'onchange' => 'getItemID($(this))'],
'pluginOptions' => [
'allowClear' => true
],
])->label(false);
?>
</div>
<div class="col-xs-2 col-sm-2 col-lg-2 nopadding">
<?= $form->field($modelsProductsales, '[{$i}]batchno')->widget(DepDrop::classname(), [
'options' => ['onchange' => 'getItemID($(this))'],
'pluginOptions'=>[
'depends'=> [Html::getInputID($modelsProductsales, "[{$i}]productname")],
'placeholder'=>'Batch No',
'url'=>Url::to(['/invoice/bills/subcat'])
]
])->label(false); ?>
</div>
JS
function getItemID(item) {
var index = item.attr("id").replace(/[^0-9.]/g, "");
var batch = product = 0;
var id = item.attr("id");
var myString = id.split("-").pop();
if (myString == "productname") {
fetch = index.concat("-batchno");
product = item.val();
batch = $("#productsales-"+fetch+"").val();
} else {
fetch = index.concat("-productname");
batch = item.val();
product = $("#productsales-"+fetch+"").val();
}
$.get('index.php?r=invoice/bills/get-for-itemid',{ prodname : product, batchno : batch }, function(data){
var data = $.parseJSON(data);
var getItemid = data;
itemID = "productsales-".concat(index).concat("-itemid");
$("#"+itemID+"").val(getItemid["itemid"]);
});
}
I've added a textinput field in my production form. The unitprice fills up when I select productname field drop down. But when I'm saving the data, I'm getting following error -
SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'unitprice' cannot be null
The SQL being executed was: INSERT INTO `bottle` (`usedate`, `useqty`, `productname`, `bottlename`, `unitprice`) VALUES ('2016-04-21', '12', 'CEFO', 'Enter', NULL)
The last "NULL" is the value for unitprice.
actionCreate in productionController-
public function actionCreate()
{
$model = new Production();
$productname = new Productnames();
$bottle = new Bottle();
$bottlename = new Bottlename();
if ($model->load(Yii::$app->request->post()) && $productname->load(Yii::$app->request->post()))
{
$model->save();
//$bottle->attributes = $model->attributes;
$bottle->usedate = $model->productiondate;
$bottle->useqty = $model->prodqty;
$bottle->productname = $model->productname;
$bottle->bottlename = $productname->bottletype;
$bottle->unitprice = $bottlename->unitprice;
// $employee->emp_mobile = $model->emp_mobile;
$bottle->save();
return $this->redirect(['create']);
} else {
return $this->render('create', [
'model' => $model,
'bottle' => $bottle,
'productname' => $productname,
'bottlename' => $bottlename,
]);
}
}
Production _form
<?php
use yii\helpers\Html;
use yii\helpers\Url;
use yii\widgets\ActiveForm;
use yii\web\View;
use frontend\assets\XyzAsset;
use yii\helpers\ArrayHelper;
use dosamigos\datepicker\DatePicker;
use kartik\select2\Select2;
use frontend\modules\production\models\Productbatch;
use frontend\modules\production\models\Productnames;
use kartik\depdrop\DepDrop;
use yii\helpers\Json;
use frontend\modules\production\models\Bottlename;
//XyzAsset::register($this);
/* #var $this yii\web\View */
/* #var $model frontend\modules\production\models\Production */
/* #var $form yii\widgets\ActiveForm */
?>
<div class="production-form">
<?php $form = ActiveForm::begin(); ?>
<!--<?= Html::a('Select Product', ['/production/productbatch/index'], ['class'=>'btn btn-primary']) ?> -->
<?= $form->field($model, 'productiondate')->widget(
DatePicker::className(), [
// inline too, not bad
'inline' => false,
// modify template for custom rendering
//'template' => '<div class="well well-sm" style="background-color: #fff; width:250px">{input}</div>',
'clientOptions' => [
'autoclose' => true,
'format' => 'yyyy-mm-dd'
]
]);?>
<!-- echo CHtml::button("(+)",array('title'=>"Select Product",'onclick'=>'js:selectproductforproduction();')); -->
<?= $form->field($model, 'productname')->widget(Select2::classname(), [
'data' => ArrayHelper::map(Productnames::find()->all(),'productnames_productname','productnames_productname'),
'language' => 'en',
'options' => ['placeholder' => 'Select Product Name', 'id' => 'catid'],
'pluginOptions' => [
'allowClear' => true
],
]); ?>
<?= $form->field($model, 'batchno')->widget(DepDrop::classname(), [
'options'=>['id'=>'subcat-id'],
'pluginOptions'=>[
'depends'=>['catid'],
'placeholder'=>'Select BatchNo',
'url'=>Url::to(['/production/productbatch/subcat'])
]
]); ?>
<?= $form->field($model, 'prodqty')->textInput() ?>
<?= $form->field($productname, 'bottletype')->textInput() ?>
<?= $form->field($bottlename, 'unitprice')->textInput() ?>
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
$script = <<< JS
$('#catid').change(function(){
var catid = $(this).val();
$.get('index.php?r=production/productnames/get-for-production',{ catid : catid }, function(data){
//alert(data);
var data = $.parseJSON(data);
$('#productnames-bottletype').attr('value',data.bottletype);
$('#bottlename-unitprice').attr('value',data.bottletype0.unitprice);
});
});
JS;
$this->registerJs($script);
?>
The action to get the data array
public function actionGetForProduction($catid)
{
$bottle = Productnames::find()->with('bottletype0')->where(['productnames_productname'=>$catid])->asArray()->one();
//$bottle -> select(['productnames.productnames_productname','productnames.bottletype','bottlename.unitprice'])->from('Productnames')->leftJoin('bottlename','productnames.bottletype = bottlename.bottlename')->where(['productnames_productname'=>$catid])->limit(1);
echo Json::encode($bottle);
This code works fine except the last unitprice. Please help.
You fotgot to add $bottlename->load(Yii::$app->request->post()) in if condition. So add like as,
if ($model->load(Yii::$app->request->post()) && $productname->load(Yii::$app->request->post()) && $bottlename->load(Yii::$app->request->post())) {
.......
}