开发者

Symfony forms: how to change default widget for form generation

开发者 https://www.devze.com 2022-12-30 22:36 出处:网络
I\'m using a custom Widget for date fields, and I want to use it in all my forms. The problem is that symfon开发者_开发知识库y uses the default sfWidgetFormDate. What I want is to change this default

I'm using a custom Widget for date fields, and I want to use it in all my forms. The problem is that symfon开发者_开发知识库y uses the default sfWidgetFormDate. What I want is to change this default widget in order to generate forms with my custom Widget. I don't want to change by hand all the forms generated.

The only approach I have found is the trik of modify BaseFormDoctrine.php:

public function setup()
{
    foreach($this->getWidgetSchema()->getFields() as $name=>$widget)
    {
        if($widget instanceof sfWidgetFormDate) 
        {
            $this->widgetSchema[$name] = new sfWidgetFormJQueryDate(array(
                'config' => '{}',
                'image'=>'/images/calendar.png',
            ));
        }
    }
}


What you could do is create your own form generator class.

class myFormGenerator extends sfDoctrineGenerator
{

  public function getWidgetClassForColumn($column)
  { 
    switch ($column->getDoctrineType())
    {
      case 'date':
        return 'sfWidgetFormJQueryDate';
        break;
      default:
        return parent::getWidgetClassForColumn($column); 
    }
  }
}

Save that somewhere sensible in your lib folder, clearing the cache etc..

Then rerun your for generator like so...

php doctrine:build-forms --generator-class='myFormGenerator'

I haven't tried any of the above, but the theory is sound I think...

Have a look at the following files to see where I figured this out from:

lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/task/sfDoctrineBuildFormsTask.class.php
lib/vendor/symfony/lib/plugins/sfDoctrinePlugin/lib/generator/sfDoctrineFormGenerator.class.php


Following johnwards answer, as I want to define default options for the widget, I also override the function to do that:

class myFormGenerator extents sfDoctrineFormGenerator
{

  public function getWidgetClassForColumn($column)
  { 
    ...
  }

  public function getWidgetOptionsForColumn($column)
  {
    switch ($column->getDoctrineType())
    {
      case 'date':
        return "array('config' => '{}', 'image'=>'/images/calendar.png')";
    break;
      default:
        return parent::getWidgetOptionsForColumn($column); 
    }
  }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消