2009-01-28

symfony & mark fields as required, part 2

In previous post - "symfony & mark fields as required" we have a solution for symfony to mark required forms field automatically.

But - it's not fully OOP. so ...

1. the main idea - create custom formatter.

2. inheritence


Base class for all generated forms - is BaseFormPropel
It's also generated from template sfPropelFormBaseTemplate.php which is in propel plugin.
Fix it. (class will be extends from CustomBaseForm instead of sfFormPropel)

[?php

/**
* Project form base class.
*
* @package ##PROJECT_NAME##
* @subpackage form
* @author ##AUTHOR_NAME##
* @version SVN: $Id: sfPropelFormBaseTemplate.php 9304 2008-05-27 03:49:32Z dwhittle $
*/
abstract class BaseFormPropel extends CustomBaseForm
{
public function setup()
{
}
}


3. create CustomBaseForm (put it to /lib/form )

/**
* Custom form base class.
*
* @package shopportal
* @subpackage form
* @author gEndelf
*/
abstract class CustomBaseForm extends sfFormPropel
{
public function getTranslationCatalogue() {
return "";
}

public function render($attributes = array())
{
$formatterObj = $this->widgetSchema->getFormFormatter();

if(!is_null($formatterObj)) {
$formatterObj->setValidatorSchema($this->getValidatorSchema());

if(($translationCatalogue = $this->getTranslationCatalogue()) != "") {
$this->widgetSchema->getFormFormatter()->setTranslationCatalogue($translationCatalogue);
}
}

return parent::render($attributes);
}

public function __toString()
{
try
{
return $this->renderUsing("Store");
}
catch (Exception $e)
{
self::setToStringException($e);
// we return a simple Exception message in case the form framework is used out of symfony.
return 'Exception: '.$e->getMessage();
}
}
}


3. If your form uses translation catalogue


/**
* Contacts form.
*/
class ContactsForm extends BaseContactsForm
{
public function configure()
{
// ...
}

public function getTranslationCatalogue() {
return "contact_form";
}
}


4. Last step

symfony propel:build-all
symfony cc


Advantages - you form doesn't contain repeatable code (guys - it's OOP :)

1 comment:

matt said...

this does not work for forms that are embedded into others. How would this work?