In symfony, how to set the value of a form field?

I override my doSave () method to basically do the following: I have an sfWidgetFormPropelChoice field that the user can select, or enter a new parameter. How to change the value of a widget? Or maybe I'm approaching this wrong. So, here is how I redefined the doSave () method:

public function doSave($con = null)
{
    // Save the manufacturer as either new or existing.
    $manufacturer_obj = ManufacturerPeer::retrieveByName($this['manufacturer_id']->getValue());
    if (!empty($manufacturer_obj))
    {
        $this->getObject()->setManufacturerId($manufacturer_obj->getId()); // NEED TO CHANGE THIS TO UPDATE WIDGET VALUE INSTEAD?
    }
    else
    {
        $new = new Manufacturer();
        $new->setName($this['manufacturer_id']->getValue());
        $new->save();
        $this->getObject()->setManufacturerId($new->getId()); // NEED TO CHANGE THIS TO UPDATE WIDGET VALUE INSTEAD?
    }

    parent::doSave($con);
}
+5
source share
3 answers

You must use setDefault or setDefaults, and then it will auto-populate with bound values.

(sfForm) setDefault ($name, $default)
(sfForm) setDefaults ($defaults)

Using

$form->setDefault('WidgetName', 'Value');
$form->setDefaults(array(
    'WidgetName' => 'Value',
));
+9
source

You can do this in action:

$this->form->getObject()->setFooId($this->foo->getId()) /*Or get the manufacturer id or name from request here */
$this->form->save();

, Peer, - .

, , - .

, Peer:

public function save(PropelPDO $con= null)
{
  if ($this->isNew() && !$this->getFooId())
  {
    $foo= new Foo();
    $foo->setBar('bar');
    $this->setFoo($foo);
   } 
}
+2

Two assumptions: a) your form gets the name of the manufacturer and b) your model wants the manufacturer ID

public function doSave($con = null)
{
    // retrieve the object from the DB or create it
    $manufacturerName = $this->values['manufacturer_id'];
    $manufacturer = ManufacturerPeer::retrieveByName($manufacturerName);
    if(!$manufacturer instanceof Manufacturer)
    {
        $manufacturer = new Manufacturer();
        $manufacturer->setName($manufacturerName);
        $manufacturer->save();
    }

    // overwrite the field value and let the form do the real work
    $this->values['manufacturer_id'] = $manufacturer->getId();

    parent::doSave($con);
}
+1
source

All Articles