1

I'm using a front end form so logged-in users can create a new entry ("post") or edit an existing entry. Here's the controller for figuring out whether it's a new or existing entry:

{# Get the entry being edited from the url parameter #}
{% set entry_id = craft.app.request.getParam('id') %}
{% if entry_id %}
  {% set post = craft.entries({
    id: entry_id,
    status: null
  }).one() %}
{% else %}
  {% set post = null %}
{% endif %}

For the form fields, I'm using Twig partials and with { 'entry' : post }.

This works great for editing a post, and I can create a new post as long as I enter the info that Craft expects. However, there are some required fields, and I want to show error messages when those fields are missing, rather than the post silently failing to be created.

Per the entry form documentation, I'm including the suggested macro and this chunk of code with my required headline field:

{% if entry is defined %}
  {{ errorList(entry.getErrors('headline')) }}
{% endif %}

Desired behavior: if I try to save a new entry that's missing a headline, I should get the error message for that field.

Actual behavior: This gives me a runtime error: Impossible to invoke a method ("getErrors") on a null variable.

I've tried setting post = {} for an empty object, but Twig seems to see that as an array and can't invoke getErrors on that either.

How should I go about addressing this?

1

Thanks to a teammate, got this working!

Needed to change the conditional wrapping my error messages from

{% if entry is defined %}

to

{% if entry is defined and entry is not null %}

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.