Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP ( Wordpress) - Select multiple - show "selected" state not working

I can´t seem to get the multiple select to display the selected = "selected" attribute when saving or refreshing .

Everything works (db insert is OK, results output OK), but i can not get the selected values to show after refreshing .

I am trying to use the selected() function from the wp core ..

The code (it is inside a widget class and serves for a fairly simple widget ) :

<!-- List Custom Fields Hide Underscore (hide=no) -->
 <p>
  <?php $keys_no = $this->k99_cfsw_get_all_cf_array('no');?>
   <?php if ( $keys_no ) { ?>

  <label for="<?php echo $this->get_field_id('cfl2'); ?>"><?php _e('Select your custom field','k99_gelosa_domain'); ?></label> 

    <select multiple="multiple" class="chzn-select" style="width:150px;height:29px;" size="5" id="<?php echo $this->get_field_id('cfl2'); ?>" name="<?php echo $this->get_field_name('cfl2'); ?>[]" value="<?php $instance['cfl2'] ?>">
    <option  value="<?php isset($instance['cfl2']) ? _e($instance['cfl2']) : _e('#NONE#'); ?>"><?php isset($instance['cfl2']) ? _e('multiple') /*_e($instance['cfl2'])*/ : _e('#NONE#'); ?></option>

    <!--<option value="#NONE#"><?php //echo $cfl; ?></option>-->

    <!--<option value="------">-------</option>-->
    <?php
        foreach ( $keys_no as $key ) {
            echo "\n<option value='" .esc_attr($key) . "'". selected( $instance['cfl2'],esc_attr($key) ,FALSE).">". esc_html($key) . "</option>";
        }
    ?>
    </select>
    <?php

} ?>
</p>

as a side note and a bonus question - , I am using also the chosen JS - it is also working ok, (except that it does not show the selected items ..) but have also a small bug that it will not initiate when the widget is closed - only after saving in an open state ...

like image 408
Obmerk Kronen Avatar asked Jan 15 '23 12:01

Obmerk Kronen


1 Answers

never-mind, found it , the answer is :

 selected(true, in_array($key, $instance['cfl2']), false)
like image 158
Obmerk Kronen Avatar answered Jan 17 '23 09:01

Obmerk Kronen