I have a Plugin which saves data from a form the user enters on my front-end. When the input data is wrong and I display my validation errors using getErrors from the Model I want to re-populate all my form fields with the submitted data in my Twig template.

Right now I'm doing this like this:

<input type="text" name="fieldName" value="{% if model is defined %}{{ model.fieldName}}{% endif %}"/>

Is this the correct way of doing this or is there a better practice?

Seems like there's to many unnecessary if statements going on...

Thank you


The way the Craft docs do it is basically how you are already:

<label for="userLastName">Last Name *</label>
<input id="userLastName" type="text" name="fields[userLastName]" {%- if entry is defined %} value="{{ entry.userLastName }}"{% endif -%}>
  • Cool. Then I guess this is the way to go forward. Cheers! :) Oct 28 '14 at 12:56
  • 1
    Worth noting... You can also use Twig's ternary syntax: {{- entry is defined ? 'value="'~entry.userLastName~'"' -}}
    – Lindsey D
    Oct 28 '14 at 14:56

If you use that form to edit entries AND add new ones, then yes, this is probably the correct way to do this. But if this is an edit only form / template then you could check for the model once and if no model is defined don't show your form at all.

{% if model is defined %}
    <input type="text" name="fieldName" value="{{ model.fieldName}}"/>
{% endif %}
  • This is for a regular form the user submits info with and if the validation fails the user is promted with having to correct it's data before re-submitting. Oct 28 '14 at 12:17
  • No. Then using it inline within your input fields is correct, @naboo!
    – carlcs
    Oct 28 '14 at 12:57

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.