Add to an array the content generated by a foreach - php

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

Related

Adding Multiple Products to Basket using PHP Sessions

Ive built a basket/checkout system for an e-commerce site, and have used session variables to store product name, price and quantity and can have them be displayed on my checkout page.
I'm struggling to be able to add different products to the basket, when the user goes to another product and clicks the add to basket button it removes the first product from the basket. does anyone know how I could change my code so that different products can be added to the basket without removing any products that are currently in the variable. and also how could I add the Quantity to the URL so that I can add it to the basket. the quantity is an input box on the products page that the user can tryp the number of products into.
this is my products page -
<?php
require('includes/application_top.php');
$page_title='Details';
require('includes/site_header.php');
$_GET['prod_ID'];
$product_id = isset($_REQUEST['prod_ID']) ? (int) $_REQUEST['prod_ID'] : 0;
$pound ="£";
?>
<style>
<?php
require('css/prod_details.css');
?>
</style>
<br>
<br>
<br>
<br>
<br>
<?php $product = get_product_details1($freshKickz_conn); ?>
<?php foreach($product as $productdetails) {
?>
<main class="container">
<!-- Left Column / Headphones Image -->
<div class="left-column">
<img data-image="red" class="active" src="<?= htmlspecialchars($productdetails['images']) ?>" style="height: 400px; width: 400px;" alt="">
</div>
<!-- Right Column -->
<div class="right-column">
<!-- Product Description -->
<div class="product-description">
<h1><?= htmlspecialchars($productdetails['prod_Name']) ?></h1>
<p><?= htmlspecialchars($productdetails['prod_Details']) ?></p>
</div>
<!-- Product Pricing -->
<div class="product-price">
<span><?=$pound?><?= htmlspecialchars($productdetails['prod_Price'])?></span>
Add to Basket
</div>
<br>
<div class="quantity">
<span>Quantity</span>
<br>
<input type="number" min="1" max="9" step="1" value="1">
</div>
</div>
</main>
<?php
} ?>
<script src="js/prodJS.js"></script>
<script>
$(document).ready(function () {
$('.color-choose input').on('click', function () {
var headphonesColor = $(this).attr('data-image');
$('.active').removeClass('active');
$('.left-column img[data-image = ' + headphonesColor + ']').addClass('active');
$(this).addClass('active');
});
});
</script>
<?php
require('includes/application_bottom.php');
require('includes/site_footer.php');
?>
and this is my basket/checkout page -
<?php
require('includes/application_top.php');
$page_title='Your Basket';
require('includes/site_header.php');
if ( ! isset($_SESSION['basket'])) {
$_SESSION['basket'] = array();
}
$pound ="£";
$action = $_REQUEST['action'] ?? '';
$err = '';
if($_REQUEST['action']=='add_product'){
$_SESSION['basket'][$_REQUEST['name']]=$_REQUEST['quantity']=$_REQUEST['quantity'];
}
?>
<style>
<?php
require('css/basket.css');
?>
</style>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div class="row">
<div class="col-75">
<div class="container">
<form action="successful_order.php">
<div class="row">
<div class="col-50">
<h3>Billing Address</h3>
<label for="fname"><i class="fa fa-user"></i> Full Name</label>
<input type="text" id="fname" name="firstname" placeholder="John M. Doe">
<label for="email"><i class="fa fa-envelope"></i> Email</label>
<input type="text" id="email" name="email" placeholder="john#example.com">
<label for="adr"><i class="fa fa-address-card-o"></i> Address</label>
<input type="text" id="adr" name="address" placeholder="542 W. 15th Street">
<label for="city"><i class="fa fa-institution"></i> City</label>
<input type="text" id="city" name="city" placeholder="New York">
<div class="row">
<div class="col-50">
<label for="state">County</label>
<input type="text" id="county" name="county" placeholder="Cheshire">
</div>
<div class="col-50">
<label for="zip">PostCode</label>
<input type="text" id="postcode" name="postcode" placeholder="SK11 6TF">
</div>
</div>
</div>
<div class="col-50">
<h3>Payment</h3>
<label for="fname">Accepted Cards</label>
<div class="icon-container">
<i class="fa fa-cc-visa" style="color:navy;"></i>
<i class="fa fa-cc-amex" style="color:blue;"></i>
<i class="fa fa-cc-mastercard" style="color:red;"></i>
<i class="fa fa-cc-discover" style="color:orange;"></i>
</div>
<label for="cname">Name on Card</label>
<input type="text" id="cname" name="cardname" placeholder="John More Doe">
<label for="ccnum">Credit card number</label>
<input type="text" id="ccnum" name="cardnumber" placeholder="1111-2222-3333-4444">
<label for="expmonth">Exp Month</label>
<input type="text" id="expmonth" name="expmonth" placeholder="September">
<div class="row">
<div class="col-50">
<label for="expyear">Exp Year</label>
<input type="text" id="expyear" name="expyear" placeholder="2018">
</div>
<div class="col-50">
<label for="cvv">CVV</label>
<input type="text" id="cvv" name="cvv" placeholder="352">
</div>
</div>
</div>
</div>
<label>
<input type="checkbox" checked="checked" name="sameadr"> Shipping address same as billing
</label>
<input type="submit" value="Checkout" class="btn">
</form>
</div>
</div>
<div class="col-25">
<div class="container">
<h4>Cart
<span class="price" style="color:black">
<i class="fa fa-shopping-cart"></i>
</span>
</h4>
<br>
<br>
<p><span class="name"><?= $_REQUEST['name'] ?></span> <span class="price"><span class="name"><?= $_REQUEST['quantity'] ?><br></span><?= $pound ?><?= $_REQUEST['price'] ?></span></p>
<hr>
<p>Total <span class="price" style="color:black"><b>$30</b></span></p>
</div>
</div>
</div>
<?php
require('includes/application_bottom.php');
require('includes/site_footer.php');
?>
First of all you should avoid using GET request to perform an action.
Next try to use product id because name can be same for different products.
So my offer for product page:
<?php
require('includes/application_top.php');
$page_title='Details';
require('includes/site_header.php');
$product_id = isset($_REQUEST['prod_ID']) ? (int) $_REQUEST['prod_ID'] : 0;
$pound ="£";
?>
<style>
<?php
require('css/prod_details.css');
?>
</style>
<br>
<br>
<br>
<br>
<br>
<?php $product = get_product_details1($freshKickz_conn); ?>
<?php foreach($product as $productdetails): ?>
<main class="container">
<!-- Left Column / Headphones Image -->
<div class="left-column">
<img data-image="red" class="active" src="<?= htmlspecialchars($productdetails['images']) ?>" style="height: 400px; width: 400px;" alt="">
</div>
<!-- Right Column -->
<div class="right-column">
<!-- Product Description -->
<div class="product-description">
<h1><?= htmlspecialchars($productdetails['prod_Name']) ?></h1>
<p><?= htmlspecialchars($productdetails['prod_Details']) ?></p>
</div>
<!-- Product Pricing -->
<form action="basket_page.php" method="POST">
<div class="product-price">
<span><?=$pound?><?= htmlspecialchars($productdetails['prod_Price'])?></span>
<input type="hidden" name="action" value="add_product" />
<!-- i'm not sure what index did you use for id so -->
<input type="hidden" name="id" value="<?php echo htmlspecialchars($productdetails['prod_Name']); ?>" />
<input type="hidden" name="price" value="<?php echo htmlspecialchars($productdetails['prod_Price']); ?>" />
<input type="hidden" name="name" value="<?php echo htmlspecialchars($productdetails['prod_Name']); ?>" />
<button type="submit" class="cart-btn">Add to Basket</button>
</div>
<br>
<div class="quantity">
<span>Quantity</span>
<br>
<input type="number" min="1" max="9" step="1" value="1">
</div>
</form>
</div>
</main>
<?php endforeach; ?>
<script src="js/prodJS.js"></script>
<script>
$(document).ready(function () {
$('.color-choose input').on('click', function () {
var headphonesColor = $(this).attr('data-image');
$('.active').removeClass('active');
$('.left-column img[data-image = ' + headphonesColor + ']').addClass('active');
$(this).addClass('active');
});
});
</script>
<?php
require('includes/application_bottom.php');
require('includes/site_footer.php');
?>
Next you can use associative array for your session. Don't forget to check all user input. It is important.
<?php
require('includes/application_top.php');
$page_title = 'Your Basket';
require('includes/site_header.php');
if (!isset($_SESSION['basket'])) {
$_SESSION['basket'] = [];
}
$pound = "£";
$action = $_REQUEST['action'] ?? '';
$err = '';
if ($action === 'add_product') {
$id = isset($_POST['id']) ? (int) $_POST['id'] : null;
$price = isset($_POST['price']) ? (float) $_POST['price'] : null;
$number = isset($_POST['number']) ? (int) $_POST['number'] : null;
$name = isset($_POST['name']) ? trim($_POST['name']) : null;
if ($id && $price && $number) {
$_SESSION['basket'][$id] = [
'id' => $id,
'price' => $price,
'number' => $number,
'name' => $name,
];
}
}
?>
Next you have an error in rendering. You should use your session array. Not a raw input.
<div class="col-25">
<div class="container">
<h4>
Cart
<span class="price" style="color:black">
<i class="fa fa-shopping-cart"></i>
</span>
</h4>
<br>
<br>
<?php
$total = 0;
foreach ($_SESSION['basket'] as $item):
$total += $item['price'] * $item['number'];
?>
<p>
<span class="name"><?php echo htmlspecialchars($item['name']) ?></span>
<span class="price">
<span class="name"><?= $item['number'] ?><br></span>
<?= $pound ?><?= $item['price'] ?>
</span>
</p>
<hr>
<?php endforeach; ?>
<p>
Total <span class="price" style="color:black"><b>$<?= total ?></b></span>
</p>
</div>
</div>
And finally please take a look at specialized php scripts for ecommerce like WooCommerce or Magento.

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>

Disallowed key character in codeigniter

I have a view page.i have to edit a list of values.bt after submit i have an error disallowed character key.I cant find it how this error occur.
view
foreach($track_details->result() as $name) { ?>
<form class="form-horizontal" method="post" id="income_edit" action="<?php echo base_url();?>income_list_cntrl/update_income" enctype="multipart/form-data">
<input type="text" name="track_id" value="<?php echo $track_id; ?>" >
<div class="control-group">
<label class="control-label">Income Name</label>
<div class="controls">
<input type="text" class="span6 m-wrap" value="<?echo $name->income_name?>" name="income_name" id="income_name" readonly>
<?php echo form_error('income_name'); ?>
</div>
</div>
<div class="control-group">
<label class="control-label">Income Amount</label>
<div class="controls">
<input type="text" class="span6 m-wrap" value="<?echo $name->income_amount?>" name="income_amount" id="income_amount" >
<?php echo form_error('income_amount'); ?>
</div>
</div>
<div class="control-group">
<label class="control-label">Crop Quantity</label>
<div class="controls">
<input type="text" class="span6 m-wrap" value="<?echo $name->crop_quantity?>" name=crop_quantity" id="crop_quantity" >
<?php echo form_error('crop_quantity'); ?>
</div>
</div>
<div class="control-group">
<label class="control-label">Per Rate</label>
<div class="controls">
<input type="text" class="span6 m-wrap" value="<?echo $name->per_rate?>" name=per_rate" id="per_rate" >
<?php echo form_error('per_rate'); ?>
</div>
</div>
<div class="control-group">
<label class="control-label">Choose a client</label>
<div class="controls">
<select class="span6 m-wrap" name="select_client" >
<? foreach ($client_details->result() as $var) { ?>
<option <?php if($name->client_id == $var->client_id) { ?> selected="selected" <? } ?> value="<?echo $var->client_id;?>"><?echo $var->client_name;?></option>
<?}?>
</select>
<?php echo form_error('select_client'); ?>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn green" id="Submit">Submit</button>
</form>
<?}?>
controller
After removing the crop quantity and per rate no error but dont edit it.
public function update_income(){
$this->form_validation->set_error_delimiters('<div style="color:#B94A48">', '</div>');
//$this->form_validation->set_rules('income_name', 'Income name', 'required');
$this->form_validation->set_rules('income_amount', 'Income Amount', 'required');
$this->form_validation->set_rules('crop_quantity', 'Crop Quantity', 'required');
$this->form_validation->set_rules('per_rate', 'Per Rate', 'required');
$this->form_validation->set_rules('select_client', 'Client Name', 'required');
if ( $this -> form_validation -> run() === FALSE ){
$this->index();
} else {
$track_id=$this->input->post('track_id');
$income_name=$this->input->post('income_name');
$income_amount=$this->input->post('income_amount');
$crop_quantity=$this->input->post('crop_quantity');
$per_rate=$this->input->post('per_rate');
$client_name=$this->input->post('select_client');
$this->load->model('income_edit_model');
$data = array(
'income_name'=>$income_name,
'income_amount'=>$income_amount,
'crop_quantity'=>$crop_quantity,
'per_rate'=>$per_rate,
'client_name'=>$client_name,
);
$result=$this->income_edit_model->update_track_income($data,$track_id);
// redirect(base_url().'income', 'refresh');
}
}
Two problems:
First: Missing <?php open tags. Look through this and change <? to <?php
<select class="span6 m-wrap" name="select_client" >
<? foreach ($client_details->result() as $var) { ?>
<option <?php if($name->client_id == $var->client_id) { ?> selected="selected" <? } ?> value="<?echo $var->client_id;?>"><?echo $var->client_name;?></option>
<? } ?>
</select>
Second: Missing closing </div
<div class="form-actions">
<button type="submit" class="btn green" id="Submit">Submit</button>
<!-- MISSING </div> HERE -->
</form>

show value in php form

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

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