Adding a routes.php file and example POST method to App\Controllers\Mail.php

Hey guys, I use sage often and I constantly find myself adding in a routes file, so that I can use Vue to send my contact forms to the server to be emailed out. I was wondering if I made a pull request to the main repo with my additions that it would be considered?

I don’t mind doing that for sage - I just don’t want to waste my time if it doesn’t fit into the goal of sage.

Here are the files that would change in summary:

functions.php - add routes to the array map [‘helpers’, ‘setup’, ‘filters’, ‘admin’, ‘routes’]
add new routes.php inside the app folder with some boilerplate like:

<?php

namespace App;

// Define Routes

add_action( 'rest_api_init', function () {

register_rest_route( 'sage', '/submit-contact', array(
    'methods' => 'POST',
    'callback' => array( 'App\Controllers\Mail', 'sendContactForm' )
));

});

Then in a new Mail controller just add a static method that has a simple mail function that accepts name, email, message and directs it to the site_admin email. I think it might help people understand quicker how they can create routes like laravel to do custom server side things. Contact forms are quite common and easy to do especially if this was partially laid out for sage users.

Thanks

I like this idea to organize our code.

Being a Laravel developer as well, I liked this approach and tried it.
I’ve added ‘routes’ to the array map and added a new ‘routes.php’ file in the app folder.

I was able to call a function like ‘sendContactForm’ in a controller like ‘App\Controllers\Mail’ but… I was not able to read the posted values from a form in that function. How do you do that? $_POST seems to be empty?

Create the Mail class like so and you should be able to get the request data.

class Mail extends Controller
{
    public static function sendContactForm( $request ){
        $data = $request->get_params();
        $name = $data['name'];
    }
 }

Yes thank you that worked.

It turned out my problem was on the front end: my ajax posting was not correct.
Thanks!

This topic was automatically closed after 42 days. New replies are no longer allowed.