Symfony 1.2 - sfForm - Yet another useful function - part 2

A couple of weeks ago i have shown you really useful example about unsetting sfForm fields - unsetAllExcept. Since that i was palying with sfForm and i found more functions that could help you working with symfony forms.

All methods shown below have to be added to BasePropelForm class (or Doctrine depending on ORM we use).

Setting single form value
There is no really simple way to set single value of field - i’m not talking about setting default value. We can call getValue on Form but not setValue. Imagine situation when we post a form and just after binding we want to set value. You can find exampe in this post.


<?php

   /**
   * Sets a value for a form field.
   *
   * @param string $field	The field name
   * @param mixed  $value	The default value
   */
    public function setValue($field, $value){

    	if(!in_array($field, array_keys($this->values))){

    		throw new sfException(sprintf('Unkown field" "%s" in "%s" object.', $field, get_class($this)));
    	}

    	$this->values[$field] = $value;
    }

?>


Getting single embed form
Sometimes we need to get single embedded Form to call on it our custom method or get some value. So:


<?php

  /**
   * Gets the embedded form by given name.
   *
   * @param string $name  Name of embedded form
   * @return moxed sfForm obejct
   */
  public function getEmbeddedForm( $name)
  {
      return ( isset($this->embeddedForms[$name]) ) ? $this->embeddedForms[$name] : null;
  }

?>

Setting and getting parent form
Next three functions i’m using together during embedding forms. The problem i had lately, was that my embedded form knew nothing about his parent (i will try to show you some example next time). So i added protected field “parentForm” which i’m setting during embedding process.


<?php

abstract class BaseFormPropel extends sfFormPropel
{
  protected $parentForm = null;

    # We are overriding embedForm method
  public function embedForm($name, sfForm $form, $decorator = null)
  {
   	$form->setParentForm($this);

   	parent::embedForm($name,$form, $decorator);
  }

  public function setParentForm($form){

  	$this->parentForm = $form;
  }

  public function getParentForm(){

  	return $this->parentForm;
  }

}

?>

2 Responses to “Symfony 1.2 - sfForm - Yet another useful function - part 2”


  1. 1 feliks

    pretty useful!

  2. 2 Bas

    Thanks! That was what I’m looking for. A small question. How to change the value of a form field after the POST… And no one could answer. except you :-) thanks!

Leave a Reply

PodglÄ…d komentarza:




About me:

  • PHP programmer
  • Symfony developer
  • Zend framework developer

Categories: