pinhak
(pinhak)
1
I’m new to Yii2 and PHP in general. I searched everywhere and can’t find the answear.
This is my ClientController:
public function actionCreate()
{
$model = new Client;
$model2 = new Address;
$model->getErrors();
if ($model->load(Yii::$app->request->post(),'') && $model2->load(Yii::$app->request->post(),'')) {
/* ALL VELUES ARE BEING NULL, IT DOESN'T GET ANY VALUES THAT I INFORMED TO IT
echo "<pre>";
var_dump($model2);
die; */
$client = Yii::$app->request->post();
$model->nome = $client['nome'];
$model->e_mail = $client['e_mail'];
$model->rg = $client['rg'];
$address = Yii::$app->request->post('Address');
$model2->street = $address['street'];
$model2->number = $address['number'];
$model2->neighborhood = $address['neighborhood'];
$model2->active = $address['active'];
if ($model->validate() && $model2->validate()) {
$model->save();
$model2->client_id = $model->id;
$model2->save();
return $this->redirect(['index', 'id' => $model->id]);
}
}
return $this->render('create', [
'model' => $model, 'model2' => $model2
]);
}
Hi,
did you look into the load() method what it is doing?
You call it’s second parameter as empty. So there is no formName ever given!
Do this:
if ( $model->load( Yii::$app->request->post() ) && $model2->load( Yii::$app->request->post() ) ) {
1 Like
pinhak
(pinhak)
3
Then the IF condition becomes false
softark
(Softark)
4
Hi @pinhak, welcome to the forum.
Have you read the following section of the guide?
Guide > Getting Data from Users > Getting Data for Multiple Models
The guide is for actionUpdate
, but the basic concept is the same for actionCreate
. It should be like the following:
public function actionCreate()
{
$user = new User();
$profile = new Profile();
$user->scenario = 'create';
$profile->scenario = 'create';
if ($user->load(Yii::$app->request->post()) && $profile->load(Yii::$app->request->post())) {
$isValid = $user->validate();
$isValid = $profile->validate() && $isValid;
if ($isValid) {
$user->save(false);
$profile->user_id = $user->id;
$profile->save(false);
return $this->redirect(['user/view', 'id' => $id]);
}
}
return $this->render('create', [
'user' => $user,
'profile' => $profile,
]);
}
And the view script would be:
$form = ActiveForm::begin([
'id' => 'user-create-form',
'options' => ['class' => 'form-horizontal'],
]) ?>
<?= $form->field($user, 'username') ?>
...other input fields...
<?= $form->field($profile, 'website') ?>
<?= Html::submitButton('Create', ['class' => 'btn btn-primary']) ?>
<?php ActiveForm::end() ?>
You could replace User
and Profile
with your Client
and Address
.
pinhak
(pinhak)
5
Got it. It was lack of attention. My _form had two ActiveForm::begin