Bad Request (#400) Missing required parameters: id - php

My Controller:
public function actionCreate()
{
$model = new SuratMasuk(['scenario' => 'create']);
if ($model->load(Yii::$app->request->post()))
{
try
{
$picture = UploadedFile::getInstance($model, 'imageFile');
$model->imageFile = $_POST['SuratMasuk']['id_suratmasuk'].'.'.$picture->extension;
if($model->save())
{
$picture->saveAs('uploads/' . $model->id_suratmasuk.'.'.$picture->extension);
Yii::$app->getSession()->setFlash('success','Data saved!');
return $this->redirect(['view','id'=>$model->id_suratmasuk]);
}
else
{
Yii::$app->getSession()->setFlash('error','Data not saved!');
return $this->render('create', [
'model' => $model,
]);
}
}
catch(Exception $e)
{
Yii::$app->getSession()->setFlash('error',"{$e->getMessage()}");
}
}
else
{
return $this->render('create', [
'model' => $model,
]);
}
}
getting this error message when i try to save my post. and it just uploads the text not images. i've tried $model->save(false); but not working
i'm newbie on yii, i'll appreciate your help

I guess this is because you try to pass id here:
return $this->redirect(['view', 'id' => $model->id_suratmasuk]);
and since actionView almost for sure requires id as parameter you get this error because $model->id_suratmasuk is empty.
You need to set proper rules() in SuratMasuk model.
Do not use POST variables directly, this is asking for being hacked.
Do not use save(false) if you need to save anything that comes from user (validation is a must!).
Add rules() for all attributes so there will be no surprises like with this id_suratmasuk being empty.
Check result of saveAs() on UploadedFile instance - this can go false as well.

Related

Check if data exists before posting into the database in yii2

I am trying to check if a book is already in the db to avoid duplication. The code below is popping up for both existing and the one not in the database.
public function actionCreate($book_id = 'book_id')
{
$checkmodel = Books::find()->where(['book_id' => $book_id])->one();
if ($checkmodel) {
Yii::$app->session->setFlash('error', 'The book has been borrowed, Please look for another one.');
return $this->redirect(Yii::$app->request->referrer);
}
$model = new Books();
if ($model->load(Yii::$app->request->post()) && $checkmodel->save()) {
Yii::$app->session->setFlash('Success','You have successfully borrowed the book');
return $this->redirect(['view' => 'book_id', $model->book_id]);
}
return $this->render('create', [
'model' => $model,
]);
}
You could avoid the check adding a proper validation rule in you model
anyway for your code you shou,d try checking for not null $checkmodel
if (!is_null($checkmodel) {
Yii::$app->session->setFlash('error', 'The book has been borrowed, Please look for another one.');
return $this->redirect(Yii::$app->request->referrer);
}
https://www.yiiframework.com/doc/api/2.0/yii-validators-uniquevalidator
https://www.yiiframework.com/doc/guide/2.0/en/input-validation
public function actionCreate($book_id = 'book_id')
{
$model = new Books();
// check if post request
if ( $model->load(Yii::$app->request->post()) ) {
// check if book_id exists in table
if ( ! Books::find()->where(['book_id' => $book_id])->one() ) {
// save new record to model
if ( ! $model->save() ) {
// set error message and redirect to 'create' page
Yii::$app->session->setFlash('Error','There was some error in processing your request');
return $this->redirect(Yii::$app->request->referrer);
}
// if model is saved successfully, redirect to 'view' page
Yii::$app->session->setFlash('Success','You have successfully borrowed the book');
return $this->redirect(['view', 'book_id' => $model->book_id]);
} else {
// if book_id exist in table, show error message
Yii::$app->session->setFlash('error', 'The book has been borrowed, Please look for another one.');
return $this->redirect(Yii::$app->request->referrer);
}
}
return $this->render('create', [
'model' => $model,
]);
}
It's always better to check "false" condition in if statements than true. Helps us write cleaner code.
Also there was a syntax error in your redirect to view statement

`Missing required parameter : id` after a successful update

why did I get this bad request (#400) error after submitting my update on my 'news' section :
Missing required parameters: id
This is my update function
php
public function actionUpdate($id)
{
$model = $this->findModel($id);
$oldFile = $model->getImageFile();
$currentImage=$model->image;
if ($model->load(Yii::$app->request->post())) {
// process uploaded image file instance
$image = $model->uploadImage();
// revert back if no valid file instance uploaded
if ($image === false) {
$model->image = $currentImage;
}
if ($model->save()) {
// upload only if valid uploaded file instance found
if ($image !== false && unlink($oldFile)) { // delete old and overwrite
$path = $model->getImageFile();
$image->saveAs($path);
}
return $this->redirect(['view', ['id'=>$model->id,'image'=>$model->image],
]);
}
} else {
return $this->render('update', [
'model'=>$model,
]);
}
}
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
Please note that the updating and uploading image process were actually a success (that's why I didn't show my model's method code that my actionUpdate called). If I go directly to view the recently updated page and view the content, it clearly displays the updated contents along with the image without problem. The error only occurs just right after the update is submitted. I thought I had pass the parameter after the update by this line :
return $this->redirect(['view', ['id'=>$model->id,'image'=>$model->image],
Right before that line I even echo $model->id to test and it echoed out the id.
I've looked for similar problem in StackOverflow and find someone suggested this :
php
if($model->save())
{
$lastInsertID = $model->getPrimaryKey();
return $this->redirect(['view', 'id' => $lastInsertID]);
}
But it didn't work. Any idea?
You should pass URL as flat array:
return $this->redirect(['view', 'id' => $model->id,'image' => $model->image]);

Laravel 5.1 Form Validation Redirect With Input Problems

I've a problem with Laravel 5.1 Redirect With Input. I can't seem to get old values from submitted input.
I've been research for any post in stack overflow and still stuck in this problem.
This is my request controller
public function create() {
$this->data["pageDescription"] = "Add new page.";
$this->data["pageSubtitle"] = $this->data["pageTitle"] . " Add New";
$this->data["formAction"] = adminRoute("page");
return view("admin.page.form")->with("data", $this->data)->withInput(Input::old());
}
and this is my submitted controller
public function store(Request $request) {
Input::flash();
$validator = Validator::make($request->all(), [
"title" => "required|max:100",
"url_title" => "required|max:100",
"meta_description" => "required|max:50",
"content_title" => "required|max:100",
"content_description_id" => "required",
"status" => "required|in:pending,published",
"add_more_content" => "required|in:true,false"
]);
if($validator->fails()) {
return redirect()->back()
->with("data", $this->data)
->withErrors($validator)
->withInput();
} else {
return redirect()->back()->withInput();
}
}
It's kinda weird because when I dump Session::all() before I redirect()->back() the _old_input is exists
But when I dump Session::all() on my function create() the _old_input is empty.
Even when I skip the validation, and use
redirect()->back()->withInput();
I still got the same problem, the old values input empty
This is my form view
Anybody know what I am doing it wrong?
Thank youu
Did you get validation error? I'm not 100% sure, but I think redirect()->back() calls to the GET method of your form.

Yii2 submit data with link

I'm writing simple shopping app and I have some issues with the add to cart link
I'm passing al the same parameter that were on Yii's default Crud form via get and i want to save them in database. Sad thing is when I tried to simply get 'post' to 'get' like this: its not working
if ($model->load(Yii::$app->request->get()) && $model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
I think I am missing something very simple but I'm rather new to this so any help will be appreciated.
Oh well i fixed that :D
public function actionCreate()
{
$model = new Koszyk();
$model->setAttributes($_GET);
if ($model->save()) {
return $this->redirect(['view', 'id' => $model->id]);
}
else {
$m =$_GET;
return $this->render('create', [
'model' => $model,'param'=>$m
]);
}
}

Yii framework. Can't save model

I have problem with Yii. I have following code in controller:
...
$user = User::model()->find("user_id = :id AND type='1'", array('id'=>$user->id));
$user->time=new CDbExpression('NOW()');
$user->status=1;
$user->save();
...
And Im getting this error:
Call to undefined method stdClass::save()
What's wrong?
oo i see you need to test if you have a user
just do :
if($user)
is your model extand a CactiveRecord ?
you should display the errors to know what's wrong
if(!$user->save()){
var_dump($user->getErrors());
}
this will be helpfull
Your error is to classic to knwo exactly what went wrong! here's a problem that could be the reason of your error:
When you find your user, if it doesn't find it the method will return false then the rest of the operations will fail. You should perform something like:
$user = User::model()->find("user_id = :id AND type='1'", array('id'=>$user->id));
if($user !== null) {
$user->time=new CDbExpression('NOW()');
$user->status=1;
$user->save();
}
if ($model->load(Yii::$app->request->post())) {
$model->startDate = $modifiedStartDate;
$model->timeFrom = $modifiedFromTime;
$model->timeTo = $modifiedToTime;
//echo '<pre>';
//print_r($model);exit;
$model->save();
//return $this->redirect(['view', 'id' => $model->id]);
return $this->redirect(['timelog/index']);
} else {
return $this->render('create',
[
'model' => $model,
]);
}
//why the error occurs while using the $method->save(); function.

Categories