Calculated fields in objects

I have been trying to add calculated fields to a custom module. I have tried the following, which appears to work. I was wondering if I had missed something obvious that is going to bite me in the backside at a later date.

  1. Created a custom module using Module Builder

  2. Renamed the table in the database, changing it from <module_name> to <module_name>_real

  3. Created a view in the database using

CREATE VIEW <module_name> as 
    SELECT *, <insert calculations> AS <new_field_name> 
    FROM <module_name>_real
  1. Edited the module’s vardefs.php, adding a new property, called real_table:
    'table' => '<module_name>,
    'real_table' => '<module_name>_real',
    'audited' => true,
  1. Edited the module’s vardefs.php, adding a new field:
  '<new_field_name>' =>
  array (
    'required' => false,
    'name' => '<new_field_name>',
    'vname' => '<new_field_label>',
    'type' => 'currency',
    'massupdate' => 0,
    'no_default' => true,
    'comments' => '',
    'help' => '',
    'importable' => 'false',
    'duplicate_merge' => 'disabled',
    'duplicate_merge_dom_value' => '0',
    'audited' => false,
    'inline_edit' => false,
    'reportable' => true,
    'unified_search' => false,
    'merge_filter' => 'disabled',
    'enable_range_search' => false,
    'studio' => 'visible',
    'auto_increment' => true,  /* this is to prevent the field being inserted/updated */
  ),
  1. Edited the <module>.php file to override the getTableName() method:
    public function getTableName() {
        if ($this->in_save) {
            global $dictionary;
            if (!isset($dictionary[$this->getObjectName()])) {
                $GLOBALS['log']->fatal('Dictionary doesn\'t contains an index: '
 . $this->getObjectName());
                return null;
            }
            return $dictionary[$this->getObjectName()]['real_table'];

        } else {
            return parent::getTableName();
        }
    }

So far, this allows me to create and edit instances of my new module, view them in lists and in reports.

Any thoughts?

Thanks,

Carl

1 Like

Hackish, but quite interesting B-)

I am curious to know your impressions in the coming weeks, tell us if it works well and if you are going to use it like this in your project.