0

I have a content type 'invoice'

I want to add a field invoice_number for example: ABC2012001

  • ABC: prefix,

  • 2012: changes Every year,

  • 001 : nr of invoice (reset every year)

THE field is autoincrement.

How can I do this? Is it possible without programming or do I have to use THE hook functions?

ronalchn
  • 12,225
  • 10
  • 51
  • 61
user1704548
  • 75
  • 1
  • 10

1 Answers1

0

You could do this with a custom module using the node_presave hook. The users only enter the prefix value into the 'invoice_number' field. Before the node is saved to the database your hook does the following:

if the node is of type 'invoice' and has not yet been saved 'nid == 0'

  • gets the current year
  • gets the current number of invoices for this year (either from a stored variable or a database query)
  • alters the field value and appends the year/number

So something along the lines of this:

<?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));
    }

}
mmiles
  • 961
  • 6
  • 9