I want have added an extra field to a table and want to use db_update in hook_update_N to populate it with a sanitized copy of a preexisting field.

Just copying a pre-existing field is trivial if one uses db_update().

  ->expression('field_copyof_unsafe_value', 'field_unsafe_value')

However, what I want to do something like this:

  ->expression('field_plain_value', check_plain('field_unsafe_value'))

I.e. pass the value of field_unsafe_value through some function before storing it in the new field.

For avoidance of misunderstanding: I know the code above will not work (and that it will throw an exception). It is pseudo-code to illustrate what I want to achieve.

My question is: Is it possible to use a function call in db_update() to compute value to store, and if "yes": How to do it?

  • 2
    Only if it’s a MySQL function, otherwise you’ll need to SELECT the existing data, loop through it and update. Also bear in mind there are revision tables, those need to be updated too – Clive Aug 25 '18 at 18:42
  • @Clive. Thanks! I've already written a loop using SELECT. It just seems so clunky. At least it is good to know that I don't need to waste more time looking for this. – Free Radical Aug 25 '18 at 18:49
  • The Drupal convention is to sanitize during output not input. – No Sssweat Aug 26 '18 at 0:21
  • @NoSssweat. I know. The question is about using a function call in db_update() . Sanitation is only used as an example, as I assumed that the PHP function check_plain() is well known do Drupal developers. – Free Radical Aug 26 '18 at 4:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.