Ir para conteúdo

POWERED BY:

Arquivado

Este tópico foi arquivado e está fechado para novas respostas.

vieira.rrafael

Inscrição em três passos

Recommended Posts

Tenho as seguintes tabelas (apenas para ilustração).

CREATE TABLE `contact_users` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`email` varchar(100) NOT NULL,
`cell_phone` varchar(16) DEFAULT NULL,
`fixed_phone` varchar(16) DEFAULT NULL,
`user_id` int(11) DEFAULT NULL,	PRIMARY KEY  (`id`),
UNIQUE KEY `id` (`id`))	DEFAULT CHARSET=latin1,
COLLATE=latin1_swedish_ci,
ENGINE=MyISAM;

CREATE TABLE `groups` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) NOT NULL,	PRIMARY KEY  (`id`),
UNIQUE KEY `name` (`name`))	DEFAULT CHARSET=latin1,
COLLATE=latin1_swedish_ci,
ENGINE=MyISAM;

CREATE TABLE `profile_users` (
`id` int(20) NOT NULL AUTO_INCREMENT,
`name` varchar(100) NOT NULL,
`age` int(11) NOT NULL,
`user_id` int(11) DEFAULT NULL,
`sex` varchar(1) NOT NULL,	PRIMARY KEY  (`id`),
UNIQUE KEY `id` (`id`))	DEFAULT CHARSET=latin1,
COLLATE=latin1_swedish_ci,
ENGINE=MyISAM;

CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varchar(50) NOT NULL,
`group_id` int(11) DEFAULT NULL,	PRIMARY KEY  (`id`),
UNIQUE KEY `username` (`username`))	DEFAULT CHARSET=latin1,
COLLATE=latin1_swedish_ci,
ENGINE=MyISAM;

A ideia é bem simples: o usuário, na tela de inscrição, cadastra o login, dados do perfil e alguns meios de contato.

<div class="users form">
   <?php echo $this->Form->create('User'); ?>
   <?php
   $data_of_user = array(
       'legend' => __('Registro de novo usuário', TRUE),
       'username' => array('label' => 'Nome de usuário', 'maxlength' => 50),
       'password' => array('label' => 'Senha', 'maxlength' => 10),
       'password_confirmation' => array('label' => 'Repita a senha', 'maxlength' => 10, 'type' => 'password'),
       'group_id'
   );

   $profile_of_user = array(
       'legend' => __('Dados do seu perfil', TRUE),
       'ProfileUser.name' => array('label' => 'nome'),
       'ProfileUser.age' => array('label' => 'Idade'),
       'ProfileUser.sex' => array('label' => 'Sexo', 'type' => 'select', 'options' => array('M' => 'Masculino', 'F' => 'Feminino'),
           'selected' => 'M', 'empty' => FALSE)
   );

   $contact_of_user = array(
       'legend' => __('Seu contato', TRUE),
       'ContactUser.email',
       'ContactUser.cell_phone' => array('label' => 'Telefone celular'),
       'ContactUser.fixed_phone' => array('label' => 'telefone fixo')
   );

   echo $this->Form->inputs($data_of_user);
   echo $this->Form->inputs($profile_of_user);
   echo $this->Form->inputs($contact_of_user);
   ?>

   <?php echo $this->Form->end(__('Submit', true)); ?>
</div>

Está funcionando. Mas aí, eu decidi dividir em 3 passos. Então, ficou assim:

Adicionei ao controlador UsersController.php

<?php
class UsersController extends AppController {

   function registerLogin() {
       if (!empty($this->data)) {
           $this->Session->write('login', $this->data);
           $this->redirect(array('action' => 'registerProfile'));
       }
   }

   function registerProfile() {
       if (!empty($this->data)) {
           $this->Session->write('profile', $this->data);
           $this->redirect(array('action' => 'registerContact'));
       }
   }

   function registerContact() {
       if (!empty($this->data)) {
           $dados = array_merge($this->Session->read('login'), $this->Session->read('profile'), $this->data);
           $this->User->create($dados);
           if ($this->User->saveAll($dados)) {
               $this->Session->setFlash(__('Ok', TRUE));
               $this->redirect(array('action' => 'index'));
           } else {
               $this->Session->setFlash(__('Falhou', TRUE));
           }
       }
   }
}
?>

O valor da variável

$dados

é

Array
(
   [user] => Array
       (
           [username] => kal-el
           [password] => 432a9e689fb3fbc3009a13e8051b5b2ff43f137f725a3a4e002bedb6e5639c97
           [password_confirmation] => 432a9e689fb3fbc3009a13e8051b5b2ff43f137f725a3a4e002bedb6e5639c97
           [group_id] => 1
       )

   [ProfileUser] => Array
       (
           [name] => Rafael
           [age] => 21
           [sex] => M
       )

   [ContactUser] => Array
       (
           [email] => rafael@email.com
           [cell_phone] => 9146-0104
           [fixed_phone] => 3627-0831
       )

)

Apesar disso, não funciona!

Cai no else e mostra Falhou.

Alguma teoria?

Ví esse tópico http://forum.imasters.com.br/topic/423939-perdendo-sessao-na-view/. É semelhante, mas talvez a solução seja diferente. Por isso, esse novo

tópico.

Compartilhar este post


Link para o post
Compartilhar em outros sites

Eh! O Diabo mora nos detalhes!

Consegui resolver: faltava validar os campos.

As setas indicam as linhas que alterei e fez tudo funcionar.

    function registerLogin() {
       if (!empty($this->data)) {
           /* ---> */ $this->User->create($this->data);
           /* ---> */ if ($this->User->saveAll($this->data, array('validate' => 'only'))) {
               $this->Session->write('login', $this->data);
               $this->redirect(array('action' => 'registerProfile'));
           } else {
               unset($this->data['User']['password']);
               unset($this->data['User']['password_confirmation']);
           }
       }
   }

   function registerProfile() {
       if (!empty($this->data)) {
           /* ---> */ $this->User->ProfileUser->create($this->data);
           /* ---> */ if ($this->User->ProfileUser->saveAll($this->data, array('validate' => 'only'))) {
               $this->Session->write('profile', $this->data);
               $this->redirect(array('action' => 'registerContact'));
           }
       }
   }

   function registerContact() {
       if (!empty($this->data)) {
           /* ---> */ $this->User->ContactUser->create($this->data);
           /* ---> */ if ($this->User->ContactUser->saveAll($this->data, array('validate' => 'only'))) {
               $this->data = array_merge($this->Session->read('login'), $this->Session->read('profile'), $this->data);
               $this->add();
           }
       }
   }

Eu usei

saveAll($this->data, array('validate' => 'only'))

para validar porque ainda não me entendi com o

validate()

abraços!

Resolvido.

Sabe, se eu tivesse dito que todos os dados são validados por seus respectivos modelos, talvez ficasse mais fácil ser ajudado e até mesmo resolver. O problema que esqueci do fator validação. Só quando lembrei, pude pensar na solução.

 

Usar Sessões é a melhor forma de resolver o problema?

Compartilhar este post


Link para o post
Compartilhar em outros sites

×

Informação importante

Ao usar o fórum, você concorda com nossos Termos e condições.