Skip to content

Instantly share code, notes, and snippets.

@adrexia
Last active August 29, 2015 13:59
Show Gist options
  • Save adrexia/10633396 to your computer and use it in GitHub Desktop.
Save adrexia/10633396 to your computer and use it in GitHub Desktop.
A switch field for use in Silverstripe

SwitchField.php

<?php
/**
 * Field to render a checkbox as a switch with left and right option text.
 */
class SwitchField extends CompositeField {

  public function __construct($checkboxField, $leftOption, $rightOption) {

    $this->checkboxField = $checkboxField;
    $this->leftOption = $leftOption;
    $this->rightOption = $rightOption;

    if(!$this->checkboxField instanceof CheckboxField){
      throw new Exception('First parameter of SwitchField must be an instance of CheckboxField');
    }

    parent::__construct(array($checkboxField, $leftOption, $rightOption));
  }

}

Example usage

$checkbox = new CheckboxField("Test", "Test", true);

  $fields->addFieldToTab(
    'Root.Test',
    new SwitchField(
      $checkbox,
      new LiteralField("TestLeft","TestLeft"),
      new LiteralField("TestRight","TestRight")
    )
  );

SwitchField.ss (pre specific switch html)

<div $AttributesHTML>
	$leftOption
	$checkboxField
	$rightOption
</div>
@adrexia
Copy link
Author

adrexia commented Jul 22, 2014

Note: switchfield may require overriding Fieldlist to render in template properly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment