0

My customer account register form is appearing this error when I try register a new account:

Notice: Undefined variable: data in /home/clientes/grupofiscall/public_html/diaadiatributario.com.br/app/code/local/Diaadia/Usuario/controllers/AccountController.php on line 142

AccountController.php

<?php
require_once(Mage::getModuleDir('controllers', 'Mage_Customer') . DS . 'AccountController.php');
class Diaadia_Usuario_AccountController extends Mage_Customer_AccountController

{
    /**
     * Action predispatch
     *
     * Check customer authentication for some actions
     */
    public function preDispatch()
    {
        Mage_Core_Controller_Front_Action::preDispatch();

        if (!$this->getRequest()->isDispatched()) {
            return;
        }

        $action = $this->getRequest()->getActionName();
        $openActions = array(
            'create',
            'login',
            'logoutsuccess',
            'forgotpassword',
            'forgotpasswordpost',
            'resetpassword',
            'resetpasswordpost',
            'confirm',
            'confirmation',
            'plano',
            'tempoassinatura',
            'newsletter',
            'politicasdeuso',
            'confirmacao'
        );
        $pattern = '/^(' . implode('|', $openActions) . ')/i';

        if (!preg_match($pattern, $action)) {
            if (!$this->_getSession()->authenticate($this)) {
                $this->setFlag('', 'no-dispatch', true);
            }
        } else {
            $this->_getSession()->setNoReferer(true);
        }
    }

    public function planoAction()
    {
        $this->loadLayout();
        $this->getLayout()->getBlock('head')->setTitle($this->__('Escolha do Plano'));
        $this->renderLayout();
    }

    public function tempoassinaturaAction()
    {
        $this->loadLayout();
        $this->getLayout()->getBlock('head')->setTitle($this->__('Tempo de assinatura'));
        $this->renderLayout();
    }

    public function newsletterAction()
    {
        $this->loadLayout();
        $this->getLayout()->getBlock('head')->setTitle($this->__('Cadastro Newsletter'));
        $this->renderLayout();
    }

    public function politicasdeusoAction()
    {
        $this->loadLayout();
        $this->getLayout()->getBlock('head')->setTitle($this->__('Políticas de uso'));
        $this->renderLayout();
    }

    public function confirmacaoAction()
    {
        $this->loadLayout();
        $this->getLayout()->getBlock('head')->setTitle($this->__('Confirmação'));
        $this->renderLayout();
    }

    public function getPriceHtml($product)
    {
        $this->setTemplate('catalog/product/price.phtml');
        $this->setProduct($product);
        return $this->toHtml();
    }

    public function downloadsAction()
    {
        $this->loadLayout();
        $this->getLayout()->getBlock('head')->setTitle($this->__('Downloads'));
        $this->renderLayout();
    }

    public function publicarAction()
    {
        $this->loadLayout();
        $this->getLayout()->getBlock('head')->setTitle($this->__('Publicação'));
        $this->renderLayout();
    }

    /**
     * Create customer account action
     */
    public function createPostAction()
    {
        /** @var $session Mage_Customer_Model_Session */
        $session = $this->_getSession();
        
        if ($session->isLoggedIn()) {
            $this->_redirect('*/*/');
            return;
        }
        $customer = $this->_getCustomer();
        $session->setEscapeMessages(true); // prevent XSS injection in user input
        
        if (!$this->getRequest()->isPost()) {
            $errUrl = $this->_getUrl('*/*/create', array('_secure' => true));
            $this->_redirectError($errUrl);
            return;
        }else{
            $errors = array();
            if (!$customer = Mage::registry('current_customer')) {
                $customer = Mage::getModel('customer/customer')->setId(null);
            }

            /* @var $customerForm Mage_Customer_Model_Form */
            $customerForm = Mage::getModel('customer/form');
            $customerForm->setFormCode('customer_account_create')
            ->setEntity($customer);
            

            if($this->getRequest()->getPost('tipo-pessoa') == "Física"){
                $data = $this->getRequest()->getPost('fisica');
                $data['tipo_pessoa'] = 'Física';
            }elseif($this->getRequest()->getPost('tipo-pessoa') == "Jurídica"){
                $data = $this->getRequest()->getPost('juridica');
                $data['tipo_pessoa'] = 'Jurídica';
            }

            if(strlen($data['day']) == 1){
                $data['day'] = '0'.$data['day'];
            }
            if(strlen($data['month']) == 1){
                $data['month'] = '0'.$data['month'];
            }

            $data['dob'] = $data['year'].'/'.$data['month'].'/'.$data['day'];

            $verifica = Mage::getModel('customer/customer');
            $verifica->setWebsiteId(Mage::app()->getWebsite()->getId());
            $verifica->loadByEmail($data['email']);

            if ($verifica->getId() > 0 ) {
                $this->_redirectError(Mage::getUrl('*/*/create/error/exists/', array('_secure' => true)));
            }
            $customer->setGroupId(1);
            $customer->setData($data);
        }

        try {
            $errors = $this->_getCustomerErrorsTipo($customer);

            if (empty($errors)) {
                $customer->save();
                $this->_dispatchRegisterSuccess($customer);
                $this->_successProcessRegistration($customer);
                return;
            } else {
                $this->_addSessionError($errors);
            }
        } catch (Mage_Core_Exception $e) {
            $session->setCustomerFormData($this->getRequest()->getPost());
            if ($e->getCode() === Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS) {
                $url = $this->_getUrl('customer/account/forgotpassword');
                $message = $this->__('There is already an account with this email address. If you are sure that it is your email address, <a href="%s">click here</a> to get your password and access your account.', $url);
                $session->setEscapeMessages(false);
            } else {
                $message = $e->getMessage();
            }
            $session->addError($message);
        } catch (Exception $e) {
            $session->setCustomerFormData($this->getRequest()->getPost())
            ->addException($e, $this->__('Cannot save the customer.'));
        }
        $errUrl = $this->_getUrl('*/*/create', array('_secure' => true));
        $this->_redirectError($errUrl);
    }

    /**
     * Success Registration
     *
     * @param Mage_Customer_Model_Customer $customer
     * @return Mage_Customer_AccountController
     */
    protected function _successProcessRegistration(Mage_Customer_Model_Customer $customer)
    {
        $session = $this->_getSession();
        if ($customer->isConfirmationRequired()) {
            /** @var $app Mage_Core_Model_App */
            $app = $this->_getApp();
            /** @var $store  Mage_Core_Model_Store*/
            $store = $app->getStore();
            $customer->sendNewAccountEmail(
                'confirmation',
                $session->getBeforeAuthUrl(),
                $store->getId()
            );
            $customerHelper = $this->_getHelper('customer');
            $session->addSuccess($this->__('Account confirmation is required. Please, check your email for the confirmation link. To resend the confirmation email please <a href="%s">click here</a>.',
                $customerHelper->getEmailConfirmationUrl($customer->getEmail())));
            $url = $this->_getUrl('*/*/index', array('_secure' => true));
        } else {
            $session->setCustomerAsLoggedIn($customer);
            $session->renewSession();
            $url = $this->_welcomeCustomer($customer);
        }
        //$this->_redirectSuccess($url);
        $this->_redirect('customer/account/politicasdeuso/');
        return $this;
    }

    /**
     * Validate customer data and return errors if they are
     *
     * @param Mage_Customer_Model_Customer $customer
     * @return array|string
     */
    protected function _getCustomerErrorsTipo($customer)
    {
        $errors = array();
        $request = $this->getRequest();
        if ($request->getPost('create_address')) {
            $errors = $this->_getErrorsOnCustomerAddress($customer);
        }

        $customerForm = $this->_getCustomerForm($customer);
        $customerData = $customer->getData();
        $customerErrors = $customerForm->validateData($customerData);
        if ($customerErrors !== true) {
            $errors = array_merge($customerErrors, $errors);
        } else {
            $customerForm->compactData($customerData);
            $customer->setPassword($customerData['password']);
            $customer->setConfirmation($customerData['confirmation']);
            $customerErrors = $customer->validate();
            if (is_array($customerErrors)) {
                $errors = array_merge($customerErrors, $errors);
            }
        }
        return $errors;
    }

    /**
     * Gets customer address
     *
     * @param $customer
     * @return array $errors
     */
    protected function _getErrorsOnCustomerAddress($customer)
    {
        $errors = array();
        /* @var $address Mage_Customer_Model_Address */
        $address = $this->_getModel('customer/address');
        /* @var $addressForm Mage_Customer_Model_Form */
        $addressForm = $this->_getModel('customer/form');
        $addressForm->setFormCode('customer_register_address')
            ->setEntity($address);

        $addressData = $customer->getData();//$addressForm->extractData($this->getRequest(), 'address', false);
        $addressErrors = $addressForm->validateData($addressData);
        if (is_array($addressErrors)) {
            $errors = array_merge($errors, $addressErrors);
        }
        $address->setId(null)
            ->setIsDefaultBilling($addressData['default_billing'])
            ->setIsDefaultShipping($addressData['default_shipping']);
        $addressForm->compactData($addressData);
        $customer->addAddress($address);

        $addressErrors = $address->validate();
        if (is_array($addressErrors)) {
            $errors = array_merge($errors, $addressErrors);
        }
        return $errors;
    }

    /**
     * Forgot customer password action
     */
    public function forgotPasswordPostAction()
    {
        $tipo = $this->getRequest()->getPost('tipo-pessoa', 'fisica');
        $campo = $tipo === 'juridica' ? 'cnpj' : 'cpf';
        $nome = strtoupper($campo);
        $taxvat = $this->getRequest()->getPost($campo, null);

        if ($taxvat) {
            if (!Zend_Validate::is($taxvat , 'NotEmpty')) {
                $this->_getSession()->addError($this->__($nome . ' inválido.'));
                $this->_redirect('cliente/conta/recuperar-senha');
                return;
            }

            /** @var $customer Mage_Customer_Model_Customer */
            $collection = Mage::getModel('customer/customer')->getCollection()->addFieldToFilter('taxvat', $taxvat)->load();

            if ($collection->getSize()) {
                foreach($collection as $val) {
                    $customer = $val;
                }

                if ($customer->getId()) {
                    try {
                        $newResetPasswordLinkToken =  $this->_getHelper('customer')->generateResetPasswordLinkToken();
                        $customer->changeResetPasswordLinkToken($newResetPasswordLinkToken);
                        $customer->sendPasswordResetConfirmationEmail();
                    } catch (Exception $exception) {
                        $this->_getSession()->addError($exception->getMessage());
                        $this->_redirect('cliente/conta/recuperar-senha');
                        return;
                    }
                }
                $this->_getSession()
                    ->addSuccess( $this->_getHelper('customer')
                        ->__('Se houver uma conta associada à %s você receberá um email com link para refazer sua senha.',
                            $this->_getHelper('customer')->escapeHtml($taxvat)));
                $this->_redirect('cliente/conta/');
                return;

            } else {
                $this->_getSession()->addError($this->__('Informe seu CPF ou CNPJ corretamente.'));
                $this->_redirect('cliente/conta/recuperar-senha');
                return;
            }
        } else {
            $this->_getSession()->addError($this->__('Informe seu CPF ou CNPJ corretamente.'));
            $this->_redirect('cliente/conta/recuperar-senha');
            return;
        }
    }

    /**
     * Change customer password action
     */
    public function editPostAction()
    {
        if (!$this->_validateFormKey()) {
            return $this->_redirect('*/*/edit');
        }

        if ($this->getRequest()->isPost()) {
            /** @var $customer Mage_Customer_Model_Customer */
            $customer = $this->_getSession()->getCustomer();

            /** @var $customerForm Mage_Customer_Model_Form */
            $customerForm = $this->_getModel('customer/form');
            $customerForm->setFormCode('customer_account_edit')
                ->setEntity($customer);

            $customerData = $customerForm->extractData($this->getRequest());
            $mes = $this->getRequest()->getParam('month');
            if (count($mes) == 1) {
                $mes = '0' . $mes;
            }
            $customerData['dob'] = $this->getRequest()->getParam('year').'/'.$mes.'/'.$this->getRequest()->getParam('day');

            $cnpj = $this->getRequest()->getParam('vat_id');
            if(isset($cnpj) and !empty($cnpj)){
                $address  = Mage::getModel('customer/address');
                $addressId = $this->getRequest()->getParam('id');
                if ($addressId) {
                    $existsAddress = $customer->getAddressById($addressId);
                    if ($existsAddress->getId() && $existsAddress->getCustomerId() == $customer->getId()) {
                        $address->setId($existsAddress->getId());
                    }
                }

                $address->setCustomerId($customer->getId())
                    ->setIsDefaultBilling(true)
                    ->setIsDefaultShipping(true)
                    ->setVatId($cnpj);

                $address->save();
            }

            $errors = array();
            $customerErrors = $customerForm->validateData($customerData);
            if ($customerErrors !== true) {
                $errors = array_merge($customerErrors, $errors);
            } else {
                $customerForm->compactData($customerData);
                $errors = array();

                // If password change was requested then add it to common validation scheme
                if ($this->getRequest()->getParam('change_password')) {
                    $currPass   = $this->getRequest()->getPost('current_password');
                    $newPass    = $this->getRequest()->getPost('password');
                    $confPass   = $this->getRequest()->getPost('confirmation');

                    $oldPass = $this->_getSession()->getCustomer()->getPasswordHash();
                    if ( $this->_getHelper('core/string')->strpos($oldPass, ':')) {
                        list($_salt, $salt) = explode(':', $oldPass);
                    } else {
                        $salt = false;
                    }

                    if ($customer->hashPassword($currPass, $salt) == $oldPass) {
                        if (strlen($newPass)) {
                            /**
                             * Set entered password and its confirmation - they
                             * will be validated later to match each other and be of right length
                             */
                            $customer->setPassword($newPass);
                            $customer->setConfirmation($confPass);
                        } else {
                            $errors[] = $this->__('New password field cannot be empty.');
                        }
                    } else {
                        $errors[] = $this->__('Invalid current password');
                    }
                }

                // Validate account and compose list of errors if any
                $customerErrors = $customer->validate();
                if (is_array($customerErrors)) {
                    $errors = array_merge($errors, $customerErrors);
                }
            }

            if (!empty($errors)) {
                $this->_getSession()->setCustomerFormData($this->getRequest()->getPost());
                foreach ($errors as $message) {
                    $this->_getSession()->addError($message);
                }
                $this->_redirect('*/*/editar');
                return $this;
            }

            try {
                $customer->setConfirmation(null);
                $customer->save();
                $this->_getSession()->setCustomer($customer)
                    ->addSuccess($this->__('The account information has been saved.'));

                $this->_redirect('cliente/conta');
                return;
            } catch (Mage_Core_Exception $e) {
                $this->_getSession()->setCustomerFormData($this->getRequest()->getPost())
                    ->addError($e->getMessage());
            } catch (Exception $e) {
                $this->_getSession()->setCustomerFormData($this->getRequest()->getPost())
                    ->addException($e, $this->__('Cannot save the customer.'));
            }
        }

        $this->_redirect('*/*/editar');
    }

    protected function _loginPostRedirect()
    {
        if (Mage::app()->getStore()->getCode() == 'mobile'){
            $referer = $this->getRequest()->getParam(Mage_Customer_Helper_Data::REFERER_QUERY_PARAM_NAME);

            if ($referer) {
                $url = $this->_getHelper('core')->urlDecode($referer);
                $this->_redirectUrl($url);
                return;
            }
        }

        parent::_loginPostRedirect();
    }
}

1
  • Replace if(strlen($data['day']) == 1){ with if(isset($data['day'] && strlen($data['day']) == 1){
    – S.P
    Commented May 5, 2022 at 5:43

2 Answers 2

0

In the createPostAction action, the $data variable only gets defined in an if and elseif statement. If neither of those conditions are true, $data doesn't get defined and will throw the error on subsequent attempts to interact with it.

I would define $data = array(); above the first tipo pessoa check to ensure it is initialized before any subsequent code tries to act on it.

That will fix the undefined variable error, but there might need to be more error checking if you are running into cases where typo pessoa doesn't match your expected values (Fisica, Juridica) but the code continues to process assuming values are set in $data.

    /**
     * Create customer account action
     */
    public function createPostAction()
    {
        ...
            $data = array(); // Add this line

            if($this->getRequest()->getPost('tipo-pessoa') == "Física"){
                $data = $this->getRequest()->getPost('fisica');
                $data['tipo_pessoa'] = 'Física';
            }elseif($this->getRequest()->getPost('tipo-pessoa') == "Jurídica"){
                $data = $this->getRequest()->getPost('juridica');
                $data['tipo_pessoa'] = 'Jurídica';
            }

        ...
    }

0

Yous should check array element exist or not.

Replace createPostAction function with below.

public function createPostAction()
    {
        /** @var $session Mage_Customer_Model_Session */
        $session = $this->_getSession();
        
        if ($session->isLoggedIn()) {
            $this->_redirect('*/*/');
            return;
        }
        $customer = $this->_getCustomer();
        $session->setEscapeMessages(true); // prevent XSS injection in user input
        
        if (!$this->getRequest()->isPost()) {
            $errUrl = $this->_getUrl('*/*/create', array('_secure' => true));
            $this->_redirectError($errUrl);
            return;
        }else{
            $errors = array();
            if (!$customer = Mage::registry('current_customer')) {
                $customer = Mage::getModel('customer/customer')->setId(null);
            }

            /* @var $customerForm Mage_Customer_Model_Form */
            $customerForm = Mage::getModel('customer/form');
            $customerForm->setFormCode('customer_account_create')
            ->setEntity($customer);
            

            if($this->getRequest()->getPost('tipo-pessoa') == "Física"){
                $data = $this->getRequest()->getPost('fisica');
                $data['tipo_pessoa'] = 'Física';
            }elseif($this->getRequest()->getPost('tipo-pessoa') == "Jurídica"){
                $data = $this->getRequest()->getPost('juridica');
                $data['tipo_pessoa'] = 'Jurídica';
            }

            if(isset($data['day']) && strlen($data['day']) == 1){
                $data['day'] = '0'.$data['day'];
            }
            else
            {
                $data['day'] = '0';
            }
            if(isset($data['month']) && strlen($data['month']) == 1){
                $data['month'] = '0'.$data['month'];
            }
            else
            {
                $data['month'] = '0';
            }
            if(!isset($data['year'])){
                $data['year'] = '0000';
            }

            $data['dob'] = $data['year'].'/'.$data['month'].'/'.$data['day'];

            if(isset($data['email']))
            {
                $verifica = Mage::getModel('customer/customer');
                $verifica->setWebsiteId(Mage::app()->getWebsite()->getId());
                $verifica->loadByEmail($data['email']);                
                if ($verifica->getId() > 0 ) {
                $this->_redirectError(Mage::getUrl('*/*/create/error/exists/', array('_secure' => true)));
                }
                    $customer->setGroupId(1);
                    $customer->setData($data);
                }
        }
        try {
            $errors = $this->_getCustomerErrorsTipo($customer);
            if (empty($errors)) {
                $customer->save();
                $this->_dispatchRegisterSuccess($customer);
                $this->_successProcessRegistration($customer);
                return;
            } else {
                $this->_addSessionError($errors);
            }
        } catch (Mage_Core_Exception $e) {
            $session->setCustomerFormData($this->getRequest()->getPost());
            if ($e->getCode() === Mage_Customer_Model_Customer::EXCEPTION_EMAIL_EXISTS) {
                $url = $this->_getUrl('customer/account/forgotpassword');
                $message = $this->__('There is already an account with this email address. If you are sure that it is your email address, <a href="%s">click here</a> to get your password and access your account.', $url);
                $session->setEscapeMessages(false);
            } else {
                $message = $e->getMessage();
            }
            $session->addError($message);
        } catch (Exception $e) {
            $session->setCustomerFormData($this->getRequest()->getPost())
            ->addException($e, $this->__('Cannot save the customer.'));
        }
        $errUrl = $this->_getUrl('*/*/create', array('_secure' => true));
        $this->_redirectError($errUrl);
    }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.