4webby web applications
27
Mar 2007

FreakAuth_light: custom userprofile - PART 2

FreakAuth_light: custom userprofile - PART 2 is a follow up of the first part of this tutorial about FreakAuth_light custom userprofile functionality. Now we will build a frontend controller/views to display the profile of our users an to allow the owners of the profile to edit it.

If you missed part one please go to FreakAuth_light: custom userprofile - PART 1

Again I  assume you have already installed both CI 1.5.2 and FreakAuth_light 1.0.2-Beta and that you are a bit familiar with them.

If you wanna play with custom userprofile in FreakAuth_light you should also have it enable in the FreakAith_light configuration:

application/config/freakauth_light.php
  1. //...
  2.  
  3. //TRUE/FALSE (boolean).  Whether to use custom user profile
  4. $config['FAL_create_user_profile'] = TRUE;   
  5.  
  6. //..

The source code for this tutorial is available for download in the download section. Look for the file tutorial_custom_userprofile_part2.zip

I'll call the controller to handle the userprofile visualization/editing myaccount.Before strating we need to add a couple of lines in our application/config/routes.php.

application/config/routes.php
  1. //...
  2. $route['myaccount/show/:num'] = "myaccount/show";
  3. $route['myaccount/edit/:num'] = "myaccount/edit";
  4. //...

 

DISPLAYING USER PROFILES TO EVERYBODY

Well let's start to build the controller to handle the visualization/editing of the userprofile of our users.

I'll call the controller Myaccount and I'll put it in a file called myaccount.php into the application/controllers/ folder:

application/controllers/myaccount.php
  1. <?php
  2. /**
  3. * controller to display a user custom profile and allow the owner of the
  4. * profile to modify it
  5. * @author Daniel Vecchiato
  6. * @link 4webby.com
  7. */
  8. class Myaccount extends Controller
  9. {
  10.   function Myaccount()
  11.   {
  12.     parent::Controller();
  13.    
  14.   }
  15.  
  16.   // --------------------------------------------------------------------
  17.   function index()
  18.   {
  19.     //write the code to display a list of all registered users here
  20.   }
  21.  
  22.   // -----------------------------------------------
  23.   /**
  24.    * display the profile of an requested user
  25.    * we let everybody see this profile
  26.    */
  27.   function show()
  28.   {
  29.     $id = $this->uri->segment(3);
  30.       $query = $this->usermodel->getUserById($id);
  31.    
  32.     if ($query->num_rows() == 1)
  33.         {
  34.       $row = $query->row();
  35.       $data['user']['id']= $row->id;
  36.       $data['user']['user_name']= $row->user_name;
  37.       $data['user']['email']= $row->email;
  38.      
  39.       //$countries = null;           
  40.         if ($this->config->item('FAL_use_country') && strlen($row->country_id))
  41.         {
  42.           $this->load->model('country');
  43.            
  44.           $query = $this->country->getCountryById($row->country_id);
  45.           $row = $query->row();
  46.            
  47.           //SELECT name FROM country WHERE id= $data['user']['country_id']
  48.             $data['user']['country'] = $row->name;
  49.         }
  50.        
  51.         $query->free_result();
  52.        
  53.         //
  54.         if ($this->config->item('FAL_create_user_profile')==TRUE)
  55.         {
  56.           //get data from the user_profile table
  57.           $data['user_profile']= $this->freakauth_light->_getUserProfile($id);
  58.           $data['f_r'] = $this->freakauth_light->_buildUserProfileFieldsRules();
  59.           $data['label'] = $data['f_r']['fields'];
  60.         }
  61.        
  62.         }
  63.         else
  64.         {
  65.           $data['error_message']='The record you are looking for does not exist';
  66.         }
  67.      
  68.         $this->load->view('view', $data);
  69.   }
  70. ?>

Everybody will be able to see the userprofile of our users.

The method show() will take care of displaying the userprofile for the user id passed into the URI. 

We are not ready yet, because we need a view for letting show() work properly.

Create a file called view.php with the following inside and drop it in your application/views/ folder:

application/views/view.php
  1. <!--your HTML header here-->
  2. <h1>Userprofile for user <?=$user['user_name']?></h1>
  3. <p><?=anchor('myaccount/edit/'.$user['id'], 'EDIT')?></p>
  4. <li>username: <?=$user['user_name']?></li>
  5. <li>e-mail: <?=$user['email']?></li>
  6. <?php if ($this->config->item('FAL_use_country') && isset($user['country']))
  7.           {?>
  8.           <li>country: <?=$user['country'];?></li>
  9.         <?php
  10.           }?>
  11. <?php if ($this->config->item('FAL_create_user_profile') AND !empty($user_profile))
  12. {?>
  13.  
  14.   <?php
  15.     foreach ($user_profile as $field=>$profile)
  16.     {?>
  17.       <li><?=$label[$field]?>: <?=$profile?></li>
  18.    
  19.     <?php
  20.     }?>
  21.  
  22. <?php
  23. }
  24. elseif($this->config->item('FAL_create_user_profile') AND empty($user_profile))
  25. {?>
  26.    <p class="error">no data in DB: please add them</p>
  27. <?php
  28. } else {?><p class="error">userprofile disabled in config</p><?php }?>
  29. </ul>
  30. <!--your HTML footer here-->

Now go to www.yoursite.com/index.php/myaccount/show/1 and you will be able to see the profile of the user with id=1 

LETTING USERS TO EDIT THEIR OWN PROFILE

Next step will be to add the method edit() in our controller in order to let our users to edit their own profile. Therefore we will need to restrict  the access to this method not only to valid logged in users, but we will also check that they are the effective owners of the profile with the following statement:

  1. //let's restrict access to just the owner of this account
  2.     //if number and number==userdata['id']
  3.     if (belongsToGroup('user') AND $id === $this->db_session->userdata('id'))
  4.     {
  5.          //...
  6.     }

 

 

The method edit() requires some custom validation sules (callbacks), I won't cover them here but you will find them in the ready to plug downloadable code.Then download the source code for this tutorial if you want to test the edit() method properly.

Let's open our file myaccont.php again and add the method edit() to the Myaccount class:

application/controllers/myaccount.php
  1. // -----------------------------------------------
  2.   /**
  3.    * necessary for the user to edit his own profile
  4.    * only the user owning this profile can access this method
  5.    *
  6.    * We allow him to edit everything apart from his username that must be unique
  7.    * and therefore not changed after registration
  8.    */
  9.   function edit()
  10.   {
  11.     //www.yourdomain.com/index.php/myaccount/edit/1
  12.     $id = $this->uri->segment(3);
  13.    
  14.     //let's restrict access to just the owner of this account
  15.     //if number and number==userdata['id']
  16.     if (belongsToGroup('user') AND $id === $this->db_session->userdata('id'))
  17.     {
  18.       //loading necessary stuff
  19.       $this->lang->load('freakauth');
  20.           $this->load->model('FreakAuth_light/usermodel', 'usermodel');
  21.           $this->load->library('validation');
  22.       $this->validation->set_error_delimiters($this->config->item('FAL_error_delimiter_open'), $this->config->item('FAL_error_delimiter_close'));
  23.      
  24.         //set validation rules
  25.           $rules['password'] = 'trim|xss_clean|callback__password_check';
  26.           $rules['password_confirm'] = "trim|xss_clean|matches[password]";
  27.           $rules['email'] = 'trim|required|valid_email|xss_clean|callback__email_duplicate_check';
  28.      
  29.     }
  30.     else
  31.     {
  32.       $msg = 'your must login to access this restricted area';
  33.           $this->db_session->set_flashdata('flashMessage', $msg, 1);
  34.       redirect('' , 'location');
  35.      
  36.     }
  37.        
  38.         //do we want to set the country?
  39.         //(looks what we set in the freakauth_light.php config)
  40.         if ($this->config->item('FAL_use_country'))
  41.         {
  42.             $rules['country_id'] = $this->config->item('FAL_user_country_field_validation_register');
  43.         }
  44.            
  45.         //getting user profile custom data and setting fields and rules for validation
  46.       if ($this->config->item('FAL_create_user_profile')==TRUE)
  47.     { 
  48.         $data = $this->freakauth_light->_buildUserProfileFieldsRules();
  49.         $rules_profile= $data['rules'];
  50.         $fields = $data['fields'];
  51.         $this->validation->set_rules($rules_profile);
  52.     }
  53.        
  54.         $this->validation->set_rules($rules);
  55.        
  56.         $fields['password'] = $this->lang->line('FAL_user_password_label');
  57.         $fields['password_confirm'] = $this->lang->line('FAL_user_password_confirm_label');
  58.         $fields['email'] = $this->lang->line('FAL_user_email_label');
  59.        
  60.         //if activated in config, sets the select country box
  61.         if ($this->config->item('FAL_use_country'))
  62.         {
  63.             $fields['country_id'] = $this->lang->line('FAL_user_country_label');
  64.         }
  65.        
  66.         $this->validation->set_fields($fields);
  67.        
  68.       //this avoid 1 extra query if validation doesn't return true
  69.         if ($id!='')
  70.         { 
  71.           //gets values for the edit form
  72.           $query = $this->usermodel->getUserById($id);
  73.        
  74.    
  75.            foreach ($query->result() as $row)
  76.               {
  77.                 $data['user']['id']= $row->id;
  78.                 $data['user']['email']= $row->email;
  79.                 $data['user']['country_id']= $row->country_id;
  80.               }
  81.              
  82.         $query->free_result();
  83.        
  84.        
  85.  
  86.         if ($this->config->item('FAL_create_user_profile')==TRUE)
  87.       {
  88.         $data['user_prof']= $this->freakauth_light->_getUserProfile($id);
  89.           $data['f_r'] = $this->freakauth_light->_buildUserProfileFieldsRules();
  90.           $data['fields'] = $data['f_r']['fields'];
  91.       }
  92.        
  93.       }
  94.  
  95.       //$countries = null;           
  96.       if ($this->config->item('FAL_use_country'))
  97.       {
  98.         $this->load->model('country');
  99.            
  100.         //SELECT * FROM country
  101.           $data['countries'] = $this->country->getCountriesForSelect();
  102.       }
  103.            
  104.     if ($this->validation->run() == FALSE)
  105.         {
  106.             $this->load->view('edit', $data);
  107.             $this->output->enable_profiler(TRUE);
  108.         }
  109.      
  110.     //if everything ok
  111.     else
  112.     {     
  113.       //get form values
  114.       $values = $this->_get_form_values();
  115.      
  116.       $id = $this->db_session->userdata('id');
  117.      
  118.       //update data in DB
  119.       $where=array('id' => $id);
  120.           $this->usermodel->updateUser($where, $values['user']);
  121.          
  122.           //if we want the user profile as well
  123.           if($this->config->item('FAL_create_user_profile'))
  124.           { 
  125.                 //let's get the last insert id
  126.                 $this->load->model('Userprofile');
  127.                 $this->Userprofile->updateUserProfile($id, $values['user_profile']);
  128.           }
  129.           //set a flash message
  130.       $msg = $this->db->affected_rows().$this->lang->line('FAL_user_edited');
  131.           $this->db_session->set_flashdata('flashMessage', $msg, 1);
  132.      
  133.       //redirect to list
  134.       redirect('myaccount/show/'.$this->db_session->userdata('id'), 'location');
  135.     }
  136.   }

Ok, again for the method edit() to work we need to build a edit.php view and drop it in the application/views directory:

 

application/views/edit.php
  1. <!--your HTML header here-->
  2. <h2>Myaccount EDIT myprofile</h2>
  3. <?=form_open('/myaccount/edit/'.$user['id'])?>
  4. <!--USERPROFILE DATA-->
  5. <p><label for="email">e-mail:</label>
  6.       <?=form_input(array('name'=>'email',
  7.                          'id'=>'email',
  8.                          'maxlength'=>'120',
  9.                          'size'=>'35',
  10.                          'value'=>(isset($user['email']) ? $user['email'] : $this->validation->{'email'})))?>
  11.       <span><?=(isset($this->validation) ? $this->validation->{'email'.'_error'} : '')?></span>
  12.       </p>
  13.       <p><label for="password">password:</label>
  14.       <?=form_password(array('name'=>'password',
  15.                          'id'=>'password',
  16.                          'maxlength'=>'16',
  17.                          'size'=>'16',
  18.                          'value'=>(isset($this->validation->{'password'}) ? $this->validation->{'password'} : '')))?>
  19.       <span><?=(isset($this->validation) ? $this->validation->{'password'.'_error'} : '')?></span>
  20.       </p>
  21.  
  22.       <p><label for="password_confirm">retype password:</label>
  23.       <?=form_password(array('name'=>'password_confirm',
  24.                          'id'=>'password_confirm',
  25.                          'maxlength'=>'16',
  26.                          'size'=>'16',
  27.                          'value'=>(isset($this->validation) ? $this->validation->{'password_confirm'} : '')))?>
  28.     <span><?=(isset($this->validation) ? $this->validation->{'password_confirm'.'_error'} : '')?></span>
  29.      </p>
  30.      
  31.     <?php if ($this->config->item('FAL_use_country'))
  32.         {?>
  33.  
  34.       <p><label for="country_id">country:</label>
  35.       <?=form_dropdown('country_id',
  36.                    $countries,
  37.                    (isset($user['country_id']) ? $user['country_id'] :  $this->validation->country_id))?>
  38.   <span><?=(isset($this->validation) ? $this->validation->{'country_id'.'_error'} : '')?></span>
  39.     </p>
  40.     <?php } ?>
  41.  
  42. <?php if ($this->config->item('FAL_create_user_profile') AND !empty($fields))
  43. {
  44.   foreach ($fields as $field=>$label)
  45.   {?>
  46.   <p><label for="<?=$field?>"><?=$label?>:</label>
  47.     <?=form_input(array('name'=>$field,
  48.                       'id'=>$field,
  49.                       'maxlength'=>'45',
  50.                       'size'=>'25',
  51.                       'value'=>(isset($user_prof[$field]) ? $user_prof[$field] : $this->validation->{$field})))?>
  52.     <span><?=(isset($this->validation) ? $this->validation->{$field.'_error'} : '')?></span></p>
  53.  
  54. <?php }
  55. }
  56. elseif($this->config->item('FAL_create_user_profile') AND empty($user_profile)) {?> <p class="error">no data in DB: please add them</p>
  57. <?php } else {?><p class="error">userprofile disabled in config</p><?php }?>
  58.  
  59. <!-- END USERPROFILE DATA-->
  60.  
  61.      <input type="submit" name="Submit" value="save" />
  62.      <input type="button" name="back" class="submit" value="back" onclick="location.href = '<?=base_url();?>index.php/myaccount/<?=$user['id']?>'"/>
  63.  
  64. </form>
  65. <!--your HTML footer here-->

 

Now if you are:

  • logged in
  • and you have an user id=1 

go to www.yourdomain.com/index.php/myaccount/edit/1 and you will be able to edit your profile.

WHAT'S LEFT?!

Well we are done with user profile visualization and editing. It would also be nice to add a method to our controller in order to display all registered users with a link to their public profile.

I live this last task to you: the method is ready in the Myaccount class and it is called index()=> just fill in the code in the curly brackets {//your code here...}

I hope this tutorial has helped you to discover a bit better the custom userprofile feature of FreakAuth_light_1.0.2-Beta.

Happy coding!

Dan