Using Drupal Existing Fields To Custom Form Skip to main content

Fields To Custom Form

Saurabh Dhariwal

Saurabh Dhariwal

drupal existing fields to custom form

What if anyone needs to use existing fields added from backend to a custom form ?

After lots of research I found a drupal hook which can fulfil this requirement. Please read below to add an existing field to your custom form.

Benefits of using field attached form

  1. Field will be generated automatically
  2. Validation will be performed same as admin side
  3. Store value is easy for the same

I have a fields for ‘test’ content type, named Image (field_test_image).

Please find below how can I use my existing fields to my custom form. This is how I took my fields for my content type.

Using drupal existing fields to custom form
Below is code to use field attached form hook.

/** * 
Implements hook_form() 
*/ 
function hook_form($form, &$form_state)
 { 
$entity_type = 'node'; 
$entity_info = new stdClass(); 
$entity_info->type = 'test';
$field = 'field_test_image'; 
//to attach test content type's field to the form 

field_attach_form($entity_type, $entity_info, $form, $form_state, NULL, array('field_name' => $field)); 
$form['submit'][] = 'hook_custom_submit'; 
return $form; }
 /** *
 Implements hook_submit() 
*/ 
function hook_custom_submit($form, $form_state) 
{ 
$form_values = $form_state['values']; 
$node = new stdClass(); 
$node->type = 'test'; 
$node->field_test_image = $form_values[‘field_test_image’]; 
node_save($node); 
}

 

Using drupal existing fields to custom form

 Hope this helps you to understand and resolve the problem. We are a Professional Web Development Company, Feel free to contact us for any issues.