views:

3705

answers:

3

I'm overriding my doSave() method to basically do the following: I have a sfWidgetFormPropelChoice field that the user can either choose from, or type a new option. How can I change the widget's value? Or maybe I am approaching this the wrong way. So here is how I overrode 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'S 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'S VALUE INSTEAD?
 }

 parent::doSave($con);
}
A: 

You could do it in the action :

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

But I prefer to do the kind of work you are doing with your manufacturer directly in my Peer so my business logic is always at the same place.

What I put in my forms is mainly validation logic.

Example of what to put in the save method of the Peer :

public function save(PropelPDO $con= null)
{
  if ($this->isNew() && !$this->getFooId())
  {
    $foo= new Foo();
    $foo->setBar('bar');
    $this->setFoo($foo);
   } 
}
Dreur
Thanks for your response! How would you go about doing that work in the peer? Since it's form-related, shouldn't it go in the form? The peer doesn't have the form data that would be either an ID or a new name.
James Skidmore
A: 

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

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);
}
bb
+1  A: 

You should use setDefault or setDefaults and then it will autopopulate with the bound values.

[php]
(sfForm) setDefault ($name, $default)
(sfForm) setDefaults ($defaults)

usage

[php]
$form->setDefault('WidgetName', 'Value');
$form->setDefaults(array(
    'WidgetName' => 'Value',
));
Henrik Bjørnskov