We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Custom Validation is not getting the value fields to run

I have a couple of custom validators running smoothly with the same logic. I did not find anything incorrectly coding in this custom validator. So, please help me to find the error. I have attached the form, the controller, the custom validator, and the volt program. The issue is that I cannot get the name neither the value of the fields named as "estab" and "punto" in the custom validator.

CUSTOM VALIDATOR ValidaRucValidator.php


use Phalcon\Validation\Message;
use Phalcon\Validation\Validator;
use Phalcon\Validation\ValidatorInterface;

class ValidaRucValidator extends Validator implements ValidatorInterface {

    /**
     *
     * @param  Validation $validator
     * @param  string $attribute
     *
     * @return boolean
     */
    public function validate(Phalcon\Validation $validator, $attribute) {
        //obtain the name of the field 
        $elestab = $this->getOption("estab");

        //obtain field value
        $elestab_value = $validator->getValue($elestab);

        //obtain the name of the field 
        $elpunto = $this->getOption("punto");

        //obtain field value
        $elpunto_value = $validator->getValue($elpunto);

        // obtain the input field value
        $elruc_value = $validator->getValue($attribute);

        //try to obtain message defined in a validator
        $message = $this->getOption('message');

        $msg = 'message ' . $elestab_value . ' ' . $elpunto_value . ' ' . $elruc_value;
        print_r($msg);
        //check if the value is valid
        $ruc = Contribuyente::findFirst(array(
                    "Ruc = :ruc:  AND CodEmisor = :estab: AND Punto = :punto:",
                    'bind' => array('ruc' => $elruc_value, 'estab' => $elestab_value, 'punto' => $elpunto_value)
        ));
        if (!$ruc) {
            $message = 'NO estan registrados en nuestra base de datos el Ruc o el Establecimiento o el Punto de Emision- Vuelva ha intentarlo';
            $validator->appendMessage(new Message($message, $attribute, 'rucerror'));
        }
        if (count($validator->getMessages())) {
            return false;
        }
        return true;
    }

}

FORM SessionForm.php


use Phalcon\Forms\Form;
use Phalcon\Forms\Element\Password;
use Phalcon\Forms\Element\Text;
use Phalcon\Validation\Validator\PresenceOf;
use Phalcon\Validation\Validator\Email;

class SessionForm extends Form {

    public function initialize() {

        $ruc = new Text("ruc");
        $ruc->setLabel("Registro Unico de Contribuyentes");
        $ruc->setFilters(array('striptags', 'string'));
        $ruc->addValidators(array(
            new PresenceOf(array(
                'message' => 'No ha ingresado el numero del RUC'
                    )),
            new ValidaRucValidator(array(
                'ruc' => 'ruc',
                'message' => 'debe ingresar un numero de RUC valido'
                    ))
        ));
        $this->add($ruc);

        $estab = new Text("estab");
        $estab->setLabel("Numero Establecimiento");
        $estab->setFilters(array('striptags', 'string'));
        $estab->addValidators(array(
            new PresenceOf(array(
                'message' => 'No ha ingresado el numero del Establecimiento'
                    ))
        ));
        $this->add($estab);

        $punto = new Text("punto");
        $punto->setLabel("Numero Punto de Emision");
        $punto->setFilters(array('striptags', 'string'));
        $punto->addValidators(array(
            new PresenceOf(array(
                'message' => 'No ha ingresado el numero del Punto de Emision'
                    ))
        ));
        $this->add($punto);

        $email = new Text("email");
        $email->setLabel("Correo Electronico");
        $email->setFilters(array('striptags', 'string'));
        $email->addValidators(array(
            new PresenceOf(array(
                'message' => 'No ha ingresado la direccion de correo'
                    )),
            new Email(array(
                'message' => 'debe ingresar una direccion de correo valida'
                    ))
        ));
        $this->add($email);

        $password = new Password("password");
        $password->setLabel("Password");
        $password->addValidators(array(
            new PresenceOf(array(
                'message' => 'Debe ingresar una palabra clave'
                    )),
            new ValidaUserValidator(array(
                'correo' => 'email',
                'message' => 'El Email o el password no han sido registrados vuelva ha intentarlo'
                    ))
        ));

        $this->add($password);
    }

    public function messages($nombre) {
        if ($this->hasMessagesFor($nombre)) {
            foreach ($this->getMessagesFor($nombre) as $mensaje) {
                $this->flash->error($mensaje);
            }
        }
    }

}

VOLT index.volt

{{ content() }}
{% include "layouts/cabecera.volt" %}
<div class="jumbotron jumbotron-fluid" style="background-color: #C1C1C1">
    <div class="container-fluid">
        <div class="row">
            <div class="col col-md-6">
                {{ form('session/start', 'role': 'form', 'class': 'sky-form') }}
                <header>Log in</header>

                <fieldset>
                     <section>
                        <div class="col col-md-4">
                            <label class="label">Establecimiento y Punto de Emision</label>
                        </div>
                        <div class="col col-md-4">
                            <label class="input">
                                {{ form.render("estab", ['class': 'form-element form-element-icon']) }}
                            </label>
                            {{ form.messages('estab') }}
                        </div>
                        <div class="col col-md-4">
                            <label class="input">
                                {{ form.render("punto", ['class': 'form-element form-element-icon']) }}
                            </label>
                            {{ form.messages('punto') }}
                        </div>
                    </section>
                </fieldset>

                <fieldset>
                    <section>
                        <div class="col col-md-4">
                            <label class="label">Numero RUC</label>
                        </div>
                        <div class="col col-md-8">
                            <label class="input">
                                {{ form.render("ruc", ['class': 'form-element form-element-icon']) }}
                            </label>
                            {{ form.messages('ruc') }}
                        </div>
                    </section>
                </fieldset>

                <fieldset>
                    <section>
                        <div class="col col-md-4">
                            <label class="label">E-mail</label>
                        </div>
                        <div class="col col-md-8">
                            <label class="input">
                                {{ form.render("email", ['class': 'form-element form-element-icon']) }}
                            </label>
                            {{ form.messages('email') }}
                        </div>
                    </section>
                </fieldset>

                        <fieldset>
                    <section>
                        <div class="col col-md-4">
                            <label class="label">Password</label>
                        </div>
                        <div class="col col-md-8">
                            <label class="input">
                                {{ form.render("password", ['class': 'form-element form-element-icon']) }}
                            </label>
                            {{ form.messages('password') }}
                        </div>
                    </section>
                </fieldset>
                <footer>
                    {{ submit_button('Login', 'class': 'btn btn-primary btn-large') }}
                    {{ link_to('register', ' Registrarse ', 'class': 'btn btn-success btn-large', 'style':'color:white') }}
                </footer>
                </form>
            </div>

            <div class="col col-md-6">

                <div class="card" style="background-color: #C1C1C1">
                    <div class="card-body">
                        <h2 class="card-title">Ha creado una cuenta con nosotros?</h2>
                    </div>

                    <p>Estas son las opciones que podra realizar si se registra:</p>
                    <ul>
                        <li>Podra crear, envir y recibir mensajes.</li>
                        <li>Podra revisar el estado actual de su cuenta.</li>
                        <li>Podra bajar o imprimir uno o varios documentos electronicos</li>
                    </ul>

                </div>
            </div>
        </div>
    </div>
</div>
{% include "layouts/footer.volt" %}

CONTROLLER SessionController.php


/**
 * SessionController
 *
 * Allows to authenticate users
 */
class SessionController extends ControllerBase {

    public function initialize() {
        $this->tag->setTitle('Sign In');
        parent::initialize();
    }

    public function indexAction() {

        $form = new SessionForm;

        if ($this->request->isPost()) {

            if ($form->isValid($this->request->getPost()) != false) {

                if ($form->getMessages()) {
                    foreach ($form->getMessages() as $message) {
                        $this->flash->error((string) $message);
                    }
                }
            }
        }

        $this->view->form = $form;
    }

    /**
     * Register an authenticated user into session data
     *
     * @param Users $user
     */
    private function _registerSession(Users $user) {
        $this->session->set('auth', array(
            'id' => $user->id,
            'username' => $user->username,
            'tipo' => $user->tipo,
            'tipoId' => $user->tipoId,
            'numeroId' => $user->numeroId,
            'email' => $user->email,
            'qbid' => $user->qbid,
            'name' => $user->name
        ));
    }

    /**
     * This action authenticate and logs an user into the application
     *
     */
    public function startAction() {

        $ruc = $this->request->getPost('ruc');
        $estab = $this->request->getPost('estab');
        $punto = $this->request->getPost('punto');
        $email = $this->request->getPost('email');
        $password = $this->request->getPost('password');

        $user = Users::findFirst(array(
                    "(email = :email: OR username = :email:) AND password = :password: AND active = 'Y'",
                    'bind' => array('email' => $email, 'password' => sha1($password))
        ));
        $ruc = Contribuyente::findFirst(array(
                       "Ruc = :ruc:  AND CodEmisor = :estab: AND Punto = :punto:",
                    'bind' => array('ruc' => $elruc_value, 'estab' => $elestab_value, 'punto' => $elpunto_value)
        ));

        if ($user and $ruc) {
            $this->_registerSession($user);
            $this->flash->success('Welcome ' . $user->name);

            switch ($user->tipo) {
                case 'PROVEEDOR':
                    return $this->dispatcher->forward(
                                    [
                                        "controller" => "home",
                                        "action" => "index",
                                    ]
                    );
                    break;

                case 'CLIENTE':
                    return $this->dispatcher->forward(
                                    [
                                        "controller" => "home",
                                        "action" => "index",
                                    ]
                    );
                    break;

                default:

                    $ticket = Aticket::findFirst(array(
                                "Estado = :estado:",
                                "bind" => array("estado" => "GRABADO")
                    ));
                    if ($ticket) {
                        $this->session->set('pendiente', array(
                            "estado" => "GRABADO",
                            "RefNumber" => $ticket->getTxnID()
                        ));
                    }
                    $pago = Receivepayment::findFirst(array(
                                "Status = :estado:",
                                "bind" => array("estado" => "GRABADO")
                    ));
                    if ($pago) {
                        $this->session->set('pagopendiente', array(
                            "estado" => "GRABADO",
                            "RefNumber" => $pago->getRefNumber(),
                            "TxnID" => $pago->getTxnID()
                        ));
                    }
//                $caja = Cashier::findFirst(array(
//                            "Estado = :estado:",
//                            "bind" => array("estado" => "ABIERTO")
//                ));
//                if ($caja) {
//                    $this->session->set('cajaabierta', array(
//                        "estado" => "ABIERTO",
//                        "RefNumber" => $caja->getRefNumber()
//                    ));
//                }
                    return $this->dispatcher->forward(
                                    [
                                        "controller" => "contribuyente",
                                        "action" => "index",
                                    ]
                    );
                    break;
            }
        }

//        $this->flash->error('No existen ni la direccion de correo ni la palabra clave - Vuelva ha intentarlo');
        return $this->dispatcher->forward(
                        [
                            "controller" => "session",
                            "action" => "index",
                        ]
        );
    }

    /**
     * Finishes the active session redirecting to the index
     *
     * @return unknown
     */
    public function endAction() {
        $this->session->remove('auth');
        $this->session->remove('ruc');
        $this->session->remove('contribuyente');
        $this->session->remove('pendiente');
        $this->session->remove('pagopendiente');
        $this->flash->success('Hasta Luego!');
        session_destroy();

        return $this->dispatcher->forward(
                        [
                            "controller" => "home",
                            "action" => "index",
                        ]
        );
    }

}


23.9k
Accepted
answer

I found the issue,, sorry for bother you. I did not add the fields in the form. For instance

            new ValidaRucValidator(array(
                'establecimiento' => 'estab',
                'puntoemision' => 'punto',
                'message' => 'debe ingresar un numero de RUC valido'
                    ))