show value in php form - php

hello people have to be a form to use all form controls available and after processing all the values ​​show , I have the following code :
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Contacto</title>
</head>
<body>
<?php
// define variables and set to empty values
$nombre = $email = $comment = $consulta = "";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$nombre = test_input($_POST["nombre"]);
$email = test_input($_POST["email"]);
$evento = test_input($_POST["evento"]);
$consulta = test_input($_POST["consulta"]);
// $comment = test_input($_POST["comment"]);
$evento = test_input($_POST["evento"]);
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
<div class="contenedor">
<div id="encabezado">
</div>
<div id="contenido">
<h1>Como contactarnos</h1>
<h2>Formulario de contacto</h2>
<form id="formulario" class="formulario" action="#" method="post">
<div class="campo">
<label for="nombre">Nombre o razón social: <span>(*)</span></label>
<input name="nombre" id="nombre" type="text">
</div>
<div class="campo">
<label for="email">E-Mail: <span>(*)</span></label>
<input name="email" id="email" type="text">
</div>
<div class="campo">
Tipo de evento: <span>(*)</span>
<input name="evento" id="evento_empresarial" value="empresarial" type="radio" checked>
<label for="evento_empresarial">Empresarial</label>
<input name="evento" id="evento_particular" value="particular" type="radio">
<label for="evento_particular">Particular</label>
</div>
<div class="interlineado"> <!-- Para alinear esos campos del formulario -->
Me interesa consultar sobre: <span>(*)</span>
</div>
<div class="interlineado">
<input name="consulta" id="consulta_catering" value="catering" type="checkbox">
<label for="consulta_catering">Catering</label>
<input name="consulta" id="consulta_salones" value="salones" type="checkbox">
<label for="consulta_salones">Salones</label>
<input name="consulta" id="consulta_musica" value="musica" type="checkbox">
<label for="consulta_musica">Música</label>
<input name="consulta" id="consulta_fotografia" value="fotografia" type="checkbox">
<label for="consulta_fotografia">Fotografía</label>
</div>
<div class="campo">
<input name="consulta" id="consulta_decoracion" value="decoracion" type="checkbox">
<label for="consulta_decoracion">Decoración</label>
<input name="consulta" id="consulta_dj" value="dj" type="checkbox">
<label for="consulta_dj">DJ</label>
<input name="consulta" id="consulta_show" value="show" type="checkbox">
<label for="consulta_show">Show</label>
<input name="consulta" id="consulta_videos" value="videos" type="checkbox">
<label for="consulta_videos">Videos</label>
</div>
<div class="campo">
<label for="ubicacion">Zona donde desea el evento: <span>(*)</span></label>
<select name="ubicacion" id="ubicacion">
<option value="" selected="selected">-</option>
<option value="caba">CABA</option>
<option value="gba">GBA</option>
<option value="fueradegba">Fuera de GBA, Bs As</option>
<option value="interior">Interior</option>
</select>
</div>
<div class="interlineado">
<label for="comments">Mensaje: <span>(*)</span> </label>
</div>
<div class="mensaje">
<textarea name="comments" id="comments" rows="4" cols="50">
</textarea>
</div>
<div class="mensaje">
<input name="check" id="check" value="OK" type="submit">
<input value="Cancelar" onclick="$('form')[0].reset()" type="reset">
</div>
</form>
<div id="contacto"> <!-- Otras formas de comunicarse -->
<h2> Contacto </h2>
<div class="campo">
Teléfono:
(0220) 411-1111
</div>
<div class="campo">
Celular: (011) 15-5956-3215
</div>
<div class="campo">
Email: user#gmail.com
</div>
</div>
</div>
</div>
</div>
<?php
echo "<h2>Vos ingresaste:</h2>";
echo $nombre;
echo "<br>";
echo $email;
echo "<br>";
echo $evento;
echo "<br>";
echo $consulta;
echo "<br>";
//echo $gender;
?>
</body>
</html>
but does not display correctly checkbox displays the first thing I select ; also if I do not select anything shows me a warning , what happens?

All of your checkboxes have the same name, but you aren't saving them as an array. What you have to do is change the name in the form to name="consulta[]" and then to implode (http://php.net/implode) the array (implode(',',$_POST['consulta'])); in PHP.
As for the error you are getting it because if no checkbox is checked there is no value passed to PHP yet you are trying to give its value to a variable. Validate your form before sending to prevent users from sending it with no checkbox checked or create an if statement.

I hope I understood your question right...
So first you've got a multiple name=consulta for all the checkboxes so in $_POST you will get only the last one that has checked.
Second, you do not need the php function to clear the form, this is enough:
<input value="Cancelar" type="reset">
And third, you didn't initialize $evento

Related

Change data requirements of an input field based on the value of a select field in a web form

I am working on a web form that includes a select drop down with two options: "Cedula" (in English, "Identification") and "Pasaporte" (in English, "Passport").
Here is an image of my web form so far.
Please help me achieve the following goal: when the user selects "Cedula", they are limited to 10 digits, but when they select "Pasaporte, they are not limited to 10 digits.
Here is my code so far:
<?php
if ($_GET['id']) {
$cliente = $clienteNegocio->recuperar($_GET['id']);
$txtAction = 'Editar';
}else{
$cliente = new cliente();
$txtAction = 'Agregar';
}
?>
<div class="container">
<div class="page-header">
<h1><?php echo $txtAction; ?> Cliente</h1>
</div>
<form role="form" method="post" id="principal">
<input type="hidden" name="id" value="<?php echo $cliente->getId();?>" >
<div class="form-group">
<label for="nombre">Nombre</label>
<input type="text" class="form-control" id="nombre" name="nombre" placeholder="Nombre" value="<?php echo $cliente->getNombre();?>" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="apellido">Apellidos</label>
<input type="text" class="form-control" id="apellido" name="apellido" placeholder="Apellido" value="<?php echo $cliente->getApellido();?>" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="tipoDoc">Tipo de Documento</label>
<select class="form-control" id="tipoDoc" name="tipoDoc">
<option value="Cedula" <?php if($cliente->getTipoDoc() == 'Cedula') {echo "selected";} ?> >Cedula</option>
<option value="Pasaporte" <?php if($cliente->getTipoDoc() == 'Pasaporte') {echo "selected";} ?> >Pasaporte</option>
</select>
</div>
<div class="form-group">
<label for="nroDoc">Numero de Documento</label>
<input type="number" class="form-control" id="nroDoc" maxlength=10 oninput="if(this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"
name="nroDoc" placeholder="Numero de Documento" value="<?php echo $cliente ->getNroDoc();?>" required>
<div class="help-block with-errors"></div>
</div>
There you go.
I have written a javascript function to check the length with you select Pasaporte/Cedula.
Secondly, in <input type = "number"/> you cannot set maxLength. Hence you have to set <input type = "text" />. Also, an onKeyPress event to verify the input as number
<?php
if ($_GET['id']) {
$cliente = $clienteNegocio->recuperar($_GET['id']);
$txtAction = 'Editar';
}else{
$cliente = new cliente();
$txtAction = 'Agregar';
}
?>
<script>
function setMaxLength(){
var inputVal = document.getElementById("tipoDoc")
var selIndex = inputVal.options[inputVal.selectedIndex].value
var inputNum = document.getElementById("nroDoc");
if( selIndex === "Cedula"){
inputNum.maxLength = 10
selIndex.substr(0, 9);
inputNum.value = inputNum.value.substr(0, 9);
} else{
// Set your own limit here
// if selIndex === "Pasaporte"
inputNum.maxLength = 20
}
}
</script>
<div class="container">
<div class="page-header">
<h1><?php echo $txtAction; ?> Cliente</h1>
</div>
<form role="form" method="post" id="principal">
<input type="hidden" name="id" value="<?php echo $cliente->getId();?>" >
<div class="form-group">
<label for="nombre">Nombre</label>
<input type="text" class="form-control" id="nombre" name="nombre" placeholder="Nombre" value="<?php echo $cliente->getNombre();?>" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="apellido">Apellidos</label>
<input type="text" class="form-control" id="apellido" name="apellido" placeholder="Apellido" value="<?php echo $cliente->getApellido();?>" required>
<div class="help-block with-errors"></div>
</div>
<div class="form-group">
<label for="tipoDoc">Tipo de Documento</label>
<select class="form-control" id="tipoDoc" name="tipoDoc" onChange="setMaxLength()">
<option value="Cedula" <?php if($cliente->getTipoDoc() == 'Cedula') {echo "selected";} ?> >Cedula</option>
<option value="Pasaporte" <?php if($cliente->getTipoDoc() == 'Pasaporte') {echo "selected";} ?> >Pasaporte</option>
</select>
</div>
<div class="form-group">
<label for="nroDoc">Numero de Documento</label>
<!--
Here onKeyPress method is used to check if the input is a number
in <input type = "number"/> you cannot set maxLength
hence you have to set <input type = "text" />
-->
<input type="text" class="form-control" id="nroDoc" maxlength=10 onkeypress="if ( isNaN(this.value + String.fromCharCode(event.keyCode) )) return false;"
name="nroDoc" placeholder="Numero de Documento" value="<?php echo $cliente ->getNroDoc();?>" required>
<div class="help-block with-errors"></div>
</div>
</form>
</div>

Add to an array the content generated by a foreach

i display with a foreach the content of a user_meta in wordpress. It displays input taht fills with the values (so they can be changed). I want to be able to store each content in a new array (so i can update the user_meta next.
So here is the main code :
<?php
function edit_profile_form() {
$current_user_id = get_current_user_id();
$data = get_user_meta ($current_user_id);
if (isset($_POST['button2'])) {
delete_user_meta($current_user_id, 'experiences');
}
if(isset($_POST['button1'])) {
save_extra_profile_fields($current_user_id);
};
$experiences = get_user_meta($current_user_id, 'experiences', true);
?>
<div class="container_form">
<form method="POST">
<h3>Vos expériences</h3>
<div class="experiences_container">
<?php
if (!empty($experiences)) {
$index=0;
foreach ($experiences as $key) {
$index++;
echo($index);
echo($key);
?>
<div class="past_experience">
<div class="experience_header">
<div>
<label for="team">Nom de l'équipe</label>
<input class="team" name="team" value="<?= $key['new_experience_team'];?>"/>
</div>
<div>
<label for="role">Rôle dans l'équipe</label>
<input class="role" name="role" value="<?= $key['new_experience_role'];?>"/>
</div>
</div>
<div class="experience_textarea">
<label for="description">Description du rôle</label>
<textarea class="description" name="description"><?= $key['new_experience_description']; ?></textarea>
<label for="palmares">Palmarés avec l'équipe</label>
<textarea class="palmares" name="palmares"><?= $key['new_experience_palmares']; ?></textarea>
</div>
</div>
<?php
}
} else {
?>
<div><p>Vous n'avez encore rentré aucune expérience</p></div>
<?php
}?>
</div>
<div class="add_container">
<div id="dropdown">
<i class="fas fa-plus-square" style="margin-right: 5px;"></i>
<p id="show" onClick="dropdown()" >Ajouter une expérience</p>
</div>
<div id="experience" style="display:none;">
<label for="new_experience_team">Nom de l'équipe</label>
<input type="text" name="experiences[new_experience_team]" id="experience_team">
<label for="new_experience_role">Rôle dans l'équipe</label>
<input type="text" name="experiences[new_experience_role]" id="experience_role">
<label for="new_experience_description">Description du poste</label>
<textarea type="text" name="experiences[new_experience_description]" id="experience_description"></textarea>
<label for="new_experience_palmares">Palmarés</label>
<textarea type="text" name="experiences[new_experience_palmares]" id="experience_palmares"></textarea>
</div>
</div>
<div id="button_container">
<input type="submit" name="button1" value="Sauvegarder" id='save'/>
<input type="submit" name="button2" value="Annuler"/>
</div>
</form>
</div>
The function's one :
<?php
function save_extra_profile_fields( $user_id ) {
if (!empty($_POST['experiences'])) {
$savedexperience = get_user_meta($user_id, 'experiences', true);
if (!empty($savedexperience) && is_array($savedexperience )) {
$experiences = $savedexperience;
}
$experiences[] = $_POST['experiences'];
update_usermeta($user_id, 'experiences', $experiences);
}
}
So i want to be able to stock in a array each group of team, role, description and palmares.
I don't know if it's clear at all :/
Thanks all

Page redirects when clicked anywhere in a <div>

I am designing a website, and i encountered a problem.
In the following page "samgatha.org/register.php", wherever i click inside the form-box, it redirects to "samgatha.org/register.php". I am not able to find the problem.
Below i am posting the main code for the registeration form, i am not including the template code.
<div id="register-box">
<?php
require 'connection.php';
if($_SERVER['REQUEST_METHOD']=='POST') {
if((isset($_POST['enthu_name']))&&(isset($_POST['enthu_email']))&&(isset($_POST['enthu_contact']))&&(isset($_POST['college_name']))&&(isset($_POST['branch']))&&(isset($_POST['pass']))) {
$var_name = mysql_real_escape_string($_POST['enthu_name']);
if(!preg_match("/^[a-zA-Z ]*$/",$var_name)) {
die('Only letters and white spaces allowed in Name<br>');
}
$var_email = mysql_real_escape_string($_POST['enthu_email']);
if(!filter_var($var_email, FILTER_VALIDATE_EMAIL)) {
die("Invalid email format<br>");
}
$var_contact = mysql_real_escape_string($_POST['enthu_contact']);
$var_college = mysql_real_escape_string($_POST['college_name']);
$var_branch = mysql_real_escape_string($_POST['branch']);
$passwd = mysql_real_escape_string(md5($_POST['pass']));
$v1 = rand(0,getrandmax());
$v2 = rand(0,getrandmax());
$ac_conf = $v1.$v2;
$ac_conf_hash = md5($v1.$v2);
$v1 = rand(0,getrandmax());
$v2 = rand(0,getrandmax());
$fo_pass = $v1.$v2;
$query = "insert into student_detail (name,email,phno,college,branch,password,acc_confirm_code,forgot_pass_code)".
"values".
"('$var_name','$var_email','$var_contact','$var_college','$var_branch','$passwd','$ac_conf','$fo_pass')";
$retval = mysql_query($query);
if(!$retval) {
die('Could not register'.mysql_error());
}
$reg_conf_code = "http://samgatha.org/reg_conf.php?acconf=".$ac_conf_hash."&suse=".$var_email;
$reg_conf = "Please click on the link to activate<br>".$reg_conf_code;
mail($_POST['enthu_email'],"Samgatha Account Confirmation (no reply) link",$reg_conf);
header('Location: http://samgatha.org/login.php');
}
else {
echo "Please enter details to continue <br>";
}
}
?>
Welcome to samgatha registrations. <br>
Please fill out the following form to participate in samgatha.
<form id="sam_register" action="register.php" method="post">
<div class="reg-box-in">
<label class="i2" id="ii1" for="enthu_name">Name : </label>
<input class="i1" type="text" name="enthu_name" id="enthu_name"> <br>
</div>
<div class="reg-box-in">
<label class="i2" id="ii2" for="enthu_email">E-mail Address : </label>
<input class="i1" type="text" name="enthu_email" id="enthu_email"> <br>
</div>
<div class="reg-box-in">
<label class="i2" id="ii3" for="enthu_contact">Phone No : +91</label>
<input class="i1" type="text" name="enthu_contact" id="enthu_contact"> <br>
</div>
<div class="reg-box-in">
<label class="i2" id="ii4" for="college_name">Institute : </label>
<input class="i1" type="text" name="college_name" id="college_name"> <br>
</div>
<div class="reg-box-in">
<label class="i2" id="ii5" for="branch">Discipline : </label>
<input class="i1" type="text" name="branch" id="branch"> <br>
</div>
<div class="reg-box-in">
<label class="i2" id="ii6" for="password">Password : </label>
<input class="i1" type="text" name="pass" id="pass" maxlength="30"> <br>
</div>
<div class="reg-box-in">
<button type="submit" name="register">Register</button> <br>
</div>
</form>
</div>
And this is not the problem only with the register page.
You can check the website samgatha.org.
Various html issues
Unclosed link
<a href="login.php"><div id="register" class="lay2"><div id="registert">Sign In/Up</div></div>
<div id="register-box">
<?php
require 'connection.php';
if (!empty($_POST)) {
$var_name = mysql_real_escape_string(<?php echo htmlspecialchars($_POST["name"]); ?>);
//-- same used for post ------------
header('Location: http://samgatha.org/login.php');
}
else {
echo "Please enter details to continue <br>";
}
}
?>
Welcome to samgatha registrations. <br>
Please fill out the following form to participate in samgatha.
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?> method="post">
<div class="reg-box-in">
<label class="i2" id="ii1" for="enthu_name">Name : </label>
<input class="i1" type="text" name="enthu_name" id="enthu_name"> <br>
</div>
<div class="reg-box-in">
<label class="i2" id="ii2" for="enthu_email">E-mail Address : </label>
<input class="i1" type="text" name="enthu_email" id="enthu_email"> <br>
</div>
<div class="reg-box-in">
<label class="i2" id="ii3" for="enthu_contact">Phone No : +91</label>
<input class="i1" type="text" name="enthu_contact" id="enthu_contact"> <br>
</div>
<div class="reg-box-in">
<label class="i2" id="ii4" for="college_name">Institute : </label>
<input class="i1" type="text" name="college_name" id="college_name"> <br>
</div>
<div class="reg-box-in">
<label class="i2" id="ii5" for="branch">Discipline : </label>
<input class="i1" type="text" name="branch" id="branch"> <br>
</div>
<div class="reg-box-in">
<label class="i2" id="ii6" for="password">Password : </label>
<input class="i1" type="text" name="pass" id="pass" maxlength="30"> <br>
</div>
<div class="reg-box-in">
<button type="submit" name="register">Register</button> <br>
</form>
</div>
</div>
There is <a> tag on register-box which redirects to login.php. Please check your code it puts <a> tag.

wrong <select> value when editing php form

I really hope you can help me.
I've done a form, where I can opt if a client I'm adding to the database is "Active or "Inactive", using a dropdown select box.
My code saves all the data correctly to the datbase, but when I want to edit the client, the option displays always as "Active", ignoring the value from the database.
I have 2 files:
edita_clientes.php - the form where I can edit the clients values
salvar_edicao.php - the file that saves the edition.
Here are the codes:
edita_clientes.php:
<?php
#ini_set('display_errors', '1');
error_reporting(E_ALL);
$id = $_GET["id_cliente"];
settype($id, "integer");
mysql_connect("localhost", "root", "");
mysql_select_db("sistema");
$resultado = mysql_query("select * from tabela where id_cliente = $id");
$dados = mysql_fetch_array($resultado);
mysql_close();
?>
<form id="edita_pj" name="edita_pj" method="post" action="salvar_edicao.php">
<input type="hidden" name="id_cliente" id="id_cliente" value="<?php echo $id;?>" />
<div class="box-body">
<div class="form-group">
<label>Razão Social</label>
<input type="text" name="razao" id="razao" class="form-control" value="<?php echo $dados["razao"];?>" />
</div>
<div class="form-group">
<label>Nome Fantasia</label>
<input type="text" name="fantasia" id="fantasia" class="form-control" value="<?php echo $dados["fantasia"];?>" />
</div>
</div>
<div class="box-body">
<div class="form-group">
<label>CNPJ</label>
<input type="text" name="cnpj" id="cnpj" class="form-control" data-inputmask='"mask": "999.999.999-99"' data-mask value="<?php echo $dados["cnpj"];?>">
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-9">
<label>Logradouro</label>
<input type="text" name="logradouro" id="logradouro" class="form-control" value="<?php echo $dados["logradouro"];?>">
</div>
<div class="col-xs-3">
<label>Número</label>
<input type="text" name="numero" id="numero" class="form-control" value="<?php echo $dados["numero"];?>">
</div>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-9">
<label>Bairro</label>
<input type="text" name="bairro" id="bairro" class="form-control" value="<?php echo $dados["bairro"];?>">
</div>
<div class="col-xs-3">
<label>CEP</label>
<input type="text" name="cep" id="cep" class="form-control" data-inputmask='"mask": "99999-999"' data-mask value="<?php echo $dados["cep"];?>">
</div>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-10">
<label>Cidade</label>
<input type="text" name="cidade" id="cidade" class="form-control" value="<?php echo $dados["cidade"];?>">
</div>
<div class="col-xs-2">
<label>UF</label>
<input type="text" name="uf" id="uf" class="form-control" value="<?php echo $dados["uf"];?>">
</div>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-9">
<label>E-mail</label>
<input type="text" name="email" id="email" class="form-control" value="<?php echo $dados["email"];?>">
</div>
<div class="col-xs-3">
<label>Telefone</label>
<input type="text" name="telefone" id="telefone" class="form-control" data-inputmask='"mask": "(99) 9999.9999"' data-mask value="<?php echo $dados["telefone"];?>"/>
</div>
</div>
</div>
<div class="box-body">
<div class="row">
<div class="col-xs-9">
<label>Contato</label>
<input type="text" name="contato" id="contato" class="form-control" value="<?php echo $dados["contato"];?>">
</div>
<div class="col-xs-3">
<label>Estado</label>
<select class="form-control" name="estado" id="estado" value=""><?php echo $dados["estado"];?>
<option>Ativo</option>
<option>Inativo</option>
</select>
</div>
</div>
<div class="form-group">
<label>Observações</label>
<textarea class="form-control" name="obs" id="obs" rows="6" ><?php echo $dados["obs"];?>
</textarea>
</div>
</div>
<div class="box-footer">
<button type="submit" name="Submit" class="btn btn-primary">Salvar</button>
</div>
</form>
salvar_edicao.php:
<?php
#ini_set('display_errors', '1');
error_reporting(E_ALL);
$razao = $_POST["razao"];
$fantasia = $_POST["fantasia"];
$cnpj = $_POST["cnpj"];
$logradouro = $_POST["logradouro"];
$numero = $_POST["numero"];
$bairro = $_POST["bairro"];
$cep = $_POST["cep"];
$cidade = $_POST["cidade"];
$uf = $_POST["uf"];
$email = $_POST["email"];
$telefone = $_POST["telefone"];
$contato = $_POST["contato"];
$estado = $_POST["estado"];
$obs = $_POST["obs"];
$id = $_POST["id_cliente"];
mysql_connect("localhost", "root", "");
mysql_select_db("sistema");
mysql_query("UPDATE tabela SET razao = '$razao', fantasia = '$fantasia', cnpj = '$cnpj', logradouro = '$logradouro', numero='$numero', bairro='$bairro', cep='$cep', cidade = '$cidade', uf='$uf', email = '$email', telefone = '$telefone', contato = '$contato', estado = '$estado', obs = '$obs' WHERE tabela.id_cliente = $id");
mysql_close();
header("Location: consulta.php");
?>
You need to add 'selected' to the option that you want to be selected, based on a value from the form/db. Here is an example using $value as the option value that you want selected.
<select class="form-control" name="estado" id="estado">
<option <?php echo $value == 'Ativo' ? selected : '' ?>>Ativo</option>
<option <?php echo $value == 'Inativo' ? selected : '' ?>>Inativo</option>
</select>
Also, your <select> tag does not require a 'value' element..
The HTML select element does not have a value attribute. For the select to do what you want you need to add the selected attribute to the option you want selected. It's always showing as 'Active' because that's the first option and it is the default.
The resulting post-php HTML will need to look something like this stripped back example for 'Inactive' to be selected.
<select>
<option>Active</option>
<option selected>Inactive</option>
</select>
Thank's for all the help!
The solution I've found was:
<?php
$resultado = mysql_query("select * from tabela where id_cliente = $id");
$dados = mysql_fetch_array($resultado);
$query = mysql_query("SELECT * FROM estado");
?>
And the html part:
<select class="form-control" name="estado" id="estado">
<option selected="selected"><?php echo $dados["estado"];?></option>
<option value="Ativo">Ativo</option>
<option value="Inativo">Inativo</option>
</select>

codeigniter validation error with field "required"

i have a problem with the validation form. It does not work if i put "required", example:
controller:
public function updateBenefit(){
$result = array();
$this->load->helper(array('form', 'url'));
$this->load->library('form_validation');
$this->form_validation->set_rules('beneficio', 'Nombre del Beneficio', 'required|alpha');
$this->form_validation->set_rules('info', 'Info', 'alpha');
$this->form_validation->set_rules('descrip', 'Descripción', 'alpha');
$this->form_validation->set_rules('orden', 'Orden', 'integer');
// $this->form_validation->set_rules('fecha', 'Fecha', 'date_valid');
$this->form_validation->set_message('required', 'El campo %s es requerido');
if ($this->form_validation->run() == TRUE){
if (isset($_POST['id'])){
$idb = $_POST['id'];
$benefit = BeneficiosManager::getInstance()->getHome($idb);
$result['message'] = "Se ha modificado el Beneficio con éxito";
} else{
$benefit = BeneficiosManager::getInstance()->create();
$result['message'] = "Se ha cargado el Beneficio con éxito";
}
$benefit->nombre = ucfirst(strtolower($_POST['beneficio']));
$benefit->content = ucfirst(strtolower($_POST['descrip']));
$benefit->intro = ucfirst(strtolower($_POST['info']));
$benefit->active = $_POST['optionsRadios2'];
$benefit->orden = $_POST['orden'];
// $benefit->date = $_POST['fecha'];
BeneficiosManager::getInstance()->save($benefit);
}else{
//no se validaron los datos ingresados
$result['message'] = "Error validación";
}
echo json_encode($result);
}
view:
{extends file='admin/base/base.tpl'}
{block name='content'}
<h3>Cargar Beneficio </h3>
</br>
<form action="{site_url()}admin/updateBenefit" class="form-horizontal" method="post" id="" enctype="multipart/form-data">
<div class="control-group">
<label class="control-label">Beneficio</label>
<div class="controls">
<input type="text" name="beneficio" value="" class="m-wrap medium" />
<span class="help-inline">Nombre del Beneficio</span>
</div>
</div>
<div class="control-group">
<label class="control-label">Info</label>
<div class="controls">
<textarea name="info" class="medium m-wrap" rows="3"></textarea>
<span class="help-inline">Información Clave</span>
</div>
</div>
<div class="control-group">
<label class="control-label">Descripción</label>
<div class="controls">
<textarea name="descrip" class="large m-wrap" rows="3"></textarea>
<span class="help-inline">Descripción del Beneficio</span>
</div>
</div>
<div class="control-group">
<label class="control-label">Activo</label>
<div class="controls">
<label class="radio line">
<input type="radio" name="optionsRadios2" value="1"/>Si</input>
</label>
<label class="radio line">
<input type="radio" name="optionsRadios2" value="0"/>No</input>
</label>
<span class="help-inline">Ofrecer Beneficio</span>
</div>
</div>
<div class="control-group">
<label class="control-label">Orden</label>
<div class="controls">
<input type="text" name="orden" value="" class="m-wrap small" />
<span class="help-inline">Prioridad del Beneficio</span>
</div>
</div>
<div class="control-group">
<label class="control-label">Fecha</label>
<div class="controls">
<input type="text" name="fecha" value="{$smarty.now|date_format}" class="m-wrap medium" />
<span class="help-inline"></span>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn blue"><i class="icon-ok"></i> Guardar</button>
<button type="button" class="btn">Cancelar</button>
</div>
</form>
{/block}
what might the problem be?
if i remove the "required" field, the form validates... but if i put it, it doesn't... i don't know what else to try, can't understand why this is happening
the code is working now, thanks to #Jonathan that corrected me, and i was also making an imput mistake when i was trying this method. I was trying to put two words in the same field (i.e: bon vivir); so the correct input would be: bonvivir.
I'm not sure you are using "title" as the name of your real title input element. Because I found you use this code to assign your title.
$benefit->title = ucfirst(strtolower(trim($_POST['beneficio'])));
So you may want to try to use
$this->form_validation->set_rules('beneficio', 'Nombre del Beneficio', 'required|alpha');
instead.
I am not sure I had the right guess. Just give it a go. Hope this helps.

Categories