Skip to content

Options shorthands

Javier Prieto edited this page Dec 18, 2020 · 4 revisions

Important: This documentation is still under construction, methods and/or properties may be missing or not fully documented


This is the method to allow to Form::options() method to add a shorthand to options. In this example add a shorthand named colors to fill a select with several colors options.

Using a class (Recommended)

Create a class to handle the shorthand

// Load the OptionsHandler interface
use JPToolkit\HtmlHelper\Interfaces\OptionsHandler as InterfaceOptionsHandler;

/**
 * Add the `colors` shorthand to the Form:.options method
 */
class OptionsColorsHandler implements InterfaceOptionsHandler {

  /**
   * Adds OptionsHandler methods
   */
  use \JPToolkit\HtmlHelper\Traits\OptionsHandler;

  /**
   * The options handler name
   *
   * @var  string
   */
  private $handler = 'colors';

  /**
   * Parse the shorthand
   *
   * @param   string $options The options handler.
   * @return  array
   */
  public function parse_shorthand_handler( $options ) {
    $colors = [
        '#FFFFFF' => __( 'White', 'your-textdomain' ),
        '#808080' => __( 'Gray', 'your-textdomain' ),
        '#000000' => __( 'Black', 'your-textdomain' ),
        '#FF0000' => __( 'Red', 'your-textdomain' ),
        '#FFFF00' => __( 'Yellow', 'your-textdomain' ),
        '#008000' => __( 'Green', 'your-textdomain' ),
        '#0000FF' => __( 'Blue', 'your-textdomain' ),         
    ];

    return $colors;
  }

}

In your functions.php

function add_form_options_handler() {
   new OptionsColorsHandler();
}
add_action( 'init', 'add_form_options_handler' );

Using a filter

function add_form_options_colors_handler( $handler ) {
  // Check if is our handler, otherwise do nothing
  if ( !is_string( $handler ) || $handler != 'colors' ) {
    return $handler;
  }

  // Fill the option array
  $colors = [
      '#FFFFFF' => __( 'White', 'your-textdomain' ),
      '#808080' => __( 'Gray', 'your-textdomain' ),
      '#000000' => __( 'Black', 'your-textdomain' ),
      '#FF0000' => __( 'Red', 'your-textdomain' ),
      '#FFFF00' => __( 'Yellow', 'your-textdomain' ),
      '#008000' => __( 'Green', 'your-textdomain' ),
      '#0000FF' => __( 'Blue', 'your-textdomain' ),
  ];

  // Return the options
  return $colors;
}

// Add filter
add_filter( 'jp_toolkit_html_helper_form_options', 'add_form_options_colors_handler' );

Usage

In both cases, filter or class, you can use in your template

use JPToolkit\HtmlHelper\Form;
...
echo Form::select( 'colors' );

This outputs

<select>
  <option value="#FFFFFF">White</option>
  <option value="#808080">Gray</option>
  <option value="#000000">Black</option>
  <option value="#FF0000">Red</option>
  <option value="#FFFF00">Yellow</option>
  <option value="#008000">Green</option>
  <option value="#0000FF">Blue</option>
</select>

Clone this wiki locally