Hi there!
I’m trying to create a form in which I will be able to edit model with it’s related data.
I have a model File to store uploaded files and information about these files. It contains id, path, alt and title fields and my own written FileUpload behavior. Also I have a model Company with the following relations:[spoiler]
public function getLogo()
{
return $this->hasOne(File::className(), ['id' => 'file_id',])
->viaTable(
FileRelated::tableName(),
['entity_id' => 'id',],
function ($query) {
/** @var ActiveQuery $query */
return $query
->andWhere('entity_class = :entity_class', [':entity_class' => $this->className(),])
->andWhere('entity_field = :entity_field', [':entity_field' => 'logo',]);
}
);
}
public function getPhoto()
{
return $this->hasOne(File::className(), ['id' => 'file_id',])
->viaTable(
FileRelated::tableName(),
['entity_id' => 'id',],
function ($query) {
/** @var ActiveQuery $query */
return $query
->andWhere('entity_class = :entity_class', [':entity_class' => $this->className(),])
->andWhere('entity_field = :entity_field', [':entity_field' => 'photos',]);
}
);
}
[/spoiler]
I wrote an action in CompanyController to edit model data:[spoiler]
public function actionUpdate($id)
{
$model = $this->findModel($id);
/** @var $model Company */
if (!$model->logo) {
$model->logo = new File();
}
if (!$model->photo) {
$model->photo = new File();
}
$post = Yii::$app->request->post();
if ($model->load($post)
&& $model->logo->load(ArrayHelper::getValue($post, $model->logo->formName()), 'logo')
&& $model->photo->load(ArrayHelper::getValue($post, $model->photo->formName()), 'photo')
) {
//...
}
return $this->render('update', ['model' => $model,]);
}
[/spoiler]
In company update view:[spoiler]
/** @var $model Company */
echo $form->field($model, 'name')->textInput();
//without logo and photo in brackets these fields will override each other
echo $form->field($model->logo, '[logo]path')->fileInput();
echo $form->field($model->logo, '[logo]alt')->textInput();
echo $form->field($model->logo, '[logo]title')->textInput();
echo $form->field($model->photo, '[photo]path')->fileInput();
echo $form->field($model->photo, '[photo]alt')->textInput();
echo $form->field($model->photo, '[photo]title')->textInput();
[/spoiler]
This code works for me and allows to save related data excepting uploaded files. The FileUpload behavior trying to find files in $_FILES[‘File’][‘path’], but in reality the $_FILES array have the following structure
[spoiler]
//$_FILES dump
[
'File' => [
'name' => [
'logo' => [
'path' => '1SeGn5t5Xfw.jpg'
]
'photo' => [
'path' => '14.jpg'
]
]
'type' => [
'logo' => [
'path' => 'image/jpeg'
]
'photo' => [
'path' => 'image/jpeg'
]
]
'tmp_name' => [
'logo' => [
'path' => '/tmp/phpGevhV5'
]
'photo' => [
'path' => '/tmp/phphJYnSw'
]
]
'error' => [
'logo' => [
'path' => 0
]
'photo' => [
'path' => 0
]
]
'size' => [
'logo' => [
'path' => 96966
]
'photo' => [
'path' => 34036
]
]
]
]
[/spoiler]
Any idea how to solve this problem?