data is not inserted if not exist using save() - php

I am facing a problem with insert data using save(). using save() i successfully update data.but when the data is not exist in database with perticular id it not insert data.
controller :
public function actionContact()
{
//$profile=new Profile();
$id=YII::$app->user->id;
//$users=User::find()->where('id='.$id)->one();
//$profiles=Profile::find()->where('user_id='.$id)->one();
$this->layout="profile";
$profile=$this->findModel1($id);
$data=Yii::$app->request->post();
if($data && $profile->validate()){
$profile->mobile=Yii::$app->request->post('mobile');
$profile->city=Yii::$app->request->post('city');
$profile->zip=Yii::$app->request->post('zip');
$profile->address=Yii::$app->request->post('zip');
$profile->save();
Yii::$app->session->setFlash("Contact-success", Yii::t("user", "Contact updated"));
return $this->refresh();
}
return $this->redirect(['/users/edit']);
}
Any solution will highly appriciated.

$profile=$this->findModel1($id);
if there is no object found.
if(empty($profile)){
$profile = new Profile();
}

I think you can check this way.
$profile=$this->findModel1($id);
if($profile == null)
{
$profile = new Profile();
}
In this i have checked if model is null then create new model object. and then it performs save.

Related

Update form Cakephp 3

I am currently working on a project using cakephp 3.
I have a form to add clients which works using this in my controller :
public function add(){
$clients = $this->Clients->newEntity();
if($this->request->is('post')){
$clients = $this->Clients->patchEntity($clients, $this->request->data);
if($this->Clients->save($clients)){
$this->Flash->success(__('Client has been created.'));
return $this->redirect(['controller'=>'Clients','action'=>'index']);
}
$this->Flash->error(__('Client hasnt been created.'));
}
$this->set('clients',$clients);
}
Then I want to have the possibility to modify one of my client.
I have a table of clients and when I click on of them, I have a modify button coming (jQuery).
Then I'm on my modify page. I did some test with the doc from cake but it seems I don't understand how it works and what tools should I use.
For the moment, I have this on my Controller:
public function modify($id = null){
if(empty($id)){
throw new NotFoundException;
}
$clients = $this->Clients->get($id);
/* there should be the modify code */
$this->set('clients', $clients);
}
I don't really know what to use as I said... Any help pls?
The code for editing a record is quite straight forward:
public function modify($id = null){
if(empty($id)){
throw new NotFoundException;
}
$client = $this->Clients->get($id);
if ($this->request->is(['post', 'put']) {
$client = $this->Clients->patchEntity($client, $this->request->data);
if ($this->Clients->save($client)) {
return $this->redirect($someURL);
}
}
$this->set('client', $client);
}

Check if laravel model got saved or query got executed

I've seen alot of people using this way to check if a laravel model got saved. So now I wonder if it is a safe way.
And also can I check if the queries bellow got executed like this
Check if model got saved
Eg:
$myModel = new User();
$myModel->firstname = Input::get('firstname');
$myModel->lastname = Input::get('lastname');
$myModel->save();
//Check if user got saved
if ( ! $myModel->save())
{
App::abort(500, 'Error');
}
//User got saved show OK message
return Response::json(array('success' => true, 'user_added' => 1), 200);
Is the above a safe way to check whenever my model got saved or not?
Check if query returned a result
Eg:
$UserProduct = Product::where('seller_id', '=', $userId)->first();
if (! $UserProduct)
{
App::abort(401); //Error
}
Does above return an error if no product where found?
Check if query got executed
Eg:
$newUser = User::create([
'username' => Input::get('username'),
'email' => Input::get('email')
]);
//Check if user was created
if ( ! $newUser)
{
App::abort(500, 'Some Error');
}
//User was created show OK message
return Response::json(array('success' => true, 'user_created' => 1), 200);
Does above check if a user was created?
Check if model got saved
save() will return a boolean, saved or not saved. So you can either do:
$saved = $myModel->save();
if(!$saved){
App::abort(500, 'Error');
}
Or directly save in the if:
if(!$myModel->save()){
App::abort(500, 'Error');
}
Note that it doesn't make sense to call save() two times in a row like in your example. And by the way, many errors or problems that would keep the model from being saved will throw an exception anyways...
Check if query returned a result
first() will return null when no record is found so your check works find. However as alternative you could also use firstOrFail() which will automatically throw a ModelNotFoundException when nothing is found:
$UserProduct = Product::where('seller_id', '=', $userId)->firstOrFail();
(The same is true for find() and findOrFail())
Check if query got executed
Unfortunately with create it's not that easy. Here's the source:
public static function create(array $attributes)
{
$model = new static($attributes);
$model->save();
return $model;
}
As you can see it will create a new instance of the model with the $attributes and then call save(). Now if save() where to return true you wouldn't know because you'd get a model instance anyways. What you could do for example is check for the models id (since that's only available after the record is saved and the newly created id is returned)
if(!$newUser->id){
App::abort(500, 'Some Error');
}
You can also check the public attribute $exists on your model.
if ($myModel->exists) {
// Model exists in the database
}
I would do such move to when I use Model::create method :
$activity = Activity::create($data);
if ($activity->exists) {
// success
} else {
// failure
}
As for the Save method it's easier because $model->save() returns Bool :
$category = new Category();
$category->category_name = $request->category_name;
$is_saved = $category->save();
if ($is_saved) {
// success
} else {
// failure
}
/**
* Store a newly created country in storage.
*
* #url /country
* #method POST
* #param Request $request
* #return \Illuminate\Http\JsonResponse
*/
public function store(Request $request)
{
# Filer & only get specific parameters.
$request = $request->only('code', 'name', 'status');
# Assign login user(Auth Control).
$request['created_by'] = Auth::user()->id;
# Insert data into `countries` table.
$country = Country::create($request);
if(!$country)
throw new Exception('Error in saving data.');
}

Cannot edit particular user data with user id by form using yii framework

I am new in YII framework. I am doing update operation using YII framework. I have controller with name sitecontroller.php, model jobseekerprofile.php, view personal.php.
I got the error:
Fatal error: Call to a member function isAttributeRequired() on a non-object in E:\wamp\www\yii\framework\web\helpers\CHtml.php on line 1414
My table is job_seeker_profile
Fields
1.id
2.user_id
3.contact_no
4.gender
5.dob
6.mstatus
7.address
8.location_id
I want to edit the data in contact_no and address according to user_id
Model-Jobseekerprofile.php - rules
public function rules()
{
return array(
array('contact_no,address','required'),
);
}
controller-Sitecontroller.php
class SiteController extends Controller {
public function actionpersonal()
{
$user_id = trim($_GET['id']);
$model=Jobseekerprofile::model()->find(array(
'select'=>'contact_no,address',"condition"=>"user_id=$user_id",
'limit'=>1,));
$model = Jobseekerprofile::model()->findByPk($user_id);
if(isset($_POST['Jobseekerprofile']))
{
$model->attributes=$_POST['Jobseekerprofile'];
if($model->save())
{
$this->redirect(array('profile','user_id'=>$model->user_id));
}
}
$this->render('personal',array('model' =>$model));
}
}
Anybody help me?
Seems that $model = Jobseekerprofile::model()->findByPk($user_id) is not finding anything, so $model is null, and that is why $model->isAttributeRequired() throws an error. Check your incoming params because of this and check if there a profile with such id (or maybe you should search by attributes instead of by id?).
Besides you can use
public function actionPersonal($id) {
$model = Jobseekerprofile::model()->findByPk($id);
//
}
Instead of
public function actionpersonal() {
$user_id = trim($_GET['id']);
$model = Jobseekerprofile::model()->findByPk($user_id);
//
}
public function actionpersonal() {
$user_id = trim($_GET['id']);
$model = Jobseekerprofile::model()->findByPk($user_id);
if (isset($_POST['Jobseekerprofile'])) {
$model->attributes = $_POST['Jobseekerprofile']; //post key edited
if ($model->save()) {
$this->redirect(array('profile', 'user_id' => $model->user_id));
}
}
$this->render('personal', array('model' => $model));
}
First Check what you are getting in $_POST
and if all is ok then try to save like
$model = Jobseekerprofile::model()->findByPk($user_id);
if (isset($_POST['Jobseekerprofile'])) {
$model->attributes = $_POST['jobseekerprofile'];
$model->contact_no= $_POST['Jobseekerprofile']['contact_no']; //post key edited
$model->address = $_POST['Jobseekerprofile']['address'];
if ($model->save()) {
$this->redirect(array('profile', 'user_id' => $model->user_id));
}
}
$this->render('personal', array('model' => $model));
if not work then check what model returns
$error=$model->getErrors();
print_r($error);
above code surely gives you idea why it is not saving

CakePHP Security - Prevent Form Injection

I currently have 1 table, Users which looks like this
|**id**|**username**|**password**|**role**|**email**|
I'm using CakePHP's form helper to automatically fill in editable form fields. I'm creating an edit page in which users can change there username/password/email, but should NOT be able to change their role. I'm currently checking to make sure the user hasn't injected a role POST field into the request and was wondering if there is any better way to do this? It's trivial in this scenario with such a small table, but I can see this becoming tiresome on fields/tables with a large amount of columns. My current edit action looks like this.
public function edit($id = null)
{
$this->User->id = $id;
if(!$this->User->exists())
{
throw new NotFoundException('Invalid user');
}
$userToEdit = $this->User->findById($id);
if(!$userToEdit)
{
throw new NotFoundException('Invalid user');
}
if($this->getUserRole() != 'admin' && $userToEdit['User']['owner'] != $this->Auth->user('id'))
{
throw new ForbiddenException("You do not have permission to edit this user");
}
if($this->request->is('post') || $this->request->is('put'))
{
//Do not reset password if empty
if(empty($this->request->data['User']['password']))
unset($this->request->data['User']['password']);
if(isset($this->request->data['User']['role']))
unset($this->request->data['User']['role']);
if($this->User->save($this->request->data))
{
$this->set('success', true);
}
else
$this->set('success', false);
}
else
{
$this->request->data = $this->User->read();
//Prevent formhelper from displaying hashed password.
unset($this->request->data['User']['password']);
}
}
The third parameter of save() method lets you to define the list of fields to save. Model::save() docs
$this->User->id = $this->Auth->user('id');
$this->User->save($this->request->data, true, array('username', 'email'))

Can't get doctrine-generated form to update entity

I've created an entity that I can't update using doctrine-generated form. Here's an action:
public function executeEdit(sfWebRequest $request)
{
$this->forward404Unless($id = $request->getParameter('id'), "Required parameter 'id' must be present in request");
$this->forward404Unless($cart = Doctrine::getTable('ShoppingCart')->find($id), sprintf("No object could be retrieved by %s", $id));
$this->id = $id;
$this->form = new ShoppingCartForm($cart);
if($request->isMethod(sfRequest::POST)) {
$this->form->bind($request->getParameter('shopping_cart'));
if ($this->form->isValid())
{
$cart = $this->form->save();
$this->redirect(link_to('cart/show?id='.$cart->getId()));
}
}
}
Form's isNew() method returns false, but the sf_method is set to PUT. When I use sfRequest::PUT doctrine tries to add new entity with that id. It seems like it shouldn't behave like that so what I am doing wrong?

Categories