简体   繁体   中英

Slim framework get the data from a form

I try to make a simple form with SLIM framework. I don't know how to display the posted data. I want just to try to echo it. I heard that I need to use extra library RESPECT, I think SLIM can do such small thing.

here is my code :

require '../../vendor/slim/slim/Slim/Slim.php';
\Slim\Slim::registerAutoloader();
$app = new \Slim\Slim();

$app->get('/', function() use ($app){
    $app->render('form.php');
});

$app->post('/', function() use ($app){
    $req = $app->request();
    $errors = array();
    $params = array(
        'email' => array(
            'name'=>'Email',
            'required'=>true,
            'max_length'=>64,
        ),
        'subject' => array(
            'name'=>'Subject',
            'required'=>true,
            'max_length'=>256,
        ),
      );
        //submit_to_db($email, $subject, $message);
        $app->flash('message','Form submitted!');

    $app->redirect('./');
});

$app->run();

In Slim 2, you can access to your posted data using post() method of request() :

$app->post('/', function () use ($app) {
    $request = $app->request();
    $email = $request->post('Email');
    $subject = $request->post('Subject');
    echo "Email: $email<br/>";
    echo "Subject: $subject";
});


In Slim 3, the request is passed to the callback/controller/etc. and you can call getParam() which fetches the value from body or query string (in that order):

$app->post('/', function ($request, $response, $args) {
    $email = $request->getParam('Email');
    $subject = $request->getParam('Subject');
    echo "Email: $email<br/>";
    echo "Subject: $subject";
});

Starting from Slim 3.1 there are also getParsedBodyParam() and getFetchParam() which fetch only from body or query string. ( PR #1620 )


Just as a reminder, you can provide a default value: $request->getParam('Email', 'default_value')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM