How to use plugins in chartjs and laravel chart consoletvs/chartsjs - laravel

Need use chartjs plugin datalabels in laravel 5.8 and consoletvs/chartsjs ver 6.*
This line generate a error in laravel.
$chart->plugins(['datalabels'=>['color'=>'#223388']]);
$chart = new Chart;
$chart->labels($arrHora);
$chart->dataset('Propostas Por Hora','bar', $arrQtdHora)
->backgroundColor('#64b5f6');
$chart->options([
'responsive' => true,
//'aspectRatio' => 1,
'tooltips' => ['enabled'=>false],
'legend' => ['display' => false],
'scales' => [
'yAxes'=> [[
'display'=>false,
'ticks'=> ['beginAtZero'=> true],
'gridLines'=> ['display'=> false],
]],
'xAxes'=> [[
'categoryPercentage'=> 0.55,
//'barThickness' => 100,
'barPercentage' => 0.5,
'ticks' => ['beginAtZero' => true],
'gridLines' => ['display' => false],
]],
],
]);
$chart->plugins(['datalabels'=>['color'=>'#223388']]);
//dd($chart);
//->backgroundColor('#64b5f6');
return view('dashboard', ['chart' => $chart]);

Two things I have to clarify, after playing around with the library, I came up with the following results:
First: The function $chart->plugins is used to create inline plugins only, under chartjs/script.blade.php the file begins with:
So for each plugin array that you define it will load a view from the pluginsView array that have the same name, but I think this is not full developed yet, and since this is not what the question is about lets move on.
Second: You can perfectly a nested option use options -> plugin like I have suggested before, but there's one thing that you will have to be careful whit, is that 'plugins' can't be an array like the others, and here is why:
The function expects a string to be printed raw, so with that you can use something like:
$chart->options([
//...
'plugins' => '{datalabels: {color: \'red\'}}',
//...
]);
Which will work as expected:

I share here the complete solution of my code and if you have any comments or suggestions, you will be welcome.
/* Controller */
<?php
namespace App\Http\Controllers\dashboard;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use ConsoleTVs\Charts\Classes\Chartjs\Chart;
use DB;
class DashBoardController extends Controller
{
public function index() {
$result = DB::select('select
convert(varchar(10),data_da_solicitacao,121) data,
convert(varchar(2),data_da_solicitacao,114) hora,
COUNT(id_controle_proposta_pac) qtdHora
from contact_std_parceiros_propostas (nolock) p
where convert(varchar(10),data_da_solicitacao,121) between convert(varchar(10),getdate(),121) and convert(varchar(10),getdate(),121)
and not exists (select * from contact_std_parceiros_propostas_fora (nolock) f where f.id_controle_proposta_pac = p.id_controle_proposta_pac)
Group by convert(varchar(10),data_da_solicitacao,121), convert(varchar(2),data_da_solicitacao,114)
Order by 1');
$arrHora = array();
$arrQtdHora = array();
$i = 0;
foreach ( $result as $r )
{
$arrHora[$i] = $r->hora;
$arrQtdHora[$i] = $r->qtdHora;
$i++;
}
$chart = new Chart;
$chart->labels($arrHora);
$chart->dataset('Propostas Por Hora no dia de hoje','bar', $arrQtdHora)->backgroundColor('#64b5f6');
$chart->options([
'responsive' => true,
'legend' => ['display' => true],
'tooltips' => ['enabled'=>true],
//'aspectRatio' => 1,
'scales' => [
'yAxes'=> [[
'display'=>false,
'ticks'=> ['beginAtZero'=> true],
'gridLines'=> ['display'=> false],
]],
'xAxes'=> [[
'categoryPercentage'=> 0.8,
//'barThickness' => 100,
'barPercentage' => 1,
'ticks' => ['beginAtZero' => true],
'gridLines' => ['display' => false],
]],
],
'plugins' => '{datalabels: {color: \'red\'}}',
]);
return view('dashboard',compact('chart'));
}
}
/* view */
#extends('layout.main')
#section('titulo','Pac - DashBoard')
#section('conteudo')
<div class="row">
<div class="col s6 col m12 l12">
<div class="x_panel">
<div class="x_title">
<div class="col s6 m6 l6"><h2>Propostas do dia</h2></div>
<ul class="nav navbar-right panel_toolbox">
<li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
</li>
<li><a class="close-link"><i class="fa fa-close"></i></a></li>
</ul>
<div class="clearfix"></div>
</div>
<div class="x_content" style="display: block;">
<div class="row">
<div class="row top_tiles" id="card-0"></div>
<div class="row">
<div class="col s4 m7 l7">
<div id="graph-0" class="x_panel" style="height: 250px">
<!--<canvas id="bar-0" style="width: 70% !important;height: auto !important;">-->
{!! $chart->container() !!}
#foreach($chart->plugins as $plugins)
#include($chart->pluginsViews[$plugins])
#endforeach
<!--</canvas>-->
</div>
</div>
<div class="col s3 m5 l5">
<div id="graph-1" class="x_panel">
<canvas id="pie-1" style="width: 100% !important;height: auto !important;"></canvas>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
{!! $chart->script() !!}
#endsection

Related

Uncaught (in promise) TypeError: initialData is null - my components are wrapped in a single div but still getting the error

I am getting an initial data is null error. This has been talked about github forum, however, the answer was that the component was not wrapped in a single div. My components are. So I am still getting:
Uncaught (in promise) TypeError: initialData is null
I have a simple button that runs a function when clicked
which is produced by this code:
<div class="mx-0 col-span-1 block font-medium text-sm text-gray-700 mb-0">
<x-green-button-sm class="px-0 mx-0" title="Add a New person to the family." wire:click="createChild">
<h3 class="my-0 text-xss">Add Child</h3>
</x-green-button-sm>
#livewire('admin.shared.edit-add-child', ['showEditAddChildModal' => $showEditAddChildModal,
'editadd' => 'add', 'userid' => $user->id, 'registrantOrAdmin' => $registrantOrAdmin])
</div>
Which calls this function in the component
public function createChild(){
$this->showEditAddChildModal = true;
}
And notice that the livewire component above is passed the value of $showEditAddChildModal
The beginning of the admin.shared.edit-add-child blade component is:
<div>
<form wire:submit.prevent="save">
<x-modal.dialog wire:model="showEditAddChildModal">
......
.....
</div> // the blade component is contained in a single div as required
so the effort is to make the model visible obviously. The admin.shared.edit-add-child blade blade makes reference to models (public properties) like this
wire:model.debounce.500ms="editChild.firstname"
the EditAddChild.php component is set up like this:
<?php
namespace App\Http\Livewire\Admin\Shared;
use App\Models\Person;
use Livewire\Component;
class EditAddChild extends Component
{
public $showEditAddChildModal = false;
//(if i set the above true, the modal does show up.)
public $userid;
public $txtmsgp;
public $fullname;
public $registrantOrAdmin;
public $editadd;
public $editChild;
// (I started with public Person $editChild but the system balked at //initializing a typed variable in the mount() function)
public $dateOfBirth;
Below, note that the $this->editadd variable is passed in the #livewire call seen above. The mount() function in the EditAddChild.php component is:
public function mount(){
if($this->editadd == 'add')
$this->editChild = $this->addNewChild();
}
addNewChild() is:
public function addNewChild()
{
return Person::make(['added_by' => auth()->user()->id,
'updated_by' => null,
'family_type' => 'child',
'firstname' => '',
'lastname' => '',
'pronouns' => 'u',
'sex' => 'u',
'dob' => now(),
'age_today' => 0,
'mobile_phone' => null,
'receive_texts' => 'u',
'email' => '',
'allow_emails' => 'u',
'member' => 'u',
'allow_photos' => 'u',
'show' => 0,
]);
}
when i click on the add child button to change the x-show variable to true, the modal does not show and the console reports this:
My apologies, but I thought I would list the entire modal coponent as well. There are two parts [dialog.blade.php] :
#props(['id' => null, 'maxWidth' => null])
<x-modal :id="$id" :maxWidth="$maxWidth" {{ $attributes }}>
<div class="px-6 py-4">
<div class="text-lg">
{{ $title }}
</div>
<div class="mt-4">
{{ $content }}
</div>
</div>
<div class="px-6 py-4 bg-gray-100 text-right">
{{ $footer }}
</div>
</x-modal>
the second part being [modal.bade.php]:
#props(['id', 'maxWidth'])
#php
$id = $id ?? md5($attributes->wire('model'));
$maxWidth = [
'sm' => 'sm:max-w-sm',
'md' => 'sm:max-w-md',
'lg' => 'sm:max-w-lg',
'xl' => 'sm:max-w-xl',
'2xl' => 'sm:max-w-2xl',
'3xl' => 'sm:max-w-3xl',
'4xl' => 'sm:max-w-4xl',
'5xl' => 'sm:max-w-5xl',
'6xl' => 'sm:max-w-6xl',
'7xl' => 'sm:max-w-7xl',
][$maxWidth ?? '3xl'];
#endphp
<div
x-data="{
show: #entangle($attributes->wire('model')).defer,
focusables() {
// All focusable element types...
let selector = 'a, button, input, textarea, select, details, [tabindex]:not([tabindex=\'-1\'])'
return [...$el.querySelectorAll(selector)]
// All non-disabled elements...
.filter(el => ! el.hasAttribute('disabled'))
},
firstFocusable() { return this.focusables()[0] },
lastFocusable() { return this.focusables().slice(-1)[0] },
nextFocusable() { return this.focusables()[this.nextFocusableIndex()] || this.firstFocusable() },
prevFocusable() { return this.focusables()[this.prevFocusableIndex()] || this.lastFocusable() },
nextFocusableIndex() { return (this.focusables().indexOf(document.activeElement) + 1) % (this.focusables().length + 1) },
prevFocusableIndex() { return Math.max(0, this.focusables().indexOf(document.activeElement)) -1 },
}"
x-init="$watch('show', value => {
if (value) {
document.body.classList.add('overflow-y-hidden');
} else {
document.body.classList.remove('overflow-y-hidden');
}
})"
x-on:close.stop="show = false"
x-on:keydown.escape.window="show = false"
x-on:keydown.tab.prevent="$event.shiftKey || nextFocusable().focus()"
x-on:keydown.shift.tab.prevent="prevFocusable().focus()"
x-show="show"
id="{{ $id }}"
class="overflow-auto jetstream-modal fixed inset-0 overflow-y-auto px-4 py-6 sm:px-0 z-50"
style="display: none;"
>
<div x-show="show" class="fixed inset-0 transform transition-all" x-on:click="show = false"
x-transition:enter="ease-out duration-3000"
x-transition:enter-start="opacity-0"
x-transition:enter-end="opacity-100"
x-transition:leave="ease-in duration-3000"
x-transition:leave-start="opacity-100"
x-transition:leave-end="opacity-0">
<div class="absolute inset-0 bg-gray-500 opacity-75"></div>
</div>
<div x-show="show" class="mb-6 bg-white rounded-lg overflow-hidden shadow-xl transform transition-all sm:w-full {{ $maxWidth }} sm:mx-auto"
x-transition:enter="ease-out duration-300"
x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100"
x-transition:leave="ease-in duration-200"
x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100"
x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95">
{{ $slot }}
</div>
</div>
Please check in here
#livewire('admin.shared.edit-add-child', ['showEditChildModal' => $showEditAddChildModal,
'editadd' => 'add', 'userid' => $user->id, 'registrantOrAdmin' => $registrantOrAdmin])
precisely at "'showEditChildModal' => $showEditAddChildModal" part. You're binding the parent property ($showEditAddChildModal) to the child ('showEditChildModal'), but in the child component that property doesn't exist, instead you have declared the property as next:
public $showEditAddChildModal = false;
It's a typo of you should fix it???

is that possible to make pagination work as single item per page with navigation

Controller code:
public $paginate = [
'Employers' => ['scope' => 'employer'],
'Stories' => ['scope' => 'story',
'page' => 1,
'limit' => 1]
];
public function index()
{
//load model
$this->loadModel('Stories');
// Paginate property
$this->loadComponent('Paginator');
// In a controller action
$stories = $this->paginate($this->Stories, ['scope' => 'story']);
$employers = $this->paginate($this->Employers, ['scope' => 'employer']);
//pr($stories);
$this->set(compact('employers', 'stories'));
}
From that code must understand that the code looks as that is required but at same time i can't navigate further i also require code to run so i keep that clear code also put together code that would work according to single page but code require that code must put together a cycle that goes to next story entry without changing page that i display ie index.php.
View Code:
<div class="row">
<div class="large-8 columns" style="border-right: 1px solid #E3E5E8;">
<article>
<?php
foreach($stories as $story){
echo '<hr><div class="row">
<div class="large-6 columns">
<p>'.$this->Html->image($story['image'].'.jpg', ['alt'=>'image for article']).'</p>
</div>
<div class="large-6 columns">
<h5>'.$story['title'].'</h5>
<p>
<span><i class="fi-torso"> By '.$story['creator'].' </i></span>
<span><i class="fi-calendar"> '.$story['created'].' </i></span>
</p>
<p>'.$story['story'].'</p>
</div>
</div><hr>';
}
?>
<ul class="pagination" role="navigation" aria-label="Pagination">
<li class="disabled"><?php echo $this->Paginator->prev(' ' . __('previous')); ?></li>
<!--<li class="current">1</li>
<li>2</li>
<li>3</li>
<li>4</li>-->
<li><?php echo $this->Paginator->prev(' >> ' . __('next')); ?></li>
</ul>
</article>
</div>
Code written makes pagination appear on the view but doesn't work when i click paginator.
That is possible follow code below to make that work.
public $paginate = [
'Stories' => ['scope' => 'story',
'limit' => 1,
]
];
public function initialize(): void
{
parent::initialize();
$this->loadComponent('Paginator');
}
public function index()
{
//load model
$this->loadModel('Stories');
$this->loadModel('Sectors');
// Paginate property
$this->loadComponent('Paginator');
// In a controller action
$employers = $this->Employers->find('all');
$sectors = $this->Sectors->find('all');
$stories = $this->paginate($this->Stories->find('all', ['scope' => 'story']));
//pr($sectorsandcourses);
$this->set(compact('employers', 'stories', 'sectors'));
}
Important factor that shows up is that we put limit to number of result to show up each instance.

Displaying multiple charts on the same view

I want to display all my charts on the same view I used lavacharts I gave different no to my charts but in the view it shows me that the last chart in the controller.
Controller code:
function l()
{
$lava = new Lavacharts; // See note below for Laravel
$reasons = \Lava::DataTable();
$abs=Absencecollab::all();
$r=$abs->count();
$absm=Absencecollab::where('motif','maladie');
$tm=$absm->count();
$absc=Absencecollab::where('motif','conge');
$tc=$absc->count();
$absnj=Absencecollab::whereNull('motif');
$tnj=$absnj->count();
$pm=($tm100)/$r;
$pc=($tc100)/$r;
$pnj=($tnj100)/$r;
$reasons->addStringColumn('Reasons')
->addNumberColumn('Percent')
->addRow(['Maladie',$pm ])
->addRow(['Conge',$pc])
->addRow(['Absence non justifiée',$pnj]);
\Lava::PieChart('IMDB', $reasons, [
'title' => 'Abscences collaborateurs par motif',
'is3D' => true,
'slices' => [
['offset' => 0.2],
['offset' => 0.25],
['offset' => 0.3]
]
]);
$reasons1 = \Lava::DataTable();
$abs1=Absence::all();
$r1=$abs1->count();
$absm1=Absence::where('motif','maladie');
$tm1=$absm1->count();
$absc1=Absence::where('motif','conge');
$tc1=$absc1->count();
$absnj1=Absencecollab::whereNull('motif');
$tnj1=$absnj1->count();
$pm1=($tm1100)/$r;
$pc1=($tc1100)/$r;
$pnj1=($tnj1*100)/$r;
$reasons1->addStringColumn('Reasons')
->addNumberColumn('Percent')
->addRow(['Maladie',$pm1 ])
->addRow(['Congé parents',$pc1])
->addRow(['Absence non justifiée',$pnj1]);
\Lava::PieChart('abse', $reasons1, [
'title' => 'Abscences enfants par motif',
'is3D' => true,
'slices' => [
['offset' => 0.2],
['offset' => 0.25],
['offset' => 0.3]
]
]);
return view('statistiquesg');
view code
#piechart('IMDB', 'chart-div')
<canvas id="line" height="300" width="450"></canvas>
</div>
</section>
</div>
<!-- Bar -->
<div class="col-lg-6">
<section class="panel">
<header class="panel-heading">
Absence enfants
</header>
<div class="panel-body text-center" id="chart-div">
#piechart('abse', 'chart-div')
<canvas id="bar" height="300" width="500"></canvas>
</div>
</section>
</div>
The second parameter of #piechart is the ID of the div, both pie charts are using the chart-div id.

Yii2 Dynamic model and Ajax missing data issue

I get only partial data in controller. here is the situation
my action in controller that show the view with the form:
$model_sms = array();
$model_sms = new \yii\base\DynamicModel(['sms_code', 'iduser', 'mail_status', 'signup_control']);
$model_sms->addRule(['sms_code, iduser, mail_status, signup_control'], 'required');
$model_sms->addRule(['iduser, mail_status, signup_control'], 'integer');
$model_sms->addRule('sms_code', 'string', ['min' => 5, 'max' => 5]);
$model_sms->iduser = $user->id;
$model_sms->mail_status = $mail_status;
$model_sms->signup_control = 1;
return $this->renderAjax('_sms_confirmation', ['model_sms' => $model_sms]);
then the view code is here
<?php
use yii\helpers\Html;
use kartik\form\ActiveForm;
?>
<div class=" site-login">
<?php $form = ActiveForm::begin(['id' => 'frmsmsconfirm', 'action'=>'/index.php?r=site/confirmsms']); ?>
<div class="row">
<div class="col-md-1">
</div>
<div class="col-md-10">
<div class="formSeparator"><span>Enter SMS code</span></div>
<p class="logtxt">Please fill out the following fields to login:</p>
<?php
echo $form->field($model_sms, 'iduser')->hiddenInput()->label(false);
echo $form->field($model_sms, 'mail_status')->hiddenInput()->label(false);
echo $form->field($model_sms, 'signup_control')->hiddenInput()->label(false);
echo $form->field($model_sms, 'sms_code', [
'feedbackIcon' => [
'default' => 'phone',
'success' => 'ok',
'error' => 'exclamation-sign',
'defaultOptions' => ['class'=>'cw']
]
])->textInput(['placeholder'=>'Enter SMS code', 'class'=>'newxinput xinput'])->label('SMS code');
?>
</div>
<div class="col-md-1">
</div>
</div>
<div class="row">
<div class="col-md-1">
</div>
<div class="col-md-10">
<div class="scforget">
If you did not receive SMS <?= Html::a('send it again', ['site/smsresend']) ?>.
</div>
</div>
<div class="col-md-1">
</div>
</div>
<div class="row">
<div class="col-md-1">
</div>
<div class="col-md-10"><br><br>
<div class="form-group">
<?= Html::submitButton('Submit', ['class' => 'xsubbtn', 'name' => 'login-button']) ?>
</div><br><br>
</div>
<div class="col-md-1">
</div>
</div>
<?php ActiveForm::end(); ?>
</div>
<script>
$('#frmsmsconfirm').on('submit', function(e){
e.preventDefault();
e.stopImmediatePropagation();
var form = $(this);
alert('ajax start');
alert(form.serialize());
$.ajax({
url : form.attr('action'),
type : 'post',
data : form.serialize(),
success: function (response)
{
alert('radi a ne radi... hm');
$('#sc_content').html(response);
},
error: function ()
{
console.log('internal server error');
}
});
});
</script>
I get all correct data in alert(serialize.form), but when it is passed to another action in controller I only get sms_code, other 3 fields come blank... here is the code...
$model_sms = array();
$model_sms = new \yii\base\DynamicModel(['sms_code', 'iduser',
'mail_status', 'signup_control']);
$model_sms->addRule(['sms_code, iduser, mail_status,
signup_control'], 'required');
$model_sms->addRule(['iduser, mail_status, signup_control'],
'integer');
$model_sms->addRule('sms_code', 'string', ['min' => 5, 'max' =>
5]);
$model_sms->load(Yii::$app->request->post());
echo $model_sms->sms_code.'- xxx - <br>';
echo $model_sms->iduser.'- xxx - <br>';
echo $model_sms->mail_status.'- xxx - <br>';
echo $model_sms->signup_control.'- xxx - <br>';
exit;
Does anybod have any idea?
Thanks
You have an error at your 2 addRule() definitions:
$model_sms->addRule(['sms_code, iduser, mail_status, signup_control'], 'required');
$model_sms->addRule(['iduser, mail_status, signup_control'], 'integer');
should be:
$model_sms->addRule(['sms_code', 'iduser', 'mail_status', 'signup_control'], 'required');
$model_sms->addRule(['iduser', 'mail_status', 'signup_control'], 'integer');
The 1st parameter of addRule should be an array of attributes.

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

Resources