Default state (Add options) overrides my update options? - php

I have a check box inside my admin page and the code looks like this (this code works and i can toggle my check box off and on and able to save changes)
add_settings_field(
'my_checkbox_default',
'Checkbox:',
'my_default_checkbox_settings_function',
'override_theme_display_options',
'override_theme_display_options'
);
function my_default_checkbox_settings_function(){
$options = get_option('override_theme_display_options');
if(isset($options['my_checkbox_default'])) {
$checked = 'checked';
} else {
$checked = '';
}
update_option('my_checkbox_default', $checked);
echo "<input type='checkbox' name='override_theme_display_options[my_checkbox_default']' ".$checked." id='my_checkbox_default' />";
}
Now I want to add default state "checked" to my check box.
So my check box setting function looks like this:
function my_default_checkbox_settings_function(){
$options = get_option('override_theme_display_options');
//Added default state "checked" to my check box
add_option('my_checkbox_default',$checked = 'checked');
if(isset($options['my_checkbox_default'])) {
$checked = 'checked';
} else {
$checked = '';
}
update_option('my_checkbox_default', $checked);
echo "<input type='checkbox' name='override_theme_display_options[my_checkbox_default']' ".$checked." id='my_checkbox_default' />";
}
My check box now has "checked" state as default , but now I can't toggle my check box off and on anymore (it stays "checked" all the time no matter what I do), if I comment out my add_option() obliviously my default "checked" state will not be set but I will be able to toggle and save my check box states again.
How can I add "checked" state by default and still be able to toggle and save options for my check box?
I will be more than happy to add 50 bounty for solving this. THX!

If this is a plugin, you need to set the option for the first time with register_activation_hook. If a theme, use after_setup_theme.
There's an alternative technique for run_once described in this WPSE Answer that works quite well too.
Here's a working example loosely based on yours and some Codex samples using run_once. Note the use of the function checked().
add_action('admin_init', function()
{
// Change the "init_*" to anything else to `run_once` again
if ( wpse_25643_run_once('init_checkbox_default') )
{
add_option('my_checkbox_default', true );
}
register_setting('media','my_checkbox_default');
add_settings_field(
'my_checkbox_default',
'Checkbox:',
'my_default_checkbox_settings_function',
'media'
);
});
function my_default_checkbox_settings_function()
{
printf(
"<input name='my_checkbox_default' id='gv_thumbnails_insert_into_excerpt' type='checkbox' value='1' class='code' %s /> Explanation text",
checked( 1, get_option('my_checkbox_default'), false )
);
}
function wpse_25643_run_once( $key )
{
$test_case = get_option( 'run_once' );
if ( isset( $test_case[$key] ) && $test_case[$key] )
{
return false;
}
else
{
$test_case[$key] = true;
update_option('run_once',$test_case);
return true;
}
}

Related

WordPress: Content in foreach remains on page because it does not refresh on form submission | Reload array after form submission?

I have tried the javascript refresh options on submit (on the <form> but none of them work. If I put the javascript refresh with the submit function, then every time it refreshes, the item gets sent to the database (do not want that).
What I have tried
onsubmit="location.reload()"
onsubmit="window.location.reload()"
onsubmit="setTimeout(function () { window.location.reload(); }, 10)"
It currently renders an array of items with a checkbox. When I click the checkbox, the item gets sent to the database as read -- but it stays on the screen (unless I revisit the page manually in the address bar). I am developing in WordPress using PHP.
Perhaps there is a small trick we can use just to remove the array that is sent on submit out of the books_array as soon as the submit button is clicked? Or reload the books_array after submission?
Here is my code:
form function
<form action="<?php user_add_new();?>" method="post">
<?php
foreach($books_array as $index => $i ) {
$s = $i->title;
$o = $i->listID;
$r = $i->submittedBy;
$d = $i->bookDESC;
$t = $i->id;
$current_user = wp_get_current_user();
$current_id = $current_user->ID;
if ($r == $current_user->ID || $r == 'administrator') {
echo '<div class="user-wrap">';
echo '<div class="inner-wrap">';
echo '<!---entire checkbox--->';
echo '<div><span class="check">';
echo "<input type='checkbox' name='checkbox[]' value='$index' onChange='this.form.submit()'>";
echo "<input type='hidden' name='item$index' value='$t'>";
echo "<input type='hidden' name='listID$index' value='$o'>";
echo "<input type='hidden' name='userID$index' value='$current_id'>";
echo '</span></div>';
echo '<!---entire checkbox--->';
echo '<!---info from book--->';
echo "<div><b>$s</b><br>$d</div>";
echo "<!---info from book--->";
echo '</div>';
echo '</div>';
}
};
?>
</form>
foreach loop
function user_add_new() {
global $wpdb;
$value = $_POST["checkbox"][0];
$bookTOadd = $_POST["item" . $value];
$listTOadd = $_POST["listID" . $value];
$userID = $_POST["userID" . $value];
$addTABLE = $wpdb->prefix . 'plugin_read';
$wpdb->insert(
$addTABLE,
array(
'bookID' => $bookTOadd,
'userID' => $userID,
'listID' => $listTOadd,
)
);
}
I keep running into issues, but I am so grateful to anyone who can give a little insight on how to approach this best. Thank you for taking the time to read this!
Problem fixed by creating a WordPress action and calling/rendering it only when the form is clicked (since before the action was rendered on page load just not executed until the click, which was 1 thing causing my issue re the not refreshing the entire page after form submission). No ajax (though its great with wordpress) nor .php files (that would just be a workaround).
Removed the action="" from my form, since we'll be using wordpress to do this.
Added this line <?php wp_nonce_field('book_send', 'book_send_nonce', true, true);?> to my form, you can see that below (this will help call my action in my WordPress file, associating it with this form)
<form method="post">
<?php wp_nonce_field('book_send', 'book_send_nonce', true, true);?>
<?php
foreach($books_array as $index => $i ) {
$s = $i->title;
$o = $i->listID;
$r = $i->submittedBy;
$d = $i->bookDESC;
$t = $i->id;
$current_user = wp_get_current_user();
$current_id = $current_user->ID;
if ($r == $current_user->ID || $r == 'administrator') {
echo '<div class="user-wrap">';
echo '<div class="inner-wrap">';
echo '<!---entire checkbox--->';
echo '<div><span class="check">';
echo "<input type='checkbox' name='checkbox[]' value='$index' onChange='this.form.submit()'>";
echo "<input type='hidden' name='item$index' value='$t'>";
echo "<input type='hidden' name='listID$index' value='$o'>";
echo "<input type='hidden' name='userID$index' value='$current_id'>";
echo '</span></div>';
echo '<!---entire checkbox--->';
echo '<!---info from book--->';
echo "<div><b>$s</b><br>$d</div>";
echo "<!---info from book--->";
echo '</div>';
echo '</div>';
}
};
?>
</form>
And this is my action (steps are described in the notes within the code) which makes the post when the action is called upon submit. It only submits the data after form validation. Once the data has been submitted, it then reloads the page using a built in WP function:
add_action('book_check', function() {
if ( ( is_single() || is_page() ) &&
isset($_POST[book_send_nonce]) &&
wp_verify_nonce($_POST[book_send_nonce], 'book_send')
) {
// form validation
function validate_book_data(){
$errors = new WP_Error();
if (isset($_POST[ 'item' ]) && $_POST[ 'item' ] !== '') {
$errors->add('item_error', 'Book not selected');
}
if (isset($_POST[ 'listID' ]) && $_POST[ 'listID' ] == '') {
$errors->add('list_error', 'No valid list this belongs to.');
}
if (isset($_POST[ 'userID' ]) && $_POST[ 'userID' ] == '') {
$errors->add('user_error', 'Not signed in');
}
return $errors;
}
// If form validation passes, send the info
$pass_validation = validate_book_data($_POST);
if ( $pass_validation ) {
$value = $_POST["checkbox"][0];
$data = array(
'userID' => $_POST["userID" . $value],
'bookID' => $_POST["item" . $value],
'list' => $_POST["listID" . $value],
);
global $wpdb;
// Select the table to post the data to
$book_checked = $wpdb->prefix . 'plugin_read';
// Insert the data to the table
$wpdb->insert($book_checked, $data, '%s');
// Set page refresh
$refresh_page = wp_redirect($_SERVER['HTTP_REFERER']);
// After data is inserted, refresh the page
wp_safe_redirect( $refresh_page );
// and exit
exit();
}
}
});
Using this action solves the issue of the page not refreshing because the action is only called when the checkmark is clicked and within the action, I refresh the page only after the data has sent.
I hope this will help anyone else with the issue. Coding from 8am-2am lately really had my brain become mush so the solution took me a short bit.

How to modify default WordPress registration form?

I am creating one feature for adding user roles in WordPress default registration, it's working but I want to beautify it by adding a blank in user role selector, if it's showing a dropdown icon that will be awesome. I tried from my end but it's not showing.
My codes are: (enable 'anyone can register' here /wp-admin/options-general.php, to see the changes, now go to register /wp-login.php?action=register)
/*
show user profile in registeration
*/
//1. Add a new form element...
add_action('register_form', 'myplugin_register_form');
function myplugin_register_form()
{
global $wp_roles;
pll_e('Select Role');
echo '<select name="role" class="input">';
foreach ($wp_roles->roles as $key => $value) {
// Exclude default roles such as administrator etc. Add your own
if (!in_array($value['name'], ['Administrator', 'Editor'])) {
echo '<option value="' . $key . '">' . $value['name'] . '</option>';
}
}
echo '</select>';
}
//2. Add validation.
add_filter('registration_errors', 'myplugin_registration_errors', 10, 3);
function myplugin_registration_errors($errors, $sanitized_user_login, $user_email)
{
if (empty($_POST['role']) || !empty($_POST['role']) && trim($_POST['role']) == '') {
$errors->add('role_error', __('<strong>ERROR</strong>: You must include a role.', 'mydomain'));
}
return $errors;
}
//3. Finally, save our extra registration user meta.
add_action('user_register', 'myplugin_user_register');
function myplugin_user_register($user_id)
{
$user_id = wp_update_user(array('ID' => $user_id, 'role' => $_POST['role']));
}
Code is correct, change these lines from
echo '<select name="role" class="input">';
to
echo '<select name="role">';
this will give you a dropdown, without any conflict.
Now, these lines will give you a label
echo ('<label>Select Role</label>: ');
Paste this in your code, as per your need.
Learn inputs, form fields here https://www.w3schools.com/tags/tag_input.asp

Adding error with php in option list

Code below is part of cart66 WordPress plugin's php file. When I list options of my items for example,
T-shirt
Quantity: 1
Option: Red, Yellow, Blue
First option is always what I put first in the list. Therefore, when my customers don't pay an attention and add to cart without looking at the list they order red. I added "Please choose a pattern" option at the top but they still add that to cart and checkout. Is there a way of adding an option and making it give an error in case that option is selected ?
private function _buildOptionList($optNumber) {
$select = '';
$optionName = "options_$optNumber";
if(strlen($this->$optionName) > 1) {
$select = "\n<select name=\"options_$optNumber\" id=\"options_$optNumber\" class=\"cart66Options options_$optNumber\">";
$opts = split(',', $this->$optionName);
foreach($opts as $opt) {
$opt = str_replace('+$', '+ $', $opt);
$opt = trim($opt);
$optDisplay = str_replace('$', CART66_CURRENCY_SYMBOL, $opt);
$select .= "\n\t<option value=\"" . htmlentities($opt) . "\">$optDisplay</option>";
}
$select .= "\n</select>";
}
return $select;
}
You could use jQuery and Javascript to show an alert box.
<script type="text/javascript">
$(function() {
$('#options').change(function() {
if ($(this).attr('value') == "Please choose a pattern") {
alert("Please pick a color!");
}
});
});
</script>
Make sure to include a recent copy of jQuery in your page, and change the id="" value of the selectbox to options (without any PHP variable).
Also, don't forget to still check in PHP if the user submitted a valid color. Do this because if the user has Javascript disabled, he will still be able to choose the 'please choose a pattern' item.
That is a commercial plugin (albeit with a free "lite" version). I would first suggest checking out their support forums:
http://cart66.com/support/
If you don't mind editing the PHP yourself, then perhaps I can offer some suggestions.
E.g. you could have a blank option come first, then have the validation code reject adding the item to card when a blank item is selected. The code you pasted in looks like it takes a list of options as a comma-separated string. So you can have a blank option by starting the string with "," e.g. ",Red,Yellow,Blue". But that won't be very user-friendly, it would be better to have the first one named "Select Option" and have a value of "". Since the above code does not allow this, you could alter that code, e.g. like this:
private function _buildOptionList($optNumber) {
$select = '';
$optionName = "options_$optNumber";
if(strlen($this->$optionName) > 1) {
$select = "\n<select name=\"options_$optNumber\" id=\"options_$optNumber\" class=\"cart66Options options_$optNumber\">";
$opts = split(',', $this->$optionName);
foreach($opts as $opt) {
if($opt == "<blank>") {
$opt = "";
$optDisplay = "Select One";
} else {
$opt = str_replace('+$', '+ $', $opt);
$opt = trim($opt);
$optDisplay = str_replace('$', CART66_CURRENCY_SYMBOL, $opt);
}
$select .= "\n\t<option value=\"" . htmlentities($opt) . "\">$optDisplay</option>";
}
$select .= "\n</select>";
}
return $select;
}
Then you could have your options list be ",Red,Yellow,Blue".
You may also need to modify cart66's verification code to make sure it rejects blank selections. I don't know if it does just by looking at the above code snippet.
There are a few ways to do this. Most simply, using plain Javascript, add this to the <form> element: <form onsubmit="if ( this.options_1.selectedIndex() == 0 ) { alert( 'Please select a colour' ); return false; >
(options_1 will need to match the $optNumber used to generate the drop-down. The return false; will prevent the form from submitting)
You could use jQuery to make this neater and more flexible; for instance, give your options a special value like "_NOT_SELECTED_", and use something like
<script type="text/javascript">
jQuery(function($) {
$('form.cart66Form').bind('submit', function()
{
$('select.cart66Options').each( function()
{
if ( $(this).val() == '_NOT_SELECTED_' )
{
$('#incorrect_submission_message').show();
return false;
}
}
return true;
}
});
</script>
Finally, of course, validation is always better done on the server side, in this case meaning in the PHP, so you'll need to find where the "add to basket" action happens in the plugin (or where you can add some actions to it) and add something that checks if your special value ("_NOT_SELECTED_", or perhaps just "-") has been submitted.

Passing selected checkbox value array?

I have a checkbox down below...
It is in the loop :
<script>
function checkCheckBoxes_abel() { //check if the checkbox is checked before submitting.
if (document.payform.pay_checkbox.checked == false)
{
alert ('You didn\'t choose any of the checkboxes for payment !');
return false;
}
else
{
alert ('One or more checkboxes from payment form are checked!');
document.forms["payform"].submit();
return true;
}
}
</script>
<form name="payform" onsubmit="return checkCheckBoxes_abel();" method="POST" action="payment.php">
for($record_count=0;$record_count<$record;$record_count++)
{
<td><input type="checkbox" name="pay[]" id="pay_checkbox" value="<?php echo $amount_dueArr[$record_count];?>" onClick="checkTotal()"/></td>
}
</form>
How can I pass the value of the checkbox that is being selected ?
Thanks
can I do :
if (isset($_POST['pay']))
{
foreach($_POST["eg_payamt_"] as $key => $payamt){
echo "eg_payamt_$key => $payamt\n <br>";
}
}
on payment.php ?
Thanks
An illustration :
I have three checkboxes...
If I check one of the checkbox,
Checkbox ticked on : Array
and if I'm not checking any of them
Checkbox ticked on :
Which is correct, but the content of the Array is not only one but three of them,
How can I make it only one ? or only two ? depends on how many checkboxes are being checked.
can I do it on another field ?
it seems that it works only for one field
if (isset($_POST['pay']))
{
if(is_array($_POST['pay']))
{
//foreach($_POST["pay"] as $key => $desc)
foreach($_POST["eg_description_"] as $key => $desc)
{
echo "eg_description_$key => $desc\n <br>";
}
}
else
{
//echo 'description :'.$_POST['pay'];
echo 'description :'.$_POST["eg_description_"];
}
}
there are 2 types of values will receive in POST, if someone selects only one checkbox that will throw warning in foreach loop so you can try this way
if (isset($_POST['pay']))
{
if(is_array($_POST['pay'])) {
//foreach($_POST["eg_payamt_"] as $key => $payamt){
foreach($_POST["pay"] as $key => $payamt){
echo "eg_payamt_$key => $payamt\n <br>";
}
}
else {
echo 'pay : '. $_POST['pay'];
}
}
Check these -
http://www.kavoir.com/2009/01/php-checkbox-array-in-form-handling-multiple-checkbox-values-in-an-array.html
http://www.html-form-guide.com/php-form/php-form-checkbox.html

PHP Value for HTML Checkbox

I have a function that sets and unset's a $_SESSION variable depending on what was submitted from the form in my main page.
function if statement:
$_SESSION['search'] = true;
if($_POST['searchtv']){
$_SESSION['searchtv'] = true;
} else {
unset($_SESSION['searchtv']);
}
if($_POST['searchmovie']){
$_SESSION['searchmovie'] = true;
} else {
unset($_SESSION['searchmovie']);
}
The searchtv and searchmovie $_POST variables are set through the below checkboxes:
<input type="checkbox" name="searchmovie" value="movie" <? echo isset($_SESSION['searchmovie']) ? 'checked' : ''; ?>"/>
However the checked value always seems to be false and displays '' so no "checked" is set to display the tick in the box.
I do know that the $_SESSION variable is being set correctly however because in the same file i have another IF statement (below) that works 100%.
if(isset($_SESSION['searchtv'])){
$database->searchTV($_GET['show'], $session->uid);
}
if(isset($_SESSION['searchmovie'])){
$database->searchMovies($_GET['show'], $session->uid);
}
if(!isset($_SESSION['searchtv']) && !isset($_SESSION['searchmovie'])){
$database->searchTV($_GET['show'], $session->uid);
$database->searchMovies($_GET['show'], $session->uid);
}
If i only tick the searchtv checkbox it only runs the searchTV function and so on.. so i know it is being set and works.. just cannot get the feedback to the checkbox to say yes it was ticked when the search button was selected.
#medoix: Try changing this
<input type="checkbox" name="searchmovie" value="movie" <? echo isset($_SESSION['searchmovie']) ? 'checked' : ''; ?>"/>
to this
<input type="checkbox" name="searchmovie" value="movie" <?php if (isset($_SESSION['searchmovie'])) { echo 'checked="checked" '; } ?>/>
You realize that the portion of the code that checks $_SESSION['searchtv'] && $_SESSION['searchmovie'] near the bottom are both !isset. It'll only run if both aren't checked, rather than if they are.

Categories