<?php

/**
 * KataoMemberGroup form base class.
 *
 * @package    form
 * @subpackage katao_member_group
 * @version    SVN: $Id: sfPropelFormGeneratedTemplate.php 15484 2009-02-13 13:13:51Z fabien $
 */
class BaseKataoMemberGroupForm extends BaseFormPropel
{
  public function setup()
  {
    $this->setWidgets(array(
      'id'                            => new sfWidgetFormInputHidden(),
      'katao_member_group_name'       => new sfWidgetFormInput(),
      'katao_assoc_member_group_list' => new sfWidgetFormPropelSelectMany(array('model' => 'KataoMember')),
    ));

    $this->setValidators(array(
      'id'                            => new sfValidatorPropelChoice(array('model' => 'KataoMemberGroup', 'column' => 'id', 'required' => false)),
      'katao_member_group_name'       => new sfValidatorString(array('max_length' => 255, 'required' => false)),
      'katao_assoc_member_group_list' => new sfValidatorPropelChoiceMany(array('model' => 'KataoMember', 'required' => false)),
    ));

    $this->widgetSchema->setNameFormat('katao_member_group[%s]');

    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);

    parent::setup();
  }

  public function getModelName()
  {
    return 'KataoMemberGroup';
  }


  public function updateDefaultsFromObject()
  {
    parent::updateDefaultsFromObject();

    if (isset($this->widgetSchema['katao_assoc_member_group_list']))
    {
      $values = array();
      foreach ($this->object->getKataoAssocMemberGroups() as $obj)
      {
        $values[] = $obj->getMemberId();
      }

      $this->setDefault('katao_assoc_member_group_list', $values);
    }

  }

  protected function doSave($con = null)
  {
    parent::doSave($con);

    $this->saveKataoAssocMemberGroupList($con);
  }

  public function saveKataoAssocMemberGroupList($con = null)
  {
    if (!$this->isValid())
    {
      throw $this->getErrorSchema();
    }

    if (!isset($this->widgetSchema['katao_assoc_member_group_list']))
    {
      // somebody has unset this widget
      return;
    }

    if (is_null($con))
    {
      $con = $this->getConnection();
    }

    $c = new Criteria();
    $c->add(KataoAssocMemberGroupPeer::GROUP_ID, $this->object->getPrimaryKey());
    KataoAssocMemberGroupPeer::doDelete($c, $con);

    $values = $this->getValue('katao_assoc_member_group_list');
    if (is_array($values))
    {
      foreach ($values as $value)
      {
        $obj = new KataoAssocMemberGroup();
        $obj->setGroupId($this->object->getPrimaryKey());
        $obj->setMemberId($value);
        $obj->save();
      }
    }
  }

}
