Is it possible to define PHP-code as a default value for a cck-date field (like with a string)?
I have a cck-date field, and I want the default value to be based on a arg() variable. It needs to be a date field (and not a string), because it will be displayed on a calendar.

If it's not possible by default, would it be possible with a small hack?

Comments

gertieiv’s picture

i'm interested in this possibility too,

greetings,
geert

intru’s picture

Found a possibility to fix this using the Rules module:
http://drupal.org/project/rules

I use a hidden date field, and using a triggered rule I fill in it's value. You may have to adjust this for your own situation, but hopefully it can give you a clue how to solve this problem.

You should use the event 'content is going to be saved', and add a condition to check for the content type. Then execute custom php code:

$date = arg(3);
$node->field_date[0][value] = $date;
return array('node' => $node);
KarenS’s picture

Version: 6.x-2.0-rc4 » 6.x-2.x-dev
Category: support » feature

This would actually be a feature request. The solution in #2 is not going to behave the same as a default value. A default value sets a value before the user starts, that is overridden by whatever the user does. The rule in #2 would not provide a default value that the user would see but instead would over-write whatever they try to do, which would confuse them completely I think.

swellbow’s picture

+1 to the ability to use PHP to set default values for date fields. Thanks!

Right now I am using hook_form_alter in a custom module to provide this ability, which works fine. It certainly would be cool to be able to use PHP like other cck types.

biwashingtonial’s picture

+1 This would be a great feature.

tmsimont’s picture

The #default_value will be today's date if no value is supplied. The format for the #default_value and the #return_value is an array with three elements with the keys: 'year', month', and 'day'. For example, array('year' => 2007, 'month' => 2, 'day' => 15)

From moduleName_fieldType_entry_widget_process($element, $edit, &$form_state, $form):

 <?php
$fields[$category][$field->name] = array(
  '#type' => 'date',
  '#title' => check_plain($field->title),
  '#default_value' => array('year' => 2007, 'month' => 2, 'day' => 15),
  '#description' => _profile_form_explanation($field),
  '#required' => $field->required
);
?>

does that help?

bfr’s picture

#4 Great idea, i managed to do this in custom module too.

vasheck’s picture

I am trying to accomplish something similar... Sorry to post this under "Date module" but this is the closest post to what I'm trying to accomplish.

I created my own module (tester.info tester.module).
I have a content type “myccktype” with two fields "My Textarea 1" and "My Textarea 2".
I’m trying to assign a default value (from a taxonomy) programmatically to the textareas.

This is what I have... but these create new textareas rather than edit the existing ones.

function mymodule_ui_form_myccktype_node_form_alter(&$form, &$form_state) {

$form['field_mytextarea1'] = array(
'#type' => 'textarea',
'#title' => t('My Textarea 2'),
'#default_value' => "tester value1",
);

$form['field_mytextarea2'] = array(
'#type' => 'textarea',
'#title' => t('My Textarea 2'),
'#default_value' => "tester value 2",
);

}

Any tips would be greatly appreciated. Thank you!

my-family’s picture

+1 for the feature request - to have a possibility to set the default date via PHP like with other CCK fields. In addition, would it be possible to set "to date" value relatively to "from date"? It would help a lot. For example, in my case (intranet), users enter content which has always the same date span (1 week - it is weekly report). The "to date" must be obligatory because of Resource conflict module. But it is always "the same" - relatively - 7 days more than "from date". Thank you in advance if there could be a solution.

Canine Coaches’s picture

+1 for #9. relative date, not default, for field_date_to based on entered value in field_date_from

@swellbow @bfr if either of you are following this would you mind posting your modules here.

I am very new to php (just learning) and would appreciate it. Thanks

Chris

bfr’s picture

Component: Code » Date CCK Field

Ofcourse. My module is called fgimodule and this is the fgimodule.module file.
It takes the last node of the "worktime" type the current user has created, checks the date field, adds one day and returns that date to the form. I put some comments there for you.
Tell me if you need help.

<?php 
/**
* Implementation of hook_form_alter().
*/

//replace the "fgimodule" with the name of your module..
function fgimodule_form_alter(&$form, $form_state, $form_id) {
    switch ($form_id) 
    {
      // .. and the name of the form, usually mycontent_node_form
      case 'worktime_node_form':         
          {
            // without this you cannot use the $user object
	    global $user;

	    // check the latest submission from the user of the wanted type, worktime in my case:
	    $result=db_fetch_array(db_query("select nid from {node} where `uid` = $user->uid and `type`='worktime' order by `created` desc"));       

            // load the node to $node:
	    $node=node_load($result[nid]);                    
		
	    // convert it to array, not necessary, but there are better tools to handle arrays than objects php.
	    $node=(array)$node;                       
			
	   //load the content of the date field to $aika (aika = time in Finnish)
	   $aika=$node['field_tyoajanseuranta_datetime']['0']['value'];  
			
	  //add 1 day to the date			
	  $aika=strtotime(date("Y-m-d", strtotime($aika)) . " +1 day");  
			
	  // format it correctly			
	  $aika=date("Y-m-d H:i:s", $aika);                                              
		
	 //if the field was empty or did not exist, default to this day
	 if (empty($aika)){$aika=date("Y-d-m 00:00:01");}                
			
	//fill the field			
	$form['field_tyoajanseuranta_datetime']['0']['#default_value']['value']=$aika;           
      	break;
    	}
     }
  }

EDIT: Since people still seem to use this old code, i edited it a bit to be more sane and drupal. Thus, comments after this may not be valid anymore.

Canine Coaches’s picture

@bfr Thank you that looks awesome. Thanks for all the comments, it will help me understand what is doing what. I will have some time this week to work with this (I hope) and will post back how it went.

A couple questions I have, aika looks like I just change to time (usa). $nodez and $noodi I have not seen before (I am just beginning developing), can you give a quick explanation? Thanks again.

Chris

bfr’s picture

If you are not familiar with making modules, save the above code as my_module.module (change the name to whatever you call your module), then make a new filke and put this in it:

;$Id$
name = "My module"
description = "Module for my custom functions"
core = 6.x

save it as my_module.info,
then put both files to my_module directory in your modules directory and enable the module as usual from the admin interface. That's it.

edit: If you need some other custom things also, just make a new function, no need to make new module for everything.
edit2: Stuff removed to not confuse people since i changed the example code a bit.

saulalbert’s picture

tip #2 worked for me - thanks very much!

luke.oakes’s picture

+1 for PHP default value =) Thanks

atodorov’s picture

+1 for PHP default value.

On a related note can you help me or point me in the right direction:

In my application I want to control the range of allowed values in PHP not the default. E.g. from March 1st 2011 to April 4th 2011. Do you know how to do that? can it be implemented in the same RFE? Thanks.

SchwebDesign’s picture

Component: Date CCK Field » Code

i needed this as well, but post 11 helped me do excatly what i needed. Thanks!

dwalker51’s picture

Component: Date CCK Field » Code

I am not sure what I am doing wrong here.

I have a content type called night_report, in it I have a date cck field that I need to change its default value when the user goes to add a new night report.
This is due to the night starting on the say 15th, but some people will fill it in the next morning and the date will have changed to the 16th, So I will need to code it in that sometime, say, before midday of the next day, still have the default value set to the night before.

I created a module called dw_night, with its respective dw_night.info and dw_night.module.
Here is the code of dw_night.info

name = DW Night Report (Custom)
description = This is a custom module to set the default date of the night report. (David Walker).
core = 7.x

Here is the code of dw_night.module, I have a date field called nr_date and a text area called nr_problems, it seems that I have no problem setting the problems text area with a default value, but the date field doesn't work. Any help would be appreciated, I have seen multiple examples and pages, but none of them work.

/**
 * Implementation of hook_form_alter().
 */
function dw_night_form_alter(&$form, $form_state, $form_id) {
if (isset($form['type']) && isset($form['#node'])) {
    // Use this check to match node edit form for a particular content type.
    if ('night_report_node_form' == $form_id) {
      $form['#after_build'][] = 'dw_night_after_build';
    }
  }
}



/**
 * Modify CCK form elements on the example node form.
 */
function dw_night_after_build($form, &$form_state) {
  // TODO: Stuff!

$form['field_nr_date']["und"][0]["value"]['#value'] =   date("2000-d-m 00:00:01");
$form['field_nr_problems']["und"][0]["value"]['#value'] =  date("2000-d-m 00:00:01");

//These nr_date ones don't work , but the nr_problem has no trouble at all, I am leaving these here to show the variations I have tried.
//$form['field_nr_date']["und"][0]["value"]['value'] =   date("2000-d-m 00:00:01");
//$form['field_nr_date']["und"][0]["value"]['#default_value'] =   date("2000-d-m 00:00:01");
//$form['field_nr_date']["und"][0]["value"]['#value'] =   date('c', mktime(1, 2, 3, 4, 5, 2006));
//$form['field_nr_problems']["und"][0]["value"]['#value'] =  date('c', mktime(1, 2, 3, 4, 5, 2006));
//$form['field_nr_date']["und"][0]["value"]['value'] =   date('c', mktime(1, 2, 3, 4, 5, 2006));
//$form['field_nr_date']["und"][0]["value"]['#default_value'] =   date('c', mktime(1, 2, 3, 4, 5, 2006));
//$form['field_nr_date']["und"][0]["value"]['#value'] =  date(DATE_ATOM,mktime(0,0,0,10,3,1975));
//$form['field_nr_date']["und"][0]["value"]['value'] =  date(DATE_ATOM,mktime(0,0,0,10,3,1975));
//$form['field_nr_date']["und"][0]["value"]['#default_value'] =  date(DATE_ATOM,mktime(0,0,0,10,3,1975));
//$form['field_nr_problems']["und"][0]["value"]['#value'] =  date(DATE_ATOM,mktime(0,0,0,10,3,1975));
//$form['field_nr_problems']["und"][0]["value"]['#value'] =strtotime('2000-01-01 00:00:00');
//$form['field_nr_problems']["und"][0]["value"]['#value'] ="hello test";
//$form['field_nr_problems']["und"][0]["value"]['value'] ="hello test";
//$form['field_nr_problems']["und"][0]["value"]['#default_value'] ="hello test";

  return $form;
}
dwalker51’s picture

oops double post

JMOmandown’s picture

@dwalker51: The date field has a slightly different structure. I recommend using devel to see this for yourself. The structure to set the default value is as follows: [$date_field]['und']['0']['#default_value']['value']

doublejosh’s picture

You should never use "und" but rather LANGUAGE_NONE

DamienMcKenna’s picture

Issue summary: View changes
Status: Active » Closed (won't fix)

Unfortunately the Drupal 6 version of the Date module is no longer supported. That said, we appreciate that you took time to work on this issue. Should this request still be relevant for Drupal 7 please feel free to reopen it. Thank you.