Answer the question
In order to leave comments, you need to log in
How to write to related models in yii2?
Hello, please help me with the building. I have a page with form fields and I need to write some of these fields into one table (I have no problems with this) and I also need to make an entry from other fields into another table.
In short, the essence of the task. I have a page with form fields for filling out a goal and there are forms for filling out a plan for this goal. You can not fill them out at all, or you can add one or more stages to the plan. Help me implement this. As for just adding a goal, there are no problems here, but adding several stages to the plan has problems. I will attach all possible information that you would tell me. I searched the Internet for a solution but still could not do it. Tell me please. Thanks in advance.
This is the page itself.
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "goals".
*
* @property int $id
* @property string $goal
* @property string $date_finish_goal
* @property string $criterion_fifnish_goal
* @property int $id_user
* @property int $category_goal
* @property int $priority_goal
* @property int $status
* @property int $is_public
* @property string $need_goal
* @property string $doc
*
* @property CriteriesGoals $categoryGoal
* @property Users $user
* @property Stage[] $stages
*/
class Goals extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'goals';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['goal', 'date_finish_goal', 'criterion_fifnish_goal', 'id_user', 'category_goal', 'priority_goal', 'is_public', 'need_goal'], 'required'],
[['date_finish_goal'], 'safe'],
[['id_user', 'category_goal', 'priority_goal', 'status', 'is_public'], 'integer'],
[['goal', 'criterion_fifnish_goal', 'need_goal'], 'string', 'max' => 255],
[['category_goal'], 'exist', 'skipOnError' => true, 'targetClass' => CriteriesGoals::className(), 'targetAttribute' => ['category_goal' => 'id']],
[['id_user'], 'exist', 'skipOnError' => true, 'targetClass' => Users::className(), 'targetAttribute' => ['id_user' => 'id']],
[['doc'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'],
];
}
public function upload()
{
if ($this->validate()) {
$this->doc->saveAs('img/goals/' . $this->doc->baseName . '.' . $this->doc->extension);
return true;
} else {
return false;
}
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'goal' => 'Goal',
'date_finish_goal' => 'Date Finish Goal',
'criterion_fifnish_goal' => 'Criterion Fifnish Goal',
'id_user' => 'Id User',
'category_goal' => 'Category Goal',
'priority_goal' => 'Priority Goal',
'status' => 'Status',
'is_public' => 'Is Public',
'need_goal' => 'Need Goal',
'doc' => 'Doc',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getCategoryGoal()
{
return $this->hasOne(CriteriesGoals::className(), ['id' => 'category_goal']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getUser()
{
return $this->hasOne(Users::className(), ['id' => 'id_user']);
}
/**
* @return \yii\db\ActiveQuery
*/
public function getStages()
{
return $this->hasMany(Stage::className(), ['goal_id' => 'id']);
}
}
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "stage".
*
* @property int $id
* @property string $title
* @property string $date_finish_stage
* @property string $description
* @property int $id_user
* @property int $goal_id
*
* @property Users $goal
*/
class Stage extends \yii\db\ActiveRecord
{
public $show_stages = false;
/**
* @inheritdoc
*/
public static function tableName()
{
return 'stage';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['title', 'date_finish_stage', 'description'], 'required','when' => function ($model) {return $model->show_stages == 1;},'whenClient' => "function(attribute, value) {return $('#goals-show_stages').prop('checked');}", 'message'=>'проверка'],
[['show_stages'],'boolean'],
[['date_finish_stage'], 'date'],
[['description'], 'string'],
[['id_user', 'goal_id'], 'integer'],
[['title'], 'string', 'max' => 255],
[['goal_id'], 'exist', 'skipOnError' => true, 'targetClass' => Users::className(), 'targetAttribute' => ['goal_id' => 'id']],
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'title' => 'Title',
'date_finish_stage' => 'Date Finish Stage',
'description' => 'Description',
'id_user' => 'Id User',
'goal_id' => 'Goal ID',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getGoal()
{
return $this->hasOne(Users::className(), ['id' => 'goal_id']);
}
}
public function actionCreate()
{
$model = new Goals();
$stage = new Stage();
$model->id_user = Yii::$app->user->id;
if ($model->load(Yii::$app->request->post())) {
$model->doc = UploadedFile::getInstance($model, 'doc');
if ($model->doc) {
if($model->upload())
{
$model->doc = $model->doc->name;
$model->save();
}
}
if($model->save())
{
foreach(Yii::$app->request->post('Stage') as $stage_item)
{
$stage->title = $stage_item['title'];
$stage->description = $stage_item['description'];
$stage->date_finish_stage = $stage_item['date_finish_stage'];
$stage->save();
}
return $this->redirect(['view', 'id' => $model->id]);
}
}
return $this->render('create', [
'model' => $model,
'stage' => $stage,
]);
}
<div class="ag_2">
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<div class="ag_7_1">Напишите цель</div>
<div class="ag_6"><?= $form->field($model, 'goal')->textInput(['class'=>'input_goal','placeholder'=>'Что вы хотите?'])->label(false) ?></div>
<div class="ag_7_1">Когда цель должна быть достигнута?</div>
<div class="ag_6"><?= $form->field($model, 'date_finish_goal')->widget(DatePicker::className(), ['type' => DatePicker::TYPE_INPUT,'options'=>['class'=>'input_goal','placeholder'=>'Когда вы этого хотите?'],'language' => 'ru','pluginOptions' => ['autoclose'=>true,'format' => 'dd.mm.yyyy']])->label(false) ?></div>
<div class="ag_7_1">Как вы поймете, что цель достигнута?</div>
<div class="ag_6"><?= $form->field($model, 'criterion_fifnish_goal')->textInput(['class'=>'input_goal','placeholder'=>'Критерий завершения цели'])->label(false) ?></div>
<div class="ag_7_1">Для чего вам эта цель? Что вы получите?</div>
<div class="ag_6"><?= $form->field($model, 'need_goal')->textInput(['class'=>'input_goal','placeholder'=>'Зачем вам эта цель?'])->label(false) ?></div>
<div class="ag_7_1">Выберите категорию цели</div>
<div class="ag_7_2"><?= $form->field($model, 'category_goal')->dropDownList(ArrayHelper::map(CriteriesGoals::find()->all(),'id','name'),['prompt'=>'Выбрать категории'])->label(false) ?></div>
<div class="ag_7_1">Выберите приоритет цели</div>
<div class="ag_7_2"><?= $form->field($model, 'priority_goal')->radioList(['0' => 'Без приоритета','1' =>"<code>🔥</code>",'2' => '🔥🔥','3'=>'🔥🔥🔥'])->label(false) ?>
</div>
<div class="ag_6"><label><?= $form->field($model, 'is_public')->checkbox(array('label'=>'Не показывать цель людям')) ?></div>
<div class="ag_6"><?= $form->field($model, 'doc')->fileInput()->label(false) ?></div>
<div class="addplan" onclick="$('.ag_1_1').toggleClass('active');if($('#goals-show_stages').attr('checked')){$('#goals-show_stages').attr('checked',false)}else{$('#goals-show_stages').attr('checked',true)}">
Добавить план достижения цели
</div>
<div class="ag_1_1">
<div class="ag_3">План достижения цели</div>
<div class="stage">
<div class="ag_1_2"><?= $form->field($stage, 'title[]')->textInput(['class'=>'input_goal','placeholder'=>'Название этапа'])->label(false) ?></div>
<div class="ag_1_2"><?= $form->field($stage, 'description[]')->textarea(['class'=>'input_goal','placeholder'=>'Описание этапа'])->label(false) ?></div>
<ul class="ag_8">
<li class="ag_l"><img src="img/icon/leveldown.svg" alt=""/></li>
<li class="ag_ac"><?= $form->field($stage, 'date_finish_stage[]')->widget(DatePicker::className(), ['type' => DatePicker::TYPE_INPUT,'options'=>['class'=>'input_goal','placeholder'=>'Когда вы этого хотите?'],'language' => 'ru','pluginOptions' => ['format' => 'dd.mm.yyyy']])->label(false) ?></li>
</ul>
</div>
<div class="ag_2_1" onclick="$('.ag_1_1').find('.stage').append($('.stage').html());">Добавить этап</div>
</div>
<div class="button add_goal_button"><?= Html::submitButton('Добавить цель') ?></div>
<?php ActiveForm::end(); ?>
</div>
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question