one form - add to two tables
how can i in Symfony 1.4 and Doctrine make one form, that will add data to two tables? Default Symfony generated form for one table and module. at which point I can edit it and add their own fields? http://www.symfony-project.org/jobeet/1_4/Doctrine/en/03 generated. i would like for example add field with new category.
# config/doctrine/schema.yml
JobeetCategory:
actAs: { Timestampable: ~ }
columns:
name: { type: string(255), notnul开发者_如何学编程l: true, unique: true }
JobeetJob:
actAs: { Timestampable: ~ }
columns:
category_id: { type: integer, notnull: true }
(...)
expires_at: { type: timestamp, notnull: true }
relations:
JobeetCategory: { onDelete: CASCADE, local: category_id, foreign: id, foreignAlias: JobeetJobs }
this form add only id JobeetJob. how can i add into also JobeetCategory?
You can embed the JobeetCategory relation in the JobeetJob form. This will enable you to create a job and a category. Look for the `embedRelation()̀ method of the sfForm class.
You should override save method in your model(Lets say in JobeetJob model). And save both models in transaction. Below I save to product and composite product tables. But dont forget that save method should has 2 functionality : insert and update
public function save(Doctrine_Connection $conn = null){
try {
$conn->beginTransaction();
$isNew = $this->isNew();
parent::save($conn); #Save Product
$modelName = $this->moduleArray[$moduleName];
$productId = $this->getId();
if($isNew){ #CREATE new Composite Product and set Product ID and Module Name to it.
$cp = new CompositeProduct();
$cp->setRelatedModelID($productId);
$cp->setRelatedModelName($modelName);
$cp->setTitle($this->getTitle());
$cp->save();
}else{# UPDATE the Composite Product
$query = Doctrine_Core::getTable('CompositeProduct')
->createQuery('cp')
->where('cp.relatedmodelname = ?', $modelName)
->andWhere('cp.relatedmodelid = ?', $productId);
$cp = $query->fetchOne();
$cp->setTitle($this->getTitle());
$cp->save();
}
$conn->commit();
}catch(Doctrine_Exception $e){
$conn->rollback();
}
}
精彩评论