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

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.

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,
]);
}

Yii2 upload multiple success but save only first value to database

I'm coding a multiple upload function for my website. The upload was successful. But it's only save the first value to my database. Example i upload 3 files name 1.jpg, 2.jpg, 3.jpg. Then it will upload the 3 files successfully but save only the 1.jpg's name to database.
My controllers
public function actionCreate()
{
$model = new Resource3d();
if ($model->load(Yii::$app->request->post())) {
$model->files = UploadedFile::getInstances($model, 'files');
foreach ($model->files as $files){
$files->saveAs('uploads/resource3d/' . $files->baseName . $files->extension);
$model->path = '../web/uploads/resource3d/'. $files->baseName . $files->extension;
$model->name = $files->baseName;
$model->save();
}
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
My models:
public $files;
public function rules()
{
return [
[['name', 'path'], 'string', 'max' => 255],
[['files'], 'file', 'skipOnEmpty' => false, 'maxFiles' => 0],
];
}
Please help.
Thank you.
You are creating single object of your model Resource3d. You need to create multiple object if you want to save multiple records.
Try this :
public function actionCreate()
{
$model = new Resource3d();
if ($model->load(Yii::$app->request->post())) {
$model->files = UploadedFile::getInstances($model, 'files');
foreach ($model->files as $files){
$res_model = new Resource3d();
$res_model->load(Yii::$app->request->post());
$files->saveAs('uploads/resource3d/' . $files->baseName . $files->extension);
$res_model->path = '../web/uploads/resource3d/'. $files->baseName . $files->extension;
$res_model->name = $files->baseName;
$res_model->save();
}
return $this->redirect(['index']);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
This is just an example, change it according to your need.

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.

How to save multiple models in one form in 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,
]);
}
}

Yii2 Gii generated create view not working / saving but update does

Just started with Yii (two weeks ago).
TL;DR
Creating through Gii generated views not working, but update does, even they share the form and controller not edited.
Problem:
I use the Yii2 advanced app template.
Then I generated a model through the model generator and controller/views through the CRUD generator.
The only thing I changed is removing the two datetime fields "created_at" and "created_by" from the form and added a TimestampBehavior:
public function behaviors()
{
return [
[
'class' => TimestampBehavior::className(),
'attributes' => [
ActiveRecord::EVENT_BEFORE_INSERT => ['created_at', 'updated_at'],
ActiveRecord::EVENT_BEFORE_UPDATE => ['updated_at'],
],
// if you're using datetime instead of UNIX timestamp:
'value' => new Expression('NOW()'),
],
];
}
The strange case I have is, that the update is working, but the create not. It shows no error, it just stay on the page or renders it newly?
This is the untouched code from the controller:
(Am I getting it right that the "$model->save" in the if should save it to the databse?)
CREATE:
public function actionCreate()
{
$model = new Seminar();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
UPDATE:
public function actionUpdate($id)
{
$model = $this->findModel($id);
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
}
If further informations are needed please comment.
Thanks.
UPDATE - Solution
After the two helpful answers I tried dump the error and it shows
array(1) { ["created_at"]=> array(1) { [0]=> string(32) "Created At darf nicht leer sein." } }
As suggested I left the "created_at" in the "required" section of the rules. After cleaning it out the create works.
I think it did not show me the error because I deleted the field in the form, since the user should not enter data dirctly.
The Controllers you showed are ok.
There must be something wrong with the model. You can check what the problem is by editing the actionCreate:
public function actionCreate()
{
$model = new Seminar();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
} else {
var_dump($model->getErrors());
/*return $this->render('create', [
'model' => $model,
]);*/
}
}
Now, about your changes: since you are using the column names created_at and updated_at you can simplify the behavior by setting:
public function behaviors()
{
return [
TimestampBehavior::className()
];
};
Also, check your model rules() if the fields created_at or updated_at are there, and remove it. They are not needed anymore.
Check the rules in your model and try again. Also, try with $model->save(false). It will save the form without check validation, so the problem is that data doesn't validate.