3

I have a live entry with an 'eventTime' text field having the content '2pm'.

I also have an unpublished draft saved for that same entry with the 'eventTime' field having the content '3pm'.

I use the following code in my front end template to retrieve the draft for the entry:

{% set entry = craft.entries.section('events').type('ofs').status(null).limit(1).first() %}
{% if entry and entry.enabled %}
    {% set drafts = craft.entryRevisions.getDraftsByEntryId(entry.id) %}
    {% if drafts %}
        {% set entry = drafts[0] %}
    {% endif %}
{% endif %}

Yet the following tag in my template:

{{ entry.eventTime }}

Always displays '2pm' - even though I know the draft is being loaded, as:

{{ entry.draftId }}

Outputs the correct draft ID value.

How do I get it to display '3pm' - i.e. the correct content for the draft being loaded? I've noticed that draft data is stored differently in the database (shoved into a field called 'data' in the 'craft_entryDrafts' table). How do I get at it?

8

Figured this out myself.

The 'getDraftsByEntryId' function is only intended for displaying the list of drafts, so there is no need to populate the model (a potentially expensive task). Indeed, there is a line that unsets the 'fields' part of the data in the EntryRevisionsService.php file:

// Don't initialize the content
unset($result['data']['fields']);

Handily, there is another function called 'getDraftById' that I was able to use, which does populate the model. Therefore, my amended (and working) code is:

{% set entry = craft.entries.section('events').type('ofs').status(null).limit(1).first() %}
{% if entry and entry.enabled %}
    {% set drafts = craft.entryRevisions.getDraftsByEntryId(entry.id) %}
    {% if drafts %}
        {% set entry = craft.entryRevisions.getDraftById(drafts[0].draftId) %}
    {% endif %}
{% endif %}

Boom!

| improve this answer | |

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.