2011年8月16日

Codeigniterを使ってショッピングカートをゼロから作ってみよう。 # 6

今回はユーザ管理です。
ユーザの一覧表示、新規作成(追加)、編集、最後に削除です。
苦手なjavascriptで手間取って時間かかりました( ̄Д ̄;;


■ File Tree


■ コントローラ:User
admin/application/controllers/user.php
<?php
class User extends Controller
{
    function __construct()
    {
        parent::__construct();
        if( ! _s('admin')) redirect();
        $this->load->model('users_model', 'usersdb');
    }
    
    function index()
    {
        $this->accounts();
    }
    
    function accounts($page=0)
    {
        $this->form_validation->set_rules('delete', '', 'isArray');
        if($this->form_validation->run())
        {
            $this->usersdb->delete_array($this->input->post('delete'));
        }
        
        $data['breadcrumbs'] = array(_l('HOME')=>'', _l('USERLIST')=>'user');
        $data['h1'] = _l('USERLIST');
        $data['all'] = $this->usersdb->all($page);
        $this->layout->view('user/accounts', $data);
    }
    
    function create()
    {
        $this->form_validation->set_error_delimiters('<span class="error">', '</span>');
        $this->form_validation->set_rules('email',_l('EMAIL'),'required|valid_email|email_exist');
        $this->form_validation->set_rules('firstname',_l('FIRSTNAME'),'required|min_length[2]');
        $this->form_validation->set_rules('lastname',_l('LASTNAME'),'required|min_length[2]');
        $this->form_validation->set_rules('passwd',_l('PASSWORD'),'required|min_length[6]|matches[passwdconf]');
        if($this->form_validation->run())
        {   // insert into db
            $data = array(
                'email'     => $this->input->post('email'),
                'password'  => $this->input->post('passwd'),
                'firstname' => $this->input->post('firstname'),
                'lastname'  => $this->input->post('lastname'),
                'status'    => $this->input->post('status')
            );
            
            $this->usersdb->newuser($data);
            
            redirect('user');
        }

        $data['breadcrumbs'] = array(_l('HOME')=>'', _l('USERLIST')=>'user', _l('CREATE_USER')=>'user/create');
        $data['h1'] = _l('CREATE_USER');
        $this->layout->view('user/create', $data);
    }
    
    function edit($id)
    {   // just in case
        if($user = $this->usersdb->byId($id))
        {
            $this->form_validation->set_error_delimiters('<span class="error">', '</span>');
            $this->form_validation->set_rules('email',_l('EMAIL'),'required|valid_email|email_exist['.$id.']');
            $this->form_validation->set_rules('firstname',_l('FIRSTNAME'),'required|min_length[2]');
            $this->form_validation->set_rules('lastname',_l('LASTNAME'),'required|min_length[2]');
            if($this->input->post('passwd')) $this->form_validation->set_rules('passwd',_l('PASSWORD'),'required|min_length[6]|matches[passwdconf]');

            if($this->form_validation->run())
            {   // update user info
                $data['email'] = $this->input->post('email');
                $data['firstname'] = $this->input->post('firstname');
                $data['lastname'] = $this->input->post('lastname');
                $data['status'] = $this->input->post('status');
                if($this->input->post('passwd')) $data['password'] = $this->input->post('password');
                
                $this->usersdb->update($user, $data);
                
                redirect('user');
            }

            $data['breadcrumbs'] = array(_l('HOME')=>'', _l('USERLIST')=>'user', _l('EDIT_USER')=>'user/edit');
            $data['h1'] = _l('EDIT_USER');
            $data['user'] = $user;
            $this->layout->view('user/edit', $data);
        }
        else redirect();
    }
}
□ メソッド
index ( accounts )で一覧表示と削除。
create で新規ユーザ作成
edit で編集しています。

■ モデル:Users_model.php
extension/models/users_model.php
function newuser($data)
    {
        $data['hash'] = $this->auth->_generate_hash();
        $data['password'] = $this->auth->_encode($data['password'], $data['hash']);
        $this->db->insert($this->table, $data);
        setMessage('success', _l('SUCCESS_CREATE_USER'));
    }
    
    function update($obj, $data)
    {
        if(array_key_exists('password', $data)) $data['password'] = $this->auth->_encode($data['password'], $obj->hash);
        $this->db->where('id', $obj->id);
        $this->db->update($this->table, $data);
        setMessage('success', _l('SUCCESS_UPDATE_USER'));
    }
ユーザ追加用とアップデート用のメソッドを追加。

■ Form_validationライブラリにルール追加
extension/libraries/MY_Form_validation.php
<?php
class MY_Form_validation extends Form_validation
{
    function __construct()
    {
        parent::__construct();
    }
    
    function email_exist($email, $id=FALSE)
    {
        $this->CI->form_validation->set_message('email_exist', $this->CI->lang->line('in_use'));
        $this->CI->load->model('users_model', 'usersdb');
        return ($this->CI->usersdb->exist($email, $id)) ? FALSE : TRUE;
    }
    
    function isArray($arr)
    {
        $this->CI->form_validation->set_message('isArray', $this->CI->lang->line('is_array'));
        return (is_array($arr) && count($arr) > 0) ? TRUE : FALSE;
    }
}

■ ビュー:一覧表示&削除
admin/application/views/user/accounts.php
<div class="buttons">
<button onclick="javascript:location.href = '<?php echo base_url('user/create'); ?>';"><?php echo _l('CREATE_USER'); ?></button>
<button onclick="confirmDelSelected();"><?php echo _l('DELETE_SELECTED'); ?></button>
</div>
<?php echo form_open(uri_string()); ?>
<?php if($all): ?>
<table class="list">
<tr>
    <th><input type="checkbox" onclick="applyToAll(this);" /></th>
    <th><?php echo _l('FULLNAME'); ?></th>
    <th><?php echo _l('EMAIL'); ?></th>
<?php /*    <th><?php echo _l('ROLE'); ?></th> */ ?>
    <th><?php echo _l('STATUS'); ?></th>
    <th><?php echo _l('ACTION'); ?></th>
</tr>
<?php foreach($all as $a): ?>
<tr>
    <td><input type="checkbox" name="delete[]" value="<?php echo $a->id; ?>"<?php if($a->id==1): ?> disabled="disabled"<?php endif; ?>></td>
    <td><?php echo $a->firstname.' '.$a->lastname; ?></td>
    <td><?php echo $a->email; ?></td>
<?php /*    <td><?php echo $a->role; ?></td> */ ?>
    <td><?php echo ($a->status) ? _l('ACTIVE') : _l('INACTIVE') ; ?></td>
    <td>
        <a href="<?php echo base_url('user/edit/'.$a->id); ?>"><?php echo _l('EDIT'); ?></a>
    </td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
<?php echo form_close(); ?>

<script type="text/javascript">
function confirmDelSelected() {
    var c = 0;            
    $(":checkbox").each(function(){
        if($(this).attr('checked')) c++;
    })
    if(c > 0) { 
        if(confirm("<?php echo _l('CONFIRM_DELETE_SELECTED'); ?>")) $('form').submit();
    }
    else { alert("<?php echo _l('ALERT_PLZ_SELECT'); ?>"); }
}
</script>



全くスタイルしてない画面ですが(苦)
後でユーザレベル(タイプ)なんかを付け加えることになるでしょう。

削除する時には確認用のポップアップが表示されます。



■ ビュー:新規作成
admin/application/views/user/create.php
<?php echo form_open(uri_string()); ?>
<input type="button" value="<?php echo _l('CANCEL'); ?>" onclick="javascript:location.href = '<?php echo base_url('user'); ?>';" tabindex="9" />

<h2><?php echo _l('USER_DETAILS'); ?></h2>
<dl class="horizontal">
    <dt><?php echo _l('EMAIL'); ?></dt>
    <dd><input class="field" id="email" type="email" name="email" value="<?php echo set_value('email'); ?>" tabindex="1" /><?php echo form_error('email'); ?></dd>
    <dt><?php echo _l('LASTNAME'); ?></dt>
    <dd><input class="field" id="lastname" type="text" name="lastname" value="<?php echo set_value('lastname'); ?>" tabindex="2" /><?php echo form_error('lastname'); ?></dd>
    <dt><?php echo _l('FIRSTNAME'); ?></dt>
    <dd><input class="field" id="firstname" type="text" name="firstname" value="<?php echo set_value('firstname'); ?>" tabindex="3" /><?php echo form_error('firstname'); ?></dd>
    <dt><?php echo _l('PASSWORD'); ?></dt>
    <dd><input class="field" id="passwd" type="password" name="passwd" value="" tabindex="4" /><?php echo form_error('passwd'); ?></dd>
    <dt><?php echo _l('PASSWORDCONF'); ?></dt>
    <dd><input class="field" id="passwdconf" type="password" name="passwdconf" value="" tabindex="5" /></dd>
    <dt><?php echo _l('STATUS'); ?></dt>
    <dd>
        <select name="status" class="field" tabindex="6">
            <option value="1"><?php echo _l('ACTIVE'); ?></option>
            <option value="0"><?php echo _l('INACTIVE'); ?></option>
        </select>
    </dd>
    
    <dd><input type="submit" value="<?php echo _l('SAVE'); ?>" onclick="return check(['email','lastname','firstname','passwd','passwdconf']);" tabindex="7" /> <input type="reset" value="<?php echo _l('RESET'); ?>" tabindex="8" /></dd>
</dl>
<?php echo form_close(); ?>



javascriptは非常に簡単なチェックだけですが、javascriptとphpの両方で入力チェックしてます。
入力しないとこんな感じにハイライトされます。




■ ビュー:編集
admin/application/views/user/edit.php
<?php echo form_open(uri_string()); ?>
<input type="button" value="<?php echo _l('CANCEL'); ?>" onclick="javascript:location.href = '<?php echo base_url('user'); ?>';" tabindex="9" />

<h2><?php echo _l('USER_DETAILS'); ?></h2>
<dl class="horizontal">
    <dt><?php echo _l('EMAIL'); ?></dt>
    <dd><input class="field" id="email" type="email" name="email" value="<?php echo $user->email; ?>" tabindex="1" /><?php echo form_error('email'); ?></dd>
    <dt><?php echo _l('LASTNAME'); ?></dt>
    <dd><input class="field" id="lastname" type="text" name="lastname" value="<?php echo $user->lastname; ?>" tabindex="2" /><?php echo form_error('lastname'); ?></dd>
    <dt><?php echo _l('FIRSTNAME'); ?></dt>
    <dd><input class="field" id="firstname" type="text" name="firstname" value="<?php echo $user->firstname; ?>" tabindex="3" /><?php echo form_error('firstname'); ?></dd>
    <dt><?php echo _l('PASSWORD'); ?></dt>
    <dd><input class="field" id="passwd" type="password" name="passwd" value="" tabindex="4" /><?php echo form_error('passwd'); ?></dd>
    <dt><?php echo _l('PASSWORDCONF'); ?></dt>
    <dd><input class="field" id="passwdconf" type="password" name="passwdconf" value="" tabindex="5" /></dd>
    <dt><?php echo _l('STATUS'); ?></dt>
    <dd>
        <select name="status" class="field" tabindex="6">
            <option value="1"<?php if($user->status==1): ?> selected="selected"<?php endif; ?>><?php echo _l('ACTIVE'); ?></option>
            <option value="0"<?php if($user->status==0): ?> selected="selected"<?php endif; ?>><?php echo _l('INACTIVE'); ?></option>
        </select>
    </dd>
    
    <dd><input type="submit" value="<?php echo _l('SAVE'); ?>" onclick="return check(['email','lastname','firstname']);" tabindex="7" /> <input type="reset" value="<?php echo _l('RESET'); ?>" tabindex="8" /></dd>
</dl>
<?php echo form_close(); ?>



編集画面も似たようなものです。パスワードが入力されてない場合はスルーします。
パスワードのエラーはphpでのみ表示。javascriptは苦手・・・


だいぶ長くなってしまったので、今日はここまでにします。

0 件のコメント:

コメントを投稿