0

How to set default date today on a custom date field that is added on a contribution page via profile?

I have tried to add this in my extension but doesnt seem to work and getting populated as 01/01/1970 set after form submitted . Any help would be appreciated. Thanks

function club_civicrm_buildForm($formName, &$form) {
    if ($formName == 'CRM_Contribute_Form_Contribution_Main'
        && in_array($form->getVar('_id'), [42])
      ) {
        $defaultDate = date("d/m/Y");
        $defaults['custom_315'] = $defaultDate;
        $form->setDefaults($defaults);
      }
    }
2
  • 1
    Its should be $defaultDate = date("Ymd"); Sep 19, 2023 at 14:41
  • !thanks @PradeepNayak-CircleInt. it worked with build form function as well now.
    – Tapash
    Sep 19, 2023 at 17:33

1 Answer 1

2

I was able to achieve this by including this JS snippet in the extension instead, posting here incase it helps someone.

var now = new Date();
var day = ("0" + now.getDate()).slice(-2);
var month = ("0" + (now.getMonth() + 1)).slice(-2);
var today = now.getFullYear()+"-"+(month)+"-"+(day) ;
$('#custom_315').val(today);

EDIT: It also works with following build form function, Thanks to Pradeep for the hints.

    function club_civicrm_buildForm($formName, &$form) {
        if ($formName == 'CRM_Contribute_Form_Contribution_Main'
            && in_array($form->getVar('_id'), [42])
          ) {
           //Populate Date using the function
            $defaultDate = date("Ymd");
            $defaults['custom_315'] = $defaultDate;
            $form->setDefaults($defaults);
           //alternatively addScriptFile function to inject js
            Civi::resources()->addScriptFile('club', 'club.js');
          }
        }

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.