суббота, марта 14, 2009

Упрощение работы с sfWidgetFormSelect в sfForm

Этим постом я начну серию статьёй по symfony 1.2

Иногда необходимо использовать ограниенные списки select в админе в symfony 1.2.
Но не хочется выбирать данные для sfWidgetFormSelect из массива или yaml файла.
Поэтому можно создать свой виджет sfWidgetFormYamlSelect:

class sfWidgetFormYamlSelect extends sfWidgetFormChoice
{
public function __construct($options = array(), $attributes = array())
{
$options['choices'] = new sfCallable(array($this, 'getChoices'));
parent::__construct($options, $attributes);
}
protected function configure($options = array(), $attributes = array())
{
addRequiredOption('form_name', null);
$this->addRequiredOption('field_name', null);
$this->addOption('add_empty', false);
parent::configure($options, $attributes);
}
public function getChoices()
{
$conf_array = sfConfig::get('app_'.$this->getOption('form_name'));
$choices = array();
if(false !== $this->getOption('add_empty')){
$choices[''] = true === $this->getOption('add_empty') ? '' :
$this->getOption('add_empty');
}
$choices = array_merge($choices,$conf_array[$this->getOption('field_name')]);
return $choices;
}
}


В файле config/app.yml (если его нет, то создайте) опишите ваши поля для форм:
all:
.form_settings:
my_form1:
type: { 'yes': 'да', 'no': 'нет }
my_form2:
status: { 0: 'новый', 1: 'подтвержденный', 2: 'редактируется' }



В самой форме это будет выглядеть так:

class MyFormForm1 extends BaseMyForm1Form
{
public function configure()
{
$this->setWidget('status' , new sfWidgetFormYamlSelect(array(
'form_name'=>'my_form1',
'field_name'=>'status'
)));
}
}





Так же это можно использовать в фильтрах.

Комментариев нет: