Showing posts with label users. Show all posts
Showing posts with label users. Show all posts

Wednesday, July 13, 2011

Model: User: Display Name

When adding a record that has a relationship of "belongs to" with another table as mentioned previously, CakePHP automatically lists the records of the other table using the display name of that model. By default that display name field is "name". However, if your field doesn't have a "name" field, such as the Users table, you can specify the display name manually in the model.

Edit app/models/user.php and add the following line:
    var $displayField = 'username';
This does not support multiple fields, for example if you wanted to combine first_name and last_name. In order to do this you need to use virtualFields in your model. Virtual fields allow you to access a created field, but you cannot save it.

Edit app/models/user.php and add the following line:
    var $virtualFields = array( 'full_name' => "CONCAT(User.first_name, ' ', User.last_name)");
then change the display field from username to full_name.

Wednesday, November 10, 2010

Authentication

To set up a user login system for your CakePHP application, Cake comes with an authentication component built in. The Auth component requires a "user" table in the database with at least the fields of "username" and "password". Though they don't have to be named exactly that, it makes everything easier.

The first thing you need to do is to add the Auth component to your controllers. Since typically you want all your controllers to utilize the Auth component, it is best to create an App controller and include it in there.

Create /app/app_controller.php
<?php
class AppController extends Controller{
    var $components = array('Auth');
}
?>
If at any time you encounter trouble with your authentication, comment out this line to turn it off.

NOTE: When you explicitly define your components, you disable the default components in CakePHP, such as Session so if you want to use the session component, be sure to explicitly define it in your array.
    var $components = array('Auth','Session');
The next requirement is to have login() and logout methods in your users controller.

Exit /app/controllers/users_controller.php and add the login and logout methods as below.
    function login() {
        $this->set('title_for_layout', 'Login');
        /* If user is already logged in, redirect */
        if ($this->Auth->user()) {
            $this->redirect($this->Auth->redirect());
        }
    }

    function logout() {
        $this->redirect($this->Auth->logout());
    }
The last requirement is the view for the login action of the users controller.

Create /app/views/users/login.ctp
<?php
    echo $session->flash('auth');
    echo $form->create('User', array('action' => 'login'));
    echo $form->input('username');
    echo $form->input('password');
    echo $form->end('Login');
?>
The login view uses the form helper to create a form allowing entry of the username and password.

In a controller, the beforeFilter() method is called automatically before any other controller action. This is where you define the settings for your Auth component.

Edit /app/app_controller.php and add the beforeFilter method below.
function beforeFilter() {
    /* Set username and password fields if not using default 'username' and 'password' */
    $this->Auth->fields = array('username' => 'email', 'password' => 'password');
    /* What actions are allowed without authentication */
    $this->Auth->allow('*'); // Allow all defined methods
}
By default, the Auth component only allows the login and logout methods. Allowing all actions will allow you to create a user and set the password so you will be able to login once you lock the site down.

If you are still using scaffolding at this point however, scaffold methods are not allowed without being explicitly defined.

Edit /app/app_controller.php and change the $this->Auth->allow() command as follows:
    $this->Auth->allow('*', 'add');
Browse to http://drug-ed.com/users/add/ and create a new user with a properly hashed password so you can login.

Edit /app/app_controller.php and comment out the $this->Auth->allow() command to prevent all access to the site unless signed in. Browse to any page then login it verify it works.

If you are not allowing all actions and are explicitly defining the actions you are allowing, remember that for static pages the default action is 'display' and is required for authorization to view those pages.

Tuesday, November 9, 2010

Pagination

With a short list of records, the basic view is good enough, however, once the number of records exceeds 50 or so, it is helpful to use CakePHP's built in pagination to display pages on multiple pages. First edit /app/controllers/users_controller.php and replace this line
$this->set('users',$this->User->find('all'));
with this one
$this->set('users', $this->paginate());
Save and upload the file. Now if you browse to http://drug-ed.com/ it still works because the data pulled from the database is the same, we just haven't taken advantage of the pagination features yet. Edit /app/views/users/index.ctp and replace
    <th>ID</th>
    <th>Username</th>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Email</th>
with
    <th><?php echo $this->Paginator->sort('id');?></th>
    <th><?php echo $this->Paginator->sort('username');?></th>
    <th><?php echo $this->Paginator->sort('first_name');?></th>
    <th><?php echo $this->Paginator->sort('last_name');?></th>
    <th><?php echo $this->Paginator->sort('email');?></th>
Then after the users table within the users division add
    <p>
    <?php
        echo $this->Paginator->counter(array('format' => __('Page %page% of %pages%, showing %current% records out of %count% total, starting on record %start%, ending on %end%', true)));
    ?>
    </p>
    <div class="paging">
        <?php echo $this->Paginator->prev('<< ' . __('previous', true), array(), null, array('class'=>'disabled'));?>
        | <?php echo $this->Paginator->numbers();?>
        | <?php echo $this->Paginator->next(__('next', true) . ' >>', array(), null, array('class' => 'disabled'));?>
    </div>
Save and upload the file then browse to http://drug-ed.com/ to verify that it works. You can now click on the headers of each column to sort the users, as well as view them on multiple pages, though it requires more than 20 records for a new page.

Page Title

From your home page observe the page title, it should be something like this: "CakePHP: the rapid development php framework: Users"

The first part of the title is defined in the default layout. The layout predefines the wrapper HTML code of every page. This file is located in /cake/libs/view/layouts/default.ctp and before editing it you should move it to /app/views/layouts/default.ctp

Next, edit the page and remove the following line:
<?php __('CakePHP: the rapid development php framework:'); ?>
Upload the file and test it and your home page title should just read "Users".

Now click on the username and the title will read "Scaffold :: View :: Users" While the default titles can be helpful, you will want to change them to reflect your site's method.

Edit /app/controllers/users_controller.php and for the first line in the index() method add the following:
$this->set("title_for_layout", 'Drug-ed.com : Drug Education and Medication Adherence');
Save the changes upload the file and test it at site root. This command will also work if you add it to /app/views/users/index.ctp, however, since you are modifying variables it is best practice to do it within the controller.

Thursday, November 4, 2010

Validate Model: User

Rule 1: Never trust user input
Rule 2: When in doubt, see rule 1

For every model you should create a validate variable which will be used to validate input fields. For our user model we need to verify that username and email are unique on creation.

Since validation can be quite complex, building the validation variable one field at a time can be helpful. For full details on data validation see http://book.cakephp.org/view/1143/Data-Validation

Edit /app/models/user.php and add
    var $validate = array(
        'username' => array(
            'alphanumeric' => array(
                'rule' => '/^[a-z0-9]{3,}$/i',
                'required' => true,
                'message' => 'Username must contain only letters and numbers.'
            ),
            'unique' => array(
                'rule' => 'isUnique',
                'message' => 'This username is already taken.'
            ),
            'minlength' => array(
                'rule' => array('minlength', 5),
                'message' => 'Username must be at least 5 characters.'
            ) 
        )
    );
Upload the file then browse to http://drug-ed.com/users/add and observe how the "Username" field label is bolded and followed by a red asterisk helping to identify the required aspect of that field. Test your validation rule by trying a 2 letter username, or one composed of special characters.

Now that you are sure that field validation is working properly, add the next field. Edit /app/models/user.php and add at the end of the validate array
        ),
        'email' => array(
            'email' => array(
                'rule' => 'email',
                'required' => true,
                'message' => 'You must enter a valid email address.'
            ),
            'unique' => array(
                'rule' => 'isUnique',
                'on' => 'create',
                'message' => 'This email address is already on record.'
            )
        )
    );
Notice the line 'on' => 'create' in the email validation. When editing a user the isUnique rule will fail because the user's email is already in the database! Changing it to only verify when you create an new user will prevent this problem.

Upload the file then browse to http://drug-ed.com/users/add to again verify it works as intended.

View: User Index

Views control the display of your application. When the controller renders views, Cake will automatically look for a file name the same as the controller action. The index method is the default method called when the controller is called without an explicit action defined, so index.ctp is the default view.

Create /app/views/users/index.ctp

This file contains any actual display code, such as html, that will be used to view the results of the index() method.
<div class="users index">
    <table cellpadding="0" cellspacing="0">
    <tr>
        <th>ID</th>
        <th>Username</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Email</th>
        <th class="actions">Actions</th>
    </tr>
    <?php
    $i = 0;
    foreach ($users as $user):
        $class = null;
        if ($i++ % 2 == 0) {
            $class = ' class="altrow"';
        }
    ?>
    <tr<?php echo $class;?>>
        <td><?php echo $user['User']['id'];?></td>
        <td><?php echo $this->Html->link($user['User']['username'], array('controller' => 'users', 'action' => 'view', $user['User']['id'])); ?></td>
        <td>%lt;?php echo $user['User']['first_name']; ?></td>
        <td>%lt;?php echo $user['User']['last_name']; ?></td>
        <td>%lt;?php echo $user['User']['email']; ?></td>
        <td class="actions">
            <?php echo $this->Html->link(__('View', true), array('controller' => 'users', 'action' => 'view', $user['User']['id'])); ?>
            <?php echo $this->Html->link(__('Edit', true), array('controller' => 'users', 'action' => 'edit', $user['User']['id'])); ?>
            <?php echo $this->Html->link(__('Delete',true), array('action' => 'delete', $user['User']['id']), null, sprintf('Are you sure you want to delete # %s?', $user['User']['id'])); ?>
        </td>
    </tr>
<?php endforeach; ?>
    </table>
</div>
<div class="actions">
    <h3><?php __('Actions'); ?></h3>
    <ul>
        <li><?php echo $this->Html->link(__('New User', true), array('action' => 'add')); ?></li>
        <li><?php echo $this->Html->link(__('List Carriers', true), array('controller' => 'carriers')); ?></li>
        <li><?php echo $this->Html->link(__('New Carrier', true), array('controller' => 'carriers', 'action' => 'add')); ?></li>
        <li><?php echo $this->Html->link(__('List Reminders', true), array('controller' => 'reminders')); ?></li>
        <li><?php echo $this->Html->link(__('New Reminder', true), array('controller' => 'reminders', 'action' => 'add')); ?></li>
    </ul>
</div>
Edit /app/controller/users_controller.php Add the following method
    function index() {
        $this->set('users',$this->User->find('all'));
    }
As mentioned previously, any defined methods will override scaffolding so browse to the site root/users and view the results.

Browse to http://drug-ed.com/users/ to test the page. Observe your default user then click on the link for viewing and editing. Notice how the scaffolding still works for all methods other than those defined.

The double underscore (__) is a global CakePHP method that handles localization. Feel free to ignore it at this point.

Wednesday, November 3, 2010

Controller: Users

Create /app/controllers/users_controller.php
<?php
class UsersController extends AppController {
    var $name = 'Users';
    var $scaffold;
}
?>
Upload the file and browse to http://drug-ed.com/users to verify it works. Since Users have defined relationships with Carriers and Reminders observe the action links. Click "New User" and observe the option to select the carriers entered in earlier. Create a default user for administration and testing of your site.

Update Model: User

As mentioned previously, to coordinate with the reminder model, add the relationship to the user model. In addition while each carrier can have many users, each user belongs to a carrier so indicate that as follows as well:

Edit /app/models/user.php and add
    var $hasMany = array('Reminder');
    var $belongsTo = array('Carrier');
Upload the file.

Like when a model belongs to another model, if the foreign key is not standard you need to explicitly define it. You can also explicitly define the class name if that isn't the default also.
    var $hasMany=> array(
        'Reminder' => array(
            'className' => 'Reminder',
            'foreignKey' => 'UniqueUserID'
        )
    );

Model: User

Models provide the interface to the database. While the tables they refer to are named plurally, the models are named singularly.

Create /app/models/user.php
<?php
class User extends AppModel {
    var $name = 'User';
}
?>
If the primary key field of your table is not "id" then you need to add the variable $primaryKey, otherwise you can leave it out.
    var $primaryKey = 'unique_id';
If you didn't design your tables around CakePHP (why wouldn't you?) then you can explicitly specify the table name for your model here as well.
    var $useTable = 'table_name';
If you don't want a model to use a table, such as for display purposes only, or when pulling data from an external source, you can set the useTable variable to false.
    var $useTable = false;
Once you do that, you can set the schema for the non-table data with the _schema variable.
    var $_schema = array(
        'last_name' => array('type' => 'strong', 'length' => 50),
        'date_of_birth' => array('type' => 'date')
    );
Upload the file.

Database: Setup Users Table

Create users table
CREATE TABLE IF NOT EXISTS `users` (
  `id` int(11) NOT NULL auto_increment,
  `slug` varchar(40) NOT NULL,
  `username` varchar(30) NOT NULL,
  `password` varchar(40) NOT NULL,
  `first_name` varchar(40) NOT NULL,
  `last_name` varchar(40) NOT NULL,
  `email` varchar(100) NOT NULL,
  `email_verified` tinyint(1) NOT NULL default '0',
  `carrier_id` int(11) NOT NULL,
  `cell_number` varchar(10) NOT NULL,
  `modified` datetime NULL,
  `created` datetime NULL,
  PRIMARY KEY  (`id`),
  UNIQUE KEY `username` (`username`),
  UNIQUE KEY `slug` (`slug`),  
  UNIQUE KEY `email` (`email`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
The created and modified (or updated, either name works) fields will be filled in by CakePHP automatically, as long as they are set as DATETIME fields and default to NULL. Long field names are separated with underscores '_' so CakePHP can easily understand them.