• Or in other words, nested loop/recursive function:

    I have WP E-Commerce installed and I’m moving whole it’s dashboard to frontend.
    I have everything ready and am on the last part. In fact I thought this part was ready, until I added two variations, where I understood that it works a little bit different.

    Let me show you what I’m talking about.
    IMG1
    IMG2

    here every variation from second category is assigned to first
    like (1,a;1,b;1,c);(2,a;2,b;2,c);(3,a;3,b;3,c);

    Here is my code
    https://pastebin.com/nH9wk9JP

    So how to remake my for loop with some nested for loop ( I guess ) to work like combinations. At this moment it just creates separate variations without nesting them.

    $parent = $_POST['variationParent'];
    	$children = $_POST['variationChild'];
    	if(!empty($parent)) {
    		$affparent = wp_set_post_terms( $post_id, $parent, 'wpsc-variation', true );
    		$affchildren = wp_set_post_terms( $post_id, $children, 'wpsc-variation', true );
    		$N = count($children);
    		for($i=0; $i < $N; $i++) {
    			$cat_id = (int) $children[$i];
    			if(!in_array($cat_id,$varArray)){
    				$cat = get_term( $cat_id, 'wpsc-variation' );
    				$new_entr = array();
    				$new_entr['post_title'] = esc_attr(strip_tags($_POST['postTitle'])) . " (" . $cat->name . ")";
    							$new_entr['post_content'] = esc_attr(strip_tags($_POST['postContent']));
    								$new_entr['post_status'] = 'inherit';
    								$new_entr['post_category']	= $cat->term_id;
    								$new_entr['post_type'] = 'wpsc-product';
    								$new_entr['post_parent'] = $post_id;
    								$new_entr['post_author'] = $user_id;
    								$var_id = wp_insert_post($new_entr);
    								wp_set_post_terms( $var_id, $cat->term_id, 'wpsc-variation' );
    								update_post_meta($var_id, '_wpsc_price', $price);
    								update_post_meta($var_id, '_wpsc_special_price', $special_price);
    								update_post_meta($var_id, '_wpsc_sku', $sku);
    								update_post_meta($var_id, '_wpsc_stock', $stock);
    							}
    						}
    					}

    I think at first I need to remake my FORM to chain parents with their parent.

    Here I changed Childre[] to take also parents ID

    <fieldset>
        <ul class="formVariations" id="formVariationsID"><li>
            <?php
                $parentArray = array();
                foreach ($parentVariations as $variation) {
                    $parentArray[] = $variation->term_id;
                }
                foreach($variationCategories as $category) {
                    //var_dump($category);
                    //echo ;
                    // check if this variation is already checked
                    if (in_array($category->term_id, $parentArray)) {
                        if ($category->parent == 0) {
                            echo "</li><li class='formVariationParent'><input type='checkbox' checked name='variationParent[]' autocomplete='off' value='". $category->term_id ."'>" . $category->name . "";
                        } else {
                            echo "<ul><li class='formVariationChild'><input type='checkbox' checked name='variationChild[". $category->parent ."][]' autocomplete='off' value='". $category->term_id ."'>" . $category->name . "</li></ul>";
                        }
                    } else {
                        if ($category->parent == 0) {
                            echo "</li><li class='formVariationParent'><input type='checkbox' name='variationParent[]' autocomplete='off' value='". $category->term_id ."'>" . $category->name . "";
                        } else {
                            echo "<ul><li class='formVariationChild'><input type='checkbox' name='variationChild[". $category->parent ."][]' autocomplete='off' value='". $category->term_id ."'>" . $category->name . "</li></ul>";
                        }
                    }
                }
            ?>
        </ul>
    </fieldset>

    That’s the output of this form. first value in array is parent termID and second is ChildID.

    array(2) {
         [3]=> array(3) {
              [0]=> string(1) "4"
              [1]=> string(1) "5"
              [2]=> string(1) "6"
        }
         [7]=> array(3) {
              [0]=> string(1) "8"
              [1]=> string(1) "9"
              [2]=> string(2) "10"
        }
    }

    So my code should assign all values from parent[7] to parent[3]. meaning in the end of the loop, there will be 9 variations.

    Question is, how to solve this nested loop. count parents first and and nest that many loops (or foreach) ?

    (also might be interesting how wpsc deals with that, which I don’t understand at all https://pastebin.com/LTdh0EM4 )

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator bcworkz

    (@bcworkz)

    I’m not sure what you’re really trying to do, something like this?

    $first = array('1','2','3');
    $second = array('a','b','c');
    for($i=0; $i<3; $i++) {
    	for($n=0; $n<3; $n++) {
    		$combined[$i][$n] = $first[$i] . $second[$n];
    	}
    }
    print_r($combined);
    /* Result: Array
    ([0] => Array
        ( [0] => 1a
          [1] => 1b
          [2] => 1c )
     [1] => Array
        ( [0] => 2a
          [1] => 2b
          [2] => 2c )
     [2] => Array
        ( [0] => 3a
          [1] => 3b
          [2] => 3c )
    )*/

    Thread Starter b a

    (@mpa4hu)

    Hey bcworkz,
    Thank you for you support.

    I managed to rebuild the code wpsc is using for this task, but generally yes, it’s what I wanted.
    With that code everything works good, if I pass array manually, now I just need to select my inputs with jQuery and save it in data variable. here is a structure that code takes:

    array(1) {
    	["edit_var_val"]=> array(2) {
    		[3]=> array(3) {
    			[6]=> string(1) "1"
    			[5]=> string(1) "1"
    			[4]=> string(1) "1"
    		}
    		[12]=> array(3) {
    			[13]=> string(1) "1"
    			[14]=> string(1) "1"
    			[15]=> string(1) "1"
    		}
    	}
    }

    And here is the array I’m using with my code to manually check code:
    $data = array ( 'edit_var_val' => array ( 3 => array ( 6 => '1', 5 => '1', 4 => '1', ), 12 => array ( 13 => '1', 14 => '1', 15 => '1', ), ), );
    first is parent ID and second Child ID.
    I just never managed to select my checkbox input fields like this, I have everything for this, parentID and ChildrenID, working checkbox… but how to make this look like this array?

    <li class="formVariationParent">
      <input checked="" name="variationParent[]" autocomplete="off" value="3" type="checkbox">colors
        <ul>
          <li class="formVariationChild">
            <input checked="" name="variationChild[edit_var_val][3][4]" autocomplete="off" value="1" type="checkbox">red</li>
       </ul>
       <ul>
         <li class="formVariationChild">
           <input checked="" name="variationChild[edit_var_val][3][5]" autocomplete="off" value="1" type="checkbox">green
         </li>
       </ul>
       <ul>
         <li class="formVariationChild">
           <input checked="" name="variationChild[edit_var_val][3][6]" autocomplete="off" value="1" type="checkbox">blue
         </li>
       </ul>

    This is generated code and here is a php for it

    <fieldset>
    
        <a class="btn btn-new btn-primary" onclick="apfGenerateVariation(<?php echo $current_post ?>,<?php echo $get_admin_blog ?>,data);" style="cursor: pointer">
            <b><i class="icofont-star"></i></b>
        </a>
        <ul class="formVariations" id="formVariationsID"><li>
            <?php
                $parentArray = array();
                foreach ($parentVariations as $variation) {
                    $parentArray[] = $variation->term_id;
                }
                foreach($variationCategories as $category) {
                    //var_dump($category);
                    //echo ;
                    // check if this variation is already checked
                    if (in_array($category->term_id, $parentArray)) {
                        if ($category->parent == 0) {
                            echo "</li><li class='formVariationParent'><input type='checkbox' checked name='variationParent[]' autocomplete='off' value='". $category->term_id ."'>" . $category->name . "";
                        } else {
                            echo "<ul><li class='formVariationChild'><input type='checkbox' checked name='variationChild[edit_var_val][". $category->parent ."][". $category->term_id ."]' autocomplete='off' value='1'>" . $category->name . "</li></ul>";
                        }
                    } else {
                        if ($category->parent == 0) {
                            echo "</li><li class='formVariationParent'><input type='checkbox' name='variationParent[]' autocomplete='off' value='". $category->term_id ."'>" . $category->name . "";
                        } else {
                            echo "<ul><li class='formVariationChild'><input type='checkbox' name='variationChild[edit_var_val][". $category->parent ."][". $category->term_id ."]' autocomplete='off' value='1'>" . $category->name . "</li></ul>";
                        }
                    }
                }
            ?>
        </ul>
    </fieldset>

    Now I need some jQuery is the end of my code to collect this input fields and convert it this array structure. I can remake this form but not array structure.

    Moderator bcworkz

    (@bcworkz)

    I think I see your need in general, I see you are trying to generate an array matching a predefined structure to reflect checkbox states. It sounds like you want to do this with jQuery because the resulting array gets posted to some API you have no control over? That would preclude using PHP, which I know well. So jQuery it is, which I do not know well. Sigh.

    Anyway, you should contrive a two part checkbox field naming scheme which is easy to parse, for example: ‘3-4’, ‘3-5′, … ’12-15’. Then select the entire set of input fields inside the list tag. I’m assuming you end up with an array of DOM objects or something? My lack of jQuery knowledge is showing ?? Anyway, you need to end up with something like that by whatever means. I’m going to lapse into PHP terminology, hopefully you can figure out the jQuery equivalent. Step through each checkbox element and explode the name into it’s two parts. Use each part to specify the index for the corresponding parent and child levels of the array you are building and assigning whatever value is appropriate based on the checkbox state.

    For example, in one particular iteration of the loop through the DOM collection you find the name of the element is ’12-13′. Explode that into i so you have i[0]='12' and i[1]='13'. Convert the strings to integers if required (shouldn’t be). If this checkbox is checked, then assign an appropriate value to data, let’s use 1: data[i[0]][i[1]] = 1; otherwise I suppose we assign 0. No matter, assign what’s needed.

    Sorry about the schizo language references, I hope it makes sense and you can do something with it. Good luck!

    Thread Starter b a

    (@mpa4hu)

    ?? understood most and it worked somehow ))
    I’ve got preatty far now.
    I wrote a code for generating that variable and “onChangin” checkbox.
    Here are the codes

    jQuery('.formVariationChild > input').change(function() {
    	var c1 = {};
    	var c2 = {};
    	var add = {};
    	var child = {};
    	var child2 = {};
    
    	if(this.checked) {
    		if (jQuery(this).parent('li').parent('ul').parent('li').find('> input').is(":not(:checked)")) {
    			jQuery(this).parent('li').parent('ul').parent('li').find('> input').prop('checked', true);
    		}
    
    		add1 = jQuery(this).attr('name').split('-');
            var a = add1[0];
            var b = add1[1];
            data['edit_var_val'][a][b] = "1";
    
    	} else {
    		add1 = jQuery(this).attr('name').split('-');
    		var a = add1[0];
    		var b = add1[1];
    		if (jQuery(this).parent('li').parent('ul').parent('li').find('> input').is(":checked")) {
    			i = 0
    			if(jQuery(this).parent('li').parent('ul').parent('li').find('ul li input').is(":checked")) {
    				i++;
    			}
    			if (i === 0) {
    				jQuery(this).parent('li').parent('ul').parent('li').find('> input').prop('checked', false);
    				data['edit_var_val'][a] = {};
    			} else {
    				data['edit_var_val'][a][b] = "0";
    			}
    		}
    	}
    	alert(JSON.stringify(data));
    });

    Now there is problem from wordpress (php) side.
    I get those checkboxes from categories with

    //get variations
    	$args=array(
    		'orderby' => 'id',
    		'order' => 'ASC',
    		'taxonomy' => 'wpsc-variation',
    		'hierarchical' => 1,
    		'hide_empty' => 0
    	);
    	$variationCategories=get_categories($args);
    
    								foreach($variationCategories as $category) {
    																	//var_dump($category);
    																	//echo ;
    																	// check if this variation is already checked
    																	if (in_array($category->term_id, $parentArray)) {
    																		if ($category->parent == 0) {
    																			echo "</li><li class='formVariationParent'><input type='checkbox' checked name='variationParent[]' autocomplete='off' value='". $category->term_id ."'>" . $category->name . "";
    																		} else {
    																			echo "<ul><li class='formVariationChild'><input type='checkbox' checked name='". $category->parent ."-". $category->term_id ."' autocomplete='off' value='1'>" . $category->name . "</li></ul>";
    																		}
    																	} else {
    																		if ($category->parent == 0) {
    																			echo "</li><li class='formVariationParent'><input type='checkbox' name='variationParent[]' autocomplete='off' value='". $category->term_id ."'>" . $category->name . "";
    																		} else {
    																			echo "<ul><li class='formVariationChild'><input type='checkbox' name='". $category->parent ."-". $category->term_id ."' autocomplete='off' value='1'>" . $category->name . "</li></ul>";
    																		}
    																	}
    																}

    https://s019.radikal.ru/i619/1304/55/a59ba15ac3e3.png
    Everything is right, except the last categories “4” is what I added last but belongs to sizes categories. but because order is by Id it goes to last category.

    Moderator bcworkz

    (@bcworkz)

    Huh. Are you sure it’s parent category is correct? I would have thought sort by ID was within parent categories, not everything. If that checks out, try different 'orderby' parameters. ‘term_group’ perhaps? If all else fails, finagle the slugs to force a particular order then order by ‘slug’.

    About the rest of the code, some great progress there! I’m surprised you did so well off of my bizarre explanation. Good work!

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Moving WP-Ecommerce dashboard to front end’ is closed to new replies.