Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal: How to use fieldsets in hook_field_widget_form

So I have my hook_field_schema defining columns, and hook_field_widget_form is set up and saving all of the column values correctly.

But as soon as I put two of the fields inside of a fieldset, those values never save or get updated. I've tried setting #tree => FALSE all over the place and that isn't working either.

What am I missing? Is it just unsupported? Should I be using a form_alter hook or something to move them into a fieldset?

like image 939
Karl Avatar asked Dec 28 '22 22:12

Karl


2 Answers

I had the same problem and couldn't find a solution. After trying many things, it turned out to be something as simple as illogical. Well, in the eyes of a Drupal newbie.

At first I had something like this (stripped down version):

$element['mymodulefieldset'] = array(
  '#title' => 'Fieldset title',
  '#type' => 'fieldset',
);

and added fields to the fieldset:

$element['mymodulefieldset']['fieldname'] = array(
  '#title' => "Field title",
  '#type' => 'textfield',
  '#default_value' => '',
);

After trying lots of different scenarios I found out the next lines of code did (sort of) work. Instead of inserting a fieldset, I turned the element into a fieldset like this:

$element += array(
  '#type' => 'fieldset',
  '#tree' => true
);

Then I added fields to the element:

$element['fieldname'] = array(
  '#title' => "Field title",
  '#type' => 'textfield',
  '#default_value' => '',
);

NB: some variables like #title and #weight are controlled by "Home » Administration » Structure » Content types » [YOUR CONTENT TYPE]", others (like #collapsible and #collapsed) can be defined here.

Hope this helps you out!

like image 81
lmeurs Avatar answered Dec 31 '22 15:12

lmeurs


I know it is an old question, but there is a solution for this problem, explained in this artice, the #process part is what is used to save the fields properly.

EDIT: As the comment of @alexkb explains, the author of the article has updated his custom field sample and has removed the #process hack. For a better solution, use the GitHub code.

like image 39
o15a3d4l11s2 Avatar answered Dec 31 '22 13:12

o15a3d4l11s2