2

I'm building a simple contact form plugin and I would like to be able to provide a default form that the developer can include in his own template.

Most plugins I've seen provide the controller and all the code to process a submitted form but you still have to create your own form.

At the moment I tried 2 methods, using a hook and a template variable. While both work I was wondering if there wasn't a better/cleaner method.

The downside of using a hook is that you can't pass variables to the template (or am I wrong?) and the template variable feels like a misuse of the functionality.

Isn't there a way to use the existing twig import function? Maybe by registering a namespace twig path in the plugin?(https://symfony.com/doc/current/templating/namespaced_paths.html)

1

You can include a property to your form called $templatePath and users can insert whatever they want in this path with a default value to your own template.

When someone executed your render() function you check if the template file exists in the public template path, if so render it, it not render one of your plugin templates.

If the validation fails, you want to include the validated data with errors to the url manager, so you can access it later. During your render() function you can check if there is data and if it matches your current form element, if so render the data in your url manager instead of the element to display errors.

  • Thank you for your answer but I don't understand how this would work. What do you mean with "include a property to your form"? – dazz Jul 26 '18 at 11:47
  • Just add an additional class property php.net/manual/en/language.oop5.properties.php to your Form model that clients may set/change – Robin Schambach Jul 26 '18 at 11:49
  • Ok, and then, how would the 'user' use this in their twig template? The idea is to include the contact form template in their own template, how would the render() function be called from twig? – dazz Jul 26 '18 at 12:29
  • You would do something like {{ form.render() }} the form can be fechted via ElementQuery or via BaseRelationField like every other relation in Craft. Most Form plugins handle it that way or something similar – Robin Schambach Jul 26 '18 at 18:33

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.