Yii update profile page - php

i created a update profile page.
i have this in the controller to populate the form and also handle update:
$user = User::model()->findByPk(Yii::app()->user->id);
// Collect user input
if (isset($_POST['User'])) {
$user->attributes = $_POST['User'];
if ($user->save()) {
echo "update successfully";
}
else {
echo "update failed";
}
}
// View
$this->render('user_view', array('user'=>$user,));
however, this doesn't work. although $user->save is true, the record is not updated in the database. i've also check that $_POST['User'] is returning the updated data but $user->attributes is not saving them.
why is that so?

You need to set which model attributes are "safe" for "massive assignments". Read more about this here.
The mass attribute assignment $user->attributes will only assign to variables with validation rules. Just give the name attribute a rule, even if it's just the "safe" validator.
public function rules()
{
return array(
array('name', 'safe')
);
}
I'm pretty sure this is the problem you are having, it's happened to me!

Related

php cake Auth inside class

I need to check if a user is existing in the mgrUser table. now the propblem is the controller is in the adminController while the model is in the mgrUserModel. how do i use Auth for this? Thats the reason why I made a generic login code.
public function login() {
// if ($this->Auth->login()) {
// return $this->redirect($this->Auth->redirectUrl());
// }
// $this->Flash->error(
// __('Username ou password incorrect')
// );
//since the model is in a different view, I needed to includ the mgrModel and create a generic login
//will revamp the code to fit the built in Aut code for php cake
if(isset($_POST['submit'])) {
$User_ID = htmlspecialchars($_POST['user_id']);
$Pass = htmlspecialchars($_POST['pass']);
try {
$mgrUserModel = new MgrUser();
$isValid = $mgrUserModel->find('first', array(
'conditions' => array("user_id" => $User_ID)
));
if($isValid != null){
if (($isValid['MgrUser']['pass']) == $Pass) {
//this doesnot work
$this->Auth->allow();
$this->redirect($this->Auth->redirectUrl());
}
else{
}
}
} catch (Exception $e) {
//echo "not logged in";
}
// this echo will show the id and pass that was taken based on the user_id and pass that the user will input
//for testing only
// echo $isValid2['MgrUser']['id'];
// echo $isValid2['MgrUser']['pass'];
}
}
You need double == to compare things,
function checkMe()
{
if($user == 'me'){
$this->Auth->allow('detail');
}
}
what you did was assign "me" string to variable $user which always returns true because assignment was possible
Anyway you should use it in beforeFilter which is running before every action from this controller, which makes much more sense
public function beforeFilter() {
parent::beforeFilter();
if($user == 'me'){
$this->Auth->allow('detail');
}
}
the Auth component could be configured to read the user information via another userModel (The model name of the users table). It defaults to Users.
please consult the book for appropriate cakephp version: https://book.cakephp.org/3.0/en/controllers/components/authentication.html#configuring-authentication-handlers

Update existing record in CakePHP

I want to create the following in CakePHP:
Starting page: User enters a loginname which pre exists in the DB. Table name loginname.
Once the user has entered the right loginname, the user continues to the registration form, where the user can add personal data to the existing record.
When the user saves the form, the record with only the loginname has personal data added.
This is what i have:
Logic for starting page:
public function checkCodeRespondent() {
//set var
$password = $this->data['Respondent']['loginname'];
//set condition for hasAny function
$condition = array('Respondent.loginname'=>$password);
//if password matches continue to registreer
if($this->Respondent->hasAny($condition)){
//find data by password
$respondent = $this->findByPass($password);
//set var for current id
$id= $respondent['Respondent']['id'];
//redirect with current id
$this->redirect(array('action' => 'aanmelden', $id));
} else {
//if password does not match, return to index with errormessage
$this->redirect(array('action' => 'index'));
}
}
public function findByPass($pass) {
$respondent = $this->Respondent->find('first', array('conditions' => array('pass' => $pass)));
return $respondent;
}
And this is the logic for saving the data to the record:
public function registreren() {
if($this->request->isPost()) {
$this->Respondent->id = $id;
if ($this->Respondent->save($this->request->data)){
$this->Flash->success(__('Your post has been saved.'));
return $this->redirect(array('action' => 'index'));
} else {
}
}
I thought i got my id through the function checkCodeRespondent() , but that's not working. What am i forgetting or what am i doing wrong? If i need to give more info, i'm happy to help ofcourse.
Update: I read that i need to add echo $form->input('id');, only when i debug($this->request); the id value is empty. What do i need to change in my code?
If you have added hidden field for id then just replace:
$this->Respondent->id = $id;
By:
$this->Respondent->id = $this->request->data['Respondent']['id'];
And in your view, give name="data[Respondent][id]" in the hidden field of id like:
<input type="hidden" name="data[Respondent][id]" value="value of id">
that should work fine for you if no other issues out there.

Laravel saving post variable when there is validation error?

I am using laravel 4 , and I have a form with checkboxes and on sumbitting the form , it goes through the validation error process, if there is error how do I make it save the post values of these check boxes?
AdminRolesController:
public function postActions($action = NULL) {
// Allowed post actions..
$allowed = array('add', 'edit');
$action = in_array($action, $allowed) ? $action : NULL;
// check if action is not null
if(is_null($action))
return Redirect::to('admin/roles');
else
{
// POST ACTION
if($action == "add")
{
// put all your rules.
$rules = array(
'name'=>'required|regex:/^[a-zA-Z ]*$/|min:2',
'permission_ids' =>'required'
);
// run the validation rules on the inputs from the form
$validator = Validator::make(Input::all(), $rules);
// get all permissions or groups available
$perms = Permissions::all();
// share it to the view
// we have two parts of permissions ( 0 , 1)
// 0 : Admin Group Pages , 1: Front End Pages
View::share('perms', $perms);
if ($validator->passes())
{
// validation has passed, save user in DB
// create instance of our model..
// create a new role
$role = new Role;
$role->name = Input::get('name');
$permission_ids = Input::get('permission_ids');
// save info to db.
$role->save();
$msg = 'Role '.$role->name.' has been added';
}// end validation if
else
{
// validation has failed, display error messages
return Redirect::back()->with('message', 'The following errors occurred:')->withErrors($validator)->withInput();
}
}// end if add
}
}
I think part of the problem me redirecting with error messages , all the post values is lost , how could I still keep them?
Thanks
Your controller looks fine - all that's required to do to pass input back to the view is chaining ->withInput()
However, in your views, ensure you're populating the form using the old input values. You can do so, using Blade, by doing something like:
{{ Form::checkbox('permission_id', 'value', Input::old('permission_id)) }}

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'))

Codeigniter form post and validation

I'm not a pro, but know my way around PHP, I'm new to Codeigniter.
Been going through these tutorials: http://net.tutsplus.com/articles/news/codeigniter-from-scratch-day-5-crud/
OK, so I have a page that lists users, clicking on users name will go to an edit page, the url of that page being: index.php/users/edit/1 (where 1 is the users id)
On edit page is a form, this form contains a few parts, each part is populated from different tables in the DB. So my Controller for edit is as follows:
function edit() {
//load model
$this->load->model('users_model');
//assign user data from DB
$data['data_user'] = $this->users_model->getUser($this->uri->segment(3));
//get users Password, using username from above
$data['data_user_password']= $this->users_model->getUserPassword($data['data_user'][0]->UserName);
$data['page_content'] = 'pages/users_edit';
$this->load->view('template/template', $data);
}
Notice:
$data['data_user'] contains users data like name, username, email
$data['data_user_password'] contains users password from a different table
I can then populate the form, on users_edit.php, this all works fine.
I'm accessing this data by doing the following:
if (is_array($data_user)) {
foreach($data_user as $user)
{
$userID = $user->id;
$userName = $user->Name;
$userUserName = $user->UserName;
$userMail = $user->Mail;
$userDepartment = $user->Department;
$userWorkPhone = $user->WorkPhone;
$userHomePhone = $user->HomePhone;
$userMobile = $user->Mobile;
}
}
//user password
if (is_array($data_user_password)) {
foreach($data_user_password as $user)
{
$userPassword = $user->value;
}
}
Name:
<?php echo form_input('name', set_value('name', $userName), 'id="name" class="inputLong"'); ?>
When I post, I'm sending data to: index.php/users/update
My controller for this page so far is:
function update() {
echo '<pre>';
print_r($_POST);
echo '</pre>';
//exit();
$this->load->library('form_validation');
$this->form_validation->set_rules('name', 'Name', 'trim|required');
if ($this->form_validation->run() == FALSE)
{
$this->load->view('pages/users_edit');
}
else
{
$this->index();
}
}
For now, I'm just testing validation on users "name" where form input=name id=name
I think I'm not handling the if ($this->form_validation->run() == FALSE) part of it correctly, if the form contains data, it passes and redirects to index, if I leave name blank it either not handling the edit page correctly, or I dont know, something isnt right.. I think its because the page is being reloaded using the post array, and not passing the $data like I did in function edit().
Back to the form page, where it should be showing the validation_errors, its showing:
The Name field is required.
This is correct, however, for the rest of the fields that should be pre-populated, its showing PHP error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: userUserName
Filename: pages/users_edit.php
Line Number: 50
You could do your validation inside your edit function instead of having an update function, that way, your data is still available for your view and if the validation has errors, codeigniter will take in charge to repopulate your fields. If the validation is ok, you do your next step
function edit() {
//load model
$this->load->model('users_model');
//assign user data from DB
$data['data_user'] = $this->users_model->getUser($this->uri->segment(3));
//get users Password, using username from above
$data['data_user_password']= $this->users_model->getUserPassword($data['data_user'][0]->UserName);
$data['page_content'] = 'pages/users_edit';
$this->load->view('template/template', $data);
//is the form submitted
if(form submit){
if ($this->form_validation->run() == TRUE)
{
$this->index();
}
else
{
$this->load->view('pages/users_edit', $data);
}
}
}
$this->load->view('pages/users_edit');
Inside your function update(), after your validation you load view but you don't PASS any data variables to it. So you don't have any variables which you can access at your view file..
You have to set your variables the same way as in your function edit():
$this->load->view('template/template', $data);
Currently there is not set variable $data_user so you can't loop it and use it..

Categories