Forms
Web apps have to deal with forms almost every time. Entropy exposes a handful API that helps developers handle form requests in a simple way.
An example form for a feature like user registration may look like this:
views/register.atom.html
<form action="/users" method="post" enctype="multipart/form-data"> <input type="text" name="name" placeholder="Username"> <input type="email" name="email" placeholder="E-mail"> <input type="file" name="avatar"> <button>Register</button> </form>
Retrieving Form Fields
To obtain form control values, you need to explicitly define route request param of type Request
:
src/users/user.controller.ts
import { HttpRequest } from '@entropy/http'; import { Controller, Route } from '@entropy/router'; export class UserController extends Controller { @Route.Post('/users') public async store([], request: HttpRequest) { const name = await request.input('name'); return `Hello ${name}!`; } }
As you can see, you can easly get access to form text fields using request.input
method.
To easly obtain boolean values like type="checkbox"
HTML inputs, use the request.boolean
method:
views/register.atom.html
<form action="/users" method="post"> <!-- ... --> <input type="checkbox" name="newsletter"> <button>Register</button> </form>
src/users/user.controller.ts
export class UserController extends Controller { @Route.Post('/users') public async store([], request: HttpRequest) { const subscribe = await request.boolean('newsletter'); if (subscribe) { // Subscribe user to newsletter } } }
File Uploading
Entropy provides a simple form file uploading API as well, so you can easly send files through HTML forms without any additional configuration.
src/users/user.controller.ts
export class UserController extends Controller { @Route.Post('/users') public async store([], request: HttpRequest) { const file = await request.file('avatar'); await file.upload('public/avatars', 'avatar.png'); return 'User avatar uploaded successfully'; } }
Basically all you have to do is to provide file destination (in this case public/avatars
) and Entropy will handle everything for you.
In case you don't provide file name argument, Entropy will generate a unique name for the uploaded file. It is very useful and recommended to use for features like posting images.
src/posts/post.controller.ts
export class PostController extends Controller { @Route.Post('/posts') public async store([], request: HttpRequest) { const file = await request.file('image'); const filename = await file.upload('public/images'); return `Successfully uploaded post image public/images/${filename}`; } }