I have in my form work experience which is added dynamically with input as organisation name, department name, position and duration.
<tr>
<td><span class="serial_no">1</span></td>
<td><input type="text" name="organization[]" size="50"/></td>
<td><input type="text" name="department[]" size="50"></td>
<td><input type="text" name="positions[]" size="40"></td>
<td><input type="text" name="duration[]"></td>
</tr>
While validating in CI I did the following:
$organization = $this->input->post('organization');
$department = $this->input->post('department');
$positions = $this->input->post('positions');
$duration = $this->input->post('duration');
//printr($organization);
for($i = 0; $i < count($organization); $i++)
{
$org = $organization[$i];
$dept = $department[$i];
$pos = $positions[$i];
$dura = $duration[$i];
$this->form_validation->set_rules($org, "Organization", "trim|xss_clean|max_length[1]");
$this->form_validation->set_rules($dept, "Department", "trim|xss_clean|max_length[50]");
$this->form_validation->set_rules($pos, "Position", "trim|xss_clean|max_length[40]");
$this->form_validation->set_rules($dura, "Duration", "trim|xss_clean|integer");
}
And displayed error as:
<?php
echo form_error("organization[]");
echo form_error("department[]");
echo form_error("positions[]");
echo form_error("duration[]");
?>
Now the problem is it doesn't validate the duration as integer. Even if I put some random alpha characters it doesn't show errors.
When I validate as follows:
$this->form_validation->set_rules('organization[]', "Organization", "trim|xss_clean|max_length[50]");
$this->form_validation->set_rules('department[]', "Department", "trim|xss_clean|max_length[50]");
$this->form_validation->set_rules('positions[]', "Position", "trim|xss_clean|max_length[40]");
$this->form_validation->set_rules('duration[]',"Duration", "trim|xss_clean|numeric");
It doesn't let me submit the form as it takes duration as mandatory which it isn't.
How do I solve it?
any help/suggestions are welcome. thanks.
It doesn't let me submit the form If so, It sounds like a bug.
Temporarily, you can check whether duration[] array is empty or not:
if (! empty($_POST['duration'])) {
$this->form_validation->set_rules('duration[]',"Duration", "trim|xss_clean|numeric");
}
I'll update my answer if I found the main solution.
Update:
This is a bug as I expected, I opened a PR at CodeIgniter Repository, that would fix this issue.
So as suggested by # Hashem Qolami I did the following changes in my code and it worked.
$organization = $this->input->post('organization');
$department = $this->input->post('department');
$positions = $this->input->post('positions');
$duration = $this->input->post('duration');
foreach($organization as $ind=>$val)
{
$org = $organization[$ind];
$dept = $department[$ind];
$pos = $positions[$ind];
$dura = $duration[$ind];
$this->form_validation->set_rules("organization[".$ind."]", "Organization", "trim|xss_clean|max_length[1]");
$this->form_validation->set_rules("department[".$ind."]", "Department", "trim|xss_clean|max_length[50]");
$this->form_validation->set_rules("positions[".$ind."]", "Position", "trim|xss_clean|max_length[40]");
if(!empty($dura))
$this->form_validation->set_rules("duration[".$ind."]", "Duration", "trim|xss_clean|integer");
}
and displayed my errors as follows
for($i = 0; $i < count($organization); $i++) {
echo form_error("organization[".$i."]");
echo form_error("department[".$i."]");
echo form_error("positions[".$i."]");
echo form_error("duration[".$i."]");
}
Related
I am using validation against a correct answer while typing in a Svelte input field.
https://svelte.dev/repl/69159ccd80b34d2495bf6642a0f96de9?version=3.44.2
It works perfect, but when changing the correct answer via function to a new value, the reactivity does not apply to the validation store. This is puzzling me because I think according to the documentation it should work and dynamically also update the validation parameters to the new $answer value.
Any help is greatly appreciated.
<script>
import { guessValidator, requiredValidator } from './validators.js'
import { createFieldValidator } from './validation.js'
import { writable } from "svelte/store";
let answer = writable(null);
let clue = writable(null);
$answer = "Cheese";
$clue = "I am smelly but tasty"
const [ validity, validate, resetValidation ] = createFieldValidator(guessValidator($answer))
let guess = null
function nextWord() {
$answer = "Sun"
$clue = "I don't shine at night"
console.log($answer)
console.log($clue)
}
</script>
<input class="input"
type="text"
bind:value={guess}
placeholder={$clue}
class:field-danger={!$validity.valid}
class:field-success={$validity.valid}
use:validate={guess}
/>
{#if $validity.dirty && !$validity.valid}
<span class="validation-hint">
{$validity.message}
</span>
{:else if $validity.valid}
<span class="validation-success">
Correct!
</span>
{/if}
I have a form and a template with format .docx
The proccess of replacing variables in the templates is working well except the checkbox. In the value checkbox I have 1 and 0.
Now instead of boolean value (0 or 1), i want to have Yes and No.
My controller here:
public function edit(Stagiaire $stagiaire, $downloadName = null)
{
$id = $stagiaire ->id;
$desc1 = Stagiaire::find($id);
$my_template = new \PhpOffice\PhpWord\TemplateProcessor(public_path('templateStagiaire.docx'));
$my_template->setValue('id', $desc1->id);
$my_template->setValue('civilite', $desc1->civilite);
$my_template->setValue('prenoms', $desc1->prenoms);
$my_template->setValue('nom', $desc1->nom);
//This 3 inputs are checbox in my form
$my_template->setValue('regles_deonto', $desc1->regles_deonto);
$my_template->setValue('reglement_interieur', $desc1->reglement_interieur);
$my_template->setValue('horaires', $desc1->horaires);
//The name of my file
$first_name = $stagiaire->prenoms ;
$last_name = $stagiaire->nom ;
$filename = $first_name. " ". $last_name;
try{
$my_template->saveAs(storage_path("$filename.docx"));
}catch (Exception $e){
//handle exception
}
$downloadName = $downloadName??$filename;
return response()->download(storage_path("$filename.docx"));
}
My form
<div id="container">
<input type="checkbox" name="regles_deonto" id="regles_deonto" value="1" required
> Régles déontologies
<input type="checkbox" name="reglement_interieur" id="reglement_interieur"
value="1" required > Réglement Intérieur
<input type="checkbox" name="horaires" id="horaires" value="1" required >
Horaires
</div>
My Question is how can I replace the booleans values (0 and 1) by Yes or No in my template Word.
I need help please.
Thank in advance.
You can just do like this,
//This 3 inputs are checbox in my form
$desc1->regles_deonto = (bool)($desc1->regles_deonto) == true ? 'Yes' : 'No';
$my_template->setValue('regles_deonto', $desc1->regles_deonto);
You can do this similarly for other two values.
You may use (bool) to cast your input to a boolean and use conditional statement to get 'Yes' or 'No':
//This 3 inputs are checbox in my form
$my_template->setValue('regles_deonto', (bool) $desc1->regles_deonto ? 'Yes' : 'No');
$my_template->setValue('reglement_interieur', (bool) $desc1->reglement_interieur ? 'Yes' : 'No');
$my_template->setValue('horaires', (bool) $desc1->horaires ? 'Yes' : 'No');
My model (table with 2 primary keys and are foreign key on the same time) :
class FormationPersonnel extends Model
{
protected $fillable = ['cin', 'id_form'];
public $incrementing = false;
}
I create checkboxes with JQuery, Ajax like so :
var grabData = "";
for (let i = 0; i < data.length; i++) {
grabData +=
`<div class="col-lg-4 col-sm-6">
<div class="custom-control custom-checkbox">
<input type="checkbox" name="cin[]" id="`+data[i]["cin"]+`" class="custom-control-input" value="`+data[i]["cin"]+`">
<label for="`+data[i]["cin"]+`" class="custom-control-label">`+data[i]["cin"]+' '+data[i]["nom"]+' '+data[i]["prenom"]+`</label>
</div>
</div>`;
}
personnelsInput.html("");
personnelsInput.append(grabData);
which I give the checkboxes the same name as :
name="cin[]"
In My controller I use this code, but is not storing any data from checkboxes :
$cins = $request->cin; //I get inputs like this
foreach ($cins as $cin) {
$form_pers = new FormationPersonnel; //create new record
if ($request->has($cin)) {
$form_pers->id_form = $request->input('id_form');
$form_pers->cin = $request->input($cin);
$form_pers->save(); //save data
}
}
What is the correct way ?
The correct way to check whether the Model has cin or not is
Edited
based on the comment we put, I think I know what you're trying to do, so do it like below code to get what you need.
note
you don't know what $cins values so that's why you use if(). No need to check whether the user check (checkbox) or not. because the checked value only send by form. please try to know what data you have in your variable before coding.
I recommended you to use dd() or print_r() or others https://laraveldaily.com/echoing-dd-vs-var_dump-vs-print_r/ to check the data you got in your variable.
$cins = $request->cin; //getting all checked (from checkbox) data
foreach ($cins as $cin) {
$form_pers = new FormationPersonnel; //new model
$form_pers->id_form = $request->id_form; //get name="id_form" from form
$form_pers->cin = $cin; //put cin value (loop)
$form_pers->save(); //save
}
i tried finding this problem using google but no luck so far , so im asking for some help.
im working with a webpage on JSP and im having a little problem with ajax responseText, im testing the page on firefox and using firebug.
the problem its that the operation its completed correctly and the response text show ok on the firebug console, but it doesnt display on the <div> i assigned.
when i put an alert() inside the function handling the onreadystatechange it displays correctly as if the response was just too late, so im a bit lost.
can anyone give me an idea?
my JS handling the submit is
function validate( form ) {
var expresion = /[\b\W\d]+/;
var error=0;
var nombre = document.getElementById("Addname");
var descripcion = document.getElementById("Adddescripcion");
if(nombre.value == "" ){
nombre.focus();
nombre.style.backgroundColor="red";
alert("Los Campos no deben estar vacios");
error = error+1;
}else{
if(!(expresion.test(nombre.value))){
var temp = nombre.value.toUpperCase();
nombre.value = temp;
}else{
nombre.focus();
nombre.style.backgroundColor="red";
alert("La entrada no es valida");
error = error+1;
}
}
if( descripcion.value == "" ){
descripcion.focus();
descripcion.style.backgroundColor="red";
alert("Los Campos no deben estar vacios");
error = error+1;
}
if(error == 0){
var url = "addCarrera";
var params = "name="+ nombre.value +"&descripcion="+descripcion.value;
ajaxPost(url,params,"addres");
document.getElementById("addres").setAttribute("class","visible");
clearing();
}
}
function clearing(){
var nombre = document.getElementById("Addname");
var descripcion = document.getElementById("Adddescripcion");
nombre.value="";
descripcion.value="";
nombre.style.backgroundColor="white";
descripcion.style.backgroundColor="white";
var timer = setTimeout("ocultar()", 1500);
}
an my code handling the Ajax request its
var ajaxCall;
function ajax_request() {
if(window.XMLHttpRequest){
//codigo para IE7+,Firefox,Chrome, Opera,Safari
ajaxCall=new XMLHttpRequest();
}else{
//codigo para IE6 y 5
ajaxCall=new ActiveXObject("Microsoft.XMLHTTP");
}
}
function ajaxPost(url ,params, respuesta){
ajax_request();
ajaxCall.onreadystatechange = statechangeHandle(respuesta);
ajaxCall.open("POST",url,true);
ajaxCall.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxCall.setRequestHeader("Content-length", params.length);
ajaxCall.setRequestHeader("Connection", "close");
ajaxCall.send(params);
//alert("respuesta? "+respuesta);
}
function statechangeHandle(text){
//alert("text?"+text);
//alert("ready?"+ajaxCall.readyState);
if(ajaxCall.readyState == 4 && ajaxCall.status === 200){
//alert("prueba");
document.getElementById(text).innerHTML=ajaxCall.responseText;
//alert(ajaxCall.responseText);
}
}
the html part
<h3>Agregar Carrera</h3>
<table>
<tr>
<td>Nombre:</td>
<td><input type="text" id="Addname" size="20" /></td>
</tr>
<tr>
<td>Descripcion:</td>
<td><textarea rows="2" cols="20" id="Adddescripcion" > </textarea></td>
</tr>
<tr>
<td><input type="button" value="Agregar" onclick="validate()"></td>
</tr>
</table>
<div class="ocultar" id="addres"></div>
thanks in advance.
by the way ,the ajax at ajaxPost doesnt show a thing but for example at statechangeHandle if active te alert before the asign the responseText the html its modified correctly but if not then the div stays the same, im not quite sure what that means, its like it has to wait i dont know if im just doing something really wrong
I am using an if else in Razor view to check for null value like this:
#foreach (var item in Model)
{
<tr id="#(item.ShopListID)">
<td class="shoptablename">#Html.DisplayFor(modelItem => item.Name)
</td>
<td class="shoptableamount">
#if (item.Amount == null)
{
Html.Display("--");
}
else
{
String.Format("{0:0.##}", item.Amount);
}
</td>
</tr>
}
However, no matter my model amount is null or having a value, the html rendered do not contain any value in the amount.
I wonder why this is happening. Any idea?
Thanks...
EDIT:
Decided to did it in controller:
// Function to return shop list food item amount
public string GetItemAmount(int fid)
{
string output = "";
// Select the item based on shoplistfoodid
var shopListFood = dbEntities.SHOPLISTFOODs.Single(s => s.ShopListFoodID == fid);
if (shopListFood.Amount == null)
{
output = "--";
}
else
{
output = String.Format("{0:0.##}", shopListFood.Amount);
}
return output;
}
and call at View like:
<td class="shoptableamount">
#Html.Action("GetItemAmount", "Shop", new { fid = item.ShopListFoodID })
</td>
You have to use the #()
#if (item.Amount == null)
{
#("--");
}
else
{
#String.Format("{0:0.##}", item.Amount)
}
As noted in the comments and other answers, the Html.Display is not for displaying strings, but for displaying data from the ViewData Dictionary or from a Model. Read http://msdn.microsoft.com/en-us/library/ee310174%28v=VS.98%29.aspx#Y0
I think you want to display "-----" if amount is null.
#foreach (var item in Model)
{
<tr id="#(item.ShopListID)">
<td class="shoptablename">#Html.DisplayFor(modelItem => item.Name)
</td>
<td class="shoptableamount">
#if (item.Amount == null)
{
#Html.Raw("--")
}
else
{
String.Format("{0:0.##}", item.Amount);
}
</td>
</tr>
}
That's because you are using the Display() method incorrectly. The overload you are using is Display(HtmlHelper, String). If you are looking for "--" to be the text, you should use something like:
#Html.Label("--");
There are actually two other ways to display text from a code block in razor besides the suggested #(""), using a <text> tag and it's shorthand #:
#{
#("--")
<text>--</text>
#:--
}
The code above will display -- three times.