codeigniter update database with "TRUE" for checked items and "FALSE" for remaining unchecked items - codeigniter

I am new to php/codeignitor and trying to post changes on form checkboxes to my db. The row to modify is assigned by the gl_id below.
I am not sure how to use my update_checked function in the model to
post TRUE to each of these fields where gl_id =x and FALSE using to the remaining fields not in the array. I can create and view the array of checked values using $_POST['checked'] in the controller
and passing it to the model. Now I need to use this array to post to the db where gl_id = the value from the form in the view.
In View
<h1>Update GL id <?php echo $gl_field['gl_id'];?></h1>
<label>Stat</label>
<input type="checkbox" <?php if ($gl_field['stat'] == "TRUE") {echo "checked = checked";} ?>
name = "checked[]" id="stat" value= "stat" /><BR CLEAR="all">
<label>Exclude</label>
<input type="checkbox" <?php if ($gl_field['exclude'] == "TRUE") {echo "checked = checked";} ?>
name="checked[]" id="exclude" value= "exclude"><BR CLEAR="all">
<label>Override</label>
<input type="checkbox" <?php if ($gl_field['override'] == "TRUE") {echo "checked = checked";} ?>
name= "checked[]" id= "override" value = "override"/><BR CLEAR="all">
In Controller
public function update_table(){
$this->load->helper('form');
$this->page_nav_model->update_table();
$checked_array = $_POST['checked'];
$this->page_nav_model->update_checked($checked_array);
$this->load->view('pages/success');
}
In Model
foreach($checked_array as $true){
echo $true;
}
To clarify when I pull the information into the form in the example above all of the checkboxes are set to "TRUE" in the db so they are checked. If I uncheck stat and click submit I am able to see an array with the values (exclude, override).
I appreciate any help that sets me in the right direction.

To update your table with CI all at once, you need an array like this:
$data = array(
'column_1_name' => 'value_to_insert'
'column_2_name' => 'value_to_insert'
'column_2_name' => 'value_to_insert'
);
Right now, you have an array like this $checked_array = ('stat', 'exclude', 'override') - with more or fewer members.
To create the array that you can use in your update statement (like $data above), what you need to do is create another array with the name of each column and a value equal to 1 if it is in $checked_array or 0 if it was not in $checked array.
The function add_values() below can do that for you. You have to supply two arguments:
$all_possibilities is an array of each column name that you will want to update to either 1 or 0. In this case, it should look like $all_possibilities = array('stat', 'exclude', 'override');
$selected: this is an array with the names of the boxes that were actually selected - it is a subset of $all_possibilities (or it is the same if all the boxes were checked).
This function goes in your controller.
function add_values($all_possibilities, $selected) {
$array_for_query = array();
// this goes through each possible box that can be checked to see if that possibility was actually selected
foreach($all_possibilities as $array_member) {
// this checks to see if the current member of $all_possibilities is found in the $selected array
if (in_array($array_member, $selected)) {
// if it is, it adds that as a member of a new query $array_for_query and gives it a value of 1 (true)
$array_for_query[$array_member] = 1;
} else {
// if it is not, same as above, but gives it a value of 0
$array_for_query[$array_member] = 0;
}
}
// once all the possibilities have been checked and added to the query array, that array is returned
return $array_for_query;
}
Now you can call the function and pass the two arguments in. The returned array is assigned to $checked_and_unchecked.
$data['checked_and_unchecked'] = add_values($possibilities, $checked_array);
Make sure you also grab the gl_id from the form. You can do that with a hidden field in your view:
<input type="hidden" name="gl_id" value="<?php echo $gl_field['gl_id'];?>" />
In the controller, grab that value with
$data['gl_id'] = $this->input->post('gl_id');
Then you can pass the information to your model and update your table passing in the name of the table and the array you created.
$this->model_name->model_method($data);
This will then go in the model:
$this->db->update('table_name', $checked_and_unchecked);
$this->db->where('gl_id', $gl_id);

If a checkbox is unchecked in the HTML, the value does not get sent via $_POST. This is not accounted for in CodeIgniter. This is how I deal with this issue. In the controller:
/**
* Set post values for unchecked boxes.
*
* #access private
* #return void
*/
private function _section_checkboxes()
{
if (!$this->input->post('is_active')) {$_POST['is_active'] = 0;}
// other checkboxes here...
}
/**
* if form validation passes, run this to edit a section
*
* #access public
* #return void
*/
public function do_edit_section()
{
$this->_section_checkboxes();
if ($this->section_model->edit_section($this->input->post()))
{
redirect('success_page');
}
}
And in the model:
/**
* updates a section with active record, returns success.
*
* #access public
* #param array $data
* #return bool
*/
public function edit_section(array $data)
{
$this->db->where('id', $data['id']);
return $this->db->update('sections', $data);
}
And in the view, using the form helper:
<?=form_checkbox(array('name' => 'is_active', 'id' => 'is_active_field', 'value' => '1', 'checked' => (bool)$item->is_active))?>
Now your unchecked checkboxes are set as 0 when unchecked, 1 when checked. I hope this answers your question.

So I still needed help getting the final touches on the overall project so I wanted to post the final results here for anyone as green as I looking to control checkboxes from the db and the db from checkboxes.
Controller:
[function from Tayler and]
$all_checkbox_fields = array('stat','exclude','override');
$checked_array = $_POST['checkbox'];
$data['checkbox'] = $this->add_values($all_checkbox_fields, $checked_array);
$data['gl_id'] = $this->input->post('gl_id');
$this->page_nav_model->update_checked($data);
$this->load->view('pages/success');
Model:
public function update_checked($data){
$this->default_db->where('gl_id', $data['gl_id']);
$this->default_db->update('oracle_table', $data['checkbox']);
}
View:
<label>Stat</label>
<input type="checkbox" <?php if ($gl_field['stat'] == "1") {echo "checked = checked";} ?>
name = "checkbox[]" id="stat" value= "stat"/><BR>
<label>Exclude</label>
<input type="checkbox" <?php if ($gl_field['exclude'] == "1") {echo "checked = checked";} ?>
name="checkbox[]" id="exclude" value= "exclude"/><BR>
<label>Override</label>
<input type="checkbox" <?php if ($gl_field['override'] == "1") {echo "checked = checked";} ?>
name= "checkbox[]" id= "override" value = "override" ><BR>

Related

Do a server side validation using multiple form fields

Overriding the JFormRule function "test", I need to implement a server side validation of a value of the form field against the value of another form field in the same form. I am struggling with a probably very easy thing: How can I get the value of this other form field?
Here's an extract of my form definition easyfpu.xml:
<?xml version="1.0" encoding="utf-8"?>
<form addrulepath="/administrator/components/com_easyfpu/models/rules">
<fieldset
name="details"
label="COM_EASYFPU_EASYFPU_DETAILS"
>
<field
name="id"
type="hidden"
/>
<field
name="calories"
type="text"
label="COM_EASYFPU_EASYFPU_CALORIES_LABEL"
description="COM_EASYFPU_EASYFPU_CALORIES_DESC"
size="40"
class="inputbox validate-numfracpos"
validate="numfracpos"
required="true"
hint="COM_EASYFPU_EASYFPU_CALORIES_HINT"
message="COM_EASYFPU_EASYFPU_ERRMSG_NUMBER_FRAC"
/>
<field
name="carbs"
type="text"
label="COM_EASYFPU_EASYFPU_CARBS_LABEL"
description="COM_EASYFPU_EASYFPU_CARBS_DESC"
size="40"
class="inputbox validate-numfracpos"
validate="carbs"
required="true"
hint="COM_EASYFPU_EASYFPU_CARBS_HINT"
message="COM_EASYFPU_EASYFPU_ERRMSG_NUMBER_FRAC"
/>
</fieldset>
</form>
The value of the "carbs" field needs to be assessed against the value of the "calories" field. Here's my test routine "carbs.php":
class JFormRuleCarbs extends JFormRule
{
public function test(SimpleXMLElement $element, $value, $group = null, JRegistry $input = null, JForm $form = null)
{
// Check if value is numeric
if (!is_numeric($value)) {
$element->attributes()->message = JText::_('COM_EASYFPU_EASYFPU_ERRMSG_NUMBER_FRAC');
return false;
}
// Check if calories from carbs do not exceed total calories (1g carbs has 4 kcal)
$caloriesFromCarbs = $value * 4;
$totalCalories = $form->getValue('calories');
if ($caloriesFromCarbs > $totalCalories) {
$element->attributes()->message = JText::_('COM_EASYFPU_EASYFPU_ERRMSG_TOOMUCHCARBS');
return false;
}
return true;
}
}
Unfortunately the code $totalCalories = $form->getValue('calories'); won't return anything, probably because it's part of a fieldset. How can I get the value of this field within this test routine?
Solved!
The $form variable of the test function is not yet filled with the data from the form to be stored when the test function is called. Makes sense, as otherwise the potential errors you want to exclude by performing the test would already be stored.
Retrieve the required form value from the $input variable instead, and all is set! Here's the correct code:
​class JFormRuleCarbs extends JFormRule
{
public function test(SimpleXMLElement $element, $value, $group = null, JRegistry $input = null, JForm $form = null)
{
// Check if value is numeric
if (!is_numeric($value)) {
$element->attributes()->message = JText::_('COM_EASYFPU_EASYFPU_ERRMSG_NUMBER_FRAC');
return false;
}
// Check if calories from carbs do not exceed total calories (1g carbs has 4 kcal)
$caloriesFromCarbs = $value * 4;
$totalCalories = $input->get('calories', 0); // <-- THIS IS HOW IT WORKS!
if ($caloriesFromCarbs > $totalCalories) {
$element->attributes()->message = JText::_('COM_EASYFPU_EASYFPU_ERRMSG_TOOMUCHCARBS');
return false;
}
return true;
}
}

codeigniter pagination - how to keep on same page after deleting row

I am using codeigniter pagination library and doing update and delete through form. The problem is when I delete or update any record after delete or update I redirected back to 1st page even if I am at 4th page. How I can redirected to the same page at which I have done update or delete.
Here is my controller code for update and delete functions:
public function update_att(){
if(isset($_POST['update'])){
$u_id = $_POST['at_id'];
if($_POST['status']=="Present"){
$data = array(
'status'=>"Absent"
);
$this->db->where('at_id', $u_id);
$this->db->update('attendence', $data);
}elseif ($_POST['status']=="Absent") {
$data = array(
'status'=>"Present"
);
$this->db->where('at_id', $u_id);
$this->db->update('attendence', $data);
}
redirect("usr/att_list", "refresh");
}
}
public function delete_att(){
if (isset($_POST['delete'])) {
$at_id = $_POST['at_id'];
$this->db->where('at_id', $at_id);
$this->db->delete('attendence');
}
redirect("usr/att_list" );
}
Currently I am redirecting to the first page , any suggestion how I redirect to that page where I have done delete or update.
Add <input type='hidden' name='current_page' value='<?php echo $current_page?>' /> to your form.
Keep in mind you need to populate $current_page with something like
$current_page = ''; // empty means first page
if( isset($_REQUEST['current_page'] ){
$current_page = $_REQUEST['current_page'];
}
Then based on your sample you just modifiy the redirect path as follows (for both your functions):
public function delete_att(){
if (isset($_POST['delete'])) {
$at_id = $_POST['at_id'];
$this->db->where('at_id', $at_id);
$this->db->delete('attendence');
}
redirect("usr/att_list".(strlen($current) ? "?".$current : "" );
}
Note:
Your path to your page should look something like this domain.com/controller/your_page_with_pagination/?current_page=A_NUMBER then in your controller/your_page_with_pagination you adjust the data you wish to output based on $_GET['current_page']
Edit based on your link:
public function att_list($id = ""){
/**
* Keep your data in array
*/
$this->data = array();
/**
* Add the page number ($id) to the array
* Check for url /:id first , or else check for a $_GET/$_POST current_page (this will be triggered when you submit your form)
*/
$this->data['current_page'] = is_numeric($id) ? $id : (isset($_REQUEST['current_page'] ? $_REQUEST['current_page']: 0);
/**
* This is your 'keep on the same page' line
* $this->data['current_page'] will act as an offset in your query
* You can read about 'offset' here https://www.w3schools.com/php/php_mysql_select_limit.asp
* $this->data['my_desired_records'] must be generated into your <form> ... </form> , and the same form must contain the input with name='current_page'
*/
$this->data['my_desired_records'] = $this->your_model->get_data($this->data['current_page']);
/**
* Pass the whole array into your view
*/
$this->load->view('path/to/view', $this->data);
}
Then in your view add in your form <input type='hidden' name='current_page' value='<?php echo $this->data['current_page']?>' />

How do I insert one to many relational multi data to same table in Laravel?

My table structure is:
id | parent_id | name.
My Menu model one to many relationship is:
public function childMenus() {
return $this->hasMany( ‘App\Menu’, ’parent_id’);
}
public function parentMenus() {
return $this->belongsTo(‘App\Menu’, ‘parent_id’);
}
I am creating menus with sub menus.For example I have to set 'Parent Menu' with three child menus.For this I have created a form with four inputs field.
<form>
<input type="text" name="parent">
<input type="text" name="child[]">
<input type="text" name="child[]">
<input type="text" name="child[]">
</form>
Now I want to save parent menu with its child menus at the same time.I tried to save them in array but its not working in Laravel.
Please also explain what would be the controller method for saving this data.
Thanks in advance
You can use the saveMany method to attach multiple children to a parent.
// Assuming whatever goes into the text box goes in the "name" field.
$parent = new \App\Parent();
$parent->name = \Input::get('name');
$parent->save();
$children = [];
foreach (Input::get('child') as $child) {
$children = new \App\Child([
'name' => $child
]);
}
$parent->childMenus()->saveMany($children);
I found the solution for my question.Here I am posting...
$parent_menu = $request->input('parent');
$parent = Menu::create(['name' => $parent_menu]);
$parent->save();
$child_menus = $request->input('child');
foreach($child_menus as $child_menu) {
$child = $parent->pages()->create(['name' => $child_menu]);
$child->save();
}

CodeIgniter update page - Simple CRUD website assistance required

After looking through the forums and starting to try to create a basic CRUD website I am currently struggling to have a page that updates the articles as follows. If someone could kindly tell me where I am going wrong, I will be most greatful. I am getting a 404 error at 'news/input'
model (at news_model.php)
public function update($id, $data)
{
$this->db->where('id', $id);
$this->db->update('news', $data);
}
controller (news.php)
public function update($id){
$data = array(
'title' => $this->input->post('title'),
'slug' => $this->input->post('slug'),
'text' => $this->input->post('text'));
if($this->news_model->exists($id)) {
$this->news_model->update($id, $data);
}
else {
$this->news_model->insert($data);
}
}
html (views/news/input.php)
<h2>Update a news item</h2>
<?php echo validation_errors(); ?>
<?php echo form_open('news/update') ?>
<label for="title">Title</label>
<input type="input" name="title" /><br />
<label for="slug">Slug</label>
<input type="input" name="slug" /><br />
<label for="text">Text</label>
<textarea name="text"></textarea><br />
<input type="submit" name="submit" value="Update an item" />
You get a 404 because your news controller seems to have no method 'input'. Try adding something like this:
public function input(){
// load the form
$this->load->view('/news/input');
}
Note that for updating data you will need to fetch and pass it into the view first, then render the (filled out) form using set_val() and other CI functions.
Currently you're "hardcoding" the HTML form which makes populating and maintaining state (when validation fails) difficult. I suggest you play through the forms tutorial on the CI website.
Edit:
To create a update/insert (upsert) controller change as follows:
Controller:
function upsert($id = false){
$data['id'] = $id; // create a data array so that you can pass the ID into the view.
// you need to differntiate the bevaviour depending on 1st load (insert) or re-load (update):
if(isset($_POST('title'))){ // or any other means by which you can determine if data's been posted. I generally look for the value of my submit buttons
if($id){
$this->news_model->update($id, $this->input->post()); // there's post data AND an id -> it's an update
} else {
$this->news_model->insert($id, $this->input->post()); // there's post data but NO id -> it's an insert
}
} else { // nothing's been posted -> it's an initial load. If the id is set, it's an update, so we need data to populate the form, if not it's an insert and we can pass an empty array (or an array of default values)
if($id){
$data['news'] = $this->news_model->getOne($id); // this should return an array of the news item. You need to iterate through this array in the view and create the appropriate, populated HTML input fields.
} else {
$data['news'] = $this->news_model->getDefaults(); // ( or just array();) no id -> it's an insert
}
}
$this->load->view('/news/input',$data);
}
And amend the $id to the action-url in your view:
<?php echo form_open('news/upsert/'.$id) ?>

Custom Validator/Constraint with Arguments/Parameters in Symfony 2

I want to create a validator similar to the way GitHub handles deleting repositories. To confirm the delete, I need to enter the repo name. Here I want to confirm delete by entering the entity property "name". I will either need to pass the name to the constraint or access it in some way, how do I do that?
you could indeed use a validator constraint to do that:
1: Create a delete form (directy or using a type):
return $this->createFormBuilder($objectToDelete)
->add('comparisonName', 'text')
->setAttribute('validation_groups', array('delete'))
->getForm()
;
2: Add a public property comparisonName into your entity. (or use a proxy object), that will be mapped to the corresponding form field above.
3: Define a class level, callback validator constraint to compare both values:
/**
* #Assert\Callback(methods={"isComparisonNameValid"}, groups={"delete"})
*/
class Entity
{
public $comparisonName;
public $name;
public function isComparisonNameValid(ExecutionContext $context)
{
if ($this->name !== $this->comparisonName) {
$propertyPath = $context->getPropertyPath() . '.comparisonName';
$context->addViolationAtPath(
$propertyPath,
'Invalid delete name', array(), null
);
}
}
}
4: Display your form in your view:
<form action="{{ path('entity_delete', {'id': entity.id }) }}">
{{ form_rest(deleteForm) }}
<input type="hidden" name="_method value="DELETE" />
<input type="submit" value="delete" />
</form>
5: To verify that the delete query is valid, use this in your controller:
$form = $this->createDeleteForm($object);
$request = $this->getRequest();
$form->bindRequest($request);
if ($form->isValid()) {
$this->removeObject($object);
$this->getSession()->setFlash('success',
$this->getDeleteFlashMessage($object)
);
}
return $this->redirect($this->getListRoute());

Resources