4

Estoy tratando de hace una validación que aunque valida bien pero me resultan dos problemas mas que están relacionados. Son los siguientes: 1. Cuando valido uso el <?php echo set_value('') ?> para cada campo y cuando me devuelva los errores me queden los campos llenados y no se me borren. El problemas esta en que el textarea no funcione el set_value y no me guarda los datos. 2. Cuando valido utilizo el condicional

if( $this->form_validation->run() === FALSE){
      $datos['contenido'] = 'emails';
       $this->load->view('contacto/mailcontacto', $datos);
}

y me devuelva a la pagina y corregir los datos pero cuando corrigo y le doy submit me doy cuenta que no envia el formulario sino que mas bien me repitiera la funcion y en el url me aparece http:dominio.com/index.php/emails/emails/enviar y la pagina 404 Page Not Found The page you requested was not found. En conclusión mi idea es que al colocar los datos bien me lleve al controlador de contacto con un mensaje de correo enviado y me envíe el email de lo contrario si la validación es incorrecta no pase y me muestre los errores sin que me borre lo que he llenado y cuando los llene me envie al controlador contacto y con el mensaje la validación es correcta y claro en envíe el correo. A continuación el codigo.

// Controlador (Controllers)

<?php
class Emails extends CI_Controller{
   public function __construct(){
    parent::__construct();

    $this->load->library(array('email', 'form_validation'));
  }

  function index(){
    $datos['contenido'] = 'emails';
    $this->load->view('contacto/mailcontacto', $datos); 
  }

  function enviar() {
     $nombre = $this->input->post('nombre');
            $telefono = $this->input->post('telefono');
            $pais = $this->input->post('pais');
            $ciudad = $this->input->post('ciudad');
            $email = $this->input->post('email');
            $asunto = $this->input->post('asunto');
            $mensaje = $this->input->post('mensaje');
            $body_msg =  '<html><body><br />'.
    '<h2><font face="times new roman" color="#da0021"><span><font face="times new roman" color="#00769f"> CONTACTO</h2></font>'.
    '<table rules="all" style="border-width: 1px; border-style: dashed; border-color: #50a9d5; " cellpadding="10">' .
    "<tr><td><strong>Nombre</strong> </td><td>" . $nombre . "</td></tr>".
    "<tr><td><strong>Telefono:</strong> </td><td>" . $telefono . "</td></tr>".
    "<tr><td><strong>Pais:</strong> </td><td>" . $pais . "</td></tr>".
    "<tr><td><strong>Ciudad:</strong> </td><td>" . $ciudad . "</td></tr>".
    "<tr style=style='background: #eee;'><td><strong>Email del usuario:</strong> </td><td>" . $email. "</td></tr>".
    "<tr><td><strong>Asunto:</strong> </td><td>" . $asunto . "</td></tr>".
    "<tr><td><strong>Mensaje:</strong> </td><td>" . $mensaje . "</td></tr></table>".
    '<table rules="all" style="border-width: 0px">' .
    '<tr><td><img src="http://img/logo.png"/></td></tr></table>'.
    "<br />";


    $this->form_validation->set_rules('nombre', 'Nombre', 'trim|required|min_length[3]');
    $this->form_validation->set_rules('telefono', 'Telefono', 'trim|required|numeric');
    $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email');
    $this->form_validation->set_rules('mensaje', 'Mensaje', 'trim|required|min_length[3]');

    //Mensajes
    // %s es el nombre del campo que ha fallado
    $this->form_validation->set_message('required','El campo %s es obligatorio'); 
    $this->form_validation->set_message('alpha','El campo %s debe estar compuesto solo por letras');
    $this->form_validation->set_message('min_length', ' %s es muy corto');
    $this->form_validation->set_message('valid_email','El campo %s debe ser un email correcto');
    $this->form_validation->set_message('numeric','El campo %s debe contener solo numeros');


  if( $this->form_validation->run() === FALSE){
      $datos['contenido'] = 'emails';
       $this->load->view('contacto/mailcontacto', $datos); 
  }
  else{
     //Acción a tomas si no existe ningun error
     // Datos para enviar el correo
            $this->email->from('[email protected]', 'NOMBRE');
            $this->email->to('[email protected]');
            $this->email->bcc('[email protected]');  
            $this->email->subject($asunto);               
            $this->email->message($body_msg );


    $this->email->send();

    redirect('contacto'); // Se direcciona
  }
}
}
?>

// Vista (views) contacto/mailcontacto

<form action="emails/enviar" method="post">
<table style="margin:-01px auto; width:100%;background:#ffffff"> <tr>
      <td style="padding:10px 10px 10px 10px"><label><a style="color:#E41519">&nbsp;</a><a style="font-family: 'Roadgeek 2005 Series 1B', sans-serif; font-size:16px; color:#000000; ">Envianos un mensaje o requerimiento y un asesor lo contactara a la brevedad posible:
      </a></label></td>

    </tr></tbody></table>

    <table style="width:100%; background:#ffffff;">
  <tbody>
   <tr>

       <td style=" background:#05C421"><?php if(isset($mensaje)) echo $mensaje; ?></h2>
        <?=validation_errors();?><!--mostrar los errores de validación--></td></tr>
  </tbody>

</table>
<table style="width:100%; height:auto; background:#ffffff; margin:05px auto;">
  <tbody>
    <tr>
      <td><table style="margin:-50px auto; width:100%;  width:60%; background:#ffffff">
  <tbody>
    <tr>
      <td style="padding:20px 10px 10px 10px"><table width="200" border="1">
  <tbody>
    <tr>
      <td><label><a style="font-family: 'Roadgeek 2005 Series 1B', sans-serif; font-size:16px; color:#000000; ">Nombre:
      </a></label></td>
      <td>&nbsp;</td>
    </tr>
  </tbody>
</table>
</td>
      <td>&nbsp;</td>
      <td style="padding:20px 10px 10px 10px"><table width="200" border="1">
  <tbody>
    <tr>
      <td><label><a style="font-family: 'Roadgeek 2005 Series 1B', sans-serif; font-size:16px; color:#000000; ">Tel&eacute;fono:
      </a></label></td>
      <td>&nbsp;</td>
    </tr>
  </tbody>
</table></td>
    </tr>
    <tr>
      <td><input  type="text"  placeholder="" id="nombre" name="nombre" class="form-control logpadding margtop10 mayuscula"   autofocus="autofocus" value="<?php echo set_value('nombre') ?>" /></td>

      <td>&nbsp;</td>
     <td><input type="text" placeholder="0261000000" id="telefono" name="telefono" class="form-control logpadding margtop10" value="<?php echo set_value('telefono') ?>"/></td>
    </tr>
    <tr>
    <tr><td ><a style="color:#F0080C"><?php  echo form_error('nombre')  ?></a>  </td><td></td><td><a style="color:#F0080C"><?php  echo form_error('telefono')  ?></a> </td></tr>
      <td><a style="color:#24BCFC"> Solo  Formato Letras permitidas</a></td><br/><br/>
      <td>&nbsp;</td>
       <td><a style="color:#24BCFC">Solo  Formato N&uacute;meros permitidos</a></td><br/><br/>
    </tr>
    <tr>
      <td style="padding:10px 10px 10px 10px"><table width="200" border="1">
  <tbody>
    <tr>
      <td><br/>
      <label><a style="font-family: 'Roadgeek 2005 Series 1B', sans-serif; font-size:16px; color:#000000; ">Pais:
      </a></label></td>
      <td>&nbsp;</td>
    </tr>
  </tbody>
</table>
</td
      ><td>&nbsp;</td>
      <td style="padding:10px 10px 10px 10px"><table width="200" border="1">
  <tbody>
    <tr>
      <td><br/>
      <label><a style="font-family: 'Roadgeek 2005 Series 1B', sans-serif; font-size:16px; color:#000000; ">Ciudad:
      </a></label></td>
      <td>&nbsp;</td>
    </tr>
  </tbody>
</table></td>
    </tr>
    <tr><tr><td><a style="color:#F0080C"><?php  echo form_error('pais') ?></a></td><td></td><td><a style="color:#F0080C"><?php  echo form_error('ciudad') ?></a></td></tr>
      <td><input type="text"  id="pais" name="pais" class="form-control logpadding margtop10" value="<?php echo set_value('pais') ?>"/></td>
      <td>&nbsp;</td>
      <td><input type="text"  id="ciudad" name="ciudad" class="form-control logpadding margtop10" value="<?php echo set_value('ciudad') ?>"/></td>
    </tr>

    <tr>
      <td style="padding:10px 10px 10px 10px"><table width="200" border="1">
  <tbody>
    <tr>
      <td><br/><label><a style="font-family: 'Roadgeek 2005 Series 1B', sans-serif; font-size:16px; color:#000000; ">Email:
      </a></label></td>
      <td>&nbsp;</td>
    </tr>
  </tbody>
</table></td>
      <td>&nbsp;</td>
       <td style="padding:10px 10px 10px 10px"><table width="200" border="1">
  <tbody>
    <tr>
       <td><br/>
       <label><a style="font-family: 'Roadgeek 2005 Series 1B', sans-serif; font-size:16px; color:#000000; ">Asunto:
      </a></label></td>
      <td>&nbsp;</td>
    </tr>
  </tbody>
</table></td>
    </tr>
    <tr><tr><td><a style="color:#F0080C"><?php  echo form_error('email') ?></a></td><td></td><td><a style="color:#F0080C"><?php  echo form_error('asunto') ?></a></td></tr>
      <td><input type="text" placeholder="" id="email" name="email" class="form-control logpadding margtop10"    autofocus="autofocus" value="<?php echo set_value('email') ?>" /></td>
      <td>&nbsp;</td>
      <td><input  type="text"  placeholder="veniviajes" id="asunto" name="asunto" class="form-control logpadding margtop10 mayuscula"  value="<?php echo set_value('asunto') ?>" /></td>
    </tr>
    <tr>
      <td> <a style="color:#24BCFC"> Solo Formato Email permitido</a>
        <br/><br/></td>
      <td>&nbsp;</td>
      <td> <a style="color:#E41519"> </a>
        <br/><br/></td>
    </tr>

</table></td></tr><tr><td><table style="margin:50px auto; width:100%;  width:60%; background:#ffffff"> <tr>
      <td style="padding:10px 10px 10px 10px">  <label><a style="font-family: 'Roadgeek 2005 Series 1B', sans-serif; font-size:16px; color:#000000; ">¿En que podemos ayudarte?:
      </a></label></td>

    </tr><tr><td><textarea class="mayuscula"  rows="04" id="mensaje" name="mensaje"  style="margin-top:08px; width:80%"value="<?php echo set_value('mensaje, $foo') ?>"/></textarea></td></tr><tr><td><a style="color:#F0080C"><?php  echo form_error('mensaje') ?></a></td></tr></table></td></tr></tbody></table>
<table style="width:100%; background:#ffffff;">
  <tbody>
    <tr>
      <td><button  style=" margin:0 auto; type="submit" value="enviar" class="btn btn-primary">Enviar</button></td>
    </tr>
  </tbody>

</table>

</form>

1 respuesta 1

1

Te paso un ejemplo de como seria la validacion de un formulario mostrando los erorres individualmente y un mensaje usando session->flashdata cuando ya lo enviaste, asi como se hizo en el post anterior (en este ejemplo no quite el index.php de la url)

application/config/autoload.php

$autoload['libraries'] = array('form_validation', 'session');
$autoload['helper'] = array('url', 'form');

application/config/routes.php

$route['default_controller'] = "welcome";
$route['404_override']  = '';

$route['enviar']        = 'emails/enviar';

application/config/config.php

$config['base_url'] = 'http://localhost/form_test/';
$config['index_page'] = 'index.php';
$config['encryption_key'] = 'your_key';

applicatoin/controllers/welcome.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Welcome extends CI_Controller {

    public function index()
    {
        $this->load->view('welcome_message');
    }

        public function form_test(){
            $this->load->view('form_test');
        }
}

/* End of file welcome.php */
/* Location: ./application/controllers/welcome.php */

application/views/form_test.php

<html>
<head>
  <title>Form Test</title>
</head>
<body>
  <?php
  if( ! empty($this->session->flashdata('ok'))){
    echo $this->session->flashdata('ok');
  }
  ?>
  <form action="<?= base_url('index.php/enviar')?>" method="post">
    <table style="width:80%; margin-left:12%">
      <tbody>
        <tr>
          <td>
            <table style="width:70%; margin-left:16%; margin-right:16%;">
              <tbody>
                <tr>
                  <td><label><a >Nombre:</a></label></td>
                </tr>
                <tr>
                  <td><?= form_error('nombre');?></td>
                  <td><input type="text" id="nombre"
                    name="nombre" value="<?= set_value('nombre');?>"></td>
                </tr>
                <tr>
                  <td><label><a>Telefono:</a></label></td>
                </tr>
                <tr>
                  <td><?= form_error('telefono');?></td>
                  <td><input type="tel" id="telefono" 
                    name="telefono" value="<?= set_value('telefono');?>"></td>
                </tr>
                <tr>
                  <td style="height:30px"><label><a>Email:</a></label></td>
                </tr>
                <tr>
                  <td><?= form_error('email');?></td>
                  <td><input type="email" id="email"
                    name="email" value="<?= set_value('email');?>"></td>
                </tr>
              </tbody>
            </table>
          </td>
          <td>
            <table style="width:100%">
              <tbody>
                <tr>
                  <td style="height:30px"><label><a>Asunto:</a></label></td>
                </tr>
                <tr>
                  <td><?= form_error('asunto');?></td>
                  <td><input type="text" id="asunto" 
                     name="asunto" value="<?= set_value('asunto');?>"></td>
                </tr>
                <tr>
                  <td><label><a>Mensaje:</a></label></td>
                </tr>
                <tr>
                  <td><?= form_error('mensaje');?></td>
                  <td><textarea rows="04" id="mensaje" 
                     name="mensaje"><?= set_value('mensaje');?></textarea></td>
                </tr>
              </tbody>
            </table>
          </td>
        </tr>
      </tbody>
    </table>
    <table>
      <tbody>
        <tr>
          <td><button type="submit" value="enviar"  >Enviar</button></td>
        </tr>
      </tbody>
    </table>
  </form>
</body>
</html>

applicatoin/controllers/Emails.php

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Emails extends CI_Controller {
  public function __construct(){
    parent::__construct();
  }

  public function enviar(){        
    $this->form_validation->set_rules('nombre', 'Nombre', 'trim|required|min_length[5]|max_length[12]|xss_clean');
    $this->form_validation->set_rules('telefono', 'Telefono', 'trim|required|xss_clean');
    $this->form_validation->set_rules('asunto', 'Asunto', 'trim|required|xss_clean');
    $this->form_validation->set_rules('email', 'Email', 'trim|required|valid_email|xss_clean');
    $this->form_validation->set_rules('mensaje', 'Mensaje', 'trim|required|xss_clean');

    if( $this->form_validation->run() === FALSE){
      $this->load->view('form_test');
    }
    else{
      $_from          = '[email protected]';
      $_from2         = '[email protected]';

      $_email         = $this->input->post('email', TRUE);
      $_asunto        = $this->input->post('asunto', TRUE);
      $data           = array(
        'from'      => $_from,
        'to'        => $_email,
        'name'      => $this->input->post('nombre', TRUE),
        'phone'     => $this->input->post('telefono', TRUE),
        'subject'   => $_asunto,
        'message'   => $this->input->post('mensaje', TRUE)
      );

      $config = array (
        'mailtype' => 'html',
        'charset'  => 'utf-8',
        'priority' => '3'
      );        

      $this->load->library('email', $config);

      $this->email->from($_from, 'Contact');
      $this->email->to($_email); 
      $this->email->bcc($_from2); 
      $this->email->subject($_asunto);
      //$this->email->message($this->load->view('template_mails/contact', $data, TRUE));

      //$this->email->send();

      $this->session->set_flashdata('ok', 'Tu mensaje ha sido enviado');
      redirect('welcome/form_test', 'refresh');
    }
  }
}

/* End of file emails.php */
/* Location: ./application/controllers/emails.php */

Espero te sirva, cualquier cosa comentame cual es el problema

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.