Symfony 1.4+Doctrineで、admin generatorな環境です。editなど、自動生成なので、どこをオーバーライドすれば目的の動作になるのかわかりにくいことがありますね。
例えば、あるモデルのステータスを変更すると同時に、他のモデルに対しても操作したい場合があるとします。
まぁ、mergeFormとかembedFormとか使ってもいいのですが、今回は他テーブルのプライマリキーをフォームから選択させたかったので、汎用性のあるdoSaveでの処理を追加してみました。
symfony Forms in Action | 第11章 – Doctrine との統合 | symfony | Web PHP Framework
class BackendHogeForm extends HogeForm
{
public function configure()
{
parent::configure();
// 使用するフィールドを指定
$this->useFields(array('status'));
// 別モデルのIDリストを選択するフォームを作成する
$choices = array(100 => '100:value1', 101 => '101:value2');
$this->widgetSchema['other_model_id'] = new sfWidgetFormSelect(array('choices' => $choices));
$this->validatorSchema['other_model_id'] = new sfValidatorChoice(array('choices' => array_keys($choices)));
}
protected function doSave($con = null)
{
if ($this->getValue('status') == 'DONE') {
Doctrine::getTable('OtherModel')->find($this->getValue('other_model_id'))
->setIsSelected(TRUE)
->save();
}
return parent::doSave($con);
}
}
基本的にはdoSaveをオーバーライドするだけです。ちなみにuseFieldsメソッドを使うと必要なフィールド以外を全部unsetしてくれるので便利です。
タグ: admin generator, doctrine, PHP, symfony

HOMMA Teppei

