Create a symfony widget like sfWidgetFormDateRang

1. Create the class:

<?php
class grapheWidgetFormFrequency extends sfWidgetForm
{
protected function configure($options = array(), $attributes = array())
{
$this->addRequiredOption('number');
$this->addRequiredOption('type');

$this->addOption('template', '%number% - %type%');
}

public function render($name, $value = null, $attributes = array(), $errors = array())
{
$values = array_merge(array('number' => '', 'type' => '', 'is_empty' => ''), is_array($value) ? $value : array());

return strtr($this->translate($this->getOption('template')), array(
'%number%' => $this->getOption('number')->render($name.'[number]', $value['number']),
'%type%' => $this->getOption('type')->render($name.'[type]', $value['type']),
));
}

public function getStylesheets()
{
return array_unique(array_merge($this->getOption('number')->getStylesheets(), $this->getOption('type')->getStylesheets()));
}

public function getJavaScripts()
{
return array_unique(array_merge($this->getOption('number')->getJavaScripts(), $this->getOption('type')->getJavaScripts()));
}
}

2. use it in form class:

class ImportScheduleForm extends BaseImportScheduleForm
{
  public function configure()
  {
    $type
= array('' => '',
'hour' => 'hour',
'day' => 'day',
'week' => 'week',
'month' => 'month',
'year' => 'year',
);
$this->widgetSchema['frequency'] = new grapheWidgetFormFrequency(array(
'number' => new sfWidgetFormInput(array(), array('size' => '1')),
'type' => new sfWidgetFormChoice(array('choices' => $type)),
));
  }
}

3. forset values into the form and update the db:

class ImportScheduleForm extends BaseImportScheduleForm
{
public function updateDefaultsFromObject()
{
parent::updateDefaultsFromObject();
$freq = explode('-', $this->getObject()->getFrequency());
$this->setDefault('frequency', array(
'number' => $freq[0],
'type' => $freq[1]
));
}

public function updateObject($values = null)
{
if (null === $values){
$values = $this->values;
}
//var_dump($values['frequency']['number'],$values['frequency']['type']);die();
$obj = parent::updateObject($values);
$obj->setFrequency($values['frequency']['number'].'-'.$values['frequency']['type']);

return $obj;
}
}

Ref: http://pookey.co.uk/wordpress/archives/170-datetime-range-selector-widget-for-symfony



posted @ 2011-10-25 17:48  Lux.Y  阅读(518)  评论(0编辑  收藏  举报