Jump to content

How to make unselected checkbox destroy previous array on update


ThunderVike

Recommended Posts

I am using a WordPress theme that uses some of its own functions besides WP functions.

 

Let me make clear from the start that when I say "Multiple Checkboxes" in the paragraphs below I am NOT talking about checkboxes that each hold a single value.  I am talking about one Checkbox field that allows multiple values to be selected and puts those values into an array with one Name value and stores the output in a string in a single mysql table field.

 

Right up front, what I need during the Edit Ad functions is the inbuilt function that will Delete the previous Array of values in any multiple checkbox when the ad is updated. Right now updating the ad works for every situation except NO values selected or for Unchecking all previously selected values in a Multiple Checkbox.  If I have, for example, 4 checkboxes selected and unselect all of them before submitting the edited ad it will return the last saved array of values but not an Empty array with no checkboxes selected.

 

This theme has a Form Builder with a Custom fields builder used by the admin to create forms for a classified ads website. According to which category of ad the Ad creation procedure will show different forms, with different fields.

 

I had to manually create the capability to generate multiple checkboxes...so that the different multiple checkboxes when selected and updated to the mysql table might hold a variety of values in a comma-delimited array. That works fine.

 

When the Ad is edited on its own page, (outside of the Wordpress admin dashboard) the problem is that if a user would uncheck all checkboxes in a particular multiple checkbox then the unselected state does not overwrite the previous array of values. What returns after editing is the previous selected values.

 

I have tried jquery functions but none of them are working the way I had hoped.

 

so one type of checkbox might have a hypothetical value like this  "name="cp_checkbox_help[]" and if three options are selected then on submit the value could be--- name="cp_checkbox_help[sunday,Monday,Tuesday]"

 

I use implode and explode to store the array as comma separated and retrieve the array for editing or display.

 

I guess I need to create a Null or empty value as a default that only changes when selections are made.

 

But, since I use implode and explode to make the array "pretty" I don't know if simply specifying nothing will erase a whole array on update.

 

Here is some of the code used to see how I get what I get--

 

This displays the checkboxes that I create and name and fill with different values--

 

	case 'checkbox':
	 ?>	
	<?php 		
$options = explode(',', $result->field_values);		
echo '<div id="checkboxes"><table width="100%" border="0" cellspacing="0" cellpadding="5">
  <tr>
    <th colspan="2" scope="col">' . $result->field_label. '</th>
  </tr>';	
	$myvals= explode(',', $post_meta_val);
	foreach ($options as $option) {
{	
		 ?> 
              
              <tr>
    <td width="4%"><input style="display:inline-block; float:left;" type="<?php echo $result->field_type; ?>" name="<?php echo $result->field_name; ?>[]" class="checkbox<?php if($result->field_req) echo ' required'?>" id="<?php echo $field_label; ?>" value="<?php echo $option; ?>" <?php foreach ($myvals as $myval)
{ if (in_array($myval, array($option), true)) {echo 'checked="yes"';}}?>/></td>
    <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" ><?php echo $option . '</td>
  </tr> ' ?>   



<?php
             }     } echo '  </tr>
</table></div><div class="clr"></div>';
		 break; 

 

 

Following is the main part of the code that updates the Ad form--

 

 

 

  // update the ad and return the ad id
    $post_id = wp_update_post($update_ad);



    if($post_id) {

        // now update all the custom fields
        foreach($_POST as $meta_key => $meta_value) {
            if (cp_str_starts_with($meta_key, 'cp_'))
		if (cp_str_starts_with($meta_key, 'cp_checkbox_charley'))
$meta_value= implode(',', $_POST['cp_checkbox_charley']);
if (cp_str_starts_with($meta_key, 'cp_checkbox_help'))
$meta_value = implode(',', $_POST['cp_checkbox_help']);
if (cp_str_starts_with($meta_key, 'cp_checkbox_hello'))
$meta_value= implode(',', $_POST['cp_checkbox_hello']);
                //echo $meta_key . ' <--metakey <br/>' . $meta_value . ' <--metavalue<br/><br/>'; // for debugging
                update_post_meta($post_id, $meta_key, $meta_value);
        }

        $errmsg = '<div class="box-yellow"><b>' . __('Your ad has been successfully updated.','cp') . '</b> <a href="' . CP_DASHBOARD_URL . '">' . __('Return to my dashboard','cp') . '</a></div>';

    } else {
        // the ad wasn't updated so throw an error
        $errmsg = '<div class="box-red"><b>' . __('There was an error trying to update your ad.','cp') . '</b></div>';

    }

    return $errmsg;

}

 

Back on the Edit Ad page this is the Submit

 

 

                        <p class="submit center">
                            <input type="button" class="btn_orange" onclick="window.location.href='<?php echo CP_DASHBOARD_URL ?>'" value="<?php _e('Cancel', 'cp')?>" />  
                            <input type="submit" class="btn_orange" value="<?php _e('Update Ad »','cp') ?>" name="submit" />

 

I have a feeling what I need is just a couple of lines to detect no posted values and then... but if one checkbox array has 6 values in it and another checkbox array has only 3 values, for example, do I need to count each specific checkbox for number of values and then overwrite or will one function completely delete the previous array and its commas?

 

I would really appreciate some expert assistance here!

 

Link to comment
Share on other sites

If a checkbox is checked, its name is sent with a value of 'on.' If it isn't checked, it isn't sent at all. You should be able to check for the existence of your checkbox array in the post to determine if all boxes were unchecked. If the checkbox array isn't set, the user is trying to remove all checks.

Link to comment
Share on other sites

Thank you for taking the time to respond, lemmin.

 

But perhaps you have not really understood my request for help. I stated as carefully and accurately as I could in my question by describing what I had now, what I wanted to do, and what was NOT happening.

 

I may have, say 3 or 4 multiple checkboxes.  The "name" value carries the array. I wish there was a more explicit term to instantly convey that each multiple checkbox FORM, so to speak, arrays every select or option value into ONE String in one array to be saved into one field in a table.

 

This is an edit function that already works fine for one-select options such as a dropdown list.  The dropdown list on this page reflects what option or value was selected by the user when they first submitted the ad.

 

The multiple checkboxes I created also show what the user previously selected. They are checked for whatever values the user checked when creating the ad.  So one Multiple checkbox might have the days of the week as choices.  They might select Monday, Tuesday, Thursday and the name value might be "day_preferences['Monday,Tuesday,Thursday'] (simplified for explanation sake)

another Multiple checkbox "form" inside of the master form might hold other choices retrieved from a comma-delimited array in one database field.

 

Right now everything works fine to a point.  The user can RE-SELECT options in the checkboxes and when they hit Submit the form returns showing the new checkbox choices checked.

 

But, HERE IS THE PROBLEM I NEED SOLVED: If the user UNchecks ALL the boxes in "day_preferences[]  or any other Multiple checkbox "form" displayed on this page the UPDATE DOES NOT REPLACE THE PREVIOUS STORED ARRAY OF CHECKBOX VALUES assigned to each checkbox "form". 

 

The user will always get back whatever the last stored array was before they UNchecked ALL the boxes.

 

I need for either a default value of NULL to always exist that gets overwritten by the array of checked values anytime the user re-edits the Ad, or a function to RESET the ARRAY for just the affected Multiple checkbox "form" if ALL CHECKBOXES are UNselected.

 

For some reason I cannot get UNSET($mycheckboxOutput) (hopefully you understand this is a hypothetical for this PHP Freaks post) to work. 

 

So, I don't know how more explicit I can be.

 

I need the update action during editing to Overwrite however many values are already stored in a comma-delimited associative array for that $meta_value associated with that $meta_key WHEN all checkboxes are unchecked.  Otherwise I get the Ad unchanged in just this one area...it always shows the last stored checkbox values even if only one checkbox was selected before.

 

I need for the edit action to return Unchecked boxes if ALL are unselected before Submit.

Link to comment
Share on other sites

But, HERE IS THE PROBLEM I NEED SOLVED: If the user UNchecks ALL the boxes in "day_preferences[]  or any other Multiple checkbox "form" displayed on this page the UPDATE DOES NOT REPLACE THE PREVIOUS STORED ARRAY OF CHECKBOX VALUES assigned to each checkbox "form". 

 

The user will always get back whatever the last stored array was before they UNchecked ALL the boxes.

 

Yes. I was trying to explain why that is happening. Without seeing your code, I can only assume you iterate through the list of values sent from the form as an array (to then run your UPDATE query). If no values are checked (all values are unchecked), then the array won't even be sent; hence, not going through the code that would remove them. My suggestion was to create an if statement to check for this situation and remove everything related in that case. Since you say you have more than one set of checkboxes that could potentially be empty, you would want to check for each name individually and remove the information respectively.

 

If that still doesn't answer your question, maybe posting some code would help me understand your problem better.

Link to comment
Share on other sites

Here is  the chunk of code that takes all the custom fields and assembles them in the edit form for updating if needed.

 

I have to throw in some extra stuff to get it to differentiate the custom fields that contain the string array for checkboxes....I am constantly re-writing and testing with different ways of getting this done...this is where I am in the past few minutes and it does not UPdate the "empty array" if all checkboxes in the different named multiple checkbox forms are unselected.

 

 

  // update the ad and return the ad id
    $post_id = wp_update_post($update_ad);



    if($post_id) {

        // now update all the custom fields
        foreach($_POST as $meta_key => $meta_value) {
            if (cp_str_starts_with($meta_key, 'cp_'))
if (cp_str_starts_with($meta_key, 'cp_checkbox_charley') && is_array($_POST['cp_checkbox_help']))

$meta_value= implode(',', $_POST['cp_checkbox_charley']);
elseif 
($_POST['cp_checkbox_help']==NULL)

$meta_value=$meta_value();


if (cp_str_starts_with($meta_key, 'cp_checkbox_help'))
$meta_value = implode(',', $_POST['cp_checkbox_help']);
if (cp_str_starts_with($meta_key, 'cp_checkbox_hello'))
$meta_value= implode(',', $_POST['cp_checkbox_hello']);
                //echo $meta_key . ' <--metakey <br/>' . $meta_value . ' <--metavalue<br/><br/>'; // for debugging
                update_post_meta($post_id, $meta_key, $meta_value);
        }

 

Link to comment
Share on other sites

I thought I would write if else statements where it was first asked if the checkbox was an array and then update with the implode for comma limiting.  Else ... there is only one thing left, that the array is null, no checkboxes now selected, so make the checkbox array update itself as empty or whatever is put into that value array as a default status until some more checkboxes are selected.

 

If I look at the $meta_value field storing the $meta_key ('cp_checkbox_charley) or ('cp_checkbox_hello') etc--- in phpMyAdmin I don't even know what I am supposed to see as a value in this field if NO checkboxes are selected in the update process.

 

I don't know if it would say "null" or have nothing, or what.

 

If I could get one function to work on just one checkbox then I would add it to the other checkboxes....

Link to comment
Share on other sites

You could use a function like:

function check_box($box) {
if(isset($box) && is_array($box)) {
  return implode(', ',$box);
}
return NULL;
}

if (cp_str_starts_with($meta_key, 'cp_checkbox_charley')
$meta_value= check_box($_POST['cp_checkbox_charley']);

Link to comment
Share on other sites

jcbones, thanks for taking a stab at it but it is not that simple.

 

I tried a slight variant of your suggestion but after the update I keep getting that array unchanged, the previous checkbox array is not getting re-written into something with no string of values .

 

I need the " if (cp_str_starts_with($meta_key, 'cp_'))  " because all of the custom fields start with that and they have to be updated, too, but the meta_keys that start with some variation of "cp_checkbox" are also but custom fields but THEY are the only ones that contain associative arrays formed by the implode function.

 

So I tried an if statement in front of it and still no change, no update of the unchecked checkboxes in checkbox charley :

 

 

    $post_id = wp_update_post($update_ad);
   if($post_id) {

        // now update all the custom fields
        foreach($_POST as $meta_key => $meta_value) {
            if (cp_str_starts_with($meta_key, 'cp_'))
if (cp_str_starts_with($meta_key, 'cp_checkbox_charley') && is_array($_POST['cp_checkbox_help']))
$meta_value= implode(',', $_POST['cp_checkbox_charley']);
else {
return NULL;
}


if (cp_str_starts_with($meta_key, 'cp_checkbox_help'))
$meta_value = implode(',', $_POST['cp_checkbox_help']);
if (cp_str_starts_with($meta_key, 'cp_checkbox_hello'))
$meta_value= implode(',', $_POST['cp_checkbox_hello']);
                //echo $meta_key . ' <--metakey <br/>' . $meta_value . ' <--metavalue<br/><br/>'; // for debugging
                update_post_meta($post_id, $meta_key, $meta_value);

 

Link to comment
Share on other sites

As a further clue to a PHP diagnostician...the following function DOES EMPTY the checkbox array  ALONG WITH all of the other custom fields whose meta_key starts with "cp_"

 

So in wiping out the checkbox arrays it also wipes out the single value fields for other types of custom fields....here is the improperly written function which is doing that..

 

 

update the ad and return the ad id
    $post_id = wp_update_post($update_ad);
    if($post_id) {
        // now update all the custom fields
        foreach($_POST as $meta_key => $meta_value) {
            if (cp_str_starts_with($meta_key, 'cp_'))
if (cp_str_starts_with($meta_key, 'cp_checkbox_charley') && is_array($_POST['cp_checkbox_help']))
$meta_value= implode(',', $_POST['cp_checkbox_charley']);
// here I try to keep it from moving on to affect other custom field meta_values but it does not work--it overwrites them too with NULL
else {$meta_value= NULL ; }
if (cp_str_starts_with($meta_key, 'cp_checkbox_help'))
$meta_value = implode(',', $_POST['cp_checkbox_help']);
if (cp_str_starts_with($meta_key, 'cp_checkbox_hello'))
$meta_value= implode(',', $_POST['cp_checkbox_hello']);
                //echo $meta_key . ' <--metakey <br/>' . $meta_value . ' <--metavalue<br/><br/>'; // for debugging
                update_post_meta($post_id, $meta_key, $meta_value);
        }

 

 

 

Link to comment
Share on other sites

I just tried this and it does not change the checkbox array, that is, it does not save an empty array, it returns the last saved array where the array contained at least one value.

 

if (cp_str_starts_with($meta_key, 'cp_checkbox_charley') && is_array($_POST['cp_checkbox_help']))
$meta_value= implode(',', $_POST['cp_checkbox_charley']);
else if (cp_str_starts_with($meta_key, 'cp_checkbox_charley') && is_null($_POST['cp_checkbox_help']))$meta_value= NULL ; 

 

the same failure if I put brackets in the last line

 

if (cp_str_starts_with($meta_key, 'cp_checkbox_charley') && is_array($_POST['cp_checkbox_help']))
$meta_value= implode(',', $_POST['cp_checkbox_charley']);
else if (cp_str_starts_with($meta_key, 'cp_checkbox_charley') && is_null($_POST['cp_checkbox_help'])) {$meta_value= NULL ; }

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.