0

I want to make a module to create custom fields to a content type. But I want to be able to turn the fields on and off via the content type edit page.

So I want to add a tab to the vertical tab part at the bottom of the content type edit page where I have a single on off checkbox. When selected and saved, fields are created. When not selected the fields will be removed (or not created).

I created the option in the node type form. By using this:

function HOOK_form_node_type_form_alter(&$form, &$form_state){
$form['new_option'] = array(
    '#type' => 'details',
    '#title' => t('NEW OPTION'),
    '#group' => 'additional_settings',
);

$form['new_option']['new_option_options'] = array(
    '#type' => 'checkbox',
    '#title' => t('Create fields'),
    '#collapsible' => TRUE,
    '#collapsed' => TRUE,
    '#weight' => 10,
);
}

But how can I save the value of the checkbox in config and use it as default_value.

  • It would probably be wise to break this into two questions - I think storing the value and creating fields programmatically each have enough about them to warrant separate posts (which will naturally encourage more detailed answers to each). To get you going on the first question, though, that data is usually stored as third party settings. In the form alter you would use $node_type->getThirdPartySettings(), and in the submit handler $node_type->setThirdPartySettings() to save – Clive Jan 5 at 19:49
0

Thanks Clive, I ended up using the following code to set and get the config settings.

function module_name_form_node_type_form_alter(&$form)
{
    //get node type
    $bundle = $form['type']['#default_value'];
    $node_type = NodeType::load($bundle);

    //create vertical tab
    $form['new_option'] = array(
        '#type' => 'details',
        '#title' => t('New option'),
        '#group' => 'additional_settings',
    );

    //add checkbox to vertical tab
    $form['new_option']['new_option_options'] = array(
        '#type' => 'checkbox',
        '#title' => t('New option checkbox'),
        '#collapsible' => TRUE,
        '#collapsed' => TRUE,
        '#weight' => 10,
        '#default_value' => $node_type->getThirdPartySetting('new_option','new_option_options'),
    );

    //create submit handler
    $form['actions']['submit']['#submit'][] = 'module_name_form_submit';
}

function module_name_form_submit(&$form)
{
    //get node type
    $bundle = $form['type']['#default_value'];
    $node_type = NodeType::load($bundle);

    //set checkbox value to config and save
    $node_type->setThirdPartySetting('new_option','new_option_options',$form['new_option']['new_option_options']['#value']);
    $node_type->save();

   //enable/disable fields
}

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.