Set Default Value for Custom Field
Moe's answer is technically workable - but oof ouch my performance!

Instead, something like this:



function getElementNameFromFieldName($fieldName, $elementIndex) {
  // This function could be further optimized so it's only called once, but meh.
  $elementNames = array_keys($elementIndex);
  foreach ($fieldNames as $fieldName) {
    if (strpos($elementName, $fieldName) === 0) {
      return $elementName;
    }
  }
}

if ( $formName == 'CRM_Contact_Form_CustomData' || $form == CRM_Core_Action::ADD) {
  $custom198ElementName = getElementNameFromFieldName('custom_198', $elementIndex);
  $custom197ElementName = getElementNameFromFieldName('custom_197', $elementIndex);
  $custom160ElementName = getElementNameFromFieldName('custom_160', $elementIndex);

  $form-&gt;updateElementAttr($custom198ElementName, ['readonly']);
  $form-&gt;updateElementAttr($custom197ElementName, ['readonly']);
  $form-&gt;updateElementAttr($custom160ElementName, ['readonly']);
}

if ($form == CRM_Core_Action::ADD) {
  $customid = rand (1,10000);
  $currentDate = date('d/m/Y');

  $defaults[$custom160ElementName] = $customid;
  $defaults[$custom197ElementName] = $currentDate;
  $defaults[$custom198ElementName] = $currentDate;
  $form-&gt;setDefaults($defaults);
}


Additionally -  your code (and mine) as written will set defaults on EVERY form's ADD action.  You probably want to limit it to those that have these custom fields.