Multiple form with same model name on single page

2019-01-26 11:51发布

问题:

I have two form on a single page: login form and register form. When I submit the register form, it validates both: form fields that are in login and registeration. How can I handle it if both form have the same model (user model)

Register form

<?php echo $this->Form->create('User', array('url' => array('controller' => 'users', 'action' => 'add'))); ?>
<?php echo $this->Form->input('username', array('label' => false, 'div' => false, 'class' => 'reg_input'));?>
<?php echo $this->Form->input('email', array('label' => false, 'div' => false, 'class' => 'reg_input'));?>
<?php echo $this->Form->input('password', array('label' => false, 'div' => false, 'class' => 'reg_input'));?>
<?php echo $this->Form->input('confirm_password', array('type' => 'password', 'label' => false, 'div' => false, 'class' => 'reg_input'));?>
<?php echo $this->Form->submit(__('Submit', true), array ('class' => 'reg_button', 'div' => false)); 
  echo $this->Form->end();?>

and Login form is below

  <?php echo $this->Form->create('User', array('controller' => 'users', 'action' => 'login'))?>
  <?php echo $this->Form->input('User.username',array('label'=>false,'div'=>false, 'class' => 'reg_input'));?>
  <?php echo $this->Form->input('User.password',array('label'=>false,'div'=>false, 'class' => 'reg_input'));?>
  <?php echo $this->Form->submit(__('Log in', true), array ('class' => 'reg_button', 'div' => false)); ?>
  <?php echo $this->Form->end();?>

When I submit registration form it validates both forms, I want to validate only the registration form.

How can I handle that?

回答1:

I've come up with a "solution" (I find the approach dirty, but it works) for a different question (very similar to this). That other question worked with elements and views, though. I'll post the entire solution here to see if it helps someone (though I rather someone else comes with a different approach).

So, first: change the creation names for the two forms.

//for the registration
<?php echo $this->Form->create('Registration', 
      array('url' => array('controller' => 'users', 'action' => 'add'))); ?>
//for the login
<?php echo $this->Form->create('Login', 
      array('controller' => 'users', 'action' => 'login'))?>

The forms should work, look and post to the same actions, so no harm done.

Second step: I don't have your action code, so I'm going to explain what needs to be done in general

public function login() {
    if ($this->request->is('post')) {
        //we need to change the request->data indexes to make everything work
        if (isset($this->request->data['Login'] /*that's the name we gave to the form*/)) {
            $this->request->data['User'] = $this->request->data['Login'];
            unset($this->request->data['Login']); //clean everything up so all work as it is working now
            $this->set('formName', 'Login'); //we need to pass a reference to the view for validation display
     } //if there's no 'Login' index, we can assume the request came the normal way

    //your code that should work normally
    }
}

Same thing for the registration (only need to change 'Login' to 'Registration').

Now, the actions should behave normally, since it has no idea we changed the form names on the view (we made sure of that changing the indexes in the action). But, if there are validation errors, the view will check for them in

$this->validationErrors['Model_with_errors']

And that 'Model_with_errors' (in this case 'User') won't be displayed in the respective forms because we've changed the names. So we need to also tweak the view. Oh! I'm assuming these both forms are in a view called index.ctp, for example, but if they are on separate files (if you're using an element or similar) I recommend add the lines of code for all the files

//preferably in the first line of the view/element (index.ctp in this example)
if (!empty($this->validationErrors['User']) && isset($formName)) {
    $this->validationErrors[$formName] = $this->validationErrors['User'];
}

With that, we copy the model validation of the User to the fake-named form, and only that one. Note that if you have a third form in that view for the same model, and you use the typical $this->form->create('User'), then the validation errors will show for that one too unless you change the form name for that third one.

Doing that should work and only validate the form with the correct name.

I find this a messy approach because it involves controller-view changes. I think everything should be done by the controller, and the view shouldn't even blink about validation issues... The problem with that is that the render function of Controller.php needs to be replaced... It can be done in the AppController, but for every updgrade of Cakephp, you'll have to be careful of copying the new render function of Controller.php to the one replacing it in AppController. The advantage of that approach, though, is that the "feature" would be available for every form without having to worry about changing the views.

Well, it's just not that maintainable anyway, so better to leave it alone if it's just for this one case... If anyone is interested on how to handle this just in the controller side, though, comment and I'll post it.



回答2:

You can duplicate your model and change his name and define $useTable as the same table name.

Example :

class Registration extends AppModel {

public $useTable = 'users';

You define the action in form->create like Nunser for your login form

 <?php
    echo $this->Form->create('User',array(
        'url' => array(
            'controller' => 'Users',
            'action' => 'login',
            'user' => true
        ),
        'inputDefaults' => array(
            'div'   => false,
            'label' => false
        ),
        'novalidate'=>true,
    ));
?>

and your registration form

<?php
    echo $this->Form->create('Registration',array(
        'url' => array(
            'controller' => 'Users',
            'action' => 'validation_registration',
            'user' => false
        ),
        'inputDefaults' => array(
            'div'   => false,
            'label' => false
        ),
        'novalidate'=>true,
    ));
?>

In your controller define a method for registration validation and the most important define the render

public function validation_registration(){
    $this->loadModel('Registration');

            if($this->request->is('post')){

                if($this->Registration->save($this->request->data)){

                    --- code ---
                }else{
                    --- code ---
                }
            }

            $this->render('user_login');
}

Sorry for my english ! Have a nice day ! :D



回答3:

The create method on your login form is missing the 'url' key for creating the action attribute. I tried to re-create this once I fixed this and could not. Maybe that will fix it?