Skip to content

Instantly share code, notes, and snippets.

@fprochazka
Created August 17, 2011 11:19
Show Gist options
  • Save fprochazka/1151346 to your computer and use it in GitHub Desktop.
Save fprochazka/1151346 to your computer and use it in GitHub Desktop.
Nette Framework hack for getting controls and labels one by one
<?php
Kdyby\Forms\RadioListExtension::register();
?>
{* @param Nette\Forms\Controls\RadioList $radio *}
{foreach $radio->items as $key => $value}
{$radio->getOneControl($key)} {* Single control, instanceof HTML *}
{$radio->getOneLabel($key)} {* Single label, instanceof HTML *}
{/foreach}
<?php
namespace Kdyby\Forms;
use Nette;
use Nette\Forms\Controls\RadioList;
use Nette\Utils\Html;
use Nette\Utils\Arrays;
class RadioListExtension extends Nette\Object
{
/**
* @throws Nette\StaticClassException
*/
final public function __construct()
{
throw new Nette\StaticClassException;
}
/**
* Registers hack methods
*/
public static function register()
{
RadioList::extensionMethod('getOneControl', callback(__CLASS__, 'getOneControl'));
RadioList::extensionMethod('getOneLabel', callback(__CLASS__, 'getOneLabel'));
}
/**
* @param RadioList $radio
* @param mixed $key
* @return Html
*/
public static function getOneControl(RadioList $radio, $key)
{
if (!isset($radio->items[$key])) {
return NULL;
}
$control = self::callBaseControl($radio, 'getControl');
$index = Arrays::searchKey($radio->items, $key);
$id = $control->id;
$value = $radio->getValue() === NULL ? NULL : (string) $radio->getValue();
if ($index > 0) {
$control->data('nette-rules', NULL);
}
$control->id = $id . '-' . $index;
$control->checked = (string) $key === $value;
$control->value = $key;
return $control;
}
/**
* @param RadioList $radio
* @param mixed $key
* @return Html
*/
public static function getOneLabel(RadioList $radio, $key)
{
if (!isset($radio->items[$key])) {
return NULL;
}
$control = self::callBaseControl($radio, 'getControl');
$index = Arrays::searchKey($radio->items, $key);
$id = $control->id;
$val = $radio->items[$key];
$label = Html::el('label', array('for' => $id . '-' . $index));
if ($val instanceof Html) {
$label->setHtml($val);
} else {
$label->setText($radio->translate((string) $val));
}
return $label;
}
/**
* @hack ugly one!
* @param object $object
* @param string $method
* @return mixed
*/
private static function callBaseControl($object, $method, $args = array())
{
return Nette\Reflection\Method::from('Nette\Forms\Controls\BaseControl', $method)->invokeArgs($object, $args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment