Rendering part of form in main view - ajax

Is there any way to render partial view using AJAX that is a part of form which other part starts ActiveForm->begin() in main view?
Controller:
public function actionCreate()
{
$model = new order();
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if ($model->load(Yii::$app->request->post())) {
try {
if ($model->save()) {
Yii::$app->getSession()->setFlash('success', 'New record has been saved.');
return $this->redirect(['index']);
}
}
catch(yii\db\IntegrityException $e) {
Yii::$app->getSession()->setFlash('error', 'Cannot save new record. Please try again.');
return $this->redirect(['index']);
}
}
else {
return $this->render('create', ['model' => $model, ]);
}
}
public function actionSpecialdetform()
{
$model = new order();
return $this->renderAjax('_specialform');
}
public function actionDetform()
{
$model = new order();
return $this->renderAjax('_form');
}
View (main - create.php):
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
/* #var $this yii\web\View */
/* #var $model app\models\order */
$this->title = 'Create';
$this->params['breadcrumbs'][] = ['label' => 'Orders', 'url' => ['index']];
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="order-create">
<h1><?= Html::encode($this->title) ?></h1>
<?php $form = ActiveForm::begin(['enableAjaxValidation' => true,]); ?>
<div class="panel panel-default wizard" id="order-wizard">
<div class="wizard-steps clearfix" id="form-wizard">
<ul class="steps">
<li data-target="#step1" class="active"><span class="badge badge-info">1</span>Order</li>
<li data-target="#step2"><span class="badge">2</span>Details</li>
</ul>
</div>
<div class="step-content clearfix">
<div class="step-pane active" id="step1">
<?php echo $form->field($model, 'order_date')->input(); ?>
</div>
<div class="step-pane" id="step2">
<div id="order-details">
</div>
</div>
<div class="actions pull-left">
<button type="button" class="btn btn-default btn-sm btn-prev wizard-btn" disabled="disabled"><i class="fa fa-angle-double-left" style="margin-right:5px"></i> Previous step</button>
<button type="button" class="btn btn-default btn-sm btn-next wizard-btn" data-last="Save">Next step <i class="fa fa-angle-double-right" style="margin-left:5px"></i></button>
</div>
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
<?php
$js = '
$(document).ready(function() {
$("#order-wizard").on("change", function(e, data) {
if(data.step===1 && data.direction==="next")
{
var date = $("#order-order_date").val();
if(date==="")
{
e.preventDefault();
}
var form = null;
if(date === "2015-01-01")
{
form = "/order/specialdetform"
}
else
{
form = "order/detform"
}
$.ajax({
url: form,
dataType: "html",
success: function(data) {
$("#order-details").html(data);
}
});
}
});
});
';
$this->registerJs($js, \yii\web\View::POS_END);
?>
Partial View - (_specialform.php):
<?= $form->field($model, 'promo_code')->input(); ?>
<?= $form->field($model, 'Surname')->input(); ?>
Partial View - (_form.php):
<?= $form->field($model, 'Surname')->input(); ?>
I don't want to just create one partial view, because this is only one different field, but it's an example.

Related

I want to show a first category product when i reload my page using laravel?

currently when i click to any category related to product is showing perfectly but i need to show first category product when i reload my page first time Does anyone have an idea please help me thanks.
Controller
public function getproduct(Request $request)
{
$category_id = $request->data;
if ($category_id) {
$product = Product::with('productColorGallary')->whereHas('productCategory', function (Builder $query) use ($category_id) {
$query->where('mf_product_category_id', $category_id);
})->get();
} else {
$product = Product::with('productColorGallary')->get();
}
$data = [
'products' => $product
];
return response()->json($data, 200);
}
jquery script
<script>
$(document).ready(function(){
$('.productcategory').click(function () {
let url = "{{route('products.getproduct')}}";
let path = '{{config('wall_master_furishing.file_url')}}';
axios.get(url, {
params:{
data: $(this).data('id'),
}
}).then((res)=>{
let product =res.data.products;
$('#product').html("");
product.forEach(element => {
console.log(element);
$('#product').append(
`<div class="col-md-4 col-sm-6 col-6">
<div class="wallprodCard">
<div class="prodcardImage">
<img src="${path}${element.product_color_gallary.featured_image}" alt="">
<a class="prodcardFancy" href="${path}${element.product_color_gallary.featured_image}" data-fancybox="images" data-caption="Flooring">
<i class="fa fa-search-plus">
</i>
</a>
</div>
<div class="prodcardDescp">
<a href="{{url('')}}/wallpaper-details">
<h4 class="prodcardtitle">${element.name}
</h4>
</a>
<p class="text">${element.description}
</p>
</div>
</div>
</div>
`);
});
});
});
</script>

ajax form request from a while - confuse variable

I want to send a form with a button from a while, but I have a problem. If post the button, the form confuse the variable. E.g: i post the button with id 1, and the script get the variable from the last input.
Code:
index:
<?php
$res = getProdus();
foreach($res as $row) { ?>
<form action="addtocart.php" method="POST">
<div class="col-12 col-sm-6 col-md-4 single_gallery_item women wow fadeInUpBig" data-wow-delay="0.2s">
<div class="product-img">
<img src="img/product-img/product-1.jpg" alt="">
<div class="product-quicview">
<i class="ti-plus"></i>
</div>
</div>
<div class="product-description">
<h4 class="product-price">$39.90</h4>
<p>Jeans midi cocktail dress</p>
<input type="hidden" name="addtcart" value="<?=$row['ID'];?>">
<button type="submit" class="add-to-cart-btn">ADD TO CART</button>
</div>
</div>
</form>
<?php } ?>
the ajax request:
$(document).ready(function() {
$('form').submit(function(event) {
var formData = {
'addtcart' : $('input[name=addtcart]').val()
};
$.ajax({
type : 'POST',
url : 'addtocart.php',
data : formData,
dataType : 'json',
encode : true
})
.done(function(data) {
console.log(data);
});
event.preventDefault();
});
});
and the addtocart.php
<?php
include("includes/functions.php");
session_start();
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
if (empty($_POST['addtcart']))
$errors['addtcart'] = 'Este necesar produsul id-ului.';
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$ok = AddToCart(filtrare($_POST['addtcart']), getSpec("username", "users", "email", $_SESSION['magazin-user']));
if($ok == 1) {
$data['success'] = true;
$data['message'] = 'Success!';
} else {
$data['success'] = false;
$errors['mysqli'] = "Nu s-a realizat bine query-ul.";
$data['errors'] = $errors;
}
}
echo json_encode($data);
?>
Replace your button code with this
<button type="submit" value="<?=$row['ID'];?>" class="add-to-cart-btn">ADD TO CART</button>
and after that replace you
make changes to your script code
$(".add-to-cart-btn").click(function() {
var formData = {
'addtcart' : $(this).val()
};
.
.
.
and your rest of the code.

Yii2 conditional validation on radio box

I'm trying to use conditional validation on a attribute account_no. It should be validate only when I select the value 'old' in the attribute account_version. But it is not working. The error I'm getting is validation is required for newalso. Should I use javascript instead to validate
My code in model
return [
['account_no', 'required', 'when' => function($model) {
return $model->account_version == 'Old';
}],
]
My code in form
<?php if ($model->isNewRecord) {?>
<div class="row">
<div class="col-md-2">
<label for="">Account Version</label>
</div>
<div class="col-md-2">
<?php echo $form->field($model, 'account_version')->radioList(['New'=>'New','Old'=>'Old'])->label(false); ?>
</div>
<div id="action_block" class="col-md-6">
<div class="col-md-3">
<label for="">Account No:</label>
</div>
<div class="col-md-3">
<?= $form->field($model, 'account_no')->textInput(['maxlength' => true])->label(false) ?>
</div>
</div>
</div>
<?php } ?>
Model
[['account_no'], 'required', 'when' => function ($model) { return $model->account_version == 'Old'; }, 'whenClient' => "function (attribute, value) { return $('#modelName[account_version]').val() == 'Old'; }"],
Form
<?php $form = ActiveForm::begin(['id' => 'account-form', 'enableAjaxValidation' => true]); ?>
Controller
if($model->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);
}
}
<?php
return [
['account_no', 'required', 'when' => function ($model) {
return $model->account_no == 'Old';
}, 'whenClient' => "function (attribute, value) {
return $('#account_no').val() == 'Old';
}"]
]
?>
http://www.yiiframework.com/doc-2.0/guide-input-validation.html [reference links]

Input image in Yii2 Dynamic Form always null

I want to make dynamic input that save an image to my website.
I use yii2-dynamicform and Kartik input file extension. But, it always save it as null.
Thank you for your help
Ps : ... is other part of my code that not relevant with this question. :)
In controller :
<?php
namespace frontend\controllers;
use Yii;
use common\models\Election;
use common\models\ElectionSearch;
use common\models\Model;
use common\models\Kandidat;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\data\ActiveDataProvider;
use yii\web\Session;
use yii\web\UploadedFile;
use yii\helpers\ArrayHelper;
class ElectionController extends Controller
{
...
public function actionCreate()
{
$model = new Election();
$modelsKandidat = [new Kandidat];
if ($model->load(Yii::$app->request->post())){
$model->save();
$modelsKandidat = Model::createMultiple(Kandidat::classname());
Model::loadMultiple($modelsKandidat, Yii::$app->request->post());
// validate all models
$valid = $model->validate();
$valid = Model::validateMultiple($modelsKandidat) && $valid;
if ($valid) {
$transaction = \Yii::$app->db->beginTransaction();
try {
if ($flag = $model->save(false)) {
foreach ($modelsKandidat as $modelKandidat) {
$modelKandidat->id_election = $model->id_election;
if($modelKandidat->file = UploadedFile::getInstance($modelKandidat,'file'))
{
$imageName = date('dmyhis_').$modelKandidat->id_election;
$modelKandidat->file->saveAs('../../common/file/fotokandidat/'.$imageName.'.'.$modelKandidat->file->extension);
$modelKandidat->foto = $imageName.'.'.$modelKandidat->file->extension;
}
if (! ($flag = $modelKandidat->save(false))) {
$transaction->rollBack();
break;
}
}
}
if ($flag) {
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id_election]);
}
} catch (Exception $e) {
$transaction->rollBack();
}
}
} else {
return $this->render('create', [
'model' => $model,
'modelsKandidat' => $modelsKandidat,
]);
}
}
...
}
In _form :
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use kartik\file\FileInput;
use yii\helpers\ArrayHelper;
use dosamigos\datepicker\DatePicker;
use wbraganca\dynamicform\DynamicFormWidget;
?>
<div class="election-form">
<?php $form = ActiveForm::begin(['options'=>['enctype'=>'multipart/form-data', 'id' => 'dynamic-form']]); ?>
...
<!-- mulai input kandidat !-->
<div class="row">
<div class="panel panel-default">
<div class="panel-heading"><h4><i class="glyphicon glyphicon-envelope"></i>Vote</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' => 4, // 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' => $modelsKandidat[0],
'formId' => 'dynamic-form',
'formFields' => [
'nama',
'deskripsi',
'riwayat',
'file',
],
]); ?>
<div class="container-items"><!-- widgetContainer -->
<?php foreach ($modelsKandidat as $i => $modelsKandidat): ?>
<div class="item panel panel-default"><!-- widgetBody -->
<div class="panel-heading">
<h3 class="panel-title pull-left">Kandidat</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 (! $modelsKandidat->isNewRecord) {
echo Html::activeHiddenInput($modelsKandidat, "[{$i}]id_kandidat");
}
?>
<div class="row">
<div class="col-sm-4">
<?= $form->field($modelsKandidat, "[{$i}]nama")->textInput(['maxlength' => true]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelsKandidat, "[{$i}]deskripsi")->textarea(['rows' => 6]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelsKandidat, "[{$i}]riwayat")->textarea(['rows' => 6]) ?>
</div>
<div class="col-sm-4">
<?= $form->field($modelsKandidat, "[{$i}]file")->fileInput() ?>
</div>
</div><!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
</div>
</div>
<!-- selesai input kandidat !-->
...
<div class="form-group">
<?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>
</div>
<?php ActiveForm::end(); ?>
</div>
It's from #shoara/#zahraj answer :
I think you forgot to specify index for your file `
foreach ($modelsKandidat as $keyindex=>$modelKandidat)
{
$modelKandidat->id_election = $model->id_election;
if ($modelKandidat->file = UploadedFile::getInstance($modelKandidat, "[{$keyindex}]file")) {
.......
}
}
see demo controller and form part,imagine $modelCatalogOption in demo is your $model = new Election(); and $modelsOptionValue is your $modelsKandidat = [new Kandidat]; if you try and check your values in your controller I'm sure you can solve this problem easily. Pay attention to actionCreate

Load table from database to dropdown CodeIgniter

I have trouble with loading the table to the form_dropdown. I have tried any solution from the same trouble with me but its not working.
Here's the controller code:
<?php
class Registrasi extends Superuser_Controller
{
public $data = array(
'halaman' => 'registrasi',
'main_view' => 'program/administrasi/registrasi_list',
'title' => 'Data Registrasi',
);
public function __construct()
{
parent::__construct();
$this->load->model('program/administrasi/Registrasi_model', 'registrasi_model');
}
public function index()
{
$registrasi = $this->registrasi_model->get_all_registrasi_data();
$this->data['registrasiData'] = $registrasi;
$this->load->view($this->layout, $this->data);
}
public function tambah()
{
$this->data['namaNegara'] = $this->registrasi_model->get_nama_negara();
$this->data['main_view'] = 'program/administrasi/registrasi_form';
$this->data['form_action'] = site_url('program/administrasi/registrasi/tambah');
// Data untuk form.
if (! $_POST) {
$registrasi = (object) $this->registrasi_model->default_value;
} else {
$registrasi = $this->input->post(null, true);
}
// Validasi.
if (! $this->registrasi_model->validate('form_rules')) {
$this->data['values'] = (object) $registrasi;
$this->load->view($this->layout, $this->data);
return;
}
}
}
Here's the model code:
<?php
class Registrasi_model extends MY_Model
{
protected $_tabel = 'tb_registrasi';
protected $form_rules = array(
array(
'field' => 'Negara_Tujuan',
'label' => 'Negara Tujuan',
'rules' => 'trim|xss_clean|required|max_length[50]'
)
);
public $default_value = array(
'Negara_Tujuan' => ''
);
public function get_nama_negara()
{
$query = $this->db->query('SELECT Nama_Negara FROM tb_negara_tujuan');
return $query->result();
}
}
Here's the view code:
<div class="container">
<h2>Form Registrasi</h2>
<hr>
<?php echo form_open($form_action, array('id'=>'myform', 'class'=>'myform', 'role'=>'form')) ?>
<div class="container">
<div class="row">
<div class="form-group has-feedback <?php set_validation_style('Negara_Tujuan')?>">
<?php echo form_label('Negara Tujuan', 'negara_tujuan', array('class' => 'control-label')) ?>
<?php
foreach($namaNegara as $row)
{
echo form_dropdown('NegaraTujuan', $row->Nama_Negara);
}
?>
<?php set_validation_icon('Negara_Tujuan') ?>
<?php echo form_error('Negara_Tujuan', '<span class="help-block">', '</span>');?>
</div>
<?php echo form_button(array('content'=>'Simpan', 'type'=>'submit', 'class'=>'btn btn-primary', 'data-confirm'=>'Anda yakin akan menyimpan data ini?')) ?>
</div>
</div>
<?php echo form_close() ?>
</div>
The trouble I'm having is: Invalid argument supplied for foreach()
Your controller code must be :-
public function tambah()
{
$namaNegara[''] = 'select a option';
$namaNegaras = $this->registrasi_model->get_nama_negara();
foreach($namaNegaras as $namaNegaranew)
{
$namaNegara[$namaNegaranew->id] = $namaNegaranew->Nama_Negara ;
}
$this->data['namaNegara'] = $namaNegara;
$this->data['main_view'] = 'program/administrasi/registrasi_form';
$this->data['form_action'] = site_url('program/administrasi/registrasi/tambah');
// Data untuk form.
if (! $_POST) {
$registrasi = (object) $this->registrasi_model->default_value;
} else {
$registrasi = $this->input->post(null, true);
}
// Validasi.
if (! $this->registrasi_model->validate('form_rules')) {
$this->data['values'] = (object) $registrasi;
$this->load->view($this->layout, $this->data);
return;
}
}
And in view in place of
<?php
foreach($namaNegara as $row)
{
echo form_dropdown('NegaraTujuan', $row->Nama_Negara);
}
?>
Simply use
<?php echo form_dropdown('NegaraTujuan', $namaNegara , set_value('NegaraTujuan')); ?>
I think i have the answer for my problem:
Controller code (still same, no change whatsoever)
Model code: change the function into
public function get_nama_negara()
{
$query = $this->db->query('SELECT Nama_Negara FROM tb_negara_tujuan');
$dropdowns = $query->result();
foreach ($dropdowns as $dropdown)
{
$dropdownlist[$dropdown->Nama_Negara] = $dropdown->Nama_Negara;
}
$finaldropdown = $dropdownlist;
return $finaldropdown;
}
View code:
<div class="container">
<h2>Form Registrasi</h2>
<hr>
<?php echo form_open($form_action, array('id'=>'myform', 'class'=>'myform', 'role'=>'form')) ?>
<div class="container">
<div class="row">
<div class="form-group has-feedback <?php set_validation_style('Negara_Tujuan')?>">
<?php echo form_label('Negara Tujuan', 'negara_tujuan', array('class' => 'control-label')) ?>
<?php echo form_dropdown('NegaraTujuan', $namaNegara, set_value('NegaraTujuan'), 'class="dropdown"'); ?>
<?php set_validation_icon('Negara_Tujuan') ?>
<?php echo form_error('Negara_Tujuan', '<span class="help-block">', '</span>');?>
</div>
<?php echo form_button(array('content'=>'Simpan', 'type'=>'submit', 'class'=>'btn btn-primary', 'data-confirm'=>'Anda yakin akan menyimpan data ini?')) ?>
</div>
</div>
<?php echo form_close() ?>
</div>

Resources