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

Booleantype Bundle Laravel Package

bukashk0zzz/booleantype-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require bukashk0zzz/booleantype-bundle
    

    For Symfony Flex projects, ensure extra.symfony.allow-contrib is enabled. For non-Flex projects, manually add the bundle to config/bundles.php:

    return [
        // ...
        Bukashk0zzz\BooleanTypeBundle\BooleanTypeBundle::class => ['all' => true],
    ];
    
  2. First Use Case: Replace a standard checkbox field in a form with the custom boolean type:

    use Bukashk0zzz\BooleanTypeBundle\Form\Type\BooleanType;
    
    $builder->add('isActive', BooleanType::class, [
        'label' => 'Enable Feature',
        'required' => false,
    ]);
    
  3. Where to Look First:

    • Bundle Docs (minimal, but covers core usage).
    • src/Form/Type/BooleanType.php (custom type logic).
    • Resources/views/BooleanType/boolean_widget.html.twig (default Twig template).

Implementation Patterns

Common Workflows

  1. Basic Boolean Field:

    // In a FormType class
    $builder->add('newsletterSubscribed', BooleanType::class, [
        'label' => 'Subscribe to Newsletter',
        'attr' => ['class' => 'custom-checkbox'],
    ]);
    
    • Renders as a styled checkbox (default) or custom template.
  2. Dynamic Boolean Fields: Use in entity forms (e.g., UserType):

    $builder->add('accountVerified', BooleanType::class, [
        'label' => 'Verified',
        'disabled' => true, // Disable if immutable
    ]);
    
  3. Integration with Validation: Combine with Symfony’s Assert\Type or Assert\True/Assert\False:

    use Symfony\Component\Validator\Constraints as Assert;
    
    $builder->add('termsAccepted', BooleanType::class, [
        'constraints' => [
            new Assert\True(message: 'You must accept the terms.'),
        ],
    ]);
    
  4. Custom Templates: Override the default Twig template by creating:

    templates/BooleanType/boolean_widget.html.twig
    

    Example:

    {# Custom switch-like toggle #}
    <input type="checkbox" {{ widget.attributes }} data-toggle="switch">
    
  5. API/JSON Forms: For API platforms (e.g., Symfony UX Turbo), ensure the field returns 0/1:

    $builder->add('isPublished', BooleanType::class, [
        'mapped' => true,
        'normalization_context' => ['groups' => ['api']],
    ]);
    

Integration Tips

  • Symfony UX: Works seamlessly with Symfony UX Live Component or Turbo.
  • Doctrine: Ensure your entity property is bool or boolean:
    /**
     * @ORM\Column(type="boolean")
     */
    private bool $isActive;
    
  • Translation: Label/placeholder translations via Symfony’s translation system:
    # config/packages/translation.yaml
    en:
        boolean:
            label: 'Enable {0}Feature{1}'
    
    $builder->add('isActive', BooleanType::class, [
        'label' => 'Enable %feature%',
        'translation_domain' => 'boolean',
    ]);
    

Gotchas and Tips

Pitfalls

  1. Boolean vs. Integer:

    • The bundle converts true/false to 1/0 by default. If your database expects boolean, ensure your Doctrine mapping uses type="boolean" (not smallint).
    • Fix: Add a Normalizer to enforce types:
      use Symfony\Component\Form\DataTransformerInterface;
      
      class BooleanToIntTransformer implements DataTransformerInterface {
          public function transform($value) {
              return $value ? 1 : 0;
          }
          public function reverseTransform($value) {
              return filter_var($value, FILTER_VALIDATE_BOOLEAN);
          }
      }
      
      Register it in your BooleanType extension.
  2. Template Overrides:

    • If overriding the Twig template, ensure the {{ form_widget() }} variable is passed correctly. The default template expects:
      <input type="checkbox"
              {{ widget.attributes.add({
                  'checked': widget.vars.value ? 'checked' : ''
              }) }}
      >
      
  3. CSRF and Hidden Fields:

    • The bundle does not automatically add hidden fields for false values (unlike Symfony’s default checkbox). If you need this behavior, extend the type:
      class CustomBooleanType extends AbstractType {
          public function getParent() {
              return BooleanType::class;
          }
          public function getBlockPrefix() {
              return 'custom_boolean';
          }
          public function buildForm(FormBuilderInterface $builder, array $options) {
              $builder->addModelTransformer(new BooleanToIntTransformer());
          }
      }
      
  4. Symfony 6+ Deprecations:

    • The bundle may not support Symfony 6’s autoconfigure: true by default. If you encounter issues, manually configure the bundle in config/packages/boolean_type.yaml:
      bukashk0zzz_boolean_type:
          default_options: { required: false }
      

Debugging Tips

  1. Field Not Rendering:

    • Check if the bundle is loaded (php bin/console debug:container bukashk0zzz_boolean_type.boolean).
    • Verify the form type is correctly referenced (BooleanType::class).
  2. Value Not Persisting:

    • Inspect the submitted data with dump($form->getData()) to confirm 1/0 values.
    • Ensure your entity setter accepts bool:
      public function setIsActive(bool $isActive): self {
          $this->isActive = $isActive;
          return $this;
      }
      
  3. Template Caching:

    • Clear the Twig cache if changes to boolean_widget.html.twig aren’t reflected:
      php bin/console cache:clear
      

Extension Points

  1. Custom Widgets: Extend the bundle to support radio buttons or switches:

    // src/Form/Extension/CustomBooleanExtension.php
    use Symfony\Component\Form\AbstractTypeExtension;
    use Bukashk0zzz\BooleanTypeBundle\Form\Type\BooleanType;
    
    class CustomBooleanExtension extends AbstractTypeExtension {
        public function getExtendedType(): string {
            return BooleanType::class;
        }
        public function configureOptions(OptionsResolver $resolver) {
            $resolver->setDefaults([
                'widget_type' => 'switch', // 'checkbox', 'radio', or 'switch'
            ]);
        }
    }
    

    Register the extension in services.yaml:

    services:
        App\Form\Extension\CustomBooleanExtension:
            tags: [form.type_extension]
    
  2. Dynamic Options: Use form events to modify options dynamically:

    $builder->addEventListener(FormEvents::PRE_SET_DATA, function (FormEvent $event) {
        $data = $event->getData();
        $form = $event->getForm();
        $form->add('isAdmin', BooleanType::class, [
            'disabled' => !$data->isSuperAdmin(),
        ]);
    });
    
  3. Localization: Override translations for true/false labels:

    # config/packages/translation.yaml
    en:
        boolean:
            true_label: 'Yes'
            false_label: 'No'
    

    Then in your template:

    {{ form_label(form.isActive) }}
    <input type="checkbox"
           {{ widget.attributes.add({
               'checked': widget.vars.value ? 'checked' : '',
               'data-true': form.vars.data ? 'Yes' : '',
               'data-false': form.vars.data ? 'No' : ''
           }) }}
    >
    
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.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours