CodeIgniter - Setting Checkbox/Radio values from SQL query - codeigniter

I'm trying to create an edit page, which brings all of the original values from the database in at first, then let's the form_validation library take over afterwards. I have managed to get everything working as intended but checkboxes and radio buttons.
Here's an example of my form, pretty generic...
<input type="checkbox" name="protocols[]" value="online" <?php echo set_checkbox('protocols[]', 'online');?> />
<input type="checkbox" name="protocols[]" value="network" <?php echo set_checkbox('protocols[]', 'network');?> />
<input type="checkbox" name="protocols[]" value="splitscreen" <?php echo set_checkbox('protocols[]', 'splitscreen');?> />
The database values return as a comma separated string (online,splitscreen).
I also have another 3 field checkbox array to populate, a 9 field checkbox field, and a 3 field radio section to fill.
Any help would be greatly appreciated, thanks.

Remove the brackets from the field name in your call to set_checkbox():
<input type="checkbox" name="protocols[]" value="online" <?php echo set_checkbox('protocols', 'online');?> />
<input type="checkbox" name="protocols[]" value="network" <?php echo set_checkbox('protocols', 'network');?> />
<input type="checkbox" name="protocols[]" value="splitscreen" <?php echo set_checkbox('protocols', 'splitscreen');?> />
The form validation library will take care of checking the box or not, but it responds to the $_POST array only, so you'll have to use the third parameter to get the inputs checked by default:
set_checkbox()
Permits you to display a checkbox in the state it was submitted. The
first parameter must contain the name of the checkbox, the second
parameter must contain its value, and the third (optional) parameter
lets you set an item as the default (use boolean TRUE/FALSE).
Not a great explanation, but here's an example. First get your values from the comma separated string:
The database values return as a comma separated string (online,splitscreen).
// Something like this
$values = explode(',', $my_data); // Now it's an array
Then check if each checkbox's value is in that array:
<?php echo set_checkbox(
'protocols',
'splitscreen',
in_array('splitscreen', $values) // TRUE checks the box, FALSE does not
);?>
I'd do this in a loop for convenience reasons if nothing else. It's also worth looking at form_checkbox() which will make this a good deal easier.
See user guide for details: http://ellislab.com/codeigniter/user_guide/helpers/form_helper.html

Related

Laravel old() directive with conditional default value

I'm using Laravel 5.8, and have several input fields which of course has an old() directive on every value="" tag.
This is my example right now:
<input class="form-control input-md" name="contact_name" type="text" value="#if($edit){{ $ad->contact_name }}#else{{ old('contact_name')}}#endif">
I now that if I use this: {{ old('contact_name', "John")}}
The default value will be "John"
But I want to do a check if there is a user logged in and prefill that input with the User contact name.
My idea is something like this:
value="#if($edit){{ $ad->contact_name }}#else{{ old('contact_name', Auth::user()->name)}}#endif
And it works! But of course, it throws: Trying to get property 'name' when I get an incognito window.
So, how do I evaluate logged in users and prefill this?
You can use the optional helper:
{{ old('contact_name', optional(Auth::user())->name) }}

Angular 2 form valid by default

Having issue with form validation .
i want to submit the form only when form is valid.
but with the empty inputs and clicking on submit button is submitting the form although the inputs are empty.
<form name="equipmentForm" #f="ngForm" (ngSubmit)="f.form.valid && addEquipment()" validate>
Inputs be like this.
<input name="equimentId" class="text-input form-control" type="text" [(ngModel)]="model.equipmentNumber" pattern="^[0-9][0-9]{1,19}$" title="Equipment ID. can be upto 20 digits only.">
I cant post the whole code although.
this
f.form.valid is true from form initialization
wanted to acheive something like this
<div *ngIf="!model.equipmentModel && f.submitted" class="text-danger">
Please enter Equipment Model
</div>
So on submit i want to show this message instead of default browser's.
but this f.form.valid is goddamn true from default.
You should add required attribute to your input tags to, then as #Cobus Kruger mentioned, form will not be submitted untill it is filled.
However you can also give a try to pristine, dirty options, which allow you to check if the user did any changes to the form so in this case your condition may look like this:
<form name="equipmentForm" #f="ngForm" (ngSubmit)="f.form.valid && f.form.dirty ? addEquipment() : ''" validate>
and the input:
<input name="equimentId" class="text-input form-control" type="text" [(ngModel)]="model.equipmentNumber" pattern="^[0-9][0-9]{1,19}$" title="Equipment ID. can be upto 20 digits only." required />
In this case it will check if any changes were applied to the input, and submit the form if both conditions are met.
If you specify the required attribute on the input, then the form will not be submitted unless a value is filled in. But that only covers values that were not supplied and you may want to check for invalid values as well.
The usual way is to disable the submit button unless the form is valid. Like this:
<button type="submit" [disabled]="!f.form.valid">Submit</button>
The Angular documentation about form validation also shows this. Look near the bottom of the "Simple template driven forms" section
In function which you call on submit you can pass form as parameter and then check. In html you will need to pass form instance:
<form name="equipmentForm" #f="ngForm" (ngSubmit)="addEquipment(f)" validate>
In typescript:
addEquipment(form){
if(form.invalid){
return;
}
//If it is valid it will continue to here...
}

Add Checkbox to database in Laravel 5

Im not 100% great in html and databases but I'm getting there. What I did works but not when I'm editing a page that has checkboxes.
In my database migration:
$table->string('check_this')->nullable();
In views:
<div class="checkbox">
#if ($job->check_this == 'selected')
<label><input type="checkbox" name="check_this" value="selected" checked>Yes.</label>
#else
<label><input type="checkbox" name="check_this" value="selected">Yes.</label>
#endif
</div>
Once the checkbox is checked, it writes to the db so my if statement wont work correctly. Is there a way that if unchecked it deletes the value from the database?
Maybe I have go about this is the wrong way as in the correct format for checkboxes in a migration.
Your migration should looks like this:
$table->boolean('check_this');
and the view part:
#if ($job->check_this)
See: http://laravel.com/docs/master/schema#adding-columns for all avail types of 'columns' in Laravel.
Checkbox don't send nothing if is not cheched so the database will not update unless you check in controller and if "check_this" is not set in your request set this to 0 on database.
$obj = Obj::find($id); //get your object from database
$input = Request::all(); //or $request->all() if you use requests
if(!isset($input['check_this'])){
$input['check_this'] = 0; //or whatever you want
}
$obj->fill($input);
$obj->save();
Note:
You can simplify your view
<div class="checkbox">
<label><input type="checkbox" name="check_this" value="selected" #if ($job->check_this == 'selected') checked #endif>Yes.</label>
</div>
And of course the answer about using boolean for this field will optimize your database if you don't need this specific string.

Codeigniter pass a id to controller from view

I am using codeigniter for this project. I hava a id value in which i pass from controller A to view A. This id value is echo between an anchor tag. When this anchor tag is clicked on, it redirects to another controller B with the id value and processed this id value within controller B. Is there any other way of doing this other than using the uri class? Want to keep the url clean.
I thought of a way of appending hidden input elements when I shift from controller A to view A to controller B, but i realised it can be very messy.
Any clean ways of doing this? Thanks in advance guys!
New to using Stackoverflow See if you could understand my layout:
METHOD 1
Use the URI Class except you have good reasons not to.
From CONTROLLER_A
$data["id"] = ("ID NUMBER");
$this->load->view("VIEW_A", $data);
ANCHOR IN VIEW A
link
IN CONTROLLER_B
$id = $this->uri->segment(3);
.
METHOD 2
USE FORM POST if you want to keep things hidden:
$data["id"] = ("ID NUMBER");
$this->load->view("VIEW A", $data);
ANCHOR IN VIEW A
<form name="myform" id="myform" action="<?php echo base_url() ?>/controllerB/controllerfunction/" method="post">
<input type="hidden" name="id" id="id" value="<?php echo $id ?>" />
<input type="submit" value="See more" />
</form>
You could also use javascript to submit the form here via link if you which:
See more
Tips:You could also use css to hide submit button in the form by setting opacity to 0;
If link is within the form, you could use javascript:this.submit();
OR JQUERY
See more
$('#link').click(function() {
$('#myform').submit();
});
IN CONTROLLERB
$id = $this->input->post("id");
Well hidden inputs will work, and there's may another workaround that once you redirected to the method and use your id value i.e. get data from database, redirect again to another controller method with the clean URL you need , hope this is helpful

Codeigniter: How to redirect properly with form validation

I understand how to do it w/ a plain form w/o existing values, but let's say I have a view that I can call via http://domain.com/account/settings. let's say I have two fields, username, password and city, which are all pulled from the DB (except for password of course). So, if a user tries to submit the form and fails validation for whatever reason, where should I "redirect" them to? Right now, I have it showing the same view but the problem is, it pulls the info from the DB again. Should I be creating two different views?
The second view would essentially show the information they tried to enter along w/ the error message.
You do not need two separate views. Check out Form Helper's functions set_value(), set_select(), set_checkbox() and set_radio(). These re-populate form after its submission and validation. So in your case, you should specify the fields this way:
<input type="text"
name="username"
value="<?php echo set_value('username', $user['username']); ?>" />
<input type="text"
name="city"
value="<?php echo set_value('city', $user['city']); ?>" />
By default, the input will have $user['city'] value. But after failed validation it will be re-populated with previously entered values (including incorrect ones).
Just remember that all fields you want to re-populate need to be passed through form_validation library:
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('city', 'City', '');
On the same controller you could have something like this:
if ($this->form_validation->run('create_comment') === TRUE)
{
$this->comments_model->name = $this->input->post('name', TRUE);
$this->comments_model->email = $this->input->post('email', TRUE);
$this->comments_model->website = $this->input->post('website', TRUE);
$this->comments_model->comment = $this->input->post('comment', TRUE);
$this->comments_model->create_comment();
redirect(current_url());
}
$this->load->view('your_view');
That's all there is to it.
The idea is to have it redirect to itself or wherever you want, when the validation returns 'true' so that we kind of refresh the page, hence, update the page.
If the validation returns 'false' then you won't have to do anything.
Redirect to the same form.
And in your view give error information to the visitor.
There are two ways you can do this.
Use this error in your view. This will show validation error info.
echo validation_errors('<p class="error">','</p>');
Or you can use flashdata()
In your controller
...
...
$this->session->set_flashdata('msg', 'All fields are required. or other useful info here. Please try again!');
redirect('yourcontroller');
And in your view, you need to show it.
<?php
if ($this->session->flashdata('msg')){ //change!
echo "<div class='message'>";
echo $this->session->flashdata('msg');
echo "</div>";
}
?>
Had the same problem and discovered that a redirection makes you lose the data that would have been provided by form_error(...) or validation_errors(), except you store such data in a session or in an array being passed into the loaded view.
The point to note is that you should redirect only if the data you want passed around is in session, else you should just load a view. The latter ensures that you have your validation errors intact when you reach the loaded view.
Just load same view if form validation failed
controller
$userData=array(
'username'=NULL,
'password'=NULL
);
#set form validation rules
$this->form_validation->set_rules('username', 'Username', 'required');
$this->form_validation->set_rules('password', 'Password', 'required');
#get all posted data ,this helps you in two ways,
# 1. Get all form data and can be use here server side
# 2. repopulating the form data by passing to view page
$userData=$this->input->post(NULL, TRUE);
#check form validation result
if ($this->form_validation->run() == TRUE) {
//do the operation
redirect(URL);
}else{
$this->load->view($view, $userData);
}
View page
<form method=post action='URL'>
<input type='text' name='username'value='<?php echo $username?>'/>
<?php echo (form_error('username')) ? form_error('username', "<div style='color:red'>", "</div>") : ""; ?>
<input type='text' name='password' value='<?php echo $password?>'/>
<?php echo (form_error('username')) ? form_error('username', "<div style='color:red'>", "</div>") : ""; ?>
<input type='submit' value='submit'/>
</form>
This code display form errors and repopulate the form

Resources