Why is the input not sent to the request? - mysql

I add tag input into my form with name=fullname, but I got an error; it says that "Field 'fullname' doesn't have a default value." Is there something wrong with my code?
I have adding attribute name in my tag input, but it still doesn't work
{!! Form::open(['route' => 'users.store']) !!}
<div class="row">
<div class="col-25">
<label>Unit Name</label>
</div>
<div class="col-75">
{!! Form::select('division', $divisions, null, ['class' => 'form-control']) !!}
</div>
</div>
<div class="row">
<div class="col-25">
<label>Full Name</label>
</div>
<div class="col-75">
<input type="text" name="fullname" aria-label="fullname" autocomplete="off">
</div>
</div>
<div class="row">
<div class="col-25">
<label>Username</label>
</div>
<div class="col-75">
<input type="text" name="username" aria-label="username"" autocomplete="off">
</div>
</div>
<div class="row">
<div class="col-25">
<label>Password</label>
</div>
<div class="col-75">
<input type="password" name="password" aria-label="password" autocomplete="off">
</div>
</div>
<div class="row">
<input type="submit" value="Submit">
</div>
{!! Form::close() !!}
This is the error
This is create and store controller
public function create()
{
return view('user_super_admin.create')
->with('divisions', $this->divisions);
}
/**
* Store a newly created User in storage.
*
* #param CreateUserRequest $request
*
* #return Response
*/
public function store(CreateUserRequest $request)
{
$input = $request->all();
$user = $this->userRepository->create($input);
Flash::success('User saved successfully.');
return redirect(route('users.index'));
}
CreateUserRequest
public function rules()
{
return User::$rules;
}
User Model
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username',
'password',
'group_id',
'division_id',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* #var array
*/
protected $casts = [
'username' => 'string',
'password' => 'string',
'group_id' => 'integer',
'division_id' => 'integer',
'email_verified_at' => 'datetime',
];
public function group()
{
return $this->belongsTo("App\Models\Group");
}
public function division()
{
return $this->belongsTo("App\Models\Division");
}
}
User Repository
/**
* #var array
*/
protected $fieldSearchable = [
'fullname',
'username',
'password',
'role_id',
'division_id',
'remember_token'
];
/**
* Configure the Model
**/
public function model()
{
return User::class;
}

Related

I can't save input to database Vuejs and Laravel

I added two new input (ass1 and ass2) to a form, created the columns in the database, added it to $fillable in the model, and method in Vue file.
The challenge is that every other input saves to the database but my new inputs are not stored to the database.
If I input directly to the database, the data will show up for edit/update but will not store.
I have checked and checked through the code and can't find any issue, no error message so far.
If you need any other details I will be happy to provide them.
Please help! I'm on a deadline.
P.S. I have very little knowledge of Vuejs, it's a bit confusing.
This is my form.vue content:
<template>
<div>
<form #submit.prevent="proceed" #keydown="assessmentForm.errors.clear($event.target.name)">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label for="">{{trans('exam.assessment_name')}}</label>
<input class="form-control" type="text" v-model="assessmentForm.name" name="name" :placeholder="trans('exam.assessment_name')">
<show-error :form-name="assessmentForm" prop-name="name"></show-error>
</div>
</div>
<div class="col-12 col-sm-6">
<div class="form-group">
<label for="">{{trans('exam.assessment_description')}}</label>
<input class="form-control" type="text" v-model="assessmentForm.description" name="description" :placeholder="trans('exam.assessment_description')">
<show-error :form-name="assessmentForm" prop-name="description"></show-error>
</div>
</div>
</div>
<div class="row">
<div class="col-12">
<h6 class="card-title">{{trans('exam.assessment_type')}}</h6>
<template v-for="(detail,index) in assessmentForm.details">
<div class="row">
<div class="col-12 col-sm-3">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_name')}}
<button type="button" class="btn btn-xs btn-danger m-l-20" :key="`${index}_delete_detail`" v-confirm="{ok: confirmDeleteDetail(index)}" v-tooltip="trans('general.delete')"><i class="fas fa-times"></i></button></label>
<input class="form-control" type="text" v-model="detail.name" :name="getDetailName(index)" :placeholder="trans('exam.assessment_detail_name')">
<show-error :form-name="assessmentForm" :prop-name="getDetailName(index)"></show-error>
</div>
</div>
<div class="col-12 col-sm-1">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_code')}}</label>
<input class="form-control" type="text" v-model="detail.code" :name="getDetailCode(index)" :placeholder="trans('exam.assessment_detail_code')">
<show-error :form-name="assessmentForm" :prop-name="getDetailCode(index)"></show-error>
</div>
</div>
<div class="col-12 col-sm-2">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_max_mark')}}</label>
<input class="form-control" type="number" v-model="detail.max_mark" :name="getDetailMaxMarkName(index)" :placeholder="trans('exam.assessment_detail_max_mark')">
<show-error :form-name="assessmentForm" :prop-name="getDetailMaxMarkName(index)"></show-error>
</div>
</div>
<!-- <div class="col-12 col-sm-2">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_pass_percentage')}}</label>
<div class="input-group mb-3">
<input class="form-control" type="number" v-model="detail.pass_percentage" :name="getDetailPassPercentageName(index)" :placeholder="trans('exam.assessment_detail_pass_percentage')">
<div class="input-group-append">
<span class="input-group-text" id="basic-addon1">%</span>
</div>
</div>
<show-error :form-name="assessmentForm" :prop-name="getDetailPassPercentageName(index)"></show-error>
</div>
</div> -->
<div class="col-12 col-sm-2">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_ass1')}}</label>
<input class="form-control" type="number" v-model="detail.ass1" :name="getDetailAssessment1(index)" :placeholder="trans('exam.assessment_detail_ass1')">
<show-error :form-name="assessmentForm" :prop-name="getDetailAssessment1(index)"></show-error>
</div>
</div>
<div class="col-12 col-sm-2">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_ass2')}}</label>
<input class="form-control" type="number" v-model="detail.ass2" :name="getDetailAssessment2(index)" :placeholder="trans('exam.assessment_detail_ass2')">
<show-error :form-name="assessmentForm" :prop-name="getDetailAssessment2(index)"></show-error>
</div>
</div>
<div class="col-12 col-sm-4">
<div class="form-group">
<label for="">{{trans('exam.assessment_detail_description')}}</label>
<autosize-textarea v-model="detail.description" rows="2" :name="getDetailDescriptionName(index)" :placeholder="trans('resource.assessment_detail_description')"></autosize-textarea>
<show-error :form-name="assessmentForm" :prop-name="getDetailDescriptionName(index)"></show-error>
</div>
</div>
</div>
</template>
<div class="form-group">
<button type="button" #click="addRow" class="btn btn-info btn-sm waves-effect waves-light">{{trans('exam.add_new_assessment_detail')}}</button>
</div>
</div>
</div>
<div class="card-footer text-right">
<router-link to="/configuration/exam/assessment" class="btn btn-danger waves-effect waves-light ">{{trans('general.cancel')}}</router-link>
<button type="submit" class="btn btn-info waves-effect waves-light">
<span v-if="id">{{trans('general.update')}}</span>
<span v-else>{{trans('general.save')}}</span>
</button>
</div>
</form>
</div>
</template>
<script>
export default {
components: {},
data() {
return {
assessmentForm: new Form({
name: '',
description: '',
// details: ['name', 'code', 'max_mark', 'ass1', 'ass2', 'description']
details: []
})
};
},
props: ['id'],
mounted() {
if(!helper.hasPermission('access-configuration')){
helper.notAccessibleMsg();
this.$router.push('/dashboard');
}
if(this.id)
this.get();
else {
this.addRow();
}
},
methods: {
hasPermission(permission){
return helper.hasPermission(permission);
},
addRow(){
let new_index = this.assessmentForm.details.push({
name: '',
code: '',
max_mark: '',
ass1: '',
ass2: '',
// pass_percentage: '',
description: ''
})
},
confirmDeleteDetail(index){
return dialog => this.deleteDetail(index);
},
deleteDetail(index){
this.assessmentForm.details.splice(index, 1);
},
getDetailName(index){
return index+'_detail_name';
},
getDetailCode(index){
return index+'_detail_code';
},
getDetailMaxMarkName(index){
return index+'_detail_max_mark';
},
// getDetailPassPercentageName(index){
// return index+'_detail_pass_percentage';
// },
getDetailAssessment1(index){
return index+'_detail_ass1';
},
getDetailAssessment2(index){
return index+'_detail_ass2';
},
getDetailDescriptionName(index){
return index+'_detail_description';
},
proceed(){
if(this.id)
this.update();
else
this.store();
},
store(){
let loader = this.$loading.show();
this.assessmentForm.post('/api/exam/assessment')
.then(response => {
toastr.success(response.message);
this.assessmentForm.details = [];
this.addRow();
this.$emit('completed');
loader.hide();
})
.catch(error => {
loader.hide();
helper.showErrorMsg(error);
});
},
get(){
let loader = this.$loading.show();
axios.get('/api/exam/assessment/'+this.id)
.then(response => {
this.assessmentForm.name = response.name;
this.assessmentForm.description = response.description;
response.details.forEach(detail => {
this.assessmentForm.details.push({
name: detail.name,
code: detail.code,
max_mark: detail.max_mark,
ass1: detail.ass1,
ass2: detail.ass2,
description: detail.description
// pass_percentage: detail.pass_percentage,
});
});
loader.hide();
})
.catch(error => {
loader.hide();
helper.showErrorMsg(error);
this.$router.push('/configuration/exam/assessment');
});
},
update(){
let loader = this.$loading.show();
this.assessmentForm.patch('/api/exam/assessment/'+this.id)
.then(response => {
toastr.success(response.message);
loader.hide();
this.$router.push('/configuration/exam/assessment');
})
.catch(error => {
loader.hide();
helper.showErrorMsg(error);
});
}
}
}
</script>
This is the model (AssessmentDetail.php):
<?php
namespace App\Models\Configuration\Exam;
use Illuminate\Database\Eloquent\Model;
use Spatie\Activitylog\Traits\LogsActivity;
class AssessmentDetail extends Model
{
use LogsActivity;
protected $fillable = [
'exam_assessment_id',
'name',
'max_mark',
'ass1',
'ass2',
// 'pass_percentage',
'description',
'options'
];
protected $casts = ['options' => 'array'];
protected $primaryKey = 'id';
protected $table = 'exam_assessment_details';
protected static $logName = 'exam_assessment_detail';
protected static $logFillable = true;
protected static $logOnlyDirty = true;
protected static $ignoreChangedAttributes = ['updated_at'];
public function assessment()
{
return $this->belongsTo('App\Models\Configuration\Exam\Assessment', 'exam_assessment_id');
}
public function getOption(string $option)
{
return array_get($this->options, $option);
}
public function scopeFilterById($q, $id)
{
if (! $id) {
return $q;
}
return $q->where('id', '=', $id);
}
public function scopeFilterByExamAssessmentId($q, $exam_assessment_id)
{
if (! $exam_assessment_id) {
return $q;
}
return $q->where('exam_assessment_id', '=', $exam_assessment_id);
}
public function scopeFilterByName($q, $name, $s = 0)
{
if (! $name) {
return $q;
}
return $s ? $q->where('name', '=', $name) : $q->where('name', 'like', '%'.$name.'%');
}
}
This is my Controller (AssessmentController)
<?php
namespace App\Http\Controllers\Configuration\Exam;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\Configuration\Exam\AssessmentRequest;
use App\Repositories\Configuration\Exam\AssessmentRepository;
class AssessmentController extends Controller
{
protected $request;
protected $repo;
/**
* Instantiate a new controller instance.
*
* #return void
*/
public function __construct(
Request $request,
AssessmentRepository $repo
) {
$this->request = $request;
$this->repo = $repo;
$this->middleware('permission:access-configuration');
$this->middleware('academic.session.set');
}
/**
* Used to get all Exam Assessments
* #get ("/api/exam/assessment")
* #return Response
*/
public function index()
{
return $this->ok($this->repo->paginate($this->request->all()));
}
/**
* Used to print all Exam Assessments
* #post ("/api/exam/assessment/print")
* #return Response
*/
public function print()
{
$exam_assessments = $this->repo->print(request('filter'));
return view('print.configuration.exam.assessment', compact('exam_assessments'))->render();
}
/**
* Used to generate pdf all Exam Assessments
* #post ("/api/exam/assessment/pdf")
* #return Response
*/
public function pdf()
{
$exam_assessments = $this->repo->print(request('filter'));
$uuid = Str::uuid();
$pdf = \PDF::loadView('print.configuration.exam.assessment', compact('exam_assessments'))->save('../storage/app/downloads/'.$uuid.'.pdf');
return $uuid;
}
/**
* Used to store Exam Assessment
* #post ("/api/exam/assessment")
* #param ({
* #Parameter("name", type="string", required="true", description="Name of Exam Assessment"),
* #Parameter("description", type="text", required="optional", description="Description of Exam Assessment")
* })
* #return Response
*/
public function store(AssessmentRequest $request)
{
$exam_assessment = $this->repo->create($this->request->all());
// dd('$exam_assessment');
return $this->success(['message' => trans('exam.assessment_added')]);
}
/**
* Used to get Exam Assessment detail
* #get ("/api/exam/assessment/{id}")
* #param ({
* #Parameter("id", type="integer", required="true", description="Id of Exam Assessment"),
* })
* #return Response
*/
public function show($id)
{
return $this->ok($this->repo->findOrFail($id));
}
/**
* Used to update Exam Assessment
* #patch ("/api/exam/assessment/{id}")
* #param ({
* #Parameter("id", type="integer", required="true", description="Id of Exam Assessment"),
* #Parameter("name", type="string", required="true", description="Name of Exam Assessment"),
* #Parameter("description", type="text", required="optional", description="Description of Exam Assessment")
* })
* #return Response
*/
public function update($id, AssessmentRequest $request)
{
$exam_assessment = $this->repo->findOrFail($id);
$exam_assessment = $this->repo->update($exam_assessment, $this->request->all());
return $this->success(['message' => trans('exam.assessment_updated')]);
}
/**
* Used to reorder all Details of assessment
* #frontend ("/api/exam/assessment/{id}/reorder")
* #return Response
*/
public function reorder($id)
{
$exam_assessment = $this->repo->findOrFail($id);
$this->repo->reorder($exam_assessment, $this->request->all());
return $this->success(['message' => trans('exam.assessment_updated')]);
}
/**
* Used to delete Exam Assessment
* #delete ("/api/exam/assessment/{id}")
* #param ({
* #Parameter("id", type="integer", required="true", description="Id of Exam Assessment"),
* })
* #return Response
*/
public function destroy($id)
{
$exam_assessment = $this->repo->deletable($id);
$this->repo->delete($exam_assessment);
return $this->success(['message' => trans('exam.assessment_deleted')]);
}
}
These are the routes for the Assessment from Api.php
Route::get('/exam/assessment/{id}', 'Configuration\Exam\AssessmentController#show');
Route::post('/exam/assessment', 'Configuration\Exam\AssessmentController#store');
Route::patch('/exam/assessment/{id}', 'Configuration\Exam\AssessmentController#update');
Route::delete('/exam/assessment/{id}', 'Configuration\Exam\AssessmentController#destroy');
Thank you all for your comments.
I finally found the solution.
Apparently, in my controller(AssessmentController) my construct method is getting the input from AssessmentRepository (App\Repository).
public function __construct(
Request $request,
AssessmentRepository $repo
) {
$this->request = $request;
$this->repo = $repo;
$this->middleware('permission:access-configuration');
$this->middleware('academic.session.set');
}
Then $repo is called in my store, update, show, reorder and other methods.
I've never seen or used App\Repositories before.
You learn every day!

Can't Store More Than One FormItems Data To DB

I'm using Laravel 5.7.*.
I have a form and it's formItems, Like form HasMany formItems and formItems belongsTo form, when i hit submit, i see in DB only one formItems is stored, although i try to store more than one formitem.
Here is my store method:
public function store(Request $request) {
$formItems = collect();
// dd($request);
// dd($request->formItems);
// // dd($familymember);
foreach($request['formItems'] as $formItem) {
$formItems->push(new FormItem([
'family_name' => $formItem['family_name'],
'family_phone' => $formItem['family_phone'],
]));
}
$form = Form::create([
'user_phone' => $request['user_phone'],
'user_cnic' => $request['user_cnic'],
]);
$form->formItems()->saveMany($formItems);
}
Here is my HTML for formItems:
<form>
<fieldset>
<table class="table table-bordered fieldGroup">
<tbody>
<tr>
<td><input type="text" name="formItems[0][family_name]" class="form-control form-control-sm" placeholder="Full Name"></td>
<td><input type="text" name="formItems[0][family_phone]" class="form-control form-control-sm" placeholder="Phone"></td>
<td colspan="3">
<span class="glyphicon glyphicon glyphicon-plus" aria-hidden="true"></span>+
</td>
</tr>
</tbody>
</table>
<div class="form-group">
<div class="text-center">
<button class="btn btn-success" type="submit">Submit</button>
</div>
</div>
</fieldset>
</form>
<fieldset form="formId">
<table class="table table-bordered fieldGroupCopy" style="display: none;">
<tbody>
<tr>
<td><input type="text" name="formItems[0][family_name]" class="form-control form-control-sm" placeholder="Full Name"></td>
<td><input type="text" name="formItems[0][family_phone]" class="form-control form-control-sm" placeholder="Phone"></td>
<td><a style="align-items: center; justify-content: center; display: flex;" href="javascript:void(0)" class="btn btn-danger remove"><span class="glyphicon glyphicon glyphicon-remove" aria-hidden="true"></span>x</a></td>
</tr>
</tbody>
</table>
</fieldset>
From Model:
class Form extends Model
{
protected $fillable = [
'user_phone',
'user_cnic',
];
protected $with = [
'formItems',
];
public function formItems()
{
return $this->hasMany(FormItem::class);
}
}
FromItem Model:
class FormItem extends Model
{
protected $fillable = [
'form_id',
'family_name',
'family_phone',
];
public function form()
{
return $this->belongsTo(Form::class);
}
}
Updated Image:
dd($request->all()) result:
array:12 [▼
"_token" => "tEDC2rrDXInWeKQzFFSyk0gRoiC19Dr4HIqpf5P1"
"user_phone" => null
"user_cnic" => null
"user_dob" => null
"user_gender" => "male"
"user_landmark" => null
"user_hfname" => null
"user_address" => null
"user_name" => null
"user_family_no" => "1"
"user_email" => null
"formItems" => array:1 [▼
0 => array:6 [▼
"family_relation" => "father"
"family_name" => null
"family_dob" => null
"family_hfname" => null
"family_phone" => null
"family_email" => null
]
]
]
Please Try below code
public function store(Request $request) {
$form = Form::create([
'user_phone' => $request['user_phone'],
'user_cnic' => $request['user_cnic'],
]);
$form_items = [];
foreach($request['formItems'] as $form_item) {
$form_items[] = new FormItem([
'form_id' => $form->id,
'family_name' => $form_item['family_name'],
'family_phone' => $form_item['family_phone']
]);
}
$form->formItems()->saveMany($form_items);
}
I think you have duplicated the inputs names:
name="formItems[0][family_name]"
name="formItems[0][family_phone]"
You always have this name, and I guess it should be one number up each new item. example:
name="formItems[0][family_name]"
name="formItems[0][family_phone]"
name="formItems[1][family_name]"
name="formItems[1][family_phone]"

how to insert data in database using cakephp

i have a table name stores and i have controller name is StoresController.php and model name is Stores.php and have a add.ctp file inside Stores folder but i an unable to insert data from form.here is my add.ctp file
<div class="row form-main">
<div class="panel panel-default">
<div class="panel-body">
<?php echo $this->Form->create('Store', array('class'=>"contact-
form"));
?>
<div class="form-group">
<div class="col-sm-6">
<?php
echo $this->Form->input('name',array('required'=>false,'class'=>"form-
control", 'placeholder'=>"Enter Name","label"=>false));
?>
</div>
<div class="col-sm-6">
<?php
echo $this->Form-
>input('address1',array('required'=>false,'class'=>"form-control",
'placeholder'=>"Enter Address1","label"=>false));
?>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<input type="submit" name="submit" value="Submit" class="btn
btn-success">
<button type="submit" class="btn btn-info">Cancel</button>
</div>
</div>
<?php echo $this->Form->end(); ?>
here is my StoresController.php
<?php
App::uses('AppController', 'Controller');
class StoresController extends AppController {
var $uses = array();
var $component = array("Common");
public $paginate = array();
public function add(){
$this->layout = 'user_layout';
$user_id = $this->UserAuth->getUserId();
$owner_id = $this->Common->getOwnerId($user_id);
if ($this->request->is('post')) {
$this->Store->create();
if ($this->Store->save($this->request->data)) {
$this->Flash->success(__('User has been Added'));
return $this->redirect(array('action' => 'add'));
} $this->Flash->error(__('Unable to add your post.'));
}
}
}
?>
and i am getting error Call to a member function create() on a non-object in controller
you should be using:
$this->Form->create('Store');
public function add(){
$this->layout = 'user_layout';
$user_id = $this->UserAuth->getUserId();
$owner_id = $this->Common->getOwnerId($user_id);
if ($this->request->is('post')) {
$this->Store->create('Store');
if ($this->Store->save($this->request->data)) {
$this->Flash->success(__('User has been Added'));
return $this->redirect(array('action' => 'add'));
} $this->Flash->error(__('Unable to add your post.'));
}
}
Yes, I solved the problem. There was a minor problem. I forgot the following line in the controller:
var $uses = array('Store');

How to limit max char on redactor limiter plugin?

I have this code in my view
<div class="col-xs-6">
<?php echo $form->field($model, 'deskripsi_produk')->widget(Redactor::className(),['clientOptions'=>['autoresize'=>'true', 'limiter' => 20, 'plugins' => ['limiter'], 'buttons'=> ['html', 'formatting', 'bold', 'italic','underline','lists','horizontalrule'],]]);?>
</div>
it can limit 20 char but How I can limit text area to max string defined on model instead of limit with specific number?
Here is my model
class TbProduk extends \yii\db\ActiveRecord
{
/**
* #inheritdoc
*/
public $image;
public static function tableName()
{
return 'tb_produk';
}
public function rules()
{
return [
...
[['deskripsi_produk'], 'string', 'max' => 2000],
[['deskripsi_produk'], 'checkDesc'],
...
];
}
}
Trying to get the value via rules is a terrible idea. Instead you should create a constant in TbProduk that will hold the length:
class TbProduk extends \yii\db\ActiveRecord
{
const DESKRIPSI_PRODUK_LENGTH = 2000;
...
public function rules()
{
return [
...
[['deskripsi_produk'], 'string', 'max' => static::DESKRIPSI_PRODUK_LENGTH],
...
];
}
}
And in your view:
<div class="col-xs-6">
<?php echo $form->field($model, 'deskripsi_produk')->widget(Redactor::className(),['clientOptions'=>['autoresize'=>'true', 'limiter' => TbProduk::DESKRIPSI_PRODUK_LENGTH, 'plugins' => ['limiter'], 'buttons'=> ['html', 'formatting', 'bold', 'italic','underline','lists','horizontalrule'],]]);?>
</div>

Error in wbranca dynagrid update

Am using wbranca yii2 to create dynamic forms but the update action returns an error of
array_combine(): Both parameters should have an equal number of elements
This is the form for the update
<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' => $modelsPrItem[0],
'formId' => 'dynamic-form',
'formFields' => [
'po_item_no',
'quantity',
],
]); ?>
<div class="container-items">
<!-- widgetContainer -->
<?php foreach ($modelsPrItem as $i => $modelPrItem): ?>
<div class="item paneld">
<!-- widgetBody -->
<div class="panelf-heading">
<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="panelf-body">
<?php
// necessary for update action.
if (! $modelPrItem->isNewRecord) {
echo Html::activeHiddenInput($modelPrItem, "[{$i}]PRID");
}
?>
<div class="row">
<div class="col-md-2">
<?= $form->field($modelPrItem, "[{$i}]Quantity")->textInput(['maxlength' => 128]) ?>
</div>
<div class="col-md-2">
<?= $form->field($modelPrItem, "[{$i}]Unit_Price")->textInput(['maxlength' => 128]) ?>
</div>
<div class="col-md-2">
<?= $form->field($modelPrItem, "[{$i}]Extended_price")->textInput(['maxlength' => 128]) ?>
</div>
<div class="col-md-2">
<?= $form->field($modelPrItem, "[{$i}]Currency_ID")->dropDownList(
ArrayHelper::map(Tblcurrency::find()->all(),'CurrencyID','currency_symbol'),[]
); ?>
</div>
<div class="col-md-4">
<?= $form->field($modelPrItem, "[{$i}]Description")->textArea(['maxlength' => 128]) ?>
</div>
</div>
<!-- .row -->
</div>
</div>
<?php endforeach; ?>
</div>
<?php DynamicFormWidget::end(); ?>
</div>
This is the model:
<?php
namespace app\models;
use Yii;
use yii\helpers\ArrayHelper;
class Model extends \yii\base\Model
{
/**
* Creates and populates a set of models.
*
* #param string $modelClass
* #param array $multipleModels
* #return array
*/
public static function createMultiple($modelClass, $multipleModels = [])
{
$model = new $modelClass;
$formName = $model->formName();
$post = Yii::$app->request->post($formName);
$models = [];
if (! empty($multipleModels)) {
$keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
$multipleModels = array_combine($keys, $multipleModels);
}
if ($post && is_array($post)) {
foreach ($post as $i => $item) {
if (isset($item['id']) && !empty($item['id']) && isset($multipleModels[$item['id']])) {
$models[] = $multipleModels[$item['id']];
} else {
$models[] = new $modelClass;
}
}
}
unset($model, $formName, $post);
return $models;
}
}
The above returns an error when i run update especially when updating more than one item
The error message say that the number of element in $keys and $values (alias $multipleModels ) are not the same so you are trying to build an associative array witth a wrong pair of key => value elements
Try var_dump (or inspect with xdebug) the content of the $keys and$multipleModels and adapt the code to your real need .
if (! empty($multipleModels)) {
$keys = array_keys(ArrayHelper::map($multipleModels, 'id', 'id'));
var_dump($keys );
var_dump($multipleModels);
$multipleModels = array_combine($keys, $multipleModels);
}