Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/nebkam/symfony-traits
Few helper traits for quicker API development in Symfony
https://github.com/nebkam/symfony-traits
form helpers symfony
Last synced: about 1 month ago
JSON representation
Few helper traits for quicker API development in Symfony
- Host: GitHub
- URL: https://github.com/nebkam/symfony-traits
- Owner: nebkam
- Created: 2018-03-22T12:52:34.000Z (almost 7 years ago)
- Default Branch: master
- Last Pushed: 2024-08-09T05:47:44.000Z (5 months ago)
- Last Synced: 2024-09-25T09:34:45.213Z (3 months ago)
- Topics: form, helpers, symfony
- Language: PHP
- Homepage:
- Size: 34.2 KB
- Stars: 16
- Watchers: 3
- Forks: 2
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
[![Latest Stable Version](https://poser.pugx.org/nebkam/symfony-traits/v)](//packagist.org/packages/nebkam/symfony-traits)
# Symfony Traits
Few helper traits for quicker API development in Symfony## FormTrait
### `handleJSONForm`
- controller helper method for JSON data sent in `POST`, `PUT` or `PATCH` request content
- generally speaking, sending JSON content is more flexible than forms, for CRUD with JS frameworks.```php
public function create(Request $request)
{
$entity = new Entity();
$this->handleJSONForm($request, $entity, EntityType::class, $options = [], $clearMissingFields = true);
// persist and flush $entity
``````php
public function edit(Request $request,Entity $entity)
{
$this->handleJSONForm($request, $entity, EntityType::class, $options = [], $clearMissingFields = true);
// flush entity
```
### `handleForm`
- controller helper method for traditional form data in `GET` or `POST`
- I advice using traditional form data only when JSON is out of place (i.e. `GET` params)```php
public function example(Request $request)
{
$domain = new Domain();
if ($request->query->count() > 0)
{
$this->handleForm($request, $params, DomainType::class, $options = [], $clearMissingFields = true);
}
// do something with $domain
```### `handleUpload`
- controller helper method to validate a single file upload
- a lightweight alternative to a [File constraint](http://symfony.com/doc/current/reference/constraints/File.html), when you need just one file, not the whole form```php
public function uploadImage(Request $request)
{
$file = $this->handleUpload($request, 'image');
// do something with $file
}
```### `ValidationExceptionListener`
Since all `handle*` methods in this trait throw a `Nebkam\SymfonyTraits\ValidationException`, you have to catch it, either via `try {..} catch` in the controller or via global exception listener.
To ease this, this package includes a sample exception listener, which returns validation errors in JSON. You just have to register it as a service:```yaml
Nebkam\SymfonyTraits\EventListener\ValidationExceptionListener:
tags:
- { name: kernel.event_listener, event: kernel.exception }
```