0

我有一个内容类型“发票”

我想添加一个字段invoice_number,例如:ABC2012001

  • ABC:前缀,

  • 2012:每年都在变化,

  • 001:发票编号(每年重置)

该字段是自动增量的。

我怎样才能做到这一点?是否可以不编程或者我必须使用钩子函数?

4

1 回答 1

0

您可以使用node_presave钩子通过自定义模块执行此操作。用户只需在“invoice_number”字段中输入前缀值。在将节点保存到数据库之前,您的钩子会执行以下操作:

如果节点是“发票”类型并且尚未保存“nid == 0”

  • 获取当前年份
  • 获取今年的当前发票数量(来自存储变量或数据库查询)
  • 更改字段值并附加年份/数字

所以类似这样的事情:

<?php

function mymodule_node_presave($node){
    if (($node->type == 'invoice') && ($node->nid == 0)) { //node has not been saved
        //get the current year
        $this_year = date('Y');

        if ($count = variable_get('invoice_count_'.$this_year,0)){
            //have the invoice number
        }else{
            //get the number of invoices created this year from DB
            $count_query = "SELECT COUNT(DISTINCT nid)) FROM {node} WHERE type = :type AND FROM_UNIXTIME(created,'%Y') = :year";
            $count = db_query($count_query,array(':type'=>'invoice',':year'=>$this_year))->fetchField();
        }

        $invoice_count = $count;
        //append number with 0's?
        $invoice_count = str_repeat('0',(3-strlen($invoice_count))).$invoice_count;
        //alter the field value and append the year.number
        $node->field_invoice_number['und'][0]['value'].=$this_year.$invoice_count;
        //save the increment
        variable_set('invoice_count_'.$this_year,($count+1));
    }

}
于 2012-09-27T21:31:31.677 回答