0
votes

I'm trying to create a registration form for a user with Cake PHP. The user can be registered only, when the company ID exist and if he is allowed to register. The problem is that during registration I ask the user to specify the Company ID (company is created by an administrator, and to allow user registration the company ID must exists in database. User belongs to company)

These are my tables in database:

users id INT(11) NN, email VARCHAR(30) NN, password VARCHAR(255) NN, name VARCHAR(30) NN, company_id INT(11) NN, created DATE NN, modified DATE NN

companies id INT(11) NN, name VARCHAR(30) NN, phone VARCHAR(30), email VARCHAR(30) NN, address1 VARCHAR(50) NN, address2 VARCHAR(50) NN, town VARCHAR(30) NN, postcode VARCHAR(20), password VARCHAR(255), country_id INT(11) NN, created DATE, modified DATE,

This is User's Registration Page (View):

<div class="index large-4 medium-4 large-offset-4 medium-offset-4 columns">
    <div class="panel">
        <h3 class="text-center">Register New User</h3>
        <?= $this->Form->create($user); ?>
            <?= $this->Form->input('companyid'); ?>
            <?= $this->Form->input('name'); ?>
            <?= $this->Form->input('email'); ?>
            <?= $this->Form->input('password', array('type' => 'password')); ?>
            <?= $this->Form->submit('Register', array('class' => 'button')); ?>
        <?= $this->Form->end(); ?>
    </div>
</div>



**This is UsersController:**
    //register
    public function register(){

        $user = $this->Users->newEntity();
        //if the form is submitted
        if($this->request->is('post')){
            $user = $this->Users->patchEntity($user, $this->request->data);
            if($this->Users->save($user)){
                $this->Flash->success('Congratulation! You have successfully registered. Now you can log in');
                return $this->redirect(['action' => 'login']);
            } else {
                $this->Flash->error('Something went wrong! You did not register to the system');
            }
        }
        $this->set(compact('user'));
        $this->set('_serialize', ['user']);
    }



**AppController- Function Initialize**

public function initialize()
    {
        parent::initialize();

        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash');
        $this->loadComponent('Auth', [
            'authenticate' => [
                'Form' => [
                    'fields' => [
                        'username' => 'email',
                        'password' => 'password'
                    ]
                ]
            ],
            'loginAction' => [
                'controller' => 'Users',
                'action' => 'login'
            ]
        ]);
    }

Now. I just don't know how should I implement Registration for User in UserController in a way: Check if CompanyID exists in companies table- if yes- allow the user Registration and insert id, email, password, name, and company_id into users table. If doesn't exists display error "Company ID doesn't exists".

2

2 Answers

0
votes

Here is code for email duplication check you can modify it to check what you want In Your model write this code

    `public $validate = array
            (
                        'user_name' => array(
                            'requiredUsername' => array(
                                'rule' => array('notBlank'),
                                'message' => 'User Name is required!',
                                //'allowEmpty' => false,
                                //'required' => false,
                                //'last' => false, // Stop validation after this rule
                                //'on' => 'create', // Limit validation to 'create' or 'update' operations
                            ),
                            'alphanumeric' => array(
                                'rule'    => 'alphaNumeric',
                                'message' => 'Usernames must only contain letters and numbers.'
                            ),
        'email' => array(
                            'email' => array(
                            'rule' => array('email'),
                            'message' => 'Enter valid email id!',
                                //'allowEmpty' => false,
                                //'required' => false,
                                //'last' => false, // Stop validation after this rule
                                //'on' => 'create', // Limit validation to 'create' or 'update' operations
                            ),
                            'email_unique' => array(
                            'rule' => 'isUnique',
                            'message' => 'Mail already exist inside database',
                            'on' => 'create' // Only apply this rule upon creation of a new record
                            ),
);
public function beforeSave($options = array()) {
            // If the email key is set in the data to be saved...
            if (isset($this->data[$this->alias]['email'])) {
                // Make sure the email is not already in use by another user
                if ($this->find('count', array(
            'conditions' => array(
                $this->alias . '.id !=' => $this->data[$this->alias]['id'],
                $this->alias . '.email' => $this->data[$this->alias]['email']
            )
        )) > 0) {
          // The email is found for a user with another id, abort!
          return false;
        }
    }
}

Then in Your Controller

public function add() {
        if ($this->User->validates()) {
            // it validated logic
            if ($this->request->is('post')) {
            $this->User->create();
            if ($this->User->save($this->request->data)) {
                $this->Flash->set(__('The user has been saved.'));
                return $this->redirect(array('action' => 'index'));
            } else {
                $this->Flash->set(__('The user could not be saved. Please, try again.'));
            }
        }
        } else {
            // didn't validate logic
            $errors = $this->User->validationErrors;
            debug($errors);
            exit;
        }

        // $this->Model->validationErrors();

    }

Then finally in your View

<h1>Sign Up User</h1>
<?php echo $this->Html->script('jquery',false);?> 
<?php echo $this->Html->script('validation',false);?> 
<div style="width:300px;text-align:center ;margin:5px;display: inline-block;padding: 15px;" >

 <!-- <pre><?php echo print_r($id); ?></pre> -->

             <?php echo $this->form->create('User');
             // 'required'=>false,
        echo $this->form->input('user_name', array('id'=>'user_name','placeholder'=>'User Name','label'=>false));
        echo $this->form->input('first_name',array('id'=>'first_name','placeholder'=>'First Name','label'=>false));
        echo $this->form->input('last_name',array('id'=>'last_name','placeholder'=>'Last Name','label'=>false));
        echo $this->form->input( 'gender', array('options' => array(1 => 'Male',0 => 'Female'),'value' =>1,'div' => false,'type' => 'radio'));
        echo $this->form->email('email',array('placeholder'=>'Enter Email','label'=>false));
        echo $this->form->input('dob', array(
                                'label' => 'Date of birth',
                                'dateFormat' => 'DMY',
                                // 'selected'=>'19:08:1992',
                                'minYear' => date('Y') - 70,
                                'maxYear' => date('Y'),
                            ));
        echo $this->form->input('cnic',array('placeholder'=>'CNIC','label'=>false));
        echo $this->form->tel('mobile',array('placeholder'=>'Contact Number','label'=>false));?>
        <div >
        <?php
        echo $this->form->password('pass',array('placeholder'=>'Password','label'=>false,'before'=>'---before---'));
        echo $this->form->password('repass',array('placeholder'=>'Validate Password'));?>

        </div>
        <?php
        echo $this->form->end('Sign Up', array('formnovalidate' => true));   ?>





</div>

I hope it is what you where desiring to do