Answers.Body: <p>[UPDATED FOR 2023]</p>
  <p>The closest equivalent is using SearchKit.  You can use either Data Segmentation or text rewrites with Smarty.</p>
  <p>At the bottom of this answer is a screenshot of a Data Segment to calculate the donor level based on amount donated.  There's also a screenshot of using text rewrites to calculate the amount of time elapsed in minutes between two date/time custom fields.</p>
  <p>What you're asking for is very similar to <a href="https://www.drupal.org/project/computed_field" rel="nofollow noreferrer">Computed Field</a> for Drupal - but the nature of calculated fields is that you're writing code (or some pseudo-code formula).  At that point, it's not much further to writing the code in an extension.</p>
  <p>Furthermore, there are basic transformations available on SearchKit without rewrites (e.g. concatenate text, sum numbers).</p>
  <p>The limitation of the approaches above is that they're only available in SearchKit.  If you'd like them available as a custom field/token, there are three extensions you can investigate - <a href="https://civicrm.org/extensions/summary-fields" rel="nofollow noreferrer">Summary Fields</a>, <a href="https://civicrm.org/extensions/synopsis" rel="nofollow noreferrer">Synopsis</a> and <a href="https://docs.civicrm.org/sqltasks/en/latest/" rel="nofollow noreferrer">SQL Tasks</a>.</p>
  <p>All three extensions rely on writing SQL.  Summary Fields has some options for using triggers, but is much harder to use, and you have to build a sub-extension.  Synopsis and SQL Tasks let you write your SQL inside a UI.  Synopsis is built for the purpose and is a better experience, but SQL Tasks can also be used in many instances.</p>
  <p>[2016 answer]
  There are several approaches you can take:</p>
  <p>You can write an extension and use <a href="https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_pre/" rel="nofollow noreferrer">hook_civicrm_pre</a> to grab the fields in question and write to the custom field when your survey is created/updated.  This is relatively quick and easy.</p>
  <p>You can write a <a href="https://www.sitepoint.com/how-to-create-mysql-triggers/" rel="nofollow noreferrer">MySQL trigger</a> in your database.  This is good if you need very high performance.  However, you will need to re-add your trigger on every upgrade - unless you <a href="https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_triggerInfo/" rel="nofollow noreferrer">put it in an extension</a>.</p>
  <h4>Data Segmentation</h4>
  <p><a href="https://i.sstatic.net/Y8DwC.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/Y8DwC.png" alt="SearchKit data segments" /></a></p>
  <h4>Text Rewrites</h4>
  <p><a href="https://i.sstatic.net/U7p5M.png" rel="nofollow noreferrer"><img src="https://i.sstatic.net/U7p5M.png" alt="SearchKit text rewrites" /></a></p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2016-08-04T06:45:41.073Z
Answers.LastActivityDate: 2023-04-03T15:44:05.003Z
Answers.LastEditDate: 2023-04-03T15:44:05.003Z
Answers.UserDisplayName: Jon G - Megaphone Tech
Answers.Body: <p>Paul, very interested in this idea as well. Don't have a great answer, but here's an idea - since you're on Drupal, I wonder if this would work - using <a href="https://www.drupal.org/project/views" rel="nofollow">Views</a>, <a href="https://www.drupal.org/project/views_calc" rel="nofollow">Views Calc</a> and <a href="https://www.drupal.org/project/views_aggregator" rel="nofollow">Views Aggregator Plus</a> (perhaps along with <a href="https://www.drupal.org/project/webform_civicrm" rel="nofollow">webform-civicrm</a>) to do the calculation - add the survey answers to get a score - then saving that score back into Civi in a custom field?  </p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2016-08-04T01:55:40.407Z
Answers.Text: Thanks Joe. I can go that route (and have), but it adds a lot of complication to the flow.
Answers.UserDisplayName: pmoz
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2016-08-04T19:45:56.073Z
Answers.Text: Paul, got it. Definitely simpler to do within Civi. Look forward to a solution.
Answers.UserDisplayName: Joe McLaughlin
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2016-08-04T00:50:49.240Z
Answers.LastActivityDate: 2016-08-04T00:58:46.723Z
Answers.LastEditDate: 2016-08-04T00:58:46.723Z
Answers.UserDisplayName: Joe McLaughlin
Answers.Body: <p>I had the impression that the Summary Fields extension would be a good starting point for adding additional calculated fields. To quote</p>
  
  <blockquote>
    <p>This extension provides hook_civicrm_sumfields_definitions which allows you to add additional summary fields of your own. Example:</p>
  </blockquote>
  
  <pre><code>/**
   * Implements hook_civicrm_sumfields_definitions()
   *
   * Change "mycustom" to the name of your own extension.
   */
  function mycustom_civicrm_sumfields_definitions(&amp;$custom) {
    $custom['fields']['hard_and_soft'] = array(
      'label' =&gt; 'All contributions + soft credits',
      'data_type' =&gt; 'Money',
      'html_type' =&gt; 'Text',
      'weight' =&gt; '15',
      'text_length' =&gt; '32',
      'trigger_sql' =&gt; '(
        SELECT COALESCE(SUM(cont1.total_amount), 0)
        FROM civicrm_contribution cont1
        LEFT JOIN civicrm_contribution_soft soft
          ON soft.contribution_id = cont1.id
        WHERE (cont1.contact_id = NEW.contact_id OR soft.contact_id = NEW.contact_id)
          AND cont1.contribution_status_id = 1 AND cont1.financial_type_id IN (%financial_type_ids)
        )',
      'trigger_table' =&gt; 'civicrm_contribution',
      'optgroup' =&gt; 'mycustom', // could just add this to the existing "fundraising" optgroup
    );
    // If we don't want to add our fields to the existing optgroups or fieldsets on the admin form, we can make new ones
    $custom['optgroups']['mycustom'] = array(
      'title' =&gt; 'My group of checkboxes',
      'fieldset' =&gt; 'Custom summary fields', // Could add this to an existing fieldset by naming it here
      'component' =&gt; 'CiviContribute',
    );
  }
  </code></pre>
  
  <p>Also seems a fairly solid recipe <a href="http://www.drewslair.com/2016/06/calculated-fields-civicrm/" rel="nofollow noreferrer">here</a></p>
  
Answers.ContentLicense: CC BY-SA 4.0
Answers.CreationDate: 2024-04-29T14:09:20.303Z
Answers.Text: https://www.comeausoftware.com/database-design/calculated-fields-civicrm/ : excellent solution and relatively simple to set up. Thank you very much!
Answers.UserDisplayName: Alain Rihs
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2017-06-24T03:11:08.050Z
Answers.LastActivityDate: 2017-06-24T03:11:08.050Z
Answers.UserDisplayName: petednz - fuzion
Answers.Body: <p>Would it be useful to have a general extension that would allow arbitrary PHP to be associated with a View only custom field, and executed on save of the associated object, eg contact or contribution. The extension would provide a new permission that by default would be turned off for all roles. As a vector for security vulnerabilities and performance problems, it should be available only to sysadmin type users. <a href="https://www.drupal.org/documentation/modules/php" rel="nofollow">https://www.drupal.org/documentation/modules/php</a></p>
  
  <p>An alternative design that would have reduced usefulness, cost more to develop, yet be safer and less subject to performance concerns would make it possible to do specific arithmetic or string operations on the core or custom fields of the object associated with the view only field. Like tokens, this could include access to the core and custom fields of the associated contact if the object was something like a contribution or event registration or activity.</p>
  
Answers.ContentLicense: CC BY-SA 3.0
Answers.CreationDate: 2016-08-09T18:00:58.990Z
Answers.LastActivityDate: 2016-08-09T18:00:58.990Z
Answers.UserDisplayName: Joe Murray
Body: <p>Civi 4.6.9<br>
  Drupal 7.44</p>
  
  <p>On many occasions it would be very handy to calculate the values of custom field sets and store that calculated value within Civi.</p>
  
  <p>I'll use a survey for example. </p>
  
  <p>I'd like to create a scored survey activity type tied to a custom field set. The field set would include multiple fields, each with select options. The final field within the set would be "Score." I'd like this field to add the values of all answers. Once we calculate the survey score we can do all kinds of fancy stuff.</p>
  
  <p>I've done my due diligence but didn't find anything out there.</p>
  
  <p>If there isn't one, is the extension route the most efficient method?</p>
  
  <p>Ideally, I'd love to have "Calculated Field" be an option for data type when creating custom fields but that may be a pipe dream.</p>
  
  <p>Thanks.</p>
  
Comments.ContentLicense: CC BY-SA 3.0
Comments.CreationDate: 2017-06-24T03:11:29.503Z
Comments.Text: Hi Paul. What did you use in the end?
Comments.UserDisplayName: petednz - fuzion
Tags: <custom-fields><extension><core>
Title: Is there an extension for adding a custom field type calculated field?
ThreadText: # Is there an extension for adding a custom field type calculated field?
  
  (Asked by: username_0 on 2016-08-03)
  
  Civi 4.6.9  
  Drupal 7.44
  
  On many occasions it would be very handy to calculate the values of custom field sets and store that calculated value within Civi.
  
  I'll use a survey for example.
  
  I'd like to create a scored survey activity type tied to a custom field set. The field set would include multiple fields, each with select options. The final field within the set would be "Score." I'd like this field to add the values of all answers. Once we calculate the survey score we can do all kinds of fancy stuff.
  
  I've done my due diligence but didn't find anything out there.
  
  If there isn't one, is the extension route the most efficient method?
  
  Ideally, I'd love to have "Calculated Field" be an option for data type when creating custom fields but that may be a pipe dream.
  
  Thanks.
  
  **Tags:** custom-fields, extension, core
  
  > **Comments:**
  > **username_1**: Hi Paul. What did you use in the end?  
  
  ---
  
  ## 4 answers
  
  ### Answer by username_2 on 2016-08-04. Score: 5
  
  [UPDATED FOR 2023]
  
  The closest equivalent is using SearchKit. You can use either Data Segmentation or text rewrites with Smarty.
  
  At the bottom of this answer is a screenshot of a Data Segment to calculate the donor level based on amount donated. There's also a screenshot of using text rewrites to calculate the amount of time elapsed in minutes between two date/time custom fields.
  
  What you're asking for is very similar to [Computed Field](https://www.drupal.org/project/computed_field) for Drupal - but the nature of calculated fields is that you're writing code (or some pseudo-code formula). At that point, it's not much further to writing the code in an extension.
  
  Furthermore, there are basic transformations available on SearchKit without rewrites (e.g. concatenate text, sum numbers).
  
  The limitation of the approaches above is that they're only available in SearchKit. If you'd like them available as a custom field/token, there are three extensions you can investigate - [Summary Fields](https://civicrm.org/extensions/summary-fields), [Synopsis](https://civicrm.org/extensions/synopsis) and [SQL Tasks](https://docs.civicrm.org/sqltasks/en/latest/).
  
  All three extensions rely on writing SQL. Summary Fields has some options for using triggers, but is much harder to use, and you have to build a sub-extension. Synopsis and SQL Tasks let you write your SQL inside a UI. Synopsis is built for the purpose and is a better experience, but SQL Tasks can also be used in many instances.
  
  [2016 answer]
  There are several approaches you can take:
  
  You can write an extension and use [hook\_civicrm\_pre](https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_pre/) to grab the fields in question and write to the custom field when your survey is created/updated. This is relatively quick and easy.
  
  You can write a [MySQL trigger](https://www.sitepoint.com/how-to-create-mysql-triggers/) in your database. This is good if you need very high performance. However, you will need to re-add your trigger on every upgrade - unless you [put it in an extension](https://docs.civicrm.org/dev/en/latest/hooks/hook_civicrm_triggerInfo/).
  
  #### Data Segmentation
  
  [![SearchKit data segments](https://i.sstatic.net/Y8DwC.png)](https://i.sstatic.net/Y8DwC.png)
  
  #### Text Rewrites
  
  [![SearchKit text rewrites](https://i.sstatic.net/U7p5M.png)](https://i.sstatic.net/U7p5M.png)
  
  
  ---
  
  ### Answer by username_3 on 2016-08-04. Score: 2
  
  Paul, very interested in this idea as well. Don't have a great answer, but here's an idea - since you're on Drupal, I wonder if this would work - using [Views](https://www.drupal.org/project/views), [Views Calc](https://www.drupal.org/project/views_calc) and [Views Aggregator Plus](https://www.drupal.org/project/views_aggregator) (perhaps along with [webform-civicrm](https://www.drupal.org/project/webform_civicrm)) to do the calculation - add the survey answers to get a score - then saving that score back into Civi in a custom field?
  
  > **Comments:**
  > **username_0**: Thanks Joe. I can go that route (and have), but it adds a lot of complication to the flow.  
  > **username_3**: Paul, got it. Definitely simpler to do within Civi. Look forward to a solution.  
  
  ---
  
  ### Answer by username_1 on 2017-06-24. Score: 1
  
  I had the impression that the Summary Fields extension would be a good starting point for adding additional calculated fields. To quote
  
  This extension provides hook_civicrm_sumfields_definitions which allows you to add additional summary fields of your own. Example:
  
  /**
   * Implements hook_civicrm_sumfields_definitions()
   *
   * Change "mycustom" to the name of your own extension.
   */
  function mycustom_civicrm_sumfields_definitions(&$custom) {
    $custom['fields']['hard_and_soft'] = array(
      'label' => 'All contributions + soft credits',
      'data_type' => 'Money',
      'html_type' => 'Text',
      'weight' => '15',
      'text_length' => '32',
      'trigger_sql' => '(
        SELECT COALESCE(SUM(cont1.total_amount), 0)
        FROM civicrm_contribution cont1
        LEFT JOIN civicrm_contribution_soft soft
          ON soft.contribution_id = cont1.id
        WHERE (cont1.contact_id = NEW.contact_id OR soft.contact_id = NEW.contact_id)
          AND cont1.contribution_status_id = 1 AND cont1.financial_type_id IN (%financial_type_ids)
        )',
      'trigger_table' => 'civicrm_contribution',
      'optgroup' => 'mycustom', // could just add this to the existing "fundraising" optgroup
    );
    // If we don't want to add our fields to the existing optgroups or fieldsets on the admin form, we can make new ones
    $custom['optgroups']['mycustom'] = array(
      'title' => 'My group of checkboxes',
      'fieldset' => 'Custom summary fields', // Could add this to an existing fieldset by naming it here
      'component' => 'CiviContribute',
    );
  }
  
  Also seems a fairly solid recipe here
  
  > **Comments:**
  > **username_4**: https://www.comeausoftware.com/database-design/calculated-fields-civicrm/ : excellent solution and relatively simple to set up. Thank you very much!  
  
  ---
  
  ### Answer by username_5 on 2016-08-09. Score: 1
  
  Would it be useful to have a general extension that would allow arbitrary PHP to be associated with a View only custom field, and executed on save of the associated object, eg contact or contribution. The extension would provide a new permission that by default would be turned off for all roles. As a vector for security vulnerabilities and performance problems, it should be available only to sysadmin type users. <https://www.drupal.org/documentation/modules/php>
  
  An alternative design that would have reduced usefulness, cost more to develop, yet be safer and less subject to performance concerns would make it possible to do specific arithmetic or string operations on the core or custom fields of the object associated with the view only field. Like tokens, this could include access to the core and custom fields of the associated contact if the object was something like a contribution or event registration or activity.
  
  
  ---
  
  