<?php

// Template for creating an object class.
//
// This is based on the Torque Object.vm Velocity template.  A number of changes
// have, of course, been made to make this PHP.
//
// $Id: Object.tpl,v 1.21 2005/03/19 13:34:59 micha Exp $

// helper class
include_once 'propel/engine/builder/om/PeerBuilder.php';
include_once 'propel/engine/builder/om/ClassTools.php';

echo '<' . '?' . 'php';

$db = $table->getDatabase();
if ($table->getPackage()) {
  $package = $table->getPackage();
} else {
  $package = $targetPackage;
}

$parentClass = ClassTools::getBaseClass($table); 
?>

require_once '<?php echo ClassTools::getFilePath($parentClass) ?>';

<?php
if (! $table->isAlias()) 
{
  // If any columns in table are BLOB or CLOB then we need to make
  // sure those classes are included so we can do things like
  // if ($v instanceof Lob) etc.
  $includes_lobs = false;

  foreach ($table->getColumns() as $col) {
    if ($col->isLob()) {
      $includes_lobs = true;
      break;
    }
  }

  if($includes_lobs) 
  { 
?>
include_once 'creole/util/Clob.php';
include_once 'creole/util/Blob.php';
<?php
  }
}
?>

include_once 'propel/util/Criteria.php';
<?php
foreach ($table->getForeignKeys() as $fk) 
{
  $tblFK = $table->getDatabase()->getTable($fk->getForeignTableName());
  $className = $tblFK->getPhpName();
  if ($tblFK->getInterface()) {
    $className = $tblFK->getInterface();
  }

  $tblFKPackage = ($tblFK->getPackage() ? $tblFK->getPackage() : $package);
  $tblFKPackagePath = strtr($tblFKPackage, '.', '/');
  if ($tblFKPackagePath != "") {
    $tblFKPackagePath .= '/';
  } 
?>

// (on-demand) include_once '<?php echo ClassTools::getFilePath($tblFKPackage, $className) ?>';
// (on-demand) include_once '<?php echo ClassTools::getFilePath($tblFKPackage, $tblFK->getPhpName() . 'Peer') ?>';
<?php 
} /* ($table->getForeignKeys() as $fk) */ 
?>

include_once '<?php echo ClassTools::getFilePath($package, $table->getPhpName() . 'Peer') ?>';

/**
 * Base class that represents a row from the '<?php echo $table->getName() ?>' table.
 *
 * <?php echo $table->getDescription() ?> 
 *
<?php if ($addTimeStamp) { ?>
 * This class was autogenerated by Propel on:
 *
 * [<?php echo $now ?>]
 *
<?php } ?>
 * You should not use this class directly.  It should not even be
 * extended; all references should be to <?php echo $table->getPhpName() ?> class.
 *
 * @package <?php echo $package ?> 
 */
class <?php echo $basePrefix . $table->getPhpName() ?> extends <?php echo ClassTools::classname($parentClass) ?> 
{
  /**
  * The Peer class.
  * Instance provides a convenient way of calling static methods on a class
  * that calling code may not be able to identify.
  * @var <?php echo $table->getPhpName() ?>Peer
  */
  var $peer;

<?php
if (! $table->isAlias()) 
{
  foreach ($table->getColumns() as $col) 
  {
    $cptype = $col->getPhpNative();
    $clo=strtolower($col->getName());
    $defVal = "";
    if (($val = $col->getPhpDefaultValue()) !== null) {
      settype($val, $cptype);
      $defaultValue = var_export($val, true);
      $defVal = " = " . $defaultValue;
    }
?>
  /**
  * The value for the <?php echo $clo ?> field.
  * @var <?php echo $cptype ?> 
  */
  var $<?php echo $clo . $defVal ?>;

<?php 
    if ($col->isLazyLoad()) { 
?>
  /**
   * Whether the lazy-loaded <?php echo $clo ?> value has been loaded from database.
   * This is necessary to avoid repeated lookups if <?php echo $clo ?> column is NULL.
   * @var boolean
   */
   var $<?php echo $clo ?>_isLoaded = false;

<?php 
    } /* if ($col->isLazyLoad()) */
  } /* foreach ($table->getColumns() as $col) */
 
  foreach ($table->getColumns() as $col) 
  {
    $cfc=$col->getPhpName();
    $clo=strtolower($col->getName());
    $cptype = $col->getPhpNative();

    $defaultValue = null;
    if (($val = $col->getPhpDefaultValue()) !== null) {
      settype($val, $cptype);
      $defaultValue = var_export($val, true);
    }
    
    if ($col->getType() === PropelTypes::DATE || $col->getType() === PropelTypes::TIME || $col->getType() === PropelTypes::TIMESTAMP)
    {
      // these default values are based on the Creole defaults
      // the date and time default formats are locale-sensitive
      if ($col->getType() === PropelTypes::DATE) {
        $defaultfmt = '%x';
      } elseif ($col->getType() === PropelTypes::TIME) {
        $defaultfmt = '%X';
      } elseif ($col->getType() === PropelTypes::TIMESTAMP) {
        $defaultfmt = 'Y-m-d H:i:s';
      }
?>
  /**
  * Get the [optionally formatted] `<?php echo $cfc ?>` value.
  * <?php echo $col->getDescription() ?> 
  *
  * @param string $format The date/time format string (either date()-style or strftime()-style).
  *              If format is NULL, then the integer unix timestamp will be returned.
  * @return mixed Formatted date/time value as string or integer unix timestamp (if format is NULL) on success,
  *               PropelException, if unable to convert the date/time to timestamp.
  */
  function get<?php echo $cfc ?>($format = '<?php echo $defaultfmt ?>')
  {
<?php 
      if ($col->isLazyLoad()) { 
?>
    if (! $this-><?php echo $clo ?>_isLoaded && $this-><?php echo $clo ?> === null && !$this->isNew()) {
      if (($e = $this->load<?php echo $cfc ?>()) !== true) {
        return $e;
      }
    }
<?php
      } /* if ($col->isLazyLoad) */ 
?>
    if ($this-><?php echo $clo ?> === null || $this-><?php echo $clo?> === '') {
      return null;
    } elseif (!is_int($this-><?php echo $clo ?>)) {
      // a non-timestamp value was set externally, so we convert it
      $ts = strtotime($this-><?php echo $clo ?>);
      if ($ts === -1) {
        return new PropelException(PROPEL_ERROR_INVALID, "Unable to parse value of <?php echo $clo ?> as date/time value: " . $this-><?php echo $clo ?>);
      }
    } else {
      $ts = $this-><?php echo $clo ?>;
    }
    if ($format === null) {
      return $ts;
    } elseif (strpos($format, '%') !== false) {
      return strftime($format, $ts);
    } else {
      return date($format, $ts);
    }
  }

<?php 
    } else { /* $col->getType() != DATE | TIME | TIMESTAMP */ 
?>
  /**
  * Get the <?php echo $cfc ?> column value.
  * <?php echo $col->getDescription() ?> 
  *
  * @return <?php echo $cptype ?> 
  */
  function get<?php echo $cfc ?>()
  {
<?php 
      if ($col->isLazyLoad()) 
      { 
?>
    if (! $this-><?php echo $clo ?>_isLoaded && $this-><?php echo $clo ?> === null && !$this->isNew()) {
      if (($e = $this->load<?php echo $cfc ?>()) !== true) {
        return $e;
      }
    }

<?php 
      } /* if $col->isLazyLoad */
?>
    return $this-><?php echo $clo ?>;
  }
<?php 
    } /* $col->getType() != DATE | TIME | TIMESTAMP */
?>

<?php 
    if ($col->isLazyLoad()) 
    { 
?>
  /**
  * Load the value for the [lazy-load] `<?php echo $clo ?>` column.
  *
  * This method performs an additional query to return the value for
  * the `<?php echo $clo ?>` column, since it is not populated by
  * the hydrate() method.
  *
  * @return void
  * @returns mixed boolean TRUE on success, PropelException - any underlying error will be wrapped and re-thrown.
  */
  function load<?php echo $cfc ?>()
  {
    $c = $this->buildPkeyCriteria();
    $c->addSelectColumn(<?php echo PeerBuilder::getColumnName($col, $table->getPhpName()) ?>());

    $rs =& <?php echo $table->getPhpName()?>Peer::doSelectRS($c);

    if (Propel::isError($e =& $rs) || Propel::isError($e = $rs->next())) {
      return new PropelException(PROPEL_ERROR, "Error loading value for `<?php echo $clo ?>` column on demand.", $e);
    }

<?php
      $affix = CreoleTypes::getAffix(CreoleTypes::getCreoleCode($col->getType()));                                    
      $clo = strtolower($col->getName());
      switch($col->getType()) 
      {
        case PropelTypes::DATE:                    
        case PropelTypes::TIME:
        case PropelTypes::TIMESTAMP:
?>
    $this-><?php echo $clo ?> = $rs->get<?php echo $affix ?>(1, null);
<?php
          break;
        default:
?>
    $this-><?php echo $clo?> = $rs->get<?php echo $affix ?>(1);
<?php   
      } /* switch $col->getType */ 
?>
    if (Propel::isError($this-><?php echo $clo?>)) {
      return new PropelException(PROPEL_ERROR, "Error loading value for `<?php echo $clo ?>` column on demand.", $this-><?php echo $clo?>);
    }
      
    $this-><?php echo $clo ?>_isLoaded = true;

    return true;
  }

<?php 
    } /* if $col->isLazyLoad */ 

    if (! $table->isReadOnly())
    {
      $throwsClause = "";
      if ($complexObjectModel) 
      {
        if ($col->isForeignKey()) {
          $throwsClause = "@throws PropelException";
        }
        if (count($col->getReferrers()) > 0 ) {
          if ($throwsClause == "") {
              $throwsClause = "@throws PropelException";
          }
        }
      }
      if ($col->getType() === PropelTypes::DATE || $col->getType() === PropelTypes::TIME || $col->getType() === PropelTypes::TIMESTAMP) {
        $throwsClause = "@throws PropelException - If passed [not-null] date/time is in an invalid format.";
      }
?>
  /**
  * Set the value of `<?php echo $cfc ?>`
  * <?php echo $col->getDescription() ?> 
  *
  * @param <?php echo $cptype  ?> $v new value
  * @return void
  * <?php echo $throwsClause ?> 
  */
  function set<?php echo $cfc ?>($v)
  {
<?php 
      if ($col->isLazyLoad()) 
      { 
?>
    // explicitly set the is-loaded flag to true for this lazy load col; 
    // it doesn't matter if the value is actually set or not (logic below) as
    // any attempt to set the value means that no db lookup should be performed
    // when the get<?php echo $cfc ?>() method is called. 
    $this-><?php echo $clo ?>_isLoaded = true;
<?php 
      } /* if $col->isLazyLoad */ 
  
      if ($addSaveMethod) 
      {
        if ($col->isLob()) 
        {
          // Setting of LOB columns gets some special handling
          if ($col->getPropelType() === PropelTypes::BLOB || $col->getPropelType() === PropelTypes::LONGVARBINARY ) {
            $lobClass = "Blob";
          } else {
            $lobClass = "Clob";
          }
?>
    // if the passed in parameter is the *same* object that
    // is stored internally then we use the Lob->isModified()
    // method to know whether contents changed.
    if (is_a($v, 'Lob') && $v === $this-><?php echo $clo ?>) {
      $changed = $v->isModified();
    } else {
      $changed = ($this-><?php echo $clo ?> !== $v);
    }
    if ($changed) {
      if ( ! is_a($v, 'Lob') ) {
        $obj = new <?php echo $lobClass ?>();
        $obj->setContents($v);
      } else {
        $obj =& $v;
      }
      $this-><?php echo $clo ?> = $obj;
      $this->modifiedColumns[] = <?php echo PeerBuilder::getColumnName($col, $table->getPhpName()) ?>();
    }
<?php
        } 
        elseif ($col->getType() === PropelTypes::DATE || $col->getType() === PropelTypes::TIME || $col->getType() === PropelTypes::TIMESTAMP) 
        {
        // Setting a DATE/TIME value gets some special handling.
?>
    if ($v !== null && !is_int($v)) {
      $ts = strtotime($v);
      if ($ts === -1) {
        return new PropelException(PROPEL_ERROR_INVALID, "Unable to parse date/time value for <?php echo $clo ?> from input: " . var_export($v, true));
      }
    } else {
      $ts = $v;
    }

    if ($this-><?php echo $clo ?> !== $ts<?php if ($defaultValue !== null) { ?> || $ts === <?php echo $defaultValue ?><?php } ?>) {
      $this-><?php echo $clo ?> = $ts;
      $this->modifiedColumns[] = <?php echo PeerBuilder::getColumnName($col, $table->getPhpName()) ?>();
    }
<?php
        } 
        else 
        { 
          // NORMAL column
?>
    if ($this-><?php echo $clo ?> !== $v<?php if ($defaultValue !== null) { ?> || $v === <?php echo $defaultValue ?><?php } ?>) {
      $this-><?php echo $clo ?> = $v;
      $this->modifiedColumns[] = <?php echo PeerBuilder::getColumnName($col, $table->getPhpName()) ?>();
    }

<?php 
        } /* end normal column */
      } /* end $addSaveMethod */ 
      else 
      {
?>
      $this-><?php echo $clo ?> =& $v;

<?php
      } // if (addSaveMethod)
  
      if ($complexObjectModel) 
      {
        if ($col->isForeignKey()) 
        {
          $tblFK = $table->getDatabase()->getTable($col->getRelatedTableName());
          $colFK = $tblFK->getColumn($col->getRelatedColumnName());
          if ($col->isMultipleFK() || $col->getRelatedTableName() == $table->getName()) {
            $relCol = "";
            foreach ($col->getForeignKey()->getLocalColumns() as $columnName) {
                $column = $table->getColumn($columnName);
                $relCol .= $column->getPhpName();
            }
            if ($relCol != "") {
                $relCol = "RelatedBy".$relCol;
            }
            $varName = "a".$tblFK->getPhpName() . $relCol;
          } else {
            $varName = "a".$tblFK->getPhpName();
          }
?>
    if ($this-><?php echo $varName ?> !== null && $this-><?php echo $varName ?>->get<?php echo $colFK->getPhpName() ?>() !== $v) {
      /*
      * Save a reference to null instead of null directly as this would
      * overwrite a previous stored <?php echo $tblFK->getPhpName() ?> object.
      */
      $this-><?php echo $varName ?> =& Propel::null();
    }
<?php
        } /* if ($col->isForeignKey) */
  
        foreach ($col->getReferrers() as $fk) 
        {
          // used to be getLocalForeignMapping() which did not work.
          $flmap = $fk->getForeignLocalMapping();
          $fkColName = $flmap[$col->getName()];
          $tblFK = $fk->getTable();
          if ( $tblFK->getName() != $table->getName() ) 
          {
            $colFK = $tblFK->getColumn($fkColName);
            if ($colFK->isMultipleFK()) {
              $collName = "coll" . $tblFK->getPhpName() . "sRelatedBy" . $colFK->getPhpName();
            } else {
              $collName = "coll" . $tblFK->getPhpName() . "s";
            }
?>

      // update associated <?php echo $tblFK->getPhpName() ?>

      if ($this-><?php echo $collName ?> !== null) {
          for ($i=0,$size=count($this-><?php echo $collName ?>); $i < $size; $i++) {
              $this-><?php echo $collName ?>[$i]->set<?php echo $colFK->getPhpName()?>($v);
          }
      }
<?php     
          } /* if  $tblFk != $table */
        } /* foreach referrers */
      } /* if complex object model */ 
?>
  }

<?php
    } /* if ! $table->isReadOnly() */ 
  } /* foreach ($table->getColumns() as $col) */ 
?>
  /**
  * Hydrates (populates) the object variables with values from the database resultset.
  *
  * An offset (1-based "start column") is specified so that objects can be hydrated
  * with a subset of the columns in the resultset rows.  This is needed, for example,
  * for results of JOIN queries where the resultset row includes columns from two or
  * more tables.
  *
  * @param ResultSet $rs The ResultSet class with cursor advanced to desired record pos.
  * @param int $startcol 1-based offset column which indicates which restultset column to start with.
  * @return int next starting column
  * @throws PropelException  - Any caught Exception will be rewrapped as a PropelException.
  */
  function hydrate(&$rs, $startcol = 1)
  {
    assert('is_a($rs, "ResultSet")');

<?php 
  $n = 0;
  foreach($table->getColumns() as $col) 
  {
    if (! $col->isLazyLoad())
    {
      $affix = CreoleTypes::getAffix(CreoleTypes::getCreoleCode($col->getType()));                                    
      $clo = strtolower($col->getName());
      switch($col->getType()) 
      {
        case PropelTypes::DATE:                    
        case PropelTypes::TIME:
        case PropelTypes::TIMESTAMP:
?>
    if (Creole::isError($value = $rs->get<?php echo $affix ?>($startcol + <?php echo $n ?>, null))) {
      return new PropelException(PROPEL_ERROR_DB, "Error populating <?php echo $table->getPhpName()?> object", $value);
    }
    
    $this-><?php echo $clo ?> = $value;
<?php
          break;
        default:
?>
    if (Creole::isError($value = $rs->get<?php echo $affix ?>($startcol + <?php echo $n ?>))) {
      return new PropelException(PROPEL_ERROR_DB, "Error populating object", $value);
    }

    $this-><?php echo $clo?> = $value;
<?php
      } /* switch */
      $n++;
    } /* if ! $col->isLazyLoad() */
  } /* foreach ($table->getColumns() as $col) */

  if ($addSaveMethod) 
  { 
?>
    $this->resetModified();
<?php 
  } /* if ($addSaveMethod) */
?>
    $this->setNew(false);
    return $startcol + <?php echo $n; ?>;
  }
    
  /**
  * Builds a Criteria object containing the primary key for this object.
  *
  * Unlike buildCriteria() this method includes the primary key values regardless
  * of whether or not they have been modified.
  * 
  * @return Criteria The Criteria object containing value(s) for primary key(s).
  */
  function &buildPkeyCriteria()
  {        
    $criteria = new Criteria(<?php echo $table->getPhpName()?>Peer::DATABASE_NAME());
<?php
  foreach ($table->getColumns() as $col) 
  {
    $clo = strtolower($col->getName());
    if ($col->isPrimaryKey()) 
    { 
?>
    $criteria->add(<?php echo PeerBuilder::getColumnName($col, $table->getPhpName()) ?>(), $this-><?php echo $clo ?>);
<?php
    } /* if $col->isPrimaryKey */
  } /* foreach ($table->getColumns() as $col) */
?>
    return $criteria;
  }
    
  /**
  * Build a Criteria object containing the values of all modified columns in this object.
  *
  * @return Criteria The Criteria object containing all modified values.
  */
  function &buildCriteria()
  {        
    $criteria = new Criteria(<?php echo $table->getPhpName()?>Peer::DATABASE_NAME());

<?php
  foreach ($table->getColumns() as $col) 
  {
    $clo = strtolower($col->getName());
?>
    if ($this->isColumnModified(<?php echo PeerBuilder::getColumnName($col, $table->getPhpName()) ?>())) { 
      $criteria->add(<?php echo PeerBuilder::getColumnName($col, $table->getPhpName()) ?>(), $this-><?php echo $clo ?>);
    }

<?php
  } /* foreach */
?>
    return $criteria;
  }
    
<?php 
} /* if !table->isAlias */ 

// association code
if ($complexObjectModel) 
{
  $pVars = array();  // Array of object set method names for later reference.
  $aVars = array();  // Array of object field names for later reference.

  foreach ($table->getForeignKeys() as $fk)
  {
    $tblFK = $table->getDatabase()->getTable($fk->getForeignTableName());
    $className = $tblFK->getPhpName();

    $tblFKPackage = ($tblFK->getPackage() ? $tblFK->getPackage() : $package);
    $tblFKPackagePath = strtr($tblFKPackage, '.', '/');
    if ($tblFKPackagePath != "") {
        $tblFKPackagePath .= '/';
    }

    $relCol = "";
    foreach ($fk->getLocalColumns() as $columnName) {
      $column = $table->getColumn($columnName);
      if ($column->isMultipleFK() || $fk->getForeignTableName() == $table->getName()) {
        $relCol .= $column->getPhpName();
      }
    }

    if ($relCol != "") {
      $relCol = "RelatedBy" . $relCol;
    }

    $pVarName = $className . $relCol;
    $varName = "a" . $pVarName;
    $retVal = ($pVars[] = $pVarName);
    $retVal = ($aVars[] = $varName);
?>
  /**
  * @var <?php echo $className ?>
  */
  var $<?php echo $varName ?>;

  /**
  * Declares an association between this object and a <?php echo $className ?> object
  *
  * @param <?php echo $className ?> $v
  * @return void
  * @throws PropelException
  */
  function set<?php echo $pVarName ?>(&$v)
  {
<?php
    foreach ($fk->getLocalColumns() as $columnName) 
    {
      $column = $table->getColumn($columnName);
      $lfmap = $fk->getLocalForeignMapping();
      $colFKName = $lfmap[$columnName];
      $colFK = $tblFK->getColumn($colFKName);
?>
    if ($v === null) {
      $this->set<?php echo $column->getPhpName() ?>(<?php echo var_export($column->getPhpDefaultValue()) ?>);
    } else {
      $this->set<?php echo $column->getPhpName() ?>($v->get<?php echo $colFK->getPhpName() ?>());
    }

<?php 
    } /* foreach local col */ 
?>
    $this-><?php echo $varName ?> =& $v;
  }

<?php
    $and = "";
    $comma = "";
    $conditional = "";
    $arglist = "";
    $argsize = 0;
    foreach ($fk->getLocalColumns() as $columnName) 
    {
      $column = $table->getColumn($columnName);
      $cptype = $column->getPhpNative();
      $clo = strtolower($column->getName());
      if ($cptype == "integer" || $cptype == "float" || $cptype == "double") {
        $conditional .= $and . "\$this->". $clo ." > 0";
      } elseif($cptype == "string") {
        $conditional .= $and . "(\$this->" . $clo ." !== \"\" && \$this->".$clo." !== null)";
      } else {
        $conditional .= $and . "\$this->" . $clo ." !== null";
      }
      $arglist .= $comma . "\$this->" . $clo;
      $and = " && ";
      $comma = ", ";
      $argsize = $argsize + 1;
    }

    $pCollName = $table->getPhpName() . 's' . $relCol;
?>
  /**
  * Get the associated <?php echo $className ?> object
  *
  * @return <?php echo $className ?> The associated <?php echo $className ?> object.
  * @throws PropelException
  */
  function & get<?php echo $pVarName ?>()
  {
    // include the Peer class
    include_once '<?php echo $tblFKPackagePath . $className ?>Peer.php';

    if ($this-><?php echo $varName ?> === null && (<?php echo $conditional ?>))
    {
<?php
    if ($tblFK->isAlias()) 
    {
      if ($argsize > 1) {
?>
      $<?php echo $varName ?> =& <?php echo $className ?>Peer::retrieve<?php echo $className ?>ByPK(<?php echo $arglist ?>);
<?php
      } else { 
?>
      $<?php echo $varName ?> =& <?php echo $className ?>Peer::retrieve<?php echo $className ?>ByPK(<?php echo $arglist ?>);
<?php    
      } /* if ($argsize > 1) */
    } 
    else 
    {
      if ($argsize > 1) {
?>
      $<?php echo $varName ?> =& <?php echo $className ?>Peer::retrieveByPK(<?php echo $arglist ?>);
<?php
      } else { 
?>
      $<?php echo $varName ?> =& <?php echo $className ?>Peer::retrieveByPK(<?php echo $arglist ?>);
<?php 
      }
    } // if tblFK->isAlias
?>
      if (Propel::isError($<?php echo $varName ?>)) { return $<?php echo $varName ?>; }

      $this-><?php echo $varName ?> =& $<?php echo $varName ?>;

      /* The following can be used instead of the line above to
         guarantee the related object contains a reference
         to this object, but this level of coupling
         may be undesirable in many circumstances.
         As it can lead to a db query with many results that may
         never be used.
         $obj = <?php echo $className ?>Peer::retrieveByPK(<?php echo $arglist ?>);
         $obj->add<?php echo $pCollName ?>($this);
       */
    }

    return $this-><?php echo $varName ?>;
  }

  /**
  * Provides convenient way to set a relationship based on a
  * key.  e.g.
  * <code>$bar->setFooKey($foo->getPrimaryKey())</code>
  *
<?php 
    if (count($fk->getLocalColumns()) > 1) { 
?>
  * Note: It is important that the xml schema used to create this class
  * maintains consistency in the order of related columns between
  * <?php echo $table->getName() ?> and <?php echo $tblFK->getName() ?>.
  * If for some reason this is impossible, this method should be
  * overridden in <code><?php echo $table->getPhpName() ?></code>.
<?php 
    } 
?>
  * @return void
  * @throws PropelException
  */
  function set<?php echo $pVarName ?>Key($key)
  {
<?php 
    if (count($fk->getLocalColumns()) > 1) 
    {
      $i = 0;
      foreach ($fk->getLocalColumns() as $colName) 
      {
        $col = $table->getColumn($colName);
        $fktype = $col->getPhpNative();
?>
    $this->set<?php echo $col->getPhpName() ?>( (<?php echo $fktype ?>) $key[<?php echo $i ?>] );
<?php
        $i++;
      } /* foreach */
    } else {
      $lcols = $fk->getLocalColumns();
      $colName = $lcols[0];
      $col = $table->getColumn($colName);
      $fktype = $col->getPhpNative();
?>
    $this->set<?php echo $col->getPhpName() ?>( (<?php echo $fktype ?>) $key);
<?php 
    } 
?>
  }

<?php 
  } /*  end of foreach loop over foreign keys */

  //
  // setup foreign key associations
  //
  foreach ($table->getReferrers() as $fk) 
  {
    $tblFK = $fk->getTable();
    $tblFKPackage = ($tblFK->getPackage() ? $tblFK->getPackage() : $package);
    $tblFKPackagePath = strtr($tblFKPackage, '.', '/');
    if ($tblFKPackagePath != "") {
        $tblFKPackagePath .= '/';
    }

    $className = $tblFK->getPhpName();
    $relatedByCol = "";
    foreach ($fk->getLocalColumns() as $columnName) {
      $column = $tblFK->getColumn($columnName);
      if ($column->isMultipleFK() || $tblFK->getName() == $table->getName()) {
        // if there are seeral foreign keys that point to the same table
        // then we need to generate methods like getAuthorRelatedByColName()
        // instead of just getAuthor().  Currently we are doing the same
        // for self-referential foreign keys, to avoid confusion.
        $relatedByCol .= $column->getPhpName();
      }
    }

    if ($relatedByCol == "") {
      $suffix = "";
      $relCol = $className . "s";
      $relColMs = $className;
    } else {
      $suffix = "RelatedBy" . $relatedByCol;
      $relCol= $className . "sRelatedBy" . $relatedByCol;
      $relColMs= $className . "RelatedBy" . $relatedByCol;
    }
    $collName = "coll" . $relCol;
?>
  /**
  * Collection to store aggregation of <?php echo $collName ?>
  * @var array
  */
  var $<?php echo $collName ?>;

  /**
  * Temporary storage of <?php echo $collName ?> to save a possible db hit in
  * the event objects are add to the collection, but the
  * complete collection is never requested.
  * @return void
  */
  function init<?php echo $relCol ?>()
  {
    if ($this-><?php echo $collName ?> === null) {
      $this-><?php echo $collName ?> = array();
    }
  }

  /**
  * Method called to associate a <?php echo $tblFK->getPhpName() ?> object to this object
  * through the <?php echo $className ?> foreign key attribute
  *
  * @param <?php echo $className ?> $l $className
  * @return void
  * @throws PropelException
  */
  function add<?php echo $relColMs ?>(/*<?php echo $className ?>*/ &$l)
  {
    $this-><?php echo $collName ?>[] =& $l;
    $l->set<?php echo $table->getPhpName() . $suffix ?>($this);
  }

  /**
  * The criteria used to select the current contents of <?php echo $collName ?>.
  * @var Criteria
  */
  var $last<?php echo $relCol ?>Criteria = null;

	/**
	 * Returns the number of related <?php echo $relCol ?>
	 *
	 * @param Criteria $criteria
	 * @param boolean $distinct
	 * @throws PropelException
	 */
	function count<?php echo $relCol ?>($criteria = null, $distinct = false)
	{
		// include the Peer class
		include_once '<?php echo $tblFKPackagePath . $className ?>Peer.php';
		if ($criteria === null) {
			$criteria = new Criteria();
		}
<?php
	foreach ($fk->getForeignColumns() as $columnName) {
		$column = $table->getColumn($columnName);
		// used to be getLocalForeignMapping() but that didn't seem to work
		// (maybe a problem in translation of HashTable code to PHP).
		$flmap = $fk->getForeignLocalMapping();
		$colFKName = $flmap[$columnName];
		$colFK = $tblFK->getColumn($colFKName);
?>
		$criteria->add(<?php echo PeerBuilder::getColumnName($colFK, $className) ?>(), $this->get<?php echo $column->getPhpName() ?>() );
<?php
	} // end foreach ($fk->getForeignColumns()
?>
		return <?php echo $className ?>Peer::doCount($criteria, $distinct);
	}

  /**
  * If this collection has already been initialized with
  * an identical criteria, it returns the collection.
  * Otherwise if this <?php echo $table->getPhpName() ?> has previously
  * been saved, it will retrieve related ${relCol} from storage.
  * If this <?php echo $table->getPhpName() ?> is new, it will return
  * an empty collection or the current collection, the criteria
  * is ignored on a new object.
  *
  * @param Criteria $criteria
  * @throws PropelException
  */
  function & get<?php echo $relCol ?>($criteria = null)
  {
    // include the Peer class
    include_once '<?php echo $tblFKPackagePath . $className ?>Peer.php';

    if ($criteria === null) {
      $criteria = new Criteria();
    }

    if ($this-><?php echo $collName ?> === null)
    {
      if ($this->isNew()) {
        $this-><?php echo $collName ?> = array();
      } else {
<?php
    foreach ($fk->getForeignColumns() as $columnName)
    {
      $column = $table->getColumn($columnName);
      // used to be getLocalForeignMapping() but that didn't seem to work
      // (maybe a problem in translation of HashTable code to PHP).
      $flmap = $fk->getForeignLocalMapping();
      $colFKName = $flmap[$columnName];
      $colFK = $tblFK->getColumn($colFKName);
?>
        $criteria->add(<?php echo PeerBuilder::getColumnName($colFK, $className) ?>(), $this->get<?php echo $column->getPhpName() ?>() );
<?php 
    } /* end foreach ($fk->getForeignColumns()) */
?>

        $<?php echo $collName ?> =& <?php echo $className ?>Peer::doSelect($criteria);
        if (Propel::isError($<?php echo $collName ?>)) { return $<?php echo $collName ?>; }

        $this-><?php echo $collName ?> =& $<?php echo $collName ?>;
      }
    } else {
      // criteria has no effect for a new object
      if (!$this->isNew())
      {
        // the following code is to determine if a new query is
        // called for.  If the criteria is the same as the last
        // one, just return the collection.
<?php
    foreach ($fk->getForeignColumns() as $columnName)
    {
      $column = $table->getColumn($columnName);
      $flmap = $fk->getForeignLocalMapping();
      $colFKName = $flmap[$columnName];
      $colFK = $tblFK->getColumn($colFKName);
?>
        $criteria->add(<?php echo PeerBuilder::getColumnName($colFK, $className) ?>(), $this->get<?php echo $column->getPhpName() ?>());

<?php 
    } /* end foreach ($fk->getForeignColumns()) */
?>
        if (!isset($this->last<?php echo $relCol ?>Criteria) || !$this->last<?php echo $relCol ?>Criteria->equals($criteria))
        {
          $<?php echo $collName ?> =& <?php echo $className ?>Peer::doSelect($criteria);
          if (Propel::isError($<?php echo $collName ?>)) { return $<?php echo $collName ?>; }

          $this-><?php echo $collName ?> =& $<?php echo $collName ?>;
        }
      }
    }

    $this->last<?php echo $relCol ?>Criteria = $criteria;

    return $this-><?php echo $collName ?>;
  }

<?php
    $countFK = 0;
    foreach ($tblFK->getForeignKeys() as $dummyFK) {
      $countFK = $countFK + 1;
    }

// ------------------------------------------------------------
//
    if ($countFK >= 1)
    {
      $lastTable = "";
      foreach ($tblFK->getForeignKeys() as $fk2)
      {
        // Add join methods if the fk2 table is not this table or
        // the fk2 table references this table multiple times.

        $doJoinGet = true;
        if ( $fk2->getForeignTableName() == $table->getName() ) {
          $doJoinGet = false;
        }

        foreach ($fk2->getLocalColumns() as $columnName) {
          $column = $tblFK->getColumn($columnName);
          if ($column->isMultipleFK()) {
            $doJoinGet = true;
          }
        }

        $tblFK2 = $table->getDatabase()->getTable($fk2->getForeignTableName());
        $doJoinGet = !$tblFK2->isForReferenceOnly();
        $relatedByCol2 = "";
        foreach ($fk2->getLocalColumns() as $columnName) {
          $column = $tblFK->getColumn($columnName);
          if ($column->isMultipleFK()) {
            $relatedByCol2 .= $column->getPhpName();
          }
        }

        $fkClassName = $tblFK2->getPhpName();

        // do not generate code for self-referencing fk's, it would be
        // good to do, but it is just not implemented yet.
        if ($className == $fkClassName) {
          // $doJoinGet = false;  -- SELF REFERENCING FKs UNDER TESTING
        }

        if ($relatedByCol2 == "") {
          $relCol2 = $fkClassName;
        } else {
          $relCol2 = $fkClassName . "RelatedBy". $relatedByCol2;
        }

        if ( $relatedByCol == "") {
          // nothing?
        } else {
          if ( $relatedByCol == $relatedByCol2 ) {
            $doJoinGet = false;
          }
        }

        if ($doJoinGet)
        {
?>
  /**
  * If this collection has already been initialized with
  * an identical criteria, it returns the collection.
  * Otherwise if this <?php echo $table->getPhpName() ?> is new, it will return
  * an empty collection; or if this <?php echo $table->getPhpName() ?> has previously
  * been saved, it will retrieve related <?php echo $relCol ?> from storage.
  *
  * This method is protected by default in order to keep the public
  * api reasonable.  You can provide public methods for those you
  * actually need in <?php echo $table->getPhpName() ?>.
  */
  function & get<?php echo $relCol ?>Join<?php echo $relCol2 ?>($criteria = null)
  {
    // include the Peer class
    include_once '<?php echo $tblFKPackagePath . $className ?>Peer.php';

    if ($criteria === null) {
      $criteria = new Criteria();
    }
    
    if ($this-><?php echo $collName ?> === null) {
      if ($this->isNew()) {
         $this-><?php echo $collName ?> = array();
      } else {
<?php 
          foreach ($fk->getForeignColumns() as $columnName)
          {
            $column = $table->getColumn($columnName);
            $flMap = $fk->getForeignLocalMapping();
            $colFKName = $flMap[$columnName];
            $colFK = $tblFK->getColumn($colFKName);
?>
        $criteria->add(<?php echo PeerBuilder::getColumnName($colFK, $className) ?>(), $this->get<?php echo $column->getPhpName() ?>());
<?php 
          } /* end foreach ($fk->getForeignColumns()) */
?>

        $<?php echo $collName ?> =& <?php echo $className ?>Peer::doSelectJoin<?php echo $relCol2 ?>($criteria);
        if (Propel::isError($<?php echo $collName ?>)) { return $<?php echo $collName ?>; }

        $this-><?php echo $collName ?> =& $<?php echo $collName ?>;
      }
    } else {
      // the following code is to determine if a new query is
      // called for.  If the criteria is the same as the last
      // one, just return the collection.
<?php
          foreach ($fk->getForeignColumns() as $columnName)
          {
            $column = $table->getColumn($columnName);
            $flMap = $fk->getForeignLocalMapping();
            $colFKName = $flMap[$columnName];
            $colFK = $tblFK->getColumn($colFKName);
?>
      $criteria->add(<?php echo PeerBuilder::getColumnName($colFK, $className) ?>(), $this->get<?php echo $column->getPhpName() ?>());

<?php 
          } /* end foreach ($fk->getForeignColumns()) */
?>
      if (!isset($this->last<?php echo $relCol ?>Criteria) || !$this->last<?php echo $relCol ?>Criteria->equals($criteria))
      {
        $<?php echo $collName ?> =& <?php echo $className ?>Peer::doSelectJoin<?php echo $relCol2 ?>($criteria);
        if (Propel::isError($<?php echo $collName ?>)) { return $<?php echo $collName ?>; }

        $this-><?php echo $collName ?> =& $<?php echo $collName ?>;
      }
    }
    $this->last<?php echo $relCol ?>Criteria = $criteria;

    return $this-><?php echo $collName ?>;
  }
  
<?php 
        } /* end if($doJoinGet) */
      } /* end foreach ($tblFK->getForeignKeys() as $fk2) {*/
    } /* if countFK >= 1 */
  } /*ends foreach over table->getReferrers() */
} /* the if(complexObjectModel) */

//
// add GenericAccessors or GenericMutators?
//
if (!$table->isAlias() && ($addGenericAccessors || ($addGenericMutators && !$table->isReadOnly())))
{
	$tableColumns = $table->getColumns();
	$tablePhpname = $table->getPhpName();
?>
  /**
   * Generate a list of field names.
   *
   * @return array A list of field names
   */
  function & getFieldNames($type = TYPE_FIELDNAME)
  {
    static $fieldNames = array(
      TYPE_PHPNAME => array (<?php foreach ($tableColumns as $col) { ?>'<?php echo $col->getPhpName(); ?>', <?php } ?>),
      TYPE_COLNAME => array (<?php foreach ($tableColumns as $col) { ?>'<?php echo $table->getName() . '.' . strtoupper($col->getName()) ?>', <?php } ?>),
      TYPE_FIELDNAME => array (<?php foreach ($tableColumns as $col) { ?>'<?php echo $col->getName(); ?>', <?php } ?>),
      TYPE_NUM => array (<?php foreach ($tableColumns as $num => $col) { echo $num; ?>, <?php } ?>)
    );
	
    if (!isset($fieldNames[$type])) {
      return new PropelException('Method getFieldNames() expects the parameter $type to be one of the class constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM. ' . $type . ' was given.');
    }
	
    return $fieldNames[$type];
  }
  
  /**
   * Translates a fieldname to another type
   *
   * @param string $name field name
   * @param string $fromType One of the class type constants TYPE_PHPNAME,
   *                         TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
   * @param string $toType   One of the class type constants
   * @return string translated name of the field.
   */
  function translateFieldName($name, $fromType, $toType)
  {
    static $fieldKeys = array (
      TYPE_PHPNAME => array (<?php foreach ($tableColumns as $num => $col) { ?>'<?php echo $col->getPhpName(); ?>' => <?php echo $num; ?>, <?php } ?>),
      TYPE_COLNAME => array (<?php foreach ($tableColumns as $num => $col) { ?>'<?php echo $table->getName() . '.' . strtoupper($col->getName()) ?>' => <?php echo $num; ?>, <?php } ?>),
      TYPE_FIELDNAME => array (<?php foreach ($tableColumns as $num => $col) { ?>'<?php echo $col->getName(); ?>' => <?php echo $num; ?>, <?php } ?>),
      TYPE_NUM => array (<?php foreach ($tableColumns as $num => $col) { echo $num; ?>, <?php } ?>)
    );

    $toNames =& $this->getFieldNames($toType);
    $key = $fieldKeys[$fromType][$name];
	
    if ($key === false) {
      return new PropelException("'$name' could not be found in the field names of type '$fromType'. These are: " . print_r($fromNames, true));
    }
	
    return $toNames[$key];
  }
<?php if ($addGenericAccessors) { ?>

  /**
   * Retrieves a field from the object by name passed in as a string.
   *
   * @param string $name name
   * @param string $type The type of fieldname the $name is of:
   *                     one of the class type constants TYPE_PHPNAME,
   *                     TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
   * @return mixed Value of field.
   */
  function & getByName($name, $type = TYPE_COLNAME)
  {
    $pos = $this->translateFieldName($name, $type, TYPE_NUM);
    return $this->getByPosition($pos);
  }

  /**
   * Retrieves a field from the object by Position as specified
   * in the xml schema.  Zero-based.
   *
   * @param int $pos position in xml schema
   * @return mixed Value of field at $pos
   */
  function & getByPosition($pos)
  {
    switch($pos) 
    {
<?php
      $i = 0;
      foreach ($table->getColumns() as $col) 
      {
        $cfc = $col->getPhpName();
        $cptype = $col->getPhpNative();// not safe to use it because some methods may return objects (Blob)
?>
      case <?php echo $i ?>:
        return $this->get<?php echo $cfc ?>();
        break;
<?php
        $i++;
      } /* foreach */
?>
      default:
        return null;
    } // switch()
  }

  /**
   * Exports the object as an array.
   *
   * You can specify the key type of the array by passing one of the class
   * type constants.
   *
   * @param string $keyType One of the class type constants TYPE_PHPNAME,
   *                        TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
   * @return an associative array containing the field names (as keys) and field values
   */
  function & toArray($keyType = TYPE_PHPNAME)
  {
    $keys =& $this->getFieldNames($keyType);
    $result = array(
<?php
	  foreach ($table->getColumns() as $num => $col) {
?>
      $keys[<?php echo $num ?>] => $this->get<?php echo $col->getPhpName() ?>(),
<?php
	  } /* foreach */
?>
    );
    return $result;
  }

<?php } /* ends the if($addGenericAccessors) */ ?>


<?php if ($addGenericMutators && !$table->isReadOnly()) { ?>

  /**
   * Sets a field value from the object by name passed in as a string.
   *
   * @param string $name peer name
   * @param mixed $value field value
   * @param string $type The type of fieldname the $name is of:
   *                     one of the class type constants TYPE_PHPNAME,
   *                     TYPE_COLNAME, TYPE_FIELDNAME, TYPE_NUM
   * @return void
   */
  function setByName($name, &$value, $type = TYPE_COLNAME)
  {
    $names =& $this->getFieldnames($type);
    $pos = array_search($name, $names);
    return $this->setByPosition($pos, $value);
  }
  
  /**
   * Sets a field from the object by Position as specified
   * in the xml schema.  Zero-based.
   *
   * @param int $pos position in xml schema
   * @param mixed $value field value
   * @return void
   */
  function setByPosition($pos, &$value)
  {
    switch($pos) 
    {
<?php
    $i = 0;
    foreach ($table->getColumns() as $col) 
    {
      $cfc = $col->getPhpName();
      $cptype = $col->getPhpNative();
?>
      case <?php echo $i ?>:
          $this->set<?php echo $cfc ?>($value);
          break;
<?php
      $i++;
    } /* foreach */
?>
    } // switch()
  }

  /**
   * Populates the object using an array.
   *
   * This is particularly useful when populating an object from one of the
   * request arrays (e.g. $_POST).  This method goes through the column
   * names, checking to see whether a matching key exists in populated
   * array. If so the setByName() method is called for that column.
   *
   * You can specify the key type of the array by additionally passing one
   * of the class type constants TYPE_PHPNAME, TYPE_COLNAME, TYPE_FIELDNAME,
   * TYPE_NUM. The default key type is the (peer) column name (e.g.
   * 'book.AUTHOR_ID')
   *
   * @param array  $arr     An array to populate the object from.
   * @param string $keyType The type of keys the array uses.
   * @return void
   */
  function fromArray(&$arr, $keyType = TYPE_COLNAME)
  {
    $keys =& $this->getFieldNames($keyType);
<?php
    foreach ($table->getColumns() as $num => $col) {
	  $cfc = $col->getPhpName();
	  $cptype = $col->getPhpNative();
?>
    if (array_key_exists($keys[<?php echo $num ?>], $arr)) $this->set<?php echo $cfc ?>($arr[$keys[<?php echo $num ?>]]);
<?php
    } /* foreach */
?>
  }

<?php } /* ends the if($addGenericMutators) */
    } /* ends the if($addGenericAccessors || $addGenericMutators) */
?>

<?php if (! $table->isAlias() && isset($addSaveMethod) && $addSaveMethod && ! $table->isReadOnly()) { ?>

  /**
  * Removes this object from datastore and sets delete attribute.
  *
  * @return mixed TRUE on success, PropelException on failure.
  * @throws PropelException
  * @see BaseObject::setDeleted()
  * @see BaseObject::isDeleted()
  */
  function delete()
  {
    if ($this->isDeleted()) {
      return new PropelException(PROPEL_ERROR, "This object has already been deleted.");
    }

    $con =& Propel::getConnection(<?php echo $table->getPhpName() ?>Peer::DATABASE_NAME());
    if (Propel::isError($con)) { return $con; }

    $e = $con->begin();
    if (Creole::isError($e)) { $con->rollback(); return new PropelException(PROPEL_ERROR_DB, $e); }

    $e = <?php echo $table->getPhpName() ?>Peer::doDelete($this, Param::set($con));
    if (Propel::isError($e)) { $con->rollback(); return $e; }

    $this->setDeleted(true);

    $e = $con->commit();
    if (Creole::isError($e)) { $con->rollback(); return new PropelException(PROPEL_ERROR_DB, $e); }

    return true;
  }

<?php
  if ($complexObjectModel) 
  { 
?>

  /**
  * flag to prevent endless save loop, if this object is referenced
  * by another object which falls in this transaction.
  * @var boolean
  */
  var $alreadyInSave = false;

  /**
  * Stores the object in the database.  If the object is new,
  * it inserts it; otherwise an update is performed.  This method
  * wraps the doSave() worker method in a transaction.
  *
  * @return mixed TRUE on success, PropelException on failure.
  */
  function save()
  {
    if ($this->isDeleted()) {
      return new PropelException(PROPEL_ERROR, "You cannot save an object that has been deleted.");
    }

    $con =& Propel::getConnection(<?php echo $table->getPhpName() ?>Peer::DATABASE_NAME());
    if (Propel::isError($con)) { return $con; }

    $e = $con->begin();
    if (Creole::isError($e)) { $con->rollback(); return new PropelException(PROPEL_ERROR_DB, $e); }

    $e = $this->doSave(Param::set($con));
    if (Propel::isError($e)) { $con->rollback(); return $e; }

    $e = $con->commit();
    if (Creole::isError($e)) { $con->rollback(); return new PropelException(PROPEL_ERROR_DB, $e); }

    return true;
  }
<?php 
  } /* if($complexObjectModel) */ 
?>

  /**
  * Stores the object in the database.  If the object is new,
  * it inserts it; otherwise an update is performed.
  *
  * @return void
  * @throws PropelException
  */
<?php 
  if ($complexObjectModel) 
  { 
?>
  function doSave($con = null)
<?php 
  } else { 
?>
  function save()
<?php 
  }
?>
  {
<?php 
  if(! $complexObjectModel) 
  { 
?>    if ($this->isDeleted()) {
      return new PropelException(PROPEL_ERROR, "You cannot save an object that has been deleted.");
    }

    $con =& Propel::getConnection(<?php echo $basePrefix . $table->getPhpName() ?>Peer::DATABASE_NAME());
    if (Propel::isError($con)) { return $con; }

<?php 
  }

  if ($complexObjectModel) 
  { 
?>
    /* [MA] temporarily check */
    Propel::assertParam($con, '<?php echo $table->getPhpName(); ?>', 'save', 1);

    if (! $this->alreadyInSave) {
      $this->alreadyInSave = true;

<?php 
    if ( ! empty($pVars)) 
    { 
?>
      // We call the save method on the following object(s) if they
      // were passed to this object by their coresponding set
      // method.  This object relates to these object(s) by a
      // foreign key reference.
<?php
      for($i=0,$_i=count($aVars); $i < $_i; $i++) 
      {
        $aVarName = $aVars[$i];
?>
      if ($this-><?php echo $aVarName ?> !== null) {
        if ($this-><?php echo $aVarName ?>->isModified()) {
          if (Propel::isError($e = $this-><?php echo $aVarName ?>->save())) {
              return $e;
          }
        }
        $this->set<?php echo $pVars[$i] ?>($this-><?php echo $aVarName ?>);
      }

<?php 
      } /* foreach */ 
    } /* if count(pVars) */ 
  } /* if complexObjectMode */ 
?>
      // If this object has been modified, then save it to the database.
      if ($this->isModified()) {
        if ($this->isNew()) {
          $pk = <?php echo $table->getPhpName() ?>Peer::doInsert($this, <?php if($complexObjectModel) {?>$con<?php } else { ?>Param::set($con)<?php } ?>);
          if (Propel::isError($pk)) { return $pk; }
<?php 
  if ($table->getIdMethod() != "none") {
    if (count($pks = $table->getPrimaryKey())) {
      foreach ($pks as $pk) {
        if ($pk->isAutoIncrement()) {
?>
          $this->set<?php echo $pk->getPhpName();?>( $pk );  //[IMV] update autoincrement primary key
<?php
        }
      }
    }
  }
?>
          $this->setNew(false);
        }
        else {
          $e = <?php echo $table->getPhpName() ?>Peer::doUpdate($this, <?php if($complexObjectModel) {?>$con<?php } else { ?>Param::set($con)<?php } ?>);
          if (Propel::isError($e)) { return $e; }
        }
        $this->resetModified(); // [HL] After being saved an object is no longer 'modified'
      }

<?php
  if ($complexObjectModel) 
  {
    foreach ($table->getReferrers() as $fk) 
    {
      $tblFK = $fk->getTable();
      if ( $tblFK->getName() != $table->getName() ) 
      {
        $className = $tblFK->getPhpName();
        $relCol = "";
        foreach ($fk->getLocalColumns() as $columnName) {
          $column = $tblFK->getColumn($columnName);
          if ($column->isMultipleFK()) {
            $relCol .= $column->getPhpName();
          }
        }
  
        if ($relCol == "") {
          $relCol = $className . "s";
        } else {
          $relCol = $className . "sRelatedBy" . $relCol;
        }
  
        $collName = "coll" . $relCol;
?>
      if ($this-><?php echo $collName ?> !== null) {
        for ($i=0,$size=count($this-><?php echo $collName ?>); $i < $size; $i++) {
          if (Propel::isError($e = $this-><?php echo $collName ?>[$i]->save())) {
            return $e;
          }
        }
      }

<?php
      } /* if tableFK !+ table */
    } /* foreach getReferrers() */
  } /* if complexObjectModel */

  if ($complexObjectModel) 
  { 
?>
      $this->alreadyInSave = false;
    }

<?php 
  } /* if ($complexObjectModel) */
?>
    return true;
  }

<?php 
} /* if !table->isAlias && isset .... */ 

if (! $table->isAlias() && ! $table->isReadOnly()) 
{ 
?>
  /**
  * Validates the objects modified field values.
<?php 
  if ($complexObjectModel) 
  {
?>
  * This includes all objects related to this table.
<?php 
  } /* if ($complexObjectModel) */
?>
  *
  * If $columns is either a column name or an array of column names
  * only those columns are validated.
  *
  * @param mixed $columns Column name or an array of column names.
  *
  * @return mixed <code>true</code> if all columns pass validation
  *               or an array of <code>ValidationFailed</code> objects for columns that fail.
  */
  function & validate($columns = null)
  {
    if ($columns)
    {
      return <?php echo $table->getPhpName()?>Peer::doValidate($this, $columns);
    }

<?php 
  if (! $complexObjectModel) 
  { 
?>
    return <?php echo $table->getPhpName()?>Peer::doValidate($this);
<?php 
  } else { 
?>
    return $this->doValidate();
<?php 
  } /* if (! $complexObjectModel) */ 
?>
  }

<?php   
  if ($complexObjectModel) 
  { 
?>
  /**
  * flag to prevent endless validation loop, if this object is referenced
  * by another object which falls in this transaction.
  * @var boolean
  */
  var $alreadyInValidation = false;

  /**
  * This function performs the validation work for complex object models.
  *
  * In addition to checking the current object, all related objects will
  * also be validated.  If all pass then <code>true</code> is returned; otherwise
  * an aggreagated array of ValidationFailed objects will be returned.
  *
  * @return mixed <code>true</code> if all validations pass; array of <code>ValidationFailed</code> objets otherwise.
  */
  function & doValidate()
  {
    if (! $this->alreadyInValidation)
    {
      $this->alreadyInValidation = true;
      $retval = null;
      $failureMap = array();

<?php 
    if (count($pVars) != 0) 
    { 
?>
      // We call the validate method on the following object(s) if they
      // were passed to this object by their coresponding set
      // method.  This object relates to these object(s) by a
      // foreign key reference.
<?php
      for($i=0,$_i=count($aVars); $i < $_i; $i++) 
      {
        $aVarName = $aVars[$i];
?>
      if ($this-><?php echo $aVarName ?> !== null) {
        if (($retval = $this-><?php echo $aVarName ?>->validate()) !== true) {
          $failureMap = array_merge($failureMap, $retval);
        }
      }
<?php   
      } /* for */ 
    } /* if count(pVars) */ 
?>

      if (($retval = <?php echo $table->getPhpName()?>Peer::doValidate($this)) !== true) {
        $failureMap = array_merge($failureMap, $retval);
      }

<?php
    foreach ($table->getReferrers() as $fk) 
    {
      $tblFK = $fk->getTable();
      if ( $tblFK->getName() != $table->getName() ) 
      {
        $className = $tblFK->getPhpName();
        $relCol = "";
        foreach ($fk->getLocalColumns() as $columnName) {
          $column = $tblFK->getColumn($columnName);
          if ($column->isMultipleFK()) {
              $relCol .= $column->getPhpName();
          }
        }

        if ($relCol == "") {
          $relCol = $className . "s";
        } else {
          $relCol = $className . "sRelatedBy" . $relCol;
        }

        $collName = "coll" . $relCol;
?>
      if ($this-><?php echo $collName ?> !== null) {
        for ($i=0,$size=count($this-><?php echo $collName ?>); $i < $size; $i++) {
          if (($retval = $this-><?php echo $collName ?>[$i]->validate()) !== true) {
            $failureMap = array_merge($failureMap, $retval);
          }
        }
      }
<?php    
      } /* if tableFK !+ table */
    } /* foreach getReferrers() */
?>

      $this->alreadyInValidation = false;
      return (!empty($failureMap) ? $failureMap : true);
    }

    return true;
  }

<?php   
  } /* complexObjectModel */ 
} /* ! isAlias */ 

// PrimaryKey methods
if (!$table->isAlias()) 
{
  if (! $table->isReadOnly())
  {
    $throwsClause = "@throws PropelException";
    if (count($table->getPrimaryKey()) == 1) 
    {
      $pkeys = $table->getPrimaryKey();
      $col = $pkeys[0];
      $clo=strtolower($col->getName());
      $cptype= $col->getPhpNative();
?>
  /**
  * Set the PrimaryKey.
  *
  * @param mixed <?php echo $clo ?> Primary key.
  * @return void
  * <?php echo $throwsClause ?>
  */
  function setPrimaryKey($key)
  {
    $this->set<?php echo $col->getPhpName() ?>($key);
  }

<?php     
    } 
    elseif (count($table->getPrimaryKey()) > 1) 
    { 
?>
  var $pks = array();

  /**
  * Set the PrimaryKey.
  *
  * @param array $keys The elements of the composite key (order must match the order in XML file).
  * @return void
  * @throws PropelException
  */
  function setPrimaryKey($keys)
  {
<?php
      $i = 0;
      foreach ($table->getPrimaryKey() as $pk) 
      {
        $pktype = $pk->getPhpNative(); 
?>
    $this->set<?php echo $pk->getPhpName() ?>($keys[<?php echo $i ?>]);
<?php
        $i++;
      } /* foreach ($table->getPrimaryKey() as $pk) */
?>
  }

<?php 
    } else { /* if (count($table->getPrimaryKey()) == 1) */ 
?>

  /**
  * Dummy primary key setter.
  * For now this function needs to exist because it's mandated in the Persistent
  * interface, and because other methods will attempt to set the primary key.
  *
  * This should be removed in favor of more complex template work.
  */
  function setPrimaryKey($pk)
  {
    // do nothing, because this doesn't support primary keys
  }
<?php 
    } /* if (count($table->getPrimaryKey()) == 1) */
  } /* if ! $table->isReadOnly() */
?>

  /**
  * Returns an id that differentiates this object from others
  * of its class.
  * @return <?php if (count($table->getPrimaryKey()) === 0) { echo "null"; } elseif (count($table->getPrimaryKey()) > 1) { echo "array"; } else { $pkeys = $table->getPrimaryKey(); echo $pkeys[0]->getPhpType(); } ?>
  */
  function getPrimaryKey()
  {
<?php 
  if (count($table->getPrimaryKey()) == 1) { 
?>
    return $this->get<?php $pkeys = $table->getPrimaryKey(); echo $pkeys[0]->getPhpName()?>();
<?php 
  } 
  elseif (count($table->getPrimaryKey()) > 1) {
    $i = 0;
    foreach ($table->getPrimaryKey() as $pk) { 
?>
    $this->pks[<?php echo $i ?>] = $this->get<?php echo $pk->getPhpName() ?>();
<?php
      $i++;
    } /* foreach ($table->getPrimaryKey() as $pk) */
?>
    return $this->pks;
<?php 
  } else { 
?>

    return null;
<?php 
  } 
?>
  }

<?php 
  if (! $table->isAbstract()) 
  { 
?>
  /**
  * Makes a copy of this object.
  * It creates a new object filling in the simple attributes, but skipping any primary
  * keys that are defined for the table.
  * 
<?php 
    if ($complexObjectModel) 
    { 
?>
  * If desired, this method can also make copies of all associated (fkey referrers)
  * objects.
  *
  * @param boolean $deepCopy Whether to also copy all rows that refer (by fkey) to the current row.
  * 
<?php 
    } 
?>
  * @return <?php echo $table->getPhpName() ?> Clone of current object.
  * @throws PropelException
  */
  function copy(<?php if ($complexObjectModel) { ?>$deepCopy = false<?php } ?>) 
  {
    $copyObj = new <?php echo $table->getPhpName() ?>();
<?php

    $pkcols = array();
    foreach ($table->getColumns() as $pkcol) {
      if ($pkcol->isPrimaryKey()) { 
        $pkcols[] = $pkcol->getName(); 
      }
    }

    foreach ($table->getColumns() as $col) 
    {
      if (!in_array($col->getName(), $pkcols)) {
?>
    $copyObj->set<?php echo $col->getPhpName()?>($this-><?php echo strtolower($col->getName()) ?>);
<?php
      }
    }

    if ($complexObjectModel) 
    {
      // Avoid useless code by checking to see if there are any referrers
      // to this table:
      if (count($table->getReferrers()) > 0) 
      {
?>

    if ($deepCopy) {        
      // important: setNew(false) because this affects the behavior of
      // the getter/setter methods for fkey referrer objects.
      $copyObj->setNew(false);
<?php
        foreach ($table->getReferrers() as $fk) 
        {
          $tblFK = $fk->getTable();
          if ( $tblFK->getName() != $table->getName() ) 
          {
            $className = $tblFK->getPhpName();
            $relCol = "";
            foreach ($fk->getLocalColumns() as $columnName) {
              $column = $tblFK->getColumn($columnName);
              if ($column->isMultipleFK()) {
                $relCol .= $column->getPhpName();
              }
            }

            if ($relCol == "") {
              $pCollName = $className . "s";
              $pCollNameNoS = $className;
            } else {
              $pCollName = $className . "sRelatedBy".$relCol;
              $pCollNameNoS = $className . "RelatedBy".$relCol;
            }
?>

      foreach($this->get<?php echo $pCollName ?>() as $relObj) {
        $copyObj->add<?php echo $pCollNameNoS ?>($relObj->copy());
      }
<?php
          } /* if tblFK != table */
        } /* foreach */ 
?>
    } /* if ($deepCopy) */
<?php            
      } /* if (count referrers > 0 ) */
?>
    
    $copyObj->setNew(true);
<?php 
    } /* if complex object model */

    // this is a little redundant, but it's clearer than re-using
    // the $pkcols array  we created above
    foreach ($table->getColumns() as $col) 
    {
      if ($col->isPrimaryKey()) 
      {
        $coldefval = $col->getDefaultValue();
        // This seems to work pretty well for getting
        // the right value (including NULL)
        $coldefval = var_export($coldefval, true);
?>
    $copyObj->set<?php echo $col->getPhpName()?>(<?php echo $coldefval ?>); // this is a pkey column, so set to default value
<?php
      } // if col->isPrimaryKey
    } // foreach
?>

    return $copyObj;
  }

<?php 
  } /* if (! $table->isAbstract()) */ 
?>
  /**
  * Returns a peer instance associated with this om.  Since Peer classes
  * are not to have any instance attributes, this method returns the
  * same instance for all member of this class. The method could therefore
  * be static, but this would prevent one from overriding the behavior.
  *
  * @return <?php echo $table->getPhpName() ?>Peer
  */
  function & getPeer()
  {
    static $instance;

    if ($instance === null) {
      $instance = new <?php echo $table->getPhpName()?>Peer();
    }

    return $instance;
  }
<?php 
} /* if !table->isAlias */ 
?>

}
