Find answers, ask questions, and connect with our
community around the world.

Forums Forums Web Design WordPress How to create form that submits content to the database, and automatically displays immediately on website. Reply To: How to create form that submits content to the database, and automatically displays immediately on website.

  • daniel34798

    Guest
    December 5, 2020 at 3:31 pm

    You can display the form using a custom shortcode with `add_shortcode(…)`. Put the form HTML code on a separate file as they asked for MVC.

    For the database, be aware that WordPress doesn’t use ORM – you will have to use pure SQL via `wpdb`, unless you install an ORM library. Create your custom table during the plugin installation with `register_activation_hook(…)`.

    For the form sending, it would be easier if you could use the AJAX/REST API, but they asked for a form with a POST method, so I’m assuming they don’t want AJAX. Use a workaround I like to call “the router method”. Set the form action to “?save-contact”. Use the `init` hook to intercept all HTTP requests and look for the ones with the “save-contact” argument.

    To display the information entered on the database, you can use the session. Just store the fields in the session, and on the shortcode, check if there’s a “save-contact” on the URL arguments. If there is, then display the info from the session. If there’s not, display the form.

    I don’t know what they mean by “handle the CRUD operations” in this scenario. I’ve never seen a contact form where I can see other’s entries, delete and/or update them. Contact forms are supposed to only allow creation. Unless they want an admin dashboard to manage all this – that would make more sense.

    Don’t forget security: use nonces on the form, escape the form inputs to prevent SQL-injections, and escape the output to prevent XSS.

    To show off, you can use composer to autoload your classes. Make sure your code follows the WordPress coding style (use phpcs for this). Create the plugin using “wp-cli”. You can use Blade for your views (“jenssegers/blade” library), Eloquent for your models (“tareq1988/wp-eloquent”), and JetRouter for your router (“sformisano /jetrouter”) – but I’m afraid they wouldn’t like it as you wouldn’t be showing your skills too much.