Skip to content

Instantly share code, notes, and snippets.

@wodCZ
Created December 17, 2015 09:58
Show Gist options
  • Save wodCZ/5d7478b22e9577461aae to your computer and use it in GitHub Desktop.
Save wodCZ/5d7478b22e9577461aae to your computer and use it in GitHub Desktop.
BooleanOrNullControl for Nette framework

This control aims to add support for [not specified|no|yes] control to Nette. This can not be done easily because of non-type-safe working with keys in Nette\Forms.

Keep in mind that getValue returns TRUE|FALSE|NULL while getRawValue returns internal representation of these values.

I only used this with custom rendering, I don't know whether it renders correctly by default.

Snippet i used for rendering:

Note that use of $form[$name]->rawValue instead of value

	<div class="form-group">
		<div class="control-label col-sm-2">
			{label $name/}
		</div>
		<div class="col-sm-10">
			<div class="btn-group" data-toggle="buttons">

				{foreach $form[$name]->items as $key => $label}
					<label n:class="btn,btn-default, $form[$name]->rawValue === $key ? active" n:name="$name:$key">
						<input n:name="$name:$key"> {$label}
					</label>
				{/foreach}
			</div>
		</div>
	</div>
<?php
namespace Forms\Controls;
use Nette\Forms\Controls\RadioList;
class BooleanOrNullControl extends RadioList
{
const NULL = -1;
const FALSE = 0;
const TRUE = 1;
protected $boolOrNullItems;
/**
* @inheritDoc
*/
public function __construct($label = NULL, $nullLabel = 'Not specified', $falseLabel = 'No', $trueLabel = 'Yes')
{
$this->boolOrNullItems = [
self::NULL => $nullLabel,
self::FALSE => $falseLabel,
self::TRUE => $trueLabel,
];
parent::__construct($label, $this->boolOrNullItems);
}
/**
* @inheritDoc
*/
public function setItems(array $items, $useKeys = TRUE)
{
return parent::setItems($this->boolOrNullItems);
}
/**
* @param null|bool $value
* @return \Nette\Forms\Controls\ChoiceControl
*/
public function setValue($value)
{
if ($value === NULL) {
$value = self::NULL;
} elseif ($value === TRUE) {
$value = self::TRUE;
} elseif ($value === FALSE) {
$value = self::FALSE;
} else {
return $this->setValue((bool) $value);
}
$this->value = $value;
return $this;
}
/**
* @return bool|null
*/
public function getValue()
{
$value = parent::getValue();
if ($value === self::TRUE) {
return TRUE;
} elseif ($value === self::FALSE) {
return FALSE;
} else {
return NULL;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment