How to update the value of a single field invoking appropriate validation
Asked Answered
P

1

6

I'm making a module to allow users to update single fields on in this case, their user entity.

The code below is an example of the method I have initially been using to get it working and test other elements of the module

global $user;
$account = user_load($user->uid);
$edit = (array) $account;
$edit['field_lastname']['und'][0]['value'] = 'test';
user_save($account, $edit);

However this bypasses any field validation defined elsewhere in Drupal. I don't want to reproduce any validation written elsewhere - it's not the Drupal way!

My question is: Is there a function in Drupal 7 that can be called to update the value of a single field. I imagine such a function would clear the appropriate caches, invoke the fields validation etc.

I am aware the solution will be totally different to my current user object based one. I just can't for the life of me find the appropriate function in the API. I wander whether the fact I am looking for a save function alone is the problem - and that there are some other necessary steps that come before.

Any help gratefully appreciated.

Porshaport answered 18/2, 2011 at 11:24 Comment(0)
S
1

Check out the drupal_form_submit function. It lets you submit forms from code. In this case, you could use it to the user edit form, which would then fire the appropriate validation.

Sear answered 18/2, 2011 at 15:39 Comment(4)
Thanks Matt. I was thinking of using something like that. Ideally though, I was hoping to have to save a single value for a single field. Correct me if I'm wrong, but to re-use the forms' submit and validation functions wouldn't I have to pass all the required information to the form? - in the same way my example required firing up the original user object before altering and saving. I was hoping there might be a Drupal function to save field data itself. Perhaps I am hoping for too much and it is required to by tied to a form submissionPorshaport
You could do it the way your code sample specifies and call the validation functions yourself. Otherwise, it's the Form API that calls the validation, so by bypassing the Form API, you're bypassing the validation.Sear
Thanks again Matt. I think I am looking for a feature that isn't there ;-) I will carry on reading (and re-reading) the Field API and post back if I find exactly what I was looking for. You're right, it doesn't look like I can have it both ways at the moment. Cheers againPorshaport
I haven't used it yet. But thought I would post an update having just asked another different question here. It seems the functions I was looking for were here api.drupal.org/api/drupal/modules--field--field.attach.inc/7 and you could run field_attach_validate and then field_attach_update wrapped in some custom code. Looks good to me. When I ever get back to that project I'll let you know definitivelyPorshaport

© 2022 - 2024 — McMap. All rights reserved.