0

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>
Keith Thompson
  • 254,901
  • 44
  • 429
  • 631
  • Check demo source code http://wbraganca.com/yii2extensions/dynamicform-demo2/source-code for help to upload files.I think there are differences. – Jalali Jun 08 '16 at 06:54
  • `print_r($modelKandidat->file)` see the output – Muhammad Shahzad Jun 08 '16 at 09:35
  • please put your both `model` code. – vishuB Jun 08 '16 at 11:00
  • @vishu Election : http://pastebin.com/FMbDrYeW Kandidat : http://pastebin.com/4d1rLVfr – onusu CPlug Jun 09 '16 at 12:19
  • @MuhammadShahzad : It's says null – onusu CPlug Jun 09 '16 at 12:30
  • @shoara : I use 2 extension in here : Kartik file upload and dynamic2-form. Because the example of dynamic2-form contain some Models that I don't understand where it's come from (ex. models\query\CatalogOptionQuery) – onusu CPlug Jun 09 '16 at 12:46
  • 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")) { .......}}` – Jalali Jun 09 '16 at 12:47
  • @shoara : ''file' => '', it don't take the file. So what I need to do? Thank you – onusu CPlug Jun 09 '16 at 12:49
  • @shoara : Sorry I never heard about specify index. Can you explain it for me? Is it in the form or in the controller? Thank you If you mean in the form. I already use it (I don't use foreach I just add $i like the Utphala says in his channel) = $form->field($modelsKandidat, "[{$i}]file")->fileInput() ?> But, I don't understand where to put it. If you means to put foreach in controller. Thank you – onusu CPlug Jun 09 '16 at 12:50
  • It's in your controller.correct this but there is another problem because posted value is empty – Jalali Jun 09 '16 at 12:53
  • @shoara : I already add the key index. It's still don't work. But, I feel like I already a step foward. You really helpfull. Thank you – onusu CPlug Jun 09 '16 at 12:57
  • 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. – Jalali Jun 09 '16 at 13:07
  • @shoara : When I try to run the demo. It's error because I don't have CatalogOptionQuery Model. What model is that? How can I get it? – onusu CPlug Jun 10 '16 at 11:47
  • It's not required.You should be pay attention to actionCreate(). – Jalali Jun 10 '16 at 14:12
  • in your `Election Model` the rule() function all `required` value get when you submit your form? – vishuB Jun 11 '16 at 09:12
  • Don't add "SOLVED" to the title. To indicate that your problem has been solved, accept an appropriate answer by clicking the check mark. – Keith Thompson Jun 12 '16 at 08:18

1 Answers1

0

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

Thierry
  • 5,270
  • 33
  • 39