Thanks a lot! I was driving mad with this issue. I have a custom web service for pushing nodes to my site and thus I was receiving and set in right (well I thought was the right way to do it) on save the title_field value was set back to null. Anyway thanks again and great tip, should be included on Title module docs.
Drupal 7: Setting title module field programmatically
Submitted by Andrej Galuf on 27. November 2015.
Hello and welcome back to Drupal Tips and Tricks. Today we will be looking at the Title module in combination with Entity Translation and we will be trying to change the value of the title field programmatically.
Title module replaces the title property on an entity with a field that can hold different language values. Unfortunately, this isn't as simple as it sounds, because the core title property is defined and used by the core directly in the node table.
As a result, there are some unforseen side effects, such as problems when saving the value outside the dedicated code, for instance programmatically or from a custom form submit.
Let's look at one such example submit:
<?php $wrapper = entity_metadata_wrapper('node', $nid); $wrapper->language('en')->title_field->set('Test'); $wrapper->save();
Unfortunately, the above code does not work as expected. If you're lucky, this code won't do anything - the title value won't change. If you're unlucky, the core will break your titles completely (for instance, set a title in original language rather than translation).
How can we fix this?
First, you'll need the patch #27 here. Copy it to the title module folder and apply as usual (patch -p1 < 2267251-27.patch). Now, let's try again:
<?php // Node language is 'en' $wrapper = entity_metadata_wrapper('node', $nid); $wrapper->language('en')->title_field->set('English Title'); $wrapper->language('de')->title_field->set('German Title'); $wrapper->save();
Can you guess what this code will do? It will save the german title, but not the english one.
Title module makes sure that the title_field in original language and node title are syncronized at all times. Unfortunately, the code ignores the value in the original language when set through the title_field. Here's the correct way to save the original and translated title value:
<?php // Node language is 'en' $wrapper = entity_metadata_wrapper('node', $nid); $wrapper->title->set('English Title'); $wrapper->language('de')->title_field->set('German Title'); $wrapper->save();
Hopefully, this will save you some debugging time.