简体   繁体   中英

WYSIWYG in custom field in drupal 7

I am trying to build a custom field in drupal 7. evrything work just fine, except from the wysiwyg field. I am using the next code to build an WYSIWYG element:

$element['my_body'] = array(
  '#title' => t('Editor'),
  '#type' => 'text_format',
  '#tree' => true,
  '#rows' => 20,
  '#format' => 'filtered_html',
 );

When its not wysiwyg (regular textarea) all save go fine, but after i change it to text_format, drupal get the value of the field as array with 2 keys (value and format), and that's make an error while drupal save the values of the field. As much as i understnad it, what drupal expect to get is two deferent values (of body_filter and format) and not an body_filter array with 2 keys (value and format).

Anyone can give me a hint how to solve this issue (can't find anything relevant in google and drupal.org)?

Thanks.

I bumped into the same problem, and found a solution, thanks to Berdir's hint.

As you mentioned 'text_format' returns an array with two values like:

$items[0]['MY_WYSIWYG_FIELD'] = array(
    'value' => 'some text.',
    'format' => 'filtered_html'
);

Using hook_field_presave() I was able to prepare the values to save it into my db.

As I don't want to save the format value, I simply extract the text value from the ['MY_WYSIWYG_FIELD'] array and replace the array with the extracted value:

$items[0]['MY_WYSIWYG_FIELD'] = 'some text.';

my hook looks like this:

function MY_FIELD_MODULE_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
    if ($field['type'] == 'MY_FIELD_TYPE') {
    foreach ($items as $delta => $item) {
    if (isset($item['MY_WYSIWYG_FIELD'])) {
        $value = $item['MY_WYSIWYG_FIELD']['value'];
        $items[$delta]['MY_WYSIWYG_FIELD'] = $value;
        }
        }
    }
}

Hope this helps!

The value of text_format type fields come as $form_state['values']['my_body']['value'] .

Yes, the value of a text_format field is an array, that's how it is supposed to be.

Drupal does not save something automatically, where and how are you saving it? You simply need to fix that code to work with an array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM