2012-06-20 48 views
1

我有一個名爲Invoice。我的模型已經做了必要的CRUD for Invoice model .The attributes發票模型是像Invoice Title, Invoice No, Invoice Issue Date, Description。現在我想的是when a user will redirect to invoice create page,the input field for Invoice No should be automatically filled in the create page with last inserted id +1 and it should have prefix like INV:.So the input field for Invoice No should be like this INV:12.通過該用戶並不需要以遞增的順序手動填寫發票號。這裏是創建頁面的圖像。 enter image description here如何獲得最後插入的id在Yii中創建

+0

'$ instance_of_your_model-> primaryKey'將得到上次插入的模型。 – Leri

+0

如何在_form頁面中實現? – NewUser

+0

這不是一個好主意,如果應用程序將是多用戶。 更好的選擇是在創建表單時不顯示此字段(例如,在_form.php中顯示ID字段,只有在!!$ model-> isNewRecord時),並且_actionCreate_將重定向更改爲_update_動作(而不是Yii的默認值_view_ action) –

回答

2

首先==>This is not a good idea to store Invoice number dependent on table's unique id

所以,你應該插入最後一個發票號的數字部分+ 1文本..

現在先得到最後的發票模型,然後找到自己的發票號碼和填充字段..

在控制器..

$model = new Invoice; 

$last_invoice = Invoice::model()->find(array('order'=>'id DESC')); 
$last_invoice_number = str_replace("INV:", "", $last_invoice->invoice_mumber); 
$new_invoice_number = $last_invoice_number+1; 

$model->invoice_number = "INV:".$new_invoice_number; 

$this->render('create',array('model'=>$model)); 

編輯:

之所以不能使用Yii::app()->db->lastInsertId) ..

首先,我排在首位表示,其不會從table..second的唯一ID好相關的發票編號什麼,如果在某些其它之間有人表插入sonething。 。第三如果該數據庫連接被關閉之間開始..

+1

如何在_form.php頁面顯示? – NewUser

+0

那會自動來.. –

+0

如果模型的屬性invoice_number已賦值.. –

0

只是一個建議:

如果用戶不需要填寫發票號碼,然後你爲什麼不只是從顯示跳過它。我的意思是不要在創建時顯示它。表單提交後,您可以顯示發票號碼上的所有提交值。

表單提交後,您可以簡單地顯示發票號碼$ model - > id;其中id是數據庫中的發票號碼。

您可以使用發票號碼作爲數據庫中的主要自動增量bigint值。然後在顯示時使用INV:前綴。

希望它有幫助!

+0

非常感謝Ujjwal的建議。我正在考慮在這方面做所有事情。真的謝謝你的建議。 – NewUser

0

這是獲取Yii中最後一個insert id的簡單方法。

  Yii::app()->db->getLastInsertId(); 
相關問題