我在一种视图中有三种形式。两种形式都具有上载图像(多部分)功能,第三种形式是带有文本字段的常规形式,我想单击一次按钮就可以上载所有三种形式。有人可以帮我吗?
答案 0 :(得分:0)
尝试使用此代码,它将以单一形式上载不同表中的多个图像。
public function actionCreate()
{
$db = Yii::$app->db;
$transaction = $db->beginTransaction();
$savedFlag = false;
$model = new Company();
$divisionModel = new Division();
$prajects = new Prajects();
if ($model->load(Yii::$app->request->post()) && $prajects ->load(Yii::$app->request->post()) && $divisionModel->load(Yii::$app->request->post())) {
try{
$model->company_logo = UploadedFile::getInstance($model, 'company_logo');
if ($model->company_logo) {
$model->company_logo->saveAs('uploads/' . $model->company_logo->baseName . '.' . $model->company_logo->extension);
}
if($model->save()){
$savedFlag = true;
$divisionModel->division_logo = UploadedFile::getInstance($divisionModel, 'division_logo');
if ($divisionModel->division_logo) {
$divisionModel->division_logo->saveAs('uploads/' . $divisionModel->division_logo->baseName . '.' . $divisionModel->division_logo->extension);
}
//$divisionModel->comapnay_id = $model->id;
if(!$divisionModel->save()){
$savedFlag = false;
}
if(!$prajects->save()){
$savedFlag = false;
}
}
if($savedFlag){
$transaction->commit();
return $this->redirect(['view', 'id' => $model->id]);
}else{
$transaction->rollBack();
}
}catch (\Exception $e) {
$transaction->rollBack();
throw $e;
}
}
return $this->render('create', [
'model' => $model,
'divisionModel' => $divisionModel,
'prajects' => $prajects,
]);
}
create.php文件:
<?= $this->render('_form', [
'model' => $model,
'divisionModel' => $divisionModel,
'prajects' => $prajects,
]) ?>
_form.php文件:
<?php $form = ActiveForm::begin(); ?>
<?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>
<?= $form->field($model, 'company_logo')->fileInput() ?>
<?= $form->field($divisionModel, 'division_name')->textInput(['maxlength' => true]) ?>
<?= $form->field($divisionModel, 'division_logo')->fileInput() ?>
<?= $form->field($prajects, 'name')->textInput(['maxlength' => true]) ?>
<div class="form-group">
<?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
</div>
<?php ActiveForm::end(); ?>