Code snippets for symfony 1.x

Navigation

unset all not needed form widgets

Common Probem.

You have a large and small form. For example a contact form.

Form orginal includes 50 fields and your small form is extend form the orginal form and includes 15 fields. normaly you have to unset very 35 field in the small one.

But you could also write this lines:

class ContactSimpleForm extends ContactForm
{
  public function configure()
  {
 
    parent::configure();
 
    $this->wantedFields = array(
        'firstname',
        'lastname',
    );
 
    foreach ($this as $fieldName => $widget){
        if (!in_array($fieldName, $this->wantedFields)){
            unset($this->widgetSchema[$fieldName]);
            unset($this->validatorSchema[$fieldName]);
        }
    }
}
 
by excessive demon on 2009-09-18, tagged form  unset  validator  widget 

Comments on this snippet

gravatar icon
#1 Yanko Simeonoff on 2009-09-23 at 04:45

There is already done a method for this.

http://blog.adryjanek.eu/2009/05/14/symfony-12-sfform-unsetallexcept-better-way/

gravatar icon
#2 Jasper Lammertink on 2009-09-24 at 05:40

@Yanko: the method u send isn't fullproof. U have to check if a field is hidden: if yes, keep it. I made this function in the BaseFormPropel.class.php in your form dir.

{
    foreach ($this->getWidgetSchema()->getFields() as $name => $widget)
    {
        if (!in_array($name, $fields) && !$widget->isHidden())
        {
            unset($this[$name]);
        }
    }
 
gravatar icon
#3 Jasper Lammertink on 2009-09-24 at 05:41

sorry ubb tags are buggy:

here the right code:

public function useFields($fields)
{
    foreach ($this->getWidgetSchema()->getFields() as $name => $widget)
    {
        if (!in_array($name, $fields) && !$widget->isHidden())
        {
            unset($this[$name]);
        }
    }
}