I'm trying to save the data into the database based on the checkbox. If the checkbox is checked then save, else don't save. My idea is passing the ng-model value to php value then do validation but it doesn't work.
blade.php
<input type="checkbox" name="update_info" ng-model="item.update_info"></label>
php
$value = "{{item.update_info}}"
if ($vendor === NULL && $value === true) {
try {
DB::table('vendors')
->insert([
'vendor_id' => $vendor_id,
'price' => $price
]);
} catch(PDOException $e) {
throw new TransactionException([$e->getMessage()]);
}
}
The value of a checkbox is not a boolean type true, but a string with value 'on';
Try this:
if ($vendor === NULL && $value === 'on') {
You use value in checkbox when it is checked the value will go to the server, for eg:
<input type="checkbox" name="update_info" ng-model="item.update_info" value="1"></label>
So you can validate in the server
$value = Input::get('update_info');
if($value){ ... }
Try this and let me know how it works :)
Related
I've been trying for a few days to figure this out but can't get it to work out correctly as I run through testing the scenarios. Basically, this is on an edit form, so it's pulling the stored value from the database. I have it save as either "1" or "0", 1 being checked. It's also a single checkbox, not an array.
I'm trying to figure out how to make the session correctly store the choice of my checkbox so that if there's an error on the page, etc, it shows my session value correctly, but what happens is that the DB value usually ends up trumping that.
So how can I initially first display the DB value, but then display the session value if changed?
Here's what I've been playing with.
if(isset($_SESSION["include_due_date"])) {
$include_due_date = 'checked="checked"';
} else {
if((!isset($_SESSION["include_due_date"])) && $resInvoice[0]["include_due_date"] == 1 ) {
$include_due_date = 'checked="checked"';
} elseif((isset($_SESSION["include_due_date"])) && $resInvoice[0]["include_due_date"] == 0 ) {
$include_due_date = 'checked="checked"';
} elseif((!isset($_SESSION["include_due_date"])) && $resInvoice[0]["include_due_date"] == 0 ) {
$include_due_date = '';
}
}
Any ideas?
ADDITIONAL METHOD:
<input type="checkbox" value="1" <?php echo (isset($_SESSION['include_due_date'])?' checked="checked"' : (!isset($_SESSION['include_due_date'])) && $resInvoice[0]['include_due_date'] == 1?' checked="checked"' : ''); ?> name="include_due_date" id="include_due_date" />
So how can I initially first display the DB value, but then display
the session value if changed?
session_start(); // (Be sure to use session_start)
// If the include_due_date was set by the session
if(isset($_SESSION["include_due_date"])) {
// Set the value of $checked to the value of the session variable
// In this way, the value of the session variable takes precedence over that in the database
$checked = ($_SESSION["include_due_date"] === true);
} else {
// The session variable wasn't set, so use the value from the database to set both the checked value and the session variable.
// The next request will use the value from the session variable
if($resInvoice[0]["include_due_date"] == 1 ) {
$_SESSION["include_due_date"] = $checked = true;
} else {
$_SESSION["include_due_date"] = $checked = false;
}
}
HTML
<input type="checkbox" value="1" <?php if ($checked) echo 'checked="checked"; ?> name="include_due_date" id="include_due_date" />
This question already has answers here:
How do I add on multiple $_POST['row'] and variables? [closed]
(2 answers)
Closed 9 years ago.
I have many isset checkings:
if (isset($_POST['name']) && isset($_POST['day']) && isset($_POST['month']) && isset($_POST['year']) && isset($_POST['email']) && isset($_POST['email2'])&& isset($_POST['pass']) && isset($_POST['pass2']))
{
Is there a way to short it?
$isset = array
(
'name', 'day', 'month', 'year',
'email', 'email2', 'pass', 'pass2'
);
foreach ($isset As $set)
{
if (!isset($_POST[$set]) || empty($_POST[$set]))
{
echo 'error';
break;
}
}
Is that correct?
You could use a loop and empty only:
$keys = array('name', 'day', 'month'); // ...
foreach ($keys as $key) {
if (empty($_POST[$key])) {
// fail
break;
}
}
Or you could use array_diff_key():
if (array_diff_key(array_flip($keys), $_POST)) {
// fail (some keys not present in $_POST)
}
isset() can take multiple arguments, so you can shorten it simply like this.
if (isset($_POST['name'], $_POST['day'], $_POST['month'], $_POST['year'], $_POST['email'], $_POST['email2'], $_POST['pass'], $_POST['pass2']))
PHP Docs: http://php.net/manual/en/function.isset.php
Define a function like this:
function getPost($key, $default = null) {
if (isset($_POST[$key])) {
return $_POST[$key];
}
return $default;
}
Then you can skip the isset verification. If there's no sucho value, by default, the function will return null.
If you are sending these from an input form and your default value attribute is value="" then it will still be set in $_POST.
For example, if the previous page has:
<input type="text/css" id="email" name="email" value="" />
Then if the user leaves it blank, isset($_POST['email']) will return true, and $_POST['email'] will have a value of "". That's useless, right?
Try this.
$c = 0;
foreach($_POST as $key => $value)
{
$value = trim($value);//Makes sure there's no leading, or ending spaces. Safe to guard against a string that is " " instead of "".
if(strlen($value) > 0)
{
$c++;
}
else
{
echo "$_POST['" . $key . "'] has a problem.";
}
break;
}
Then your new if statement for whatever conditions you had in mind could be:
if($c == 8)//8 being the number of keys you're expecting to not be "" or null.
{
//Your conditions.
}
This is good to keep in mind. You are only testing 8 array keys, but what if you had 800? Something like this would be a necessity.
Depends on what you are doing, if it is to set a value, the ternary operator works wonders:
isset($_POST['day'])?$day=_POST['day'] :$day='';
after that line, $day is always set and you only test with if($day).
If there are many values, you can always run this assignment in a loop:
foreach(array('day','month','name') as $var)
{
isset($_POST[$var])?$$var=$_POST['$var']:$$var='';
}
So basically, I have a function that is ran when a post is created on wordpress. I've modified this function by adding the following code.
$episodeID = $_POST['item_meta'][137];
$episodeVersion = $_POST['item_meta'][357];
if ($episodeVersion == "Subbed") {
$value = array("Subbed");
update_field('field_48', $value, $episodeID);
}
else if ($episodeVersion == "Dubbed") {
$value = array("Dubbed");
update_field('field_48', $value, $episodeID);
}
This code basically says, if the value of a field in that post is "Subbed" then update another checkbox field by checking the "Subbed" checkbox. If it's "Dubbed" then update the checkbox field by selecting the "Dubbed" checkbox.
This works perfectly fine, however there is no time when both of these checkboxes are checked. If I add a post with the Dubbed, it'll check dubbed, then if I add a post with Subbed, it'll uncheck dubbed and check subbed.
So basically, how can I make it so it doesn't actually uncheck whatever has already been checked. So what should I use to check to see if the checkbox is unchecked or checked? Some type of boolean true / false?
Okay, so I was able to manipulate some of the code and get it to work eventually.
All I had to do was check if the Subbed checkbox was already checked when executing the dubbed if statement, and vice versa.
Here is the updated code
$episodeID = $_POST['item_meta'][137];
$episodeVersion = $_POST['item_meta'][357];
if ($episodeVersion == "Subbed" && !(get_field('episode_sdversion') && in_array('Subbed', get_field('episode_sdversion', $episodeID))) ) {
if (get_field('episode_sdversion') && in_array( 'Dubbed', get_field('episode_sdversion'))) {
$value = array("Subbed", "Dubbed");
} else {
$value = array("Subbed");
}
update_field('field_48', $value, $episodeID);
}
if ($episodeVersion == "Dubbed" && !(get_field('episode_sdversion') && in_array('Dubbed', get_field('episode_sdversion', $episodeID))) ) {
if (get_field('episode_sdversion') && in_array( 'Subbed', get_field('episode_sdversion'))) {
$value = array("Subbed", "Dubbed");
} else {
$value = array("Dubbed");
}
update_field('field_48', $value, $episodeID);
}
I have this code for a few check-boxes, works fine like this
foreach($_POST as $key => $order_type) {
if ('1' == $_POST[$key]) $_POST[$key] = '0';
}
if I negate the if it stops working and I'm sure that some are not == '1'; it just sets them to NULL.
foreach($_POST as $key => $order_type) {
if ('1' != $_POST[$key]) $_POST[$key] = '0';
}
do I miss anything ? tried with !('1' == $_POST[$key]) too.
Thanks
Checkboxes only get sent to the server if they are checked.
I assume that they have a value of 1, so you will be able to find these in the $_POST array. However, there will be none where the value is 0 (unless you specify a value of 0 in the html and check the box...).
To check checkboxes, you need to use isset as the value is really not that important, it is either set (checked) or not and then it simply does not appear.
How about a simple if/else?
if ('1' == $_POST[$key]) {
$_POST[$key] = '0'; }
else {
Do this if it's != ;
}
Sorry i could not find a proper title to this question.
I have generated the following using a for loop and I have concatenated the names of the submits buttons using the pattern below:
submit_edit_category_1
submit_edit_category_2
submit_edit_category_3
echo "<input type='submit' value = 'Edit' name='submit_edit_category_" .
$obj_categories_admin->categories[$i]['category_id'] . "'/>";
I want to loop through these values so that I can the button action whichis edit_category and the category id which is 1,2 or 3. I want to so something like:
if(isset($_POST) == 'edit_category'))
{
//code here
}
Someone suggested me to do it this way:
name="submit[which_action][which_category]"
a1 = $_POST['submit'];
$which_action = reset(array_keys($a1));
$which_category = reset(array_keys($a1[$which_action]));
This does not seem to work..Can anyone give me a different way to do it?
Thanks!
UPD: Please, use Mike's advice. It's much better to have more structured data in POST.
foreach($_POST as $key => $val) {
if(strpos($key, 'submit_edit_category_') === 0 ) {
print $key.' => '.$val.'\r\n';
print substr($key, 21 /* or 22... or 23... try yourself */ );
}
}
here what I'd do:
for the actual form, I'd use array keys to communicate action and relevant id info.
$cat_id = $obj_categories_admin->categories[$i]['category_id'];
echo "<input type='submit' value = 'Edit' name='submit[edit_category][" . $cat_id . "]'/>";
then when posted, I can do:
<?php
list($action, $action_params) = each($_POST['submit']);
list($cat_id, $button_label) = each($action_params);
print_r($_POST['submit']); // prints array('edit_category' => array('1' => 'Edit'))
echo($action); //prints "edit_category"
print_r($action_params); //prints array('1' => 'Edit')
echo($cat_id); //prints "1"
echo($button_label); //prints "Edit"
edit: for more info on each(), go here: http://us2.php.net/each . I've personally always felt that 's lack of differentation between the button label and the it's value to be frustrating. Using an array key to stuff info into the button has always been my favorite hack.
You can try this:
foreach ($_POST AS $key=>$value) {
if (strpos($key, 'submit_edit_category_') !== false) {
$catID = (int)str_replace('submit_edit_category_', '', $key);
echo 'Category ID: ' . $catID . '<br />';
}
}
I'd change the way you build the name to this:
submit__edit_category__1
Then, try this:
function filter_by_submit($var)
{
return stripos($var, "submit") !== false ? true : false;
}
$submits = array_filter(array_keys($_POST), "filter_by_submit");
foreach ($submits as $sub)
{
if ($_POST[$sub] == "Edit")
{
list($submit, $action, $id) = explode("__", $sub);
break;
}
}
$submit will hold the string "submit". $action will hold "edit_category" and $id will hold the id of the pressed button. The pressed button is determined by matching its value to the tag's value (i.e., when submit__edit_category__1 is pressed, the value "Edit" is POSTed).