Set current date in custom form element in DRUPAL8

22
April

Set current date in custom form element in DRUPAL8
By: Anonymous | Published On: Wed, 04/22/2020 - 22:13

Set current date in custom form element in DRUPAL8

Add this line at top

 use Drupal\Core\Datetime\DrupalDateTime; 

Add the following code to your form

function HOOK_form_alter(&$form, FormStateInterface $form_state, $form_id) {
	if ($form_id == 'node_article_form') {

		$form['field_date']['widget'] = array(     
        '#type' => 'datetime',
        '#title' => 'Enter Date',
        '#required' => TRUE,
		'#default_value' => DrupalDateTime::createFromTimestamp(time()),
		);  
		
		// $form['actions']['submit']['#submit'][] = 'article_edit_handler';
	}
}

This code using to create detail format according to Drupal8

DrupalDateTime::createFromTimestamp(time());

Comments

Need Help ?