PHP code example of w3r-one / json-schema-bundle

1. Go to this page and download the library: Download w3r-one/json-schema-bundle library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

w3r-one / json-schema-bundle example snippets


// config/bundles.php

return [
    // ...
    W3rOne\JsonSchemaBundle\W3rOneJsonSchemaBundle::class => ['all' => true],
];

namespace App\Controller;

use App\Entity\Partner;
use App\Form\PartnerType;
use W3rOne\JsonSchemaBundle\JsonSchema;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;

class FormController extends AbstractController
{
    public function partnerAdd(JsonSchema $jsonSchema): Response
    {
        $form = $this->createForm(PartnerType::class, new Partner(), ['validation_groups' => ['Default', 'Form-Partner']]);

        return new JsonResponse($jsonSchema($form));
    }



namespace App\Controller;

use App\Entity\Partner;
use App\Form\PartnerType;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Entity;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use W3rOne\JsonSchemaBundle\JsonSchema;
use W3rOne\JsonSchemaBundle\Utils;

class PartnerController extends AppAbstractController
{
    /**
     * @Entity("partner", expr="repository.findOne(partnerId)")
     */
    public function edit(Partner $partner, JsonSchema $jsonSchema, Request $request): Response
    {
        $form = $this->createForm(PartnerType::class, $partner, ['validation_groups' => ['Default', 'Form-Partner'], 'scope' => 'edit'])->handleRequest($request);

        if ($form->isSubmitted()) {
            if ($form->isValid()) {
                $this->em->flush();

                if ($request->isXmlHttpRequest()) {
                    return new JsonResponse([
                        'message' => 'The partner was successfully updated.',
                        'redirect_url' => $this->generateUrl('app_partner_show', ['partnerId' => $partner->getId()]),
                    ], Response::HTTP_OK);
                } else {
                    $this->addFlash('success', 'The partner was successfully updated.');

                    return $this->redirectToRoute('app_partner_show', ['partnerId' => $partner->getId()]);
                }
            } else {
                if ($request->isXmlHttpRequest()) {
                    return new JsonResponse([
                        'message' => 'There are errors in the form, please check.',
                        'errors' => Utils::getErrors($form),
                    ], Response::HTTP_BAD_REQUEST);
                } else {
                    $this->addFlash('error', 'There are errors in the form, please check.');
                }
            }
        }

        return $this->render('pages/partner/edit.html.twig', [
            'form' => $form->createView(),
            'partner' => $partner,
            'pageProps' => \json_encode([
                'form' => $jsonSchema($form),
                'errors' => Utils::getErrors($form),
                'partner' => \json_decode($this->apiSerializer->serialize($partner, ['default', 'partner'])),
            ]),
        ]);
    }
}



namespace App\Serializer;

use Symfony\Component\Serializer\Normalizer\AbstractNormalizer;
use Symfony\Component\Serializer\Normalizer\AbstractObjectNormalizer;
use Symfony\Component\Serializer\SerializerInterface;

class ApiSerializer
{
    private $serializer;

    public function __construct(SerializerInterface $serializer)
    {
        $this->serializer = $serializer;
    }

    public function serialize($data, array $groups = ['default'], array $attributes = [], array $callbacks = []): string
    {
        $context = [
            AbstractObjectNormalizer::ENABLE_MAX_DEPTH => true,
            AbstractNormalizer::GROUPS => $groups,
        ];
        if (!empty($attributes)) {
            $context[AbstractNormalizer::ATTRIBUTES] = $attributes;
        }
        if (!empty($callbacks)) {
            $context[AbstractNormalizer::CALLBACKS] = $callbacks;
        }

        return $this->serializer->serialize($data, 'json', $context);
    }
}


$builder
    ->add('name', TextType::class, [
        'label' => 'Name',
        'w3r_one_json_schema' => [
            'foo' => 'bar',
        ],
    ]);

$builder
    ->add('address', TextType::class, [
        'label' => 'Address',
        'w3r_one_json_schema' => [
            'widget' => 'google_autocomplete',
            'layout' => 'two-cols',
        ],
    ]);



namespace App\JsonSchema;

use Symfony\Component\Form\FormInterface;
use W3rOne\JsonSchemaBundle\Transformer\ObjectTransformer;
use W3rOne\JsonSchemaBundle\Utils;

class VichFileTypeTransformer extends ObjectTransformer
{
    public function transform(FormInterface $form): array
    {
        $schema = parent::transform($form);
        $schema['options']['vichFile'] = [
            'allowDelete' => $form->getConfig()->getOption('allow_delete'),
            'downloadLink' => $form->getConfig()->getOption('download_link'),
            'downloadUri' => $form->getConfig()->getOption('download_uri'),
            'downloadLabel' => $this->translator->trans($form->getConfig()->getOption('download_label'), [], Utils::getTranslationDomain($form)),
            'deleteLabel' => $this->translator->trans($form->getConfig()->getOption('delete_label'), [], Utils::getTranslationDomain($form)),
        ];

        return $schema;
    }
}



namespace App\JsonSchema;

use W3rOne\JsonSchemaBundle\Transformer\IntegerTransformer;

class PositionTypeTransformer extends IntegerTransformer
{
}



namespace App\JsonSchema;

use Symfony\Component\Form\FormInterface;
use W3rOne\JsonSchemaBundle\Transformer\Type\TextareaTypeTransformer as BaseTextAreaTypeTransformer;

class TextareaTypeTransformer extends BaseTextAreaTypeTransformer
{
    public function transform(FormInterface $form): array
    {
        $schema = parent::transform($form);
        $schema['options']['widget'] = 'wysiwyg';
        $schema['options']['wysiwyg'] = [
            'config' => [
                // ...
            ],
        ];

        return $schema;
    }
}