Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Rad Bundle Laravel Package

becklyn/rad-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle via Composer:

    composer require becklyn/rad-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        Becklyn\RadBundle\BecklynRadBundle::class => ['all' => true],
    ];
    
  2. First Use Case: AJAX Response Inject AjaxResponseBuilder into a controller:

    use Becklyn\RadBundle\AjaxResponseBuilder;
    
    class MyController extends AbstractController
    {
        public function ajaxAction(AjaxResponseBuilder $builder): Response
        {
            return $builder
                ->ok()
                ->data(['key' => 'value'])
                ->build();
        }
    }
    

    Use the mojave client to handle responses in TypeScript:

    const response = await fetch('/ajax-endpoint');
    const result = await mojave.ajaxResponse(response);
    if (!result.ok) {
        // Handle error (e.g., `result.status` = "invalid-id")
    }
    
  3. Form Extensions Extend a form type with RadFormExtension:

    use Becklyn\RadBundle\Form\Extension\RadFormExtension;
    
    class MyFormType extends AbstractType
    {
        public function buildForm(FormBuilderInterface $builder, array $options)
        {
            $builder->addExtension(new RadFormExtension());
        }
    }
    

Implementation Patterns

AJAX Workflows

  1. Consistent Response Handling Use AjaxResponseBuilder for all AJAX endpoints to enforce the protocol:

    return $builder
        ->ok()
        ->status('custom-status')
        ->data(['items' => $items])
        ->message(['text' => 'Success!', 'impact' => 'positive'])
        ->build();
    
  2. Frontend Integration Pair with mojave for TypeScript:

    // Handle redirects
    if (result.redirect) {
        window.location.href = result.redirect;
    }
    // Show toasts
    if (result.message) {
        mojave.toast(result.message);
    }
    
  3. Error Handling Return non-ok responses with descriptive status:

    return $builder
        ->fail()
        ->status('invalid-data')
        ->data(['errors' => $errors])
        ->build();
    

Form Patterns

  1. Dynamic Field Validation Use RadFormExtension to add client-side validation:

    $builder->add('email', EmailType::class, [
        'constraints' => [new NotBlank(), new Email()],
    ]);
    // Automatically adds `data-rad-constraints` attributes.
    
  2. Custom JavaScript Events Attach events via RadFormExtension:

    $builder->addExtension(new RadFormExtension([
        'events' => [
            'submit' => 'myCustomSubmitHandler',
        ],
    ]));
    
  3. Nested Form Support Extend nested forms for AJAX-driven updates:

    $builder->add('address', AddressType::class, [
        'entry_options' => ['rad' => ['ajax' => true]],
    ]);
    

Integration Tips

  1. Symfony UX Turbo/Stimulus Combine with Symfony UX for progressive enhancement:

    // Controller
    return $builder
        ->ok()
        ->data(['html' => $this->renderView('partial.html.twig')])
        ->build();
    
    // Stimulus controller
    connect() {
        this.fetch('/ajax-endpoint').then(response => {
            this.element.innerHTML = response.data.html;
        });
    }
    
  2. API Platform Override serializeContext to inject AJAX metadata:

    public function serializeContext(Operation $operation, array $uriVariables = [], array $context = []): array
    {
        $context['groups'] = ['ajax'];
        return parent::serializeContext($operation, $uriVariables, $context);
    }
    
  3. Custom Twig Functions Extend Twig with AJAX-aware helpers:

    // services.yaml
    Becklyn\RadBundle\Twig\AjaxExtension:
        tags: ['twig.extension']
    

Gotchas and Tips

Pitfalls

  1. Deprecation Warning

    • The bundle is deprecated in favor of becklyn/rad v8+.
    • Migrate to the standalone rad package for long-term support.
  2. TypeScript Mismatch

    • Ensure mojave is updated to match the AjaxResponse interface in the bundle.
    • Version skew may cause runtime type errors.
  3. Form Extension Conflicts

    • RadFormExtension may override existing form behaviors (e.g., CSRF tokens).
    • Test thoroughly with nested forms and custom form types.
  4. AJAX Redirects

    • Redirects (redirect field) are client-side only. Ensure your frontend handles them gracefully:
      if (result.redirect && !result.redirect.startsWith('http')) {
          // Assume relative path
          window.location.href = result.redirect;
      }
      

Debugging

  1. Response Validation Use var_dump($builder->getResponse()) to inspect the raw response before sending.

  2. Frontend Errors Check the browser’s Network tab for malformed AJAX responses. Validate:

    • ok is a boolean.
    • status is a non-empty string.
    • data is serializable (no circular references).
  3. Form Events Debug JavaScript events with:

    document.addEventListener('rad:submit', (e) => {
        console.log('Form submitted:', e.detail);
    });
    

Configuration Quirks

  1. Default AJAX Protocol

    • The bundle always returns HTTP 200 for AJAX requests, even on errors.
    • Configure your error tracker (e.g., Sentry) to ignore AJAX 200 responses with ok: false.
  2. Twig Autoescape Disable autoescaping for AJAX-returned HTML:

    {{ render(controller('AppController::ajaxPartial'))|raw }}
    
  3. CSRF Protection

    • AJAX forms require CSRF_TOKEN in headers. Use mojave to auto-include it:
      mojave.fetch('/submit', {
          method: 'POST',
          headers: { 'X-Requested-With': 'XMLHttpRequest' },
      });
      

Extension Points

  1. Custom Response Builders Extend AjaxResponseBuilder:

    class CustomResponseBuilder extends AjaxResponseBuilder
    {
        public function withCustomField($value): self
        {
            $this->response['custom'] = $value;
            return $this;
        }
    }
    
  2. Form Event Extensions Add custom events to RadFormExtension:

    $builder->addExtension(new RadFormExtension([
        'events' => [
            'change:email' => 'validateEmail',
        ],
    ]));
    
  3. Twig Globals Override Twig globals for AJAX-specific filters:

    // services.yaml
    Becklyn\RadBundle\Twig\AjaxRuntime:
        tags: ['twig.runtime']
    
  4. Serializer Normalization Customize serialization for AJAX responses:

    // config/packages/serializer.yaml
    Becklyn\RadBundle\Serializer\AjaxNormalizer:
        tags: [serializer.normalizer]
        arguments: ['@serializer.mapping.class_metadata_factory']
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware