Yii framework. Can't save model - php

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.

Related

How to solve Trying to get property of non-object in Laravel

I'm a beginner web developer
I'm trying to write a condition that will be fulfilled depending on what data the user will send
Condition if fulfilled by one hundred percent
But the condition else produces an error with the following text
Trying to get property 'unique_id' of non-object
If someone have info how to solv this problem I will be grateful
This is my code from controller
public function checkRestorePassword(Request $request)
{
$result['success'] = false;
$rules = [
'unique_id' => 'required',
];
$validation = Validator::make($request->all(), $rules);
if (empty($validation))
{
$result['error'] = "Enter the code that was sent to you by mail.";
return response()->json($result, 422);
}
$user = User::where('unique_id', $request->uniqueId)->first();
if ($user->unique_id === $request->uniqueId)
{
$result['success'] = 'Access to your personal account successfully restored. Please change your password.';
return response()->json($result, 200);
}
else
{
$result['success'] = false;
return response()->json($result, 422);
}
}
I think it's because $user is returning null.
so do this
if (!is_null($user) && $user->unique_id === $request->uniqueId)

how to check if data already exist when insert data

I want to ask how to to check the data if we input data if there is the same data that cannot be inserted.
My code:
$obj = new Pengajuan();
// $obj->id_pengajuan = $req->input('kode');
$obj->id_nasabah = $req->input('id_nasabah');
$obj->tgl_pengajuan = $req->input('tgl_pengajuan');
$obj->besar_pinjaman = $req->input('besar_pinjaman');
$obj->status = $req->input('status');
$simpan = $obj->save();
if ($simpan == 1) {
$status = "Tersmpan";
} else {
$status = "Gagal";
}
echo json_encode(array("status" => $status));
Above of the code add a validation like below:
$this->validate([
'id_nasabah' =>'unique:pengajuans'
]) ;
And then rest of your controller code.
try this:
public function store(Request $request)
{
$this->validate($request,[
'id_nasabah'=>'required|exists:your_table_name,id',
'tgl_pengajuan'=>'more_validations',
'besar_pinjaman'=>'more_validations',
]);
//if $this->validate() fails, it will return a response 422 code error
//else it will continue with the creation of your object
//is a good idea to use a try-catch in case of something goes wrong
try
{
$pengajuan=Pengajuan::create($request->only('id_nasabah','tgl_pengajuan','besar_pinjaman'));
return response->json([
'pengajuan'=>$pengajuan,
'status'=>'Tersmpan',
],200);//return a http code 200 ok
}
catch(Exception $e)
{
//'message'=>'this will return what is the error and line'
return response()->json([
'message'=>$e->getMessage().'/'.$e->getLine(),
'status'=>'Gagal',
],422);
}
}

strpos() expects parameter 1 to be string, object given laravel 5.5

This is my code:
public function getLists(Request $request)
{
$user = $request->user()->id;
$apikey = DB::table('apikey')->where('api_key', '=', $user);
if($apikey){
$mc = new MailChimp($apikey);
$mailchimp_ping = $mc->get('lists',['fields' =>
'lists.id,lists.name']);
return Response::json($mailchimp_ping, 200);
}
else
{
$errorResponse = [
'message' => 'Lists not found!',
'error' => '401'
];
return Response::json( $errorResponse);
}
}
I am trying to get mailchimp list based on logged in user id where i am doing wrong? is my where clause expects something else?
Any help would be highly appreciated!
Use the value() method to execute the query and get the key. For example, if a column with key is called apikey:
$apikey = DB::table('apikey')->where('api_key', $user)->value('apikey');
In my case this error came up when changed this:
Route::view('/report', '/main_pages/orders_parts/report')->name('guzorishi_order_1');
to
Route::get('/report/{order_id}', function ($order_id) {... })->name('guzorishi_order_1');
but forgot Route::view one
rename to Route::get

Bad Request (#400) Missing required parameters: id

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.

Yii2; code running in "else" block first, and then running code before "if" block?

I'm completely lost as to why this is happening, and it happens about 50% of the time.
I have a check to see if a user exists by email and last name, and if they do, run some code. If the user doesn't exist, then create the user, and then run some code.
I've done various testing with dummy data, and even if a user doesn't exist, it first creates them, but then runs the code in the "if" block.
Here's what I have.
if (User::existsByEmailAndLastName($params->email, $params->lastName)) {
var_dump('user already exists');
} else {
User::createNew($params);
var_dump("Creating a new user...");
}
And here are the respective methods:
public static function existsByEmailAndLastName($email, $lastName) {
return User::find()->where([
'email' => $email,
])->andWhere([
'last_name' => $lastName
])->one();
}
public static function createNew($params) {
$user = new User;
$user->first_name = $params->firstName;
$user->last_name = $params->lastName;
$user->email = $params->email;
$user->address = $params->address;
$user->address_2 = $params->address_2;
$user->city = $params->city;
$user->province = $params->province;
$user->country = $params->country;
$user->phone = $params->phone;
$user->postal_code = $params->postal_code;
return $user->insert();
}
I've tried flushing the cache. I've tried it with raw SQL queries using Yii::$app->db->createCommand(), but nothing seems to be working. I'm totally stumped.
Does anyone know why it would first create the user, and then do the check in the if statement?
Editing with controller code:
public function actionComplete()
{
if (Yii::$app->basket->isEmpty()) {
return $this->redirect('basket', 302);
}
$guest = Yii::$app->request->get('guest');
$params = new CompletePaymentForm;
$post = Yii::$app->request->post();
if ($this->userInfo || $guest) {
if ($params->load($post) && $params->validate()) {
if (!User::isEmailValid($params->email)) {
throw new UserException('Please provide a valid email.');
}
if (!User::existsByEmailAndLastName($params->email, $params->lastName)) {
User::createNew($params);
echo "creating new user";
} else {
echo "user already exists";
}
}
return $this->render('complete', [
'model' => $completeDonationForm
]);
}
return $this->render('complete-login-or-guest');
}
Here's the answer after multiple tries:
Passing an 'ajaxParam' parameters with the ActiveForm widget to define the name of the GET parameter that will be sent if the request is an ajax request. I named my parameter "ajax".
Here's what the beginning of the ActiveForm looks like:
$form = ActiveForm::begin([
'id' => 'complete-form',
'ajaxParam' => 'ajax'
])
And then I added this check in my controller:
if (Yii::$app->request->get('ajax') || Yii::$app->request->isAjax) {
return false;
}
It was an ajax issue, so thanks a bunch to Yupik for pointing me towards it (accepting his answer since it lead me here).
You can put validation like below in your model:
public function rules() { return [ [['email'], 'functionName'], [['lastname'], 'functionforlastName'], ];}
public function functionName($attribute, $params) {
$usercheck=User::find()->where(['email' => $email])->one();
if($usercheck)
{
$this->addError($attribute, 'Email already exists!');
}
}
and create/apply same function for lastname.
put in form fields email and lastname => ['enableAjaxValidation' => true]
In Create function in controller
use yii\web\Response;
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
else if ($model->load(Yii::$app->request->post()))
{
//place your code here
}
Add 'enableAjaxValidation' => false to your ActiveForm params in view. It happens because yii sends request to your action to validate this model, but it's not handled before your if statement.

Categories