My CiviCRM 5.56.1 runs on Drupal 7.

I try to set the default value for a custom field which is used for an Action.

I created the field in Admin -> Customized Data & Screen -> Custom Fields. The field custom_76_-1 is shown in the form, and it works, I can change the current value. This is a date field showing a year-value only, and I'd like to set it's default value from current year to 3 years before (eg. in this year from 2022 to 2019). On the UI I can set a fix date, not a relative date.

With Javascript / jQuery I can change the shown value of the year, but not the default value in the form. I tried to set the default value in the form with the code from this https://civicrm.stackexchange.com/a/33474/5877 answer, but it doesn't works for me -- I mean the default value didn't changed. As I understood, custom fields are created from an AJAX call's response, and the buildForm() function runs earlier as the AJAX call, which creates the custom field, so the default value can't be set (is this true or do / understand I something wrong?).

Please advice me how can I set the field's default value.

1 Answer 1

 * Implements hook_civicrm_buildForm().
 * @link http://wiki.civicrm.org/confluence/display/CRMDOC/hook_civicrm_buildForm
function extensionname_civicrm_buildForm($formName, $form) {
  if ('CRM_Custom_Form_CustomDataByType' == $formName
    // type == cuctom group belongs to which type i.e Contact, Event, Activity...
    && in_array($form->getVar('_type'), ['Contact'])
  ) {
    foreach ($form->getVar('_groupTree') as $customGroup) {
      // custom group name in which the field you want to set default to.
      if ($customGroup['name'] == 'custom_group_name') {
        foreach ($customGroup['fields'] as $field) {
          // custom field name you want to set default to.
          if ($field['name'] == 'custom_field_name_type_date') {
            $defaults = [
              $field['element_name'] => date('Y', strtotime('-3 years', strtotime(date('Ymd'))))

  • Thanks, both foreach are running, but no default value is set...
    – Pál Rudan
    Feb 19, 2022 at 18:00
  • what type of custom field is it? Feb 19, 2022 at 18:16
  • I created a custom group for Activities, in this group is a single field, which is a Date field, the format is "Year only" (%Y), no time is show, it's mandatory, searchable with range.
    – Pál Rudan
    Feb 20, 2022 at 10:26
  • I have updated the answer Feb 21, 2022 at 10:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.