I have added some fields to my user entity, (doing this in hook_install(), in .install file). This is in a custom module. If I uninstall this custom module I only want to uninstall those fields if users don't have any values for the field, so I don't end up losing data from my users. How can I check fields of a user?
2 Answers
I would advise against keeping those fields around after an uninstall. It's a module's responsibility to clean up after itself, and a user of your module should be able to assume that if they disable the module, the functionality will be gone, but the data remains in the database. If the user uninstalls the module, the assumption is that the module will clean up after itself - delete all its data, custom tables, created variables, etc.
If you don't want to lose any data, just disable your module without uninstalling it - then the uninstall hook doesn't run. But my suggestion is to keep to the community's expectations and properly clean up the custom database tables, fields and variables that your module has created in the uninstall_hook.
I think with open source projects like Drupal, where there are tons and tons of contributing authors and contrib modules, it's even more important for each of us to conform to the expectations of a module's behavior. Otherwise, if each module does what it wants upon uninstall, we wouldn't know what to expect in terms of our databases. What if a user has another contrib module that conflicts with your module's fields, for example? How could they ever get rid of them if your uninstall hook doesn't clean them up?
I took a stab and typed field_has_data into Google...low and behold :)
Determine whether a field has any data.
Returns
TRUE if the field has data for any entity; FALSE otherwise.
It takes a field structure as an argument, which you can get from field_info_field()
$field = field_info_field('field_name'); if (field_has_data($field)) { // ... }