2012-09-04 31 views
0

我有一個基於名爲'factor'的模型類的一般形式。在這種形式下,有一個名爲'customer'的嵌入式表單,它基於名爲'customer'的模型類。如何防止symfony中的表格保存?

這裏是我的schema.yml的相關部分:

factor: 
    actAs: 
    Timestampable: ~ 
    columns: 
    customer_id: {type: bigint} 
    final_sum: {type: Integer} 
    relations: 
    customer: {local:customer_id, foreign:id, alias: customer, foreignAlias:factors} 

customer: 
    columns: 
    name: {type: string(255), notnull:true, unique:true} 

當用戶提交的一般形式,我檢查,如果在客戶表存在CUSTOMER_NAME,如果是這樣,我想嵌入的形式「顧客」不能保存,因爲它會導致列唯一性的錯誤! 相反,我應該將customer_id設置爲已存在於db中的客戶的id。 我該如何管理?

+0

推進或學說? – Soundz

+0

學說[評論必須至少15個字符長:D] – Ehsan

+0

對不起,我承認我不能幫助你的教義,但只是提到它:推動會做這種行爲隱含。如果條目存在,則更新它,如果不存在則創建它 – Soundz

回答

0

謝謝denys281和glerendegui :)

這個問題很簡單,它可以很容易地通過嵌入解封客戶的形式和更新的因素表單對象來解決。

我加入的actions.class.php文件processForm功能下面幾行:

$pFactor=$form->getObject(); 

$customer=Doctrine_Query::create()->from('customer c')->where('c.name=?',$form['customer']['name']->getValue())->execute(); 

if(!empty($cus[0])) 
{ 
    $pFactor->setCustomer($cus[0]); 
    unset($form['customer']); 
} 

$form->save(); 
+0

然後不要忘記接受你自己的答案。 – j0k

0

我建議你不要用嵌入的表單來做。取而代之的是,使用沒有customer_id(使用unset或useFields)和簡單客戶表單的簡單因子表單。 像這樣的東西在的actions.class.php:

$this->factorForm = new SimpleFactorForm; // (without customer_id) 
$this->customerForm = new CustomerForm; // 

if($request->getMethod() == sfRequest::POST) { 
    $this->factorForm->bind($request->getPostParameter($this->factorForm->getName()); 
    $this->customerForm->bind($request->getPostParameter($this->customerForm->getName()); 

    if(($this->customerForm->isValid()) && ($this->factorForm->isValid())) { 
    // customer unique validation -- create or find a uniqueCustomerObject 
    // something like 
    $uniqueCustomerObject = Doctrine::getTable('customer')->findOneBy('name',$this->customerForm->getValue('name')); 
    if(!$uniqueCustomerObject) $uniqueCustomerObject=$this->customerForm->save(); 

    $this->factorForm->getObject()->setCustomer($uniqueCustomerObject); 
    $factor = $this->factorForm->save(); 
    } 
} 

,當然,在你的模板:

<form method="post"> 
<?php echo $factorForm; ?> 
<?php echo $customerForm; ?> 

</form> 
1

我認爲這是在你的web應用程序的邏輯存在問題。在我的意見是,問題是你有沒有好的做法。世界上有人,同名和姓,你會在這種情況下做什麼?或者,如果買方輸入錯誤的一個字母他的名字? 或者如果一個壞人進入別人的名字和姓氏。如果您創建了一個唯一的用戶名字段,那麼我認爲如果您進行註冊會很好,所以您將避免此問題,並且您只需在隱藏字段中以因子形式設置user_id。有一個很棒的插件可以代替你做所有的事情sfForkedDoctrineApplyPlugin