Search code examples
apostrophe-cms

piece._page._url nor working after adding projection


I have a widget where I can handpick links to other pages on the site.
In focuslinks-widgets/views/widget.html:

{% for piece in data.widget._pieces %}
    <div class="col-md-4 col-sm-4">
        <a href="{{ piece._page._url }}" class="button">{{ piece.title }}</a>
    </div>
{% endfor %}

My focuslinks/index.js

module.exports = {
    extend: 'apostrophe-pieces',
    name: 'focuslink',
    label: 'Fokuslink',
    pluralLabel: 'Fokuslinker',
    addFields: [
        {
            name: 'title',
            label: 'Navn',
            type: 'string',
            required: true
        },
        {
            name: '_page',
            type: 'joinByOne',
            withType: 'apostrophe-page',
            label: 'Side',
            required: true,
            idField: 'pageId'
        }
    ]
};

This was working as intended, but I had another problem resulting in slow page multiple warnings about missing projections. So for the above widget, I added projections in app.js:

'supernode-focuslinks': {},
'supernode-focuslinks-widgets': {
    extend: 'apostrophe-pieces-widgets',
    filters: {
        projection: {
            slug: 1,
            title: 1,
            type: 1,
            tags: 1
        }
    }
},

Now after this the widget is displaying as before, but there are no href url generated by {{ piece._page._url }} anymore. What am I doing wrong?


Solution

  • The projection you've written here fetches enough information to set the _url property of the piece itself, but not of the page it's joining with (.piece._page._url). To do that you're going to have to make sure your projection also includes the page id so that it can be joined.

    That would look like:

    projection: {
      title: 1,
      _url: 1,
      _page: 1
    }
    

    With this shorthand, using the name of the join itself, Apostrophe looks up the name of the idField for you. Similarly, if you specify _url: 1 Apostrophe substitutes the usual suspects needed to calculate that for a piece or page.

    You should also add a projection to the _page join itself. You don't want to pay the overhead of loading every image and who knows what else on the page just to make a link to it. That is probably what is causing the system to look back and load things more than once, resulting in the warnings you saw.