0

I got an entity type containing a long text field. If a user types in a certain character pattern ("xX" for example), this string "xX" should replaced with "×" (the proper symbol for multiplication) after saving the entity. I looked at hook_field_presave and hook_field_attach_presave but don't know how to use correctly.

This is the code i tried in a custom module:

function replace_multiplication_symbol_field_presave($entity_type, $entity, $field, $instance, $langcode, &$items) {
  if ($field['name'] == 'field_technical_description') {
    foreach ($items as $delta => $item) {
      if (isset($item['value'])) {
        $items[$delta]['value'] = str_replace('xX', '×', $items[$delta]['value']);;
      }
    }
  }
}
4
  • 1
    Can you add more detail to your question? What have you tried? Did you create a custom module for your hook to live in, do you have code you can post of it? The more detail you can get the better the answers we can give you.
    – Jance
    Dec 23, 2014 at 17:13
  • If this is just about better rendering on the front end, I would be inclined to not to transform the entered data, and implement theme_field() (note the customization options) or to use the custom_formatters module instead.
    – bhotel
    Dec 23, 2014 at 21:18
  • @Jance: I added above code which does not take any effect on my field.
    – Madam Adam
    Dec 27, 2014 at 14:28
  • @bhotel: the strings should be altered permanently: when re-editing the content, the proper html-entity should be displayed in the backend/texteditor; so custom_formatters are no option.
    – Madam Adam
    Dec 27, 2014 at 14:31

1 Answer 1

1

So, hook_field_presave, according to the documentation, "Defines custom presave behavior for this module's field types." So unless your defining a field type in your module, this is the wrong hook to use.

Instead, your gonna want to use hook_field_attach_presave. $entity_type will contain the type of entity the save is being called from (node, user, etc). $entity is the full entity object, which you can just go ahead and edit.

For example, a very basic function like so:

function replace_multiplication_symbol_field_attach_presave($entity_type, $entity){
  if(!empty($entity->field_field_technical_description['und'][0]['value'])){
  $entity->field_field_technical_description['und'][0]['value'] = "test";
  }
}

would, whenever an enity is save, check for the field field_field_technical_description and switch it's value to "test," if it's value was not null.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.