We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 22427
    • 793 Posts
    In a form there are two select fields (single value list boxes) sel1 and sel2, both may be left empty.
    On submit the values are sent in GET mode.

    A migxLoopCollection is used to display the matching records, depending on the submitted values:
    field1 has value sel1, field2 has value sel2.

    I use this where clause:
    &where=`[{
    			"field1":"[[!GETsel1]]",
    			"field2":"[[!GETsel2]]"
    		}]` 
    calling the following snippets:

    GETsel1:
    if ( isset($_GET['sel1']) ) {
        return $_GET['sel1'];
    } else {
        return "";
    };
    
    and similar GETsel2.

    The problem: If any one of the fields is empty, no record is found matching.

    What I want instead: If one of the fields is empty, it should be ignored - that is just the other condition should constrain the records to be shown. If both fields are empty, all of the records should be shown.
    E.g., if [[!GETsel2]] is empty, the where clause should give the same result as just &where=`[{ "field1":"[[!GETsel1]]" }]`

    What would be the syntax to use for the where clause to achieve this?

    This question has been answered by Bruno17. See the first response.

    • discuss.answer
      • 4172
      • 5,888 Posts
      untested snippet-code 'prepareWhere':

      $sel1 = $modx->getOption('sel1',$_GET,'');
      $sel2 = $modx->getOption('sel2',$_GET,'');
      
      $where = array();
      $output = '';
      
      if (!empty($sel1)){
          $where['field1'] = $sel1;
      }
      if (!empty($sel2)){
          $where['field2'] = $sel2;
      }
      
      if (count($where)>0){
          $output = '&where=`' . $modx->toJson($where) . '`';
      }
      
      return $output;


      and replace

      &where=`[{
                  "field1":"[[!GETsel1]]",
                  "field2":"[[!GETsel2]]"
              }]`



      with:

      [[!prepareWhere]]

        -------------------------------

        you can buy me a beer, if you like MIGX

        http://webcmsolutions.de/migx.html

        Thanks!
        • 22427
        • 793 Posts
        Works like a charm - thank you, Bruno!
        I should use $modx->toJson() more often...