Home ›
Saving message entities programmaticallySaving message entities programmatically
Submitted by Benjamin Melançon on April 18, 2016 - 8:19pm
Our use case, re-saving existing messages, is a bit more complex than it should be, but not bad. This code will work for new or existing messages.
Where $exports is an array of long text strings that is each the JSON dump received form exporting a message type through the UI:
<?php
foreach ($exports as $export) {
$entity = entity_import('message_type', $export);
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'message_type')->propertyCondition('name', $entity->name)->execute();
if ($result) {
$entity->is_new = FALSE;
$entity->id = array_shift(array_keys($result['message_type']));
}
entity_save('message_type', $entity);
$label = entity_label('message_type', $entity);
watchdog('message_type', 'Imported message_type %label.', array('%label' => $label));
}
?>
Searched words:
drupal 7 message type in code
drupal 7 message type programmatically import from export
Comments
And deleting them...
<?php
// Delete message types that are no longer used.
$names = array(
'message_name_here',
'another_message_name',
);
$result = $query->entityCondition('entity_type', 'message_type')->propertyCondition('name', $names)->execute();
entity_delete_multiple('message_type', array_keys($result));
?>
Note that if the message is provided in code, deleting just has the effect of setting it to default. (Note: Pretty sure it didn't work when deleting by name directly, rather than looking up the ID first, but i might have been looking at the wrong environment...)
Post new comment