How to hard code a Calculated Field

To create a custom Calculated Field within a module, first within the the DefaultDataMaker for the desired module add some code within the make() function. Here it is added to ProductsDefaultDataMaker.php

//Price Per Sqft Calculated field
               $attributeName = ‘pricePerSqft’;
 //Add attribute only if it doesn’t exist
                     //This will throw exception if field doesn’t exist within Product Module
                          $attributeTest = CalculatedDerivedAttributeMetadata::getByNameAndModelClassName($attributeName, ‘Product’);
               catch ( NotFoundException $e)
                   $attributeForm = new CalculatedNumberAttributeForm();
                   $attributeForm->attributeName = $attributeName;
                   $attributeForm->attributeLabels  = array(
                      ‘de’ => ‘RPSF de’,
                      ‘en’ => ‘RPSF’,
                      ‘es’ => ‘RPSF es’,
                      ‘fr’ => ‘RPSF fr’,
                      ‘it’ => ‘RPSF it’,
//Formula is the Sell Price divided by Square Feet

$attributeForm->formula  = ‘sellPrice / sqft’;

               $modelAttributesAdapterClassName = $attributeForm::getModelAttributeAdapterNameForSavingAttributeFormData();
//Add the field to the Product Module
               $adapter = new $modelAttributesAdapterClassName(new Product());
Then you will be able to add the field within your view, for example ProductEditAndDetailView.php
array(‘cells’ =>
‘elements’ => array(
array(‘attributeName’ => ‘pricePerSqft’ , ‘type’ => ‘CalculatedNumber’),

Leave a Comment