Jump to content

There MUST be a way to erase a previously saved checkbox array!


ThunderVike

Recommended Posts

Here's my second go at this since the pros in here seem to have given up on the standard methods.

 

On a WordPress site running PHP 5.0.3 (or something like that) I have multiple checkboxes that return an array of values depending on which ones are checked.

 

In the source code the checkboxes load up this way--- I will include the OUTPUT source code seen in the browser for two different multiple checkboxes  -- one named "cp_checkbox_help" and the next named "cp_checkbox_charley"

 

 

		<div id="checkboxes"><table width="100%" border="0" cellspacing="0" cellpadding="5">
  <tr>
    <th colspan="2" scope="col">help checkbox</th>
  </tr> 
              
              <tr>
    <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_help[]" class="checkbox" id="" value="Sunday" checked="yes"/></td>
    <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" >Sunday</td>
  </tr>    

              
              <tr>
    <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_help[]" class="checkbox" id="" value=" Monday" checked="yes"/></td>
    <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" > Monday</td>
  </tr>    

              
              <tr>
    <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_help[]" class="checkbox" id="" value=" Tuesday" checked="yes"/></td>
    <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" > Tuesday</td>
  </tr>    

              
              <tr>
    <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_help[]" class="checkbox" id="" value=" Wednesday" /></td>
    <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" > Wednesday</td>
  </tr>    

              
              <tr>
    <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_help[]" class="checkbox" id="" value=" Thursday" /></td>
    <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" > Thursday</td>
  </tr>    

              
              <tr>
    <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_help[]" class="checkbox" id="" value=" Friday" /></td>
    <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" > Friday</td>
  </tr>    

              
              <tr>
    <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_help[]" class="checkbox" id="" value=" Saturday" /></td>
    <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" > Saturday</td>
  </tr>    
  </tr>
</table></div><div class="clr"></div>	
	<div id="checkboxes"><table width="100%" border="0" cellspacing="0" cellpadding="5">
  <tr>
    <th colspan="2" scope="col">Staff Provided</th>
  </tr> 
              
              <tr>
    <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_charley[]" class="checkbox" id="" value="Cook" checked="yes"/></td>
    <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" >Cook</td>
  </tr>    

              
              <tr>
    <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_charley[]" class="checkbox" id="" value=" Housekeeper / Maid" checked="yes"/></td>
    <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" > Housekeeper / Maid</td>
  </tr>    

              
              <tr>
    <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_charley[]" class="checkbox" id="" value=" Gardener" checked="yes"/></td>
    <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" > Gardener</td>
  </tr>    

              
              <tr>
    <td width="4%"><input style="display:inline-block; float:left;" type="checkbox" name="cp_checkbox_charley[]" class="checkbox" id="" value=" Watchman" checked="yes"/></td>
    <td width="96%"style="vertical-align:top; text-indent: 7px; text-align: left;" > Watchman</td>
  </tr>    
  </tr>
</table></div><div class="clr"></div>

 

This code is on an EDIT page that allows a user identified by their post_id to just edit the Classified Ad they "own" and created.

 

They are not given access to the WordPress Dashboard--just to this Edit function page.

 

Here they can click on a list of their own ads and change things.

 

As long as they select or unselect individual checkboxes within "cp_checkbox_help" or "cp_checkbox_charley" or "cp_checkbox_hello" and Submit the form the page returns with the new checked values showing correctly.

 

HOWEVER, if they UNSELECT ALL associated checkboxes in one or both or all three of these multiple checkboxes when the ad is updated the former values return for checkboxes.  The previous saved array does not get overwritten.

 

I need help in modifying this code so that it detects the change if all checkboxes within a specific name are UNSELECTED and THEN overwrites that darned array!

 

As my code shows-- JUST for the multiple checkbox arrays I IMPLODE and put a comma between each value and it is saved that way.

 

Each array will have a different number of values inside and so I cannot just stick an UNSET in front of it.

 

Finally, I need to confine the overwriting of the $meta_value array to JUST the $meta_key identified as 'cp_checkbox_charley'...otherwise in some tests of different way to write this I get the $meta_value wiped out for everything.

 

And I must find a way to EXCLUDE these checkbox arrays so that the OTHER custom fields that start with "cp_" have their $meta_value's retained and updated either before or after running through the checkboxes.

 

    // 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']);
else if (cp_str_starts_with($meta_key, 'cp_checkbox_charley') && is_null($_POST['cp_checkbox_help']))$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);
        }

        $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;

}

 

I know SOME PHP GENIUS has got a great solution!  :confused: :confused:

 

Link to comment
Share on other sites

OK, I'm a bit of a newbie at PHP and I didn't read everything you wrote too well, but perhaps you can do something like this.

 

for ($i = 0; $i < count($yourArray); $i++) {
	$yourArray[$i] = null;
}

 

That's a suggestion to solve a part of your problem. Hope it helps one way or another - otherwise you will have to wait a little longer for one of those geniuses to come around. :)

Link to comment
Share on other sites

Well, I'll take a swing at it. I read through your other post the other day, and I figured yall were on the way to solving it.  First, I have a question.  This code is a little confusing. In the second IF statement, you refer to checkbox_charley AND checkbox_help - is that correct, or should they both be CHARLEY?

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 if (cp_str_starts_with($meta_key, 'cp_checkbox_charley') && is_null($_POST['cp_checkbox_help']))$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);
}

 

At any rate, I would think you need to assign an empty string to $meta_value if no checkboxes are checked. When no checkboxes (in that array) are checked, the array will NOT be set. So I would think that this would work: ...

 

No, that's not going to work.  If the checkbox array does not exist (because nothing is checked) then the "foreach ($_POST ..." is NOT going to come across the checkbox array and it will never clear it.  I guess the easiest thing to do would be add a couple of lines before the foreach:

if($post_id) {

    // Make sure the checkbox arrays exist 
    if (! isset($_POST['cp_checkbox_charley'])) $_POST['cp_checkbox_charley'] = array();
    if (! isset($_POST['cp_checkbox_help'])) $_POST['cp_checkbox_help'] = array();
    if (! isset($_POST['cp_checkbox_hello'])) $_POST['cp_checkbox_hello'] = array();

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

        update_post_meta($post_id, $meta_key, $meta_value);
}

 

Of course, I have not worked with WordPress so I have no idea what is going on behind the scenes.  Also, I am at work and have no way to test this code.  You may not even need the IF (ISSET inside the loop.  I think implode() will return an empty string if run on an empty array. I think you can add to the $_POST arrray like that, I don't see any reason why you couldn't.  But that is the problem, you are not finding the empty array inside the foreach.

Link to comment
Share on other sites

Andy17 and DavidAM, thanks so much for volunteering some help. I will have to wait hours now to test this, unfortunately.

 

DavidAM, you are correct....cp_checkbox_charley and cp_checkbox_help don't match but you made me realize that I posted an OLD snatch of the code that I copied to a separate log document of my steps to find a solution.

 

I did subsequently correct the mismatches and still had problems.

 

I will try these suggestions and see if I can nail this problem to the wall finally.

Link to comment
Share on other sites

DavidAM, you had a more complete solution so I took it and rewrote it just slightly so that it also updated the Other custom fields that started with "cp_" but that had a single string value not in a comma delimited array.  It looks like this now and it WORKS!

 

Halleleujah!  I will post it now and THEN since you were so expert, I will show you the code that retrieves the masterwork that you created and see if you can make an alteration to that to complete my last project!

 

Here's your code with my slight alteration:

 

if($post_id) {

    // Make sure the checkbox arrays exist 
    if (! isset($_POST['cp_checkbox_charley'])) $_POST['cp_checkbox_charley'] = array();
    if (! isset($_POST['cp_checkbox_help'])) $_POST['cp_checkbox_help'] = array();
    if (! isset($_POST['cp_checkbox_hello'])) $_POST['cp_checkbox_hello'] = array();

    // 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')) {
            if (isset($_POST['cp_checkbox_charley']))
                $meta_value= implode(',', $_POST['cp_checkbox_charley']);
            else
                $meta_value = '';
        }
        if (cp_str_starts_with($meta_key, 'cp_checkbox_help')) {
            if (isset($_POST['cp_checkbox_help']))
                $meta_value = implode(',', $_POST['cp_checkbox_help']);
            else
                $meta_value = '';
        }
        if (cp_str_starts_with($meta_key, 'cp_checkbox_hello'))
            if (isset($_POST['cp_checkbox_hello']))
                $meta_value= implode(',', $_POST['cp_checkbox_hello']);
            else
                $meta_value = '';
        }

        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;

}

 

IT WORKS!!!  I CAN UNSELECT ANYTHING AND EVERYTHING AND DARNED IF IT DOESN'T UPDATE BEAUTIFULLY!!

 

Here then is the last thing that I notice now.  The OUTPUT of this in the Post or Ad is for checkbox values to show up in a list.

 

So I wrote a query that just looks for the checkbox values for "help" and "hello" and "charley" (for sake of brevity) and then explodes them and spits them back out for an unordered list.  But now it still produces one empty list dot..for each empty series of checkboxes and the label for for that list.  I should now modify the following code so that if the array is empty from being unselected and updated from your code, David, that these lists do not get generated AT ALL.

 

David, Genius, Can you tell me how to make this code simply not generate a single line of anything IF any of the arrays coming back are empty now?  It must be at the start where I have the if($results).  It seems to me that even an empty array qualifies as "$results"

 

// give us the complete CHECKBOX FIELDS in a list
function dh_list_checkbox_list($postid) {
    global $wpdb;
                                         // give us the complete checkbox fields in a list
        $sql = $wpdb->prepare("SELECT `wp_cp_ad_fields` . `field_label` , `wp_cp_ad_fields` . `field_name` ,`wp_postmeta` . `post_id` , `wp_postmeta` . `meta_key` , `wp_postmeta` . `meta_value`  FROM wp_cp_ad_fields , wp_postmeta  WHERE  `wp_cp_ad_fields` . `field_name` = `wp_postmeta` . `meta_key` AND `wp_postmeta` . `meta_key` LIKE '%%checkbox%%' AND `wp_postmeta` . `post_id` = ($postid) ORDER by `field_label` ASC ");

        // now we should have the postid so show the form layout based on the category selected
  $results = $wpdb->get_results($sql);
    if($results) 
{
 foreach ($results as $result) :
            // now grab all ad fields and print out the field label and value
         
echo '<h4>' . $result->field_label .'</h4>
<br>
<ul>' ; 	
	$options = explode(',', $result->meta_value);

                foreach ($options as $option) {
                ?> 
<li><?php echo $option; ?></li> <?php
    } echo '</ul>
<br>
<div class="clr"></div>';   
endforeach;

 }
 }

 

 

If the c

 

Link to comment
Share on other sites

I should be more clear---since I am looking for the output of three different stored arrays for the 3 multiple checkboxes I will get some like

 

 

How Funky

  • Funky
  • Even more funky
  • the most funky

 

Cool Things

  • Ice cream
  • Snowcones
  • Frozen Mars bars
  • Me

 

 

However now I get this for each unchecked checkbox

 

Title of checkbox


 

Where an array is empty now I want to simply skip over that checkbox and its title completely (the empty one list item does not even get generated.

Link to comment
Share on other sites

Try using an if(! empty() at the begining of each loop:

if($results) 
{
  foreach ($results as $result) :
    // now grab all ad fields and print out the field label and value
    if (! empty($result->meta_value)) {
      echo '<h4>' . $result->field_label .'</h4>
<br>
<ul>' ; 

      $options = explode(',', $result->meta_value);
      foreach ($options as $option) {
?> 
<li><?php echo $option; ?></li> <?php
      } 
      echo '</ul>
<br>
<div class="clr"></div>';   
    }
  endforeach;
}

 

Although you may have to check the field_label to make sure you are only skipping the checkboxes. That is, if there are other fields that will appear in the foreach($results ...

 

 

Link to comment
Share on other sites

Thank you DavidAM!

 

I reworked the code suggestion you gave because it was giving errors that did not allow the page to load.  So, through my usual trial and error mode of modifications I thought about what your code suggestion was trying to do and re-applied it to both the field label and the LIST options and voila!  Page loaded and I got what I was looking for.

 

If the User-Editor completely unselects a range of checkboxes and updates their ad/post then the resulting Public View in the website only shows the results of multiple checkboxes where there has been at least one selection.  So, with your help, I have exactly what I have been aiming for!

 

The list of values or no values (empty list line) does not get output at all and its label or Title does not get output either.  JUST the Lists with titles that have at least one Option checkbox selected by the User-editor.

 

Here's what I did with your original idea...that now works perfectly:

Thank you, DavidAM!  YOU the MAN!

 

// give us the complete CHECKBOX FIELDS in a list
function dh_list_checkbox_list($postid) {
    global $wpdb;
                                         // give us the complete checkbox fields in a list
        $sql = $wpdb->prepare("SELECT `wp_cp_ad_fields` . `field_label` , `wp_cp_ad_fields` . `field_name` ,`wp_postmeta` . `post_id` , `wp_postmeta` . `meta_key` , `wp_postmeta` . `meta_value`  FROM wp_cp_ad_fields , wp_postmeta  WHERE  `wp_cp_ad_fields` . `field_name` = `wp_postmeta` . `meta_key` AND `wp_postmeta` . `meta_key` LIKE '%%checkbox%%' AND `wp_postmeta` . `post_id` = ($postid) ORDER by `field_label` ASC "); 

  $results = $wpdb->get_results($sql);

    if($results) 
{

foreach ($results as $result) :
            // now grab all ad fields and print out the field label and value

if(!empty($result->meta_value))	
{         
echo '<div id="checkboxlist"><h4>' . $result->field_label .'</h4>
<ul>' ; }	
if(!empty($result->meta_value))	{	$options = explode(',', $result->meta_value);

                foreach ($options as $option) 
			{
                ?> 
<li><?php echo $option; ?></li> <?php
    } 
echo '</ul>
<br></div>
<div class="clr"></div>'; 
}
endforeach; }


 }

 

Link to comment
Share on other sites

Glad to help.  You might want to mark the topic as solved. There's a green button at the bottom of the page (a couple of lines below the REPLY line). That way, someone searching for checkbox arrays will know there is a solution to the problem.

 

Good luck with the site. 

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.