How to save multiple models in one form in Yii2 - yii2

I'm doing a form where I enter the data in two models in a single form. My question is how to record data entry in actionCreate () and call these models in a single form.
These are my inscritoController.php
public function actionCreate()
{
$model = new Inscrito();
$modelEmpresa = new Empresa();
if ($model->load(Yii::$app->request->post()) && $model->load(Yii::$app->request->post()) && $modelEmpresa->save() && $modelEmpresa->save())
{
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'modelEmpresa' => $modelEmpresa,
]);
}
}
And Error:
PHP Notice – yii\base\ErrorException
Undefined variable: modelEmpresa

add this line in your controller
use app\models\Empresa;

Load Yii::$app->request->post() to $modelEmpresa and confirm model call in your controller use app\models\Empresa;
public function actionCreate()
{
$model = new Inscrito();
$modelEmpresa = new Empresa();
if ($model->load(Yii::$app->request->post()) && $modelEmpresa->load(Yii::$app->request->post()) && $model->save() && $modelEmpresa->save())
{
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
'modelEmpresa' => $modelEmpresa,
]);
}
}

Related

Save multiple selections from a listbox - Yii2

I have made a Listbox depend on a dropDownList, when selecting an option from the dropDownList brings me a list of data that is added to the Listbox, it works to save a single option but the problem occurs when trying to save multiple selections, I cannot save more than 1 option, I have tried to add a foreach in my controller but it throws an error.
DropDownList
<?php echo $form->field($model, 'group_id')->widget(Select2::classname(), [
'data' => $seccion->lgrupo, //I get the group list
'size' => Select2::MEDIUM,
'theme' => Select2::THEME_BOOTSTRAP,
'options' => [
'placeholder' => '-- '.Yii::t('backend', 'Select').' --',
'onchange'=>'
$.post( "lists?id="+$(this).val(), function( data ) {//I get the list of people registered in the group and send it to the listbox
$( "select#assignment-user_id" ).html( data );
});',
],
'pluginOptions' => [
'allowClear' => true,
],
'addon' => [
'prepend' => [
'content' => Html::icon('building')
],
]
]); ?>
ListBox
<?php echo $form->field($model2, 'users_id')->listBox([] ,['multiple'=>true,'size'=>17]
); ?>
Groups Controller
public function actionCreate()
{
$model = new Groups();
$model2 = new Assignment();
$seccion = new Group();
if ($model->load(Yii::$app->request->post()) && $model2->load(Yii::$app->request->post())) {
if ($model->save(false)) {
foreach ($model2->users_id as $i => $as) {
$as->assign_group_id = $model->id_group_list;
if ($model2->save()) {
} else {
// error in saving model
}
}
return $this->redirect(['view', 'id' => $model->id_group]);
}
}
return $this->render('create', [
'model' => $model,
'model2' => $model2,
'seccion' => $seccion,
]);
}
Tables
I hope your can tell me what I'm doing wrong.
public function actionCreate()
{
$model = new Groups();
$model2 = new Assignment();
$seccion = new Group();
if ($model->load(Yii::$app->request->post()) && $model2->load(Yii::$app->request->post())) {
if ($model->save(false)) {
foreach ($model2->users_id as $user_id) {
$assignmentModel = new Assignment();
$assignmentModel->user_id= $user_id;
$assignmentModel->assign_group_id = $model->id_group_list;
//$assignmentModel->area= ''; //if you want to set some value to these fields
//$assignmentModel->assignment= '';
if ($assignmentModel->save()) {
} else {
// error in saving model
}
}
return $this->redirect(['view', 'id' => $model->id_group]);
}
}
return $this->render('create', [
'model' => $model,
'model2' => $model2,
'seccion' => $seccion,
]);
}

Records are getting saved even after validation fails in yii2

I have a model Taluka where we are supposed to select district and enter as many talukas.
But the issue is that records are getting saved even if some talukas are empty.
Here is my code:
public function actionCreate()
{
$model = new Taluka();
if ($model->load(Yii::$app->request->post()) ) {
$talukaslist = $model->talukas;
if(is_array($talukaslist))
{
foreach($talukaslist as $taluka)
{
if($taluka == null)
{
return $this->render('create', [
'model' => $model,
]);
}
else
if($taluka!=null)
{
$talukaRecord = new Taluka();
$talukaRecord->DistrictId = $model->DistrictId;
$talukaRecord->Taluka = $taluka;
$talukaRecord->save(false);
}
}
}
return $this->redirect(['index']);
}
else {
return $this->render('create', [
'model' => $model,
]);
}
}

yii2 is not getting id in action after $model->save() and when I click the update item icon

I have a yii2 project, I am developing on my windows localhost and hosting remotely on linux.
Locally (windows) every thing is perfect.
While on linux, I have $model->id = null after $nodel->save(), although data is saved.
public function actionCreate() {
$model = new AppBreakingNews();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
I have tried die($model->id) after the save, it printed null.
Moreover, when I click on the update icon in the grid view, I am facing the same problem.
The AppBreakingNews is as follows:
<?php
namespace app\models\appmodels;
use app\models\BreakingNews;
use yii\behaviors\TimestampBehavior;
class AppBreakingNews extends BreakingNews {
public function behaviors() {
return [
[
'class' => TimestampBehavior::className(),
'createdAtAttribute' => 'created_at',
'updatedAtAttribute' => 'updated_at',
'value' => date('Y-m-d H:i:s'),
],
];
}
}
Notice that appBreakingNews extends the model BreakingNews that is generated by yii2 without any change.
Thanks in advance..
Please try to save model->save(false); because i think it validate something from model file.
public function actionCreate() {
$model = new AppBreakingNews();
if ($model->load(Yii::$app->request->post()) && $model->save(false)) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
or can you please print your model file here.

How to save current user_id to database (YII2)

I try to save current user_id to the education table in database. However,the data of user_id is not filled. This is my code.
At model
public function rules()
{
return [
[['year', 'fieldstudy', 'institute', 'grade'], 'required'],
[['user_id'], 'integer'],
[['year', 'fieldstudy', 'institute', 'grade'], 'string', 'max' => 255],
];
}
public function attributeLabels()
{
return [
'education_id' => 'Education ID',
'user_id' => 'User ID',
'year' => 'Year',
'fieldstudy' => 'Fieldstudy',
'institute' => 'Institute',
'grade' => 'Grade',
];
}
public function getUser()
{
return $this->hasOne(User::className(), ['user_id' => 'user_id']);
}
At controller
public function actionCreate()
{
$model = new Education();
$model->user_id =Yii::$app->user->id;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->education_id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
How can I solve my problem and fix my code? Thanks
update Yii::$app->user->id to Yii::$app->user->identity->id.
public function actionCreate()
{
$model = new Education();
if ($model->load(Yii::$app->request->post())) {
$model->user_id =Yii::$app->user->identity->id;
if($model->save()){
return $this->redirect(['view', 'id' => $model->education_id]);
}
}
return $this->render('create', [
'model' => $model,
]);
}
You have to check two things
Check whether the user is logged in.
Use Yii2 debugger to see whether we are getting the id value of the logged in user by the code Yii::$app->user->id or Yii::$app->user->id
Use Yii2 debugger to check whether the correct user id value we are getting by using the code
Yii::info("User id=".Yii::$app->user->id);
Full code you have to try in the controller is given below
public function actionCreate() {
$model = new Education();
//checking whether we are getting the logged in user id value
Yii::info("User id=".Yii::$app->user->id);
$model->user_id = Yii::$app->user->id;
if ($model->load(Yii::$app->request->post()) && $model->save()) {
//checking here the saved user id value in table
Yii::info("checking User id after saving model=".$model->user_id);
return $this->redirect(['view', 'id' => $model->education_id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Now after running the application you can check using Yii2 debugger the values that are set in the user id in various places.

Can't upload files reliably in Yii2

I got this method that's intended to upload a file, but sometimes it does so when $this->imageFile is not instantiated. I have no idea why.
public function upload()
{
$path = Url::to('#webroot/images/photos/');
$filename = strtolower($this->username) . '.jpg';
$this->imageFile->saveAs($path . $filename);
return true;
}
I call the method upload() in beforeSave() like this:
public function beforeSave($insert)
{
if(parent::beforeSave($insert)){
if($this->isNewRecord)
{
$this->password = Yii::$app->security->generatePasswordHash($this->password);
}
$this->upload();
return true;
}
else
{
return false;
}
}
I called this method like 100 times with mixed results. I have no idea why this method call doesn't give the same result. It should either never work or always work, but for some reason the code is not deterministic at all.
public function actionCreate()
{
$model = new Member();
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
Another thing, when I use this code, I get a file, but the username is blank so I get a .jpeg file without a name.
public function actionCreate()
{
$model = new Member();
$model->imageFile = UploadedFile::getInstance($model, 'imageFile');
$model->upload();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
<?php
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
In the If clause you are redirecting to view and $model disappears between requests naturally. But in else you sending $model to view directly. It looks like the buggy section.
The other one, when you move the $model->upload() to actionCreate, you are placing it before If statement but you are loading the post to the model in if clause so, naturally user wasn't loading when you are trying to upload.
If you are prefer to send $model->upload() to action just be sure to call following method before upload. $model->load(Yii::$app->request->post())