What I'm about to show might be the most horrific code in existence, so be prepared. I'm new to PHP and received a CodeIgniter project. Here we go:
In my edit_article view, I dynamically generate <input> fields and make them accessible to the controller by posting them as an array, notice name="pricelevel_checked_array[]":
<form id="form-work" class="form-horizontal" role="form" autocomplete="off" method="post">
<!-- excluded code to display form content -->
<?php
$pricelevel_array = array();
$count = 0; ?>
<?php foreach($array_used_for_loop as $item_used_for_loop): ?>
<?php $article_group_price = ""; ?>
<!-- excluded code to fill $article_group_price -->
<div class="col-sm-2">
<div class="checkbox">
<span class="bg-transparent left">
<input type="checkbox" data-init-plugin="switchery" data-size="small" data-color="primary" id="<?=$count?>"
<?php if($article_group_price !== ""): ?>
<?php array_push($pricelevel_array, 1); ?>
checked="checked"
<?php else: array_push($pricelevel_array, 0); ?>
<?php endif; ?>
onchange="groupprice_active_changed(this)"/>
</span>
</div>
</div>
<input hidden type="number" id="pricelevel_checked_array" name="pricelevel_checked_array[]" value="<?=$pricelevel_array[$count];?>">
<?php $count++; ?>
<?php endforeach; ?>
</form>
As you can see, I fill that array with 1's or 0's depending on the value of $article_group_price (I get these values from the controller and originally the database).
It all works fine upon first loading the view and the array is filled correctly, but I can't seem to update the array when I check- or uncheck a checkbox.
I've tried to do this quick and dirty using javascript onchange="groupprice_active_changed(this)" where I would use the $count variable to change the index of the array, but unfortunatly that didn't work out since I only get one value and not the entire array:
<script>
function groupprice_active_changed(obj) {
if($(obj).is(":checked")){
alert("Yes checked");
var input_value_array = document.getElementById('pricelevel_checked_array').value;
console.log(input_value_array);
for (index = 0; index < input_value_array.length; index++) {
console.log(input_value_array[index]);
}
}else{
alert("not checked")
}
}
</script>
How can I best update this array or change my code so I can post the dynamic generated checkboxes to the controller? Another problem is that I need the checkbox-id in the controller, even if it's false. And that the browser doesn't post an unchecked checkbox value. So, just passing the checkboxes isn't an option.
I'm of course prepared to post more code.
Thank you
Disclaimer: Please no steal
View: Complete code
Controller: Complete code
Edit 1: Changed 'php' to 'the browser' in the last section
Edit 2: Added as good as the whole code because filtering out will only make it more difficult.
One technique I have see used to make checkboxes behave better is to use
a hidden input with the same name as the checkbox. Put the hidden input before
the checkbox. If the checkbox is not checked, the value of the hidden input
gets sent. If you check the checkbox then the checkbox value overrides the hidden input.
This works because only one of the values is sent. The browser sends the later one.
Take a look at the following example.
<html>
<head>
</head>
<body>
<div>
<form method="post">
<input type="hidden" name="foo" value="off">
<input type="checkbox" name="foo" /> Foo
<input type="submit" />
</form>
</div>
</body>
</html>
<?php if ( ! empty($_POST) ) : ?>
<div> Hello </div>
<div>
Checkbox is <?= $_POST['foo']?>
</div>
<?php endif ?>
I eventually made the decision to drop the whole array approach and follow the KISS principle by passing my index to the controller. I use these indexes to only save the rows that are checked. Thanks to #ryantxr for showing me that I was overthinking all this.
v_edit_article
<?php $index = 0; ?>
<?php foreach($array_used_for_loop as $item_used_for_loop): ?>
<?php $article_group_price = ""; ?>
<!-- excluded code to fill $article_group_price -->
<div class="col-sm-2">
<div class="checkbox">
<span class="bg-transparent left">
<input type="checkbox" name="group_active[]" data-init-plugin="switchery" data-size="small" data-color="primary" value="<?=$index;?>"
<?php if($article_group_price !== ""): ?>
checked="checked"
<?php endif; ?>/>
</span>
</div>
</div>
</div>
<?php $index++; ?>
<?php endforeach; ?>
admin (controller)
public function edit_article($id) {
// Excluded code
$group_prices_active = array();
if(isset($data['group_active'])):
echo "<script>console.log('GROUP_ACTIVE ".print_r($data['pricelevel_checked'])."');</script>";
foreach($data['group_active'] as $value):
array_push($group_prices_active, $group_prices[$value]);
endforeach;
echo "<script>console.log('GROUP_PRICES_ACTIVE ".print_r($group_price_active)."');</script>";
unset($data['group_active']);
endif;
// Excluded code
$this->m_articles->edit_article($data, $id, $article_types, $group_prices_active);
$this->session->set_flashdata('succes', $this->lang->line('edit_success'));
redirect('/administrator/articles', 'refresh');
}
Related
to be honest this is more of a how to then help with code i already have. So i hope this is okay, else of course i will delete my question again. Anyway here goes i have a site with boxes, with a picture headline and a submit button. All the info in these boxes is being delivered, from my database. And of course in my database i also have a id cell, and if i try to echo out the id cell with the rest of the info in the box it shows up fine. But when i try to assign the id output variable to a header location, i do for some weird reason always get the id 3. Eventhough the id´s shows up perfectly fine, in the boxes. I have included my php code and i am still a beginner to php so sorry for this noob question. :)
session_start();
include 'connection.php';
$sqlSelect = mysqli_query($con,"SELECT * FROM inspi");
while ($feed=mysqli_fetch_array($sqlSelect))
{
$id = $feed['id'];
if(isset($_POST['readArticle']))
{
$id = $_SESSION['id'];
header("Location:"."redirect.php?".SID.$idArticle);
}
?>
<div class="contentBoxOne">
<img width="100%" height="170px" src="userpics/<?php echo $feed['image']; ?>">
<div class="line"></div>
<form method="post" action="">
<input type="submit" name="readArticle" class="readArticle" value="Læs nu!">
</form>
<?php $idArticle= $feed['id'];?>
<h2><?php echo $feed['headline'];?></h2>
</div>
You are setting $idArticle at the bottom of the loop but trying to use it at the top so it will be pulling it from the previous result. Try:
while ($feed=mysqli_fetch_assoc($sqlSelect)){
$idArticle= $feed['id'];
$sid = $_SESSION['id'];
if(isset($_POST['readArticle']))
{
header("Location:"."redirect.php?".$sid.$idArticle);
}
//rest of code
}
You will have to put div inside the loop.
I also replaced the header redirect with form action attribute (you may want to replace method POST with GET instead).
ID is passed with a hidden field
<?php
include 'connection.php';
$sqlSelect = mysqli_query($con,"SELECT * FROM inspi");
while ($feed=mysqli_fetch_assoc($sqlSelect))
{
$id = (int)$feed['id'];
?>
<div class="contentBoxOne">
<img width="100%" height="170px" src="userpics/<?php echo $feed['image']; ?>">
<div class="line"></div>
<form method="post" action="redirect.php">
<input type="hidden" name="id" value="<?php echo $id; ?>">
<input type="submit" name="readArticle" class="readArticle" value="Læs nu!">
</form>
<h2><?php echo $feed['headline']; ?></h2>
debug: <pre><?php print_r($feed); ?></pre>
</div>
<?php } // end of while loop ?>
I'm making a To do application with PHP (school assignment)
At this moment, I can add tasks to the list. Deleting is the next problem.
The "problem" is that I HAVE to use PHP to delete the corresponding div. (It needs to delete the div i'm clicking)
My question: what's the best practice to do that? (Working with a specific number maybe?)
Index.php
<div class="container">
<form action="/Periodeopdracht/index.php" method="POST">
<div class="headerToDo">
<input class="addText title" type="text" value="Click to add a task" name="nextToDo">
<input class="clickablePlus" type="submit" value="+" name="submit"></div>
</form>
<?php if(!$empty): ?>
<?php foreach ($_SESSION["todoList"] as $_SESSION["key"] => $toDo): ?>
<div class="toDo">
<form action="/Periodeopdracht/index.php" method="POST">
<button value="<?php echo $_SESSION["key"] ?>" name="done" class="done" type="submit" >V</button>
<div value="<?php echo $_SESSION["key"] ?>" class="textToDo"><?= $toDo ?></div>
</form>
</div>
<?php endforeach ?>
<?php endif ?>
</div>
application.php:
<?php
session_start();
$GLOBALS["empty"] = true;
$_SESSION['todoList'] = isset($_SESSION['todoList']) ? $_SESSION['todoList'] : array();
if(isset($_POST["submit"]))
{
$empty = false;
array_unshift($_SESSION['todoList'], $_POST["nextToDo"]);
}
if (isset($_POST['done'])) {
foreach ($_SESSION["todoList"] as $key => $toDo) {
if ($toDo == $_POST['done']) {
unset($_SESSION['todoList'][$key]);
break;
}
}
}
?>
foreach ($_SESSION["todoList"] as $key => $toDo)
then use $key as the value of your "done" button, When processing you can just unset($_SESSION['todoList'][$key])
you will have to check that the key is valid coming from the post though.
Add a <hidden> field to each toDo with, the id of the toDo, then you will know what to remove from the toDo list.
In addition to what exussum was stating. U'll need to define in your HTML which todo item u want to delete. Atm your just posting an empty button. Change your html to something like this:
<div class="toDo">
<form action="/../index.php" method="POST">
<button name="done" class="done" value="<?= $toDO ?>" type="submit">V</button>
<div class="textToDo"><?= $toDo ?></div>
</form>
</div>
Now if you post the form the variable $_POST['done'] will contain the task that is completed. Now the check this :
<?php
if (isset($_POST['done']) {
foreach ($_SESSION["todoList"] as $key => $toDo) {
if ($toDo == $_POST['done']) {
unset($_SESSION['todoList'][$key]);
break; //terminates the loop as we found the correct item
}
}
$empty = empty($_SESSION["todoList"]);
}
I'm not a huge fan of posting raw values to check whether items need to be deleted.
Its beter to work with (unique) id's if you are using these.
I am new to code igniter. I've created a form but it is not display properly.
When I put
<?php echo form_open('sms'); ?> instead of <form action="">tag
here in my form and controller, I can't understand why it is not displayed.
<?php echo form_open('sms'); ?>
<p>
<label><strong>Username</strong>
<input type="text" name="textfield" class="inputText" id="textfield" />
</label>
</p>
<p>
<label><strong>Password</strong>
<input type="password" name="textfield2" class="inputText" id="textfield2" />
</label>
</p>
<input type="submit" value="Authentification" name="auth" />
<label>
<input type="checkbox" name="checkbox" id="checkbox" />
Remember me</label>
</form>
and my controller is
<?php
class sms extends CI_Controller{
function school(){
$this->load->view('school/index.php');
if($this->input->post('auth',TRUE)){
$this->load->view('school/dashboard.php');
}
else{
$this->load->view('school/index.php');
}
}
}
?>
If this is your entire script for the most part, it looks like you need to load the helper first from the CodeIgniter Form Helper Page.
If you don't have this line, try adding it before the form_open() function:
<?php $this->load->helper('form'); ?>
While I have used CodeIgniter, it's been a while. Let me know if that changes the result.
Edit: Since you've chosen my answer I'll include this one, credits go out to devo:
You could change </form> to: <?php echo form_close(); ?>. There are pros and cons for this method though, and without using arguments you might be better off sticking with </form>.
I'll explain further:
<div class="registration">
<div class="form-box">
<?php $this->load->helper( 'form' ); ?>
<?php $end = '</div></div>'; ?>
<?php echo form_open( 'register' ); ?>
<!-- Form Inputs Here -->
<?php echo form_close( $end ); ?>
<!-- Echos '</form></div></div>' -->
So for closing the form without arguments, the </form> tag works best, both by performance and simplicity. The example used above is a rather simplistic view of what you can do with it, since what I wrote is not very efficient either.
However, this is still php we're talking about, so perhaps the craftier among us could put it to better use.
End Edit
Have you loaded the form helper? You can use $this->load->helper('form'); in your controller action, her inside function school(). You can then use form helper in the view pages.
Load form helper,
$this->load->helper('form');
And use,
echo form_close()
Instead of,
</form>
First in your Controller put in:
$this->load->helper('form');
And Change </form> to :
<?php echo form_close(); ?>
--EDIT---
i have created a text box area where users can input some data,
Basically when i press the submit button, it should save the inputted data. here is the full code, i can't fix it. :/
The user entry does not get updated.
<?php
if ( $act == "htmlprofile" ) {
?>
<div class="contentcontainer">
<div class="contentmboardheaderarea"><img src="images/header.png" />
<div style=”word-wrap: break-word”><div class="contentheadertext"><?php echo "$hlang2"; ?></div></div></div>
<div class="contentheading">
<form id="htmlform" name="htmlform" method="post" action="options.php?act=htmlsubmit">
<div class="contentheading4">
<?php echo "$olang15"; ?></div>
</div>
<div class="contentmboardlistarea2"><textarea id="htmlprofile" name="htmlprofile" cols="33" rows="10"><?php echo $qry2[htmlprofile];?>
</textarea></div></form>
<div class="contentbuttonarea">
<div class="contentbutton1" onClick="document.location.href = 'profile.php?act=index'";><?php echo "$glang3"; ?></div>
<div class="contentbutton2" onClick="document.forms['htmlform'].submit();"><?php echo "$glang21"; ?></div>
<div class="contentbutton3"></div>
<div class="contentbutton4"></div>
<div class="contentbutton5" onClick="document.location.href = 'help.php#htmlprofile'";><?php echo "$glang5"; ?></div>
</div>
</div>
<?php
}
?>
<?php
if ( $act == "htmlsubmit" ) {
$save ='Profile updated successfully';
$query4 = "UPDATE members SET htmlprofile = '$htmlprofile' WHERE username = '$myuser'";
mysql_query($query4);
?>
There is no value attribute in textarea you have to enter the content between the <textarea>text</textarea>
See for reference tag_textarea
It should be like this
<textarea id="htmlprofile" name="htmlprofile" cols="33" rows="16" >
<?php echo $qry2[htmlprofile]; ?>
</textarea>
Refer to this answer also which-value-will-be-sent-by-textarea-and-why
Your div contentheadertext is not contained within the <form></form> so if you have inputs there, they won't be included in the form submission.
To resolve, move the opening <form> tag higher, so that it encloses all inputs.
the submit works fine. But you have no variables with the post data definied. And textareas haven't "value". And when you don't need fixed strings in your echo, don't use the "
try the following:
<textarea id="htmlprofile" name="htmlprofile" cols="33" rows="16"><?php echo htmlspecialchars($_POST['htmlprofile']); ?></textarea>
if you are trying to use a php variable inside HTML do that simply by echo $myvariable ; Quotes not required there. But if u are trying to echo a string use quotes just like echo 'mystring' .
Moreover when you are trying to pass some values as part of form submission, the required values should be between the tags
if you want to show any value inside text area, remember it doesn't have a 'value' attribute. So write the code like this: value to be displayed
I Have a form which when submitted needs to go to the page and then show one of 4 hidden divs depending on the page.
Here is the form
<form>
<input id="place" name="place" type="text">
<input name="datepicker" type="text" id="datepicker">
<input type="submit" name="submit" id="submit" />
</form>
Here is the page
<div id="brighton">
<p>Brighton</p>
</div>
<div id="devon">
<p>Devon</p>
</div>
<div id="search">
<p>search</p>
</div>
<div id="variety">
<p>variety</p>
</div>
So if Brighton is typed into the place input i need the form to submit the page and show the Brighton div and if Devon is typed in to show the Devon div etc and if the 2/12/2012 is typed into the date picker input and Brighton into the place input it goes to the page and shows the variety div.
i also need it so if the 1/12/2012 is typed in to the date picker input the page redirects to the page show.html.
any help would be greatly appreciated
thanks.
This is easy if you know PHP at all. It looks like you need a good, easy start. Then you will be able to achieve this in seconds.
Refer to W3SCHOOLS PHP Tutorial.
To achieve what you have mentioned, first make the following changes in your form:
<form action="submit.php" method="post">
<input id="place" name="place" type="text">
<input name="datepicker" type="text" id="datepicker">
<input type="submit" name="submit" id="submit" />
</form>
Create a new file called submit.php and add the following code:
<?php
$place = $_POST['place'];
$date = $_POST['datepicker'];
if ($date == '1/12/2012') {
header('Location: show.html');
exit;
}
?>
<?php if ($place == 'Brighton''): ?>
<div id="brighton">
<p>Brighton</p>
</div>
<?php elseif ($place == 'Devon'): ?>
<div id="devon">
<p>Devon</p>
</div>
<?php elseif ($place == 'search'): ?>
<div id="search">
<p>search</p>
</div>
<?php elseif ($place == 'Variety'): ?>
<div id="variety">
<p>variety</p>
</div>
<?php endif; ?>
Now the above example is not the complete solution, but it gives you an idea as to how you can use if-then-else construct in PHP to compare values and do as desired.
Post your form to a php page and then check the posted form parameters to determine which div to show.
<?php
if ($_POST["place"] == "Brighton") {
?>
<div id="brighton">
<p>Brighton</p>
</div>
<?php
} else if ($_POST["place"] == "Devon") {
?>
<div id="devon">
<p>Devon</p>
</div>
<?php
}
?>
Do that for each div and parameter combination. Make sure you set the "method" attribute on your form to "post":
<form action="somepage.php" method="post">...</form>
In the resulting HTML you will only see the one that matches the form parameter.