2

I have no idea why I cannot find an answer to this. I've been able to do this with other fields except the 'title' field.

I have a form which I need to automatically populate the title field. I don't want the user to populate it, so I'm hiding it by wrapping it in a that's hidden.

I used hook_form_alter() to add a callback function to the form's #submit array, but those functions are called after the validation. This would result in an error telling the user to enter a title.

Now I'm trying to use hook_form_alter and adding a validation callback function to the BEGINNING of the array like so:

function previous_meetings_form_alter(&$form, $form_state, $form_id)
{
    //Hide the title field
    $form['title']['#prefix'] = '<div style="display: none;">';
    $form['title']['#suffix'] = '</div>';
    //Callback function to execute before validation
    array_unshift($form['#validate'], '_previous_meetings_set_meeting_title');
}

Here is the callback function that is being called but NOT working:

function _previous_meetings_set_meeting_title(&$form, &$form_state)
{
    $form_state['values']['title'] = 'SOMETHING';
}

What am I doing wrong? Can I set values in a validation callback? Is there a right approach to this?

Thanks!

  • Which form are you altering? Is the title field a field API field, or a normal form field? – kiamlaluno Nov 14 '12 at 2:44
  • 1
    Try [Automatic Nodetitles][1] module that may help you – monymirza Nov 14 '12 at 4:44
3

If you use #prefix and #suffix with display:none, it is hidden in display, but submitted and will be validated for required.
Try to use #required = FALSE and #type = 'hidden' and then set title in your submit handler.

function previous_meetings_form_alter(&$form, $form_state, $form_id)
{
    // Hide the title field
    $form['title']['#required'] = FALSE;
    $form['title']['#type'] = 'hidden';
    // Callback function to execute before validation
    array_unshift($form['#submit'], '_previous_meetings_set_meeting_title');

}

And you could also use Automatic Nodetitles with which you may use token replacement.

  • 1
    I submitted my answer before seeing this (it wouldn't let me answer it since I'm new). Your solution similar to mine though. Thank you :D – Richard Robinson Nov 14 '12 at 16:54
1

Nevermind...got it. My solution:

function previous_meetings_form_alter(&$form, $form_state, $form_id)
{
     $form['title']['#required'] = FALSE;
     $form['title']['#prefix'] = '<div style="display: none;">';
     $form['title']['#suffix'] = '</div>';
     $form['#submit'][] = '_previous_meetings_set_meeting_title';
}

function _previous_meetings_set_meeting_title(&$form, &$form_state)
{
    $form_state['values']['title'] = 'SOMETHING';
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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