[],
'multiple' => false,
'select2options' => [],
];
}
/**
* Render select2 control output in the editor.
*
* Used to generate the control HTML in the editor using Underscore JS
* template. The variables for the class are available using `data` JS
* object.
*
* @since 1.0.0
* @access public
*/
public function content_template() {
$control_uid = $this->get_control_uid();
?>
<# if ( data.label ) {#>
{{{ data.label }}}
<# } #>
<# var multiple = ( data.multiple ) ? 'multiple' : ''; #>
<# _.each( data.options, function( option_title, option_value ) {
var value = data.controlValue;
if ( typeof value == 'string' ) {
var selected = ( option_value === value ) ? 'selected' : '';
} else if ( null !== value ) {
var value = _.values( value );
var selected = ( -1 !== value.indexOf( option_value ) ) ? 'selected' : '';
}
#>
{{{ option_title }}}
<# } ); #>
<# if ( data.description ) { #>
{{{ data.description }}}
<# } #>
validate_value( $value, $config );
}
/**
* Validate the value is listed in the control options config.
*
* Avoid change settings like `html_tag` & `title_size` to a `script` tag.
*
* @param string|array $value
* @param array $config
*
* @return string|array
*/
private function validate_value( $value, array $config ) {
// Handle multiple select.
if ( ! empty( $config['multiple'] ) ) {
$validated_value = [];
foreach ( $value as $index => $item ) {
if ( isset( $config['options'][ $item ] ) ) {
$validated_value[ $index ] = $item;
}
}
$value = $validated_value;
$is_valid = true;
} else {
$is_valid = isset( $config['options'][ $value ] );
}
// If it's not one of the control options. reset it to default.
if ( ! $is_valid ) {
$value = $config['default'];
}
return $value;
}
}