发票的Drupal自定义文件类型

时间:2012-09-27 20:39:55

标签: drupal-7 content-type invoice

我有一个内容类型'发票'

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

  • ABC:前缀,

  • 2012:每年都有变化,

  • 001:发票的nr(每年重置)

该领域是自动增量。

我该怎么做?是否可以不编程或者我必须使用THE钩子函数?

1 个答案:

答案 0 :(得分:0)

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

如果节点属于'invoice'类型且尚未保存'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));
    }

}