Skip to content

Instantly share code, notes, and snippets.

@webdesign2be
Created July 31, 2014 17:57
Show Gist options
  • Select an option

  • Save webdesign2be/270cada08d9e51e8b4d3 to your computer and use it in GitHub Desktop.

Select an option

Save webdesign2be/270cada08d9e51e8b4d3 to your computer and use it in GitHub Desktop.

Revisions

  1. webdesign2be created this gist Jul 31, 2014.
    78 changes: 78 additions & 0 deletions CheckboxSelectViewHelper.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,78 @@
    <?php
    namespace Sms\SmsBlog\ViewHelpers;

    /**
    * The form checkbox select view helper
    *
    * @scope prototype
    */
    class CheckboxSelectViewHelper extends \TYPO3\CMS\Fluid\ViewHelpers\Form\SelectViewHelper {

    /**
    * @var mixed
    */
    protected $selectedValue = NULL;

    public function render() {
    $options = $this->getOptions();
    if (empty($options)) {
    $options = array('' => '');
    }
    $this->setErrorClassAttribute();
    $content = '';
    // Register field name for each checkbox for the token generation.
    $content .= $this->renderHiddenFieldForEmptyValue();
    foreach ($options as $option) {
    $this->registerFieldNameForFormTokenGeneration($option);
    }
    $content .= $this->renderCheckboxes($options);
    return $content;
    }

    /**
    * Render the checkboxes.
    *
    * @param array $options the options for the form.
    * @return string rendered checkboxes.
    */
    protected function renderCheckboxes($options) {
    $output = '';
    foreach ($options as $value => $label) {
    $isSelected = $this->isSelected($value);
    $output .= $this->renderCheckbox($value, $label, $isSelected) . chr(10);
    }
    return $output;
    }

    /**
    * Render one checkbox
    *
    * @param string $value value attribute of the checkbox (will be escaped)
    * @param string $label content of the checkbox (will be escaped)
    * @param boolean $isSelected specifies whether or not to add selected attribute
    * @return string the rendered checkbox
    */
    protected function renderCheckbox($value, $label, $isSelected) {
    $output = '<label class="checkbox"><input type="checkbox" name="' . $this->getName() . '" value="' . htmlspecialchars($value) . '"';
    if ($isSelected) {
    $output .= ' checked="checked"';
    }
    $output .= '><span class="labeltext">' . htmlspecialchars($label) . '</span></label>';
    return $output;
    }

    /**
    * Get the name of this form element.
    * Either returns arguments['name'], or the correct name for Object Access.
    *
    * In case property is something like bla.blubb (hierarchical), then [bla][blubb] is generated.
    *
    * @return string Name
    */
    protected function getName() {
    $name = $this->getNameWithoutPrefix() . '[]';
    return $this->prefixFieldName($name);
    }

    }
    ?>