如何在Yii2中提交多部分表格?

时间:2015-10-04 13:16:32

标签: javascript ajax forms yii2

我的表单有问题,因为它无法序列化图像文件。那么如何使用ajax提交包含Yii2中图像文件输入的表单? (下面你可以看到活动表格和js代码。)

<div class="cars-form">

<?php $form = ActiveForm::begin(['options'=>['id'=>$model->formName(),'enableAjaxValidation'=>true,'enctype'=>'multipart/form-data']]); ?>

<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>

<?=$form->field($model, 'colour')->widget(ColorInput::classname(), ['options' => ['placeholder' => 'Select Color...'],]); ?>

<?=$form->field($model, 'imageFile')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*'],'pluginOptions' => [
        'previewFileType' => 'image',
        'showUpload' => false],]);?>

<?= $form->field($model, 'price')->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

$('form#{$model->formName()}').on('beforeSubmit',function(e)
    {var \$form =$(this);
    $.post(
    \$form.attr("action"),
    \$form.serializefiles()
    )
    .done(function(result) 
    {
    if (result == 1)
    {
      $(\$form).trigger("reset");
      $.pjax.reload({container:'#cars'});
    }

    else
    {
      $("#message").html(result);
    }

    }).fail(function(data)
    {console.log("server error: " + data);});
    return false;
});

JS;
$this->registerJs($script);?>

(控制器)

public function actionCreate()
{
    $model = new Cars();

    if ($model->load(Yii::$app->request->post())) {

        $imageName= $model->name;
        $model->imageFile= UploadedFile::getInstance($model,'imageFile');
        $model->imageFile->saveAs('carsimages/'.$imageName.'.'.$model->imageFile->extension);
        $model->image='carsImages/'.$imageName.'.'.$model->imageFile->extension;

        if($model->save())
        //{
            //return $this->redirect(['view', 'id' => $model->id]);
        //}
        {
           echo 1;
        }

        else
        {
            echo 0;
        }                   
    }

    else {
    return $this->renderAjax('create', [
            'model' => $model,
    ]);
}}

0 个答案:

没有答案