4

I am attempting to create a "dynamic" button. By that I mean I want the user to be able to update the text and the target (href) of where the button links to when clicked.

So I created fields: buttonText and buttonTarget.

buttonText is just a plain text field - no problem.

For the buttonTarget field type I chose "Entry" and selected the source(s) in the checklist that follows with a limit of one. So far so good.

In my actual entry, I enter the buttonText of "Hello World". Preview the page and "Hello World" shows up as the button text. So far so good.

Lets say I have a page called "Hello". For my buttonTarget field I click on "Add an Entry" and choose "Hello" from the entry list.

When I preview my site now, I get this error:

Object of class Craft\ElementCriteriaModel could not be converted to string

That makes perfect sense since I need everything to evaluate to a string. I'm not sure how I can output (for lack of better words) the object so that I can see/find what properties are.

Here is what I am using to display the button:

html

<p><a href="{{entry.buttonTarget}}" class="btn btn-default">{{entry.buttonText}}</a></p>

I assume I need something like {{entry.buttonTarget.uri}} but I haven't been able to find out what the actual parameter is I need. {{entry.uri}} outputs nothing.

EDIT

Doing this gets the result I am after: {{entry.slug}} This uses the current entry's slug instead of the custom field value. Which is ok - I can use the slug as the href target. Ideally I'd like to use the custom field though.

| improve this question | | | | |
11

Even if you set the limit to 1, Craft always returns an array of entries. So you need to add first() to access the first (and only) entry.

{{ entry.buttonTargets.first() }}

It you don't add a property, this returns the entry's title by default. So you additionally need to add url to output the URL of that entry.

{{ entry.buttonTargets.first().url }}
| improve this answer | | | | |
  • Thank you so much! This is exactly the hint I needed. I'm "new" to Craft, (love it) and didn't realize that regardless Craft will always return an array. Adding the additional property (url, id etc) makes perfect sense to get the value(s) I am after. Thank you! – Damon Feb 6 '15 at 17:24
  • 1
    @dragonslovetacos a good thing to do is to always name the field handle in plurals for such fields: buttonTargets instead of buttonTarget for your Entries Field or assets for an Asset Field even if restricted to only take one asset. – carlcs Feb 6 '15 at 17:28
  • Great advice - will do! – Damon Feb 6 '15 at 17:34
  • 1
    You should also check that that first entry exists: {% if entry.buttonTargets.first() %}{{ entry.buttonTargets.first().url }}{% endif %} – Marion Newlevant Feb 6 '15 at 20:12

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.