coder1.com

  • home
  • drupal articles
  • contact
Home

Adding a CCK Field to a Custom Form

Mike Milano — October 8, 2010 - 1:19am

Recently I wanted to add a CCK combo field into a custom form. Why would you need to do this? Well, my reason was to re-use a combo field with the 'add another item' functionality. Using the node form was not an option.

In this example we have a CCK combo field named "guests". Each guest has a first name, last name, and email address. The content type the guests field is in is my_event.

When adding this code to your form function, the guests field will display just as it does on the node form.

  1. <?php
  2. // include the content file
  3. module_load_include('inc', 'content', 'includes/content.node_form');
  4. $field = content_fields('field_guests', 'my_event');
  5. $form['#field_info']['field_guests'] = $field;
  6. $form += (array) content_field_form($form, $form_state, $field);
  7. ?>

Next thing I needed to do was pre-populate the guest information based on the node. If you know of a better way to achieve this, please comment! ... however, this was all I could come up with.

  1. <?php
  2. if (is_array($node->field_guests)) {
  3. $delta = 0;
  4.  
  5. // reults always appear in wrong order, so reverse sort them.. not sure why
  6. rsort($node->field_guests);
  7.  
  8. // loop through the guests in the node and set the default values
  9. foreach ($node->field_guests as $item) {
  10. $form['field_guests'][$delta] = $default_item;
  11. $form['field_guests'][$delta]['firstname']['#default_value'] = $item['firstname'];
  12. $form['field_guests'][$delta]['lastname']['#default_value'] = $item['lastname'];
  13. $form['field_guests'][$delta]['email']['#default_value'] = $item['email'];
  14. $delta++;
  15. }
  16. }
  17. ?>

  • CCK
  • Drupal 6

Post new comment

The content of this field is kept private and will not be shown publicly.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <em> <strong> <img> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <h3> <h4> <h5> <h6> <h7>
  • Lines and paragraphs break automatically.
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>. The supported tag styles are: <foo>, [foo].

More information about formatting options

Poll

Have you used any NoSQL Databases?:

User login

  • Request new password

Navigation

  • Recent posts

  • home
  • drupal articles
  • contact