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

Crudgeneratorbundle Laravel Package

dlmappstools/crudgeneratorbundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation Add the bundle to your composer.json:

    composer require dlmappstools/crudgeneratorbundle
    

    Enable it in config/bundles.php:

    return [
        // ...
        DlmAppsTools\CrudGeneratorBundle\DlmAppsToolsCrudGeneratorBundle::class => ['all' => true],
    ];
    
  2. Configuration Publish the default config:

    php bin/console dlm-apps-tools:crud:generate:config
    

    Edit config/packages/dlmapps_tools_crud_generator.yaml to define your CRUD entities and fields.

  3. First Use Case Generate a basic CRUD for a User entity:

    php bin/console dlm-apps-tools:crud:generate --entity=App\Entity\User
    

    This creates:

    • Controller (src/Controller/UserCrudController.php)
    • Twig templates (templates/crud/user/)
    • Form types (src/Form/UserType.php)
    • Optional: Repository, Service, and Event listeners (if configured).

Implementation Patterns

Workflow: Iterative CRUD Development

  1. Define Entity & Fields Configure your entity in config/packages/dlmapps_tools_crud_generator.yaml:

    dlmapps_tools_crud_generator:
        entities:
            App\Entity\User:
                fields:
                    - { name: username, type: text, label: 'Username' }
                    - { name: email, type: email, label: 'Email' }
                actions:
                    - list
                    - create
                    - edit
                    - delete
    
  2. Generate & Customize Run the generator:

    php bin/console dlm-apps-tools:crud:generate --entity=App\Entity\User --overwrite
    
    • Extend the Controller: Override methods in UserCrudController (e.g., configureActions()).
    • Customize Forms: Extend UserType to add validation or dynamic fields:
      public function buildForm(FormBuilderInterface $builder, array $options)
      {
          parent::buildForm($builder, $options);
          $builder->add('isActive', CheckboxType::class, ['label' => 'Active']);
      }
      
  3. Integrate with Existing Logic

    • Services: Inject services into the controller via constructor or getServices().
    • Events: Listen to CRUD events (e.g., prePersist, postRemove) in your EventSubscriber:
      public static function getSubscribedEvents()
      {
          return [
              UserCrudEvents::PRE_PERSIST => 'onPrePersist',
          ];
      }
      
  4. Routing & Security

    • Use Symfony’s security to protect routes:
      # config/routes.yaml
      user_crud:
          resource: '@DlmAppsToolsCrudGeneratorBundle/Resources/config/routing/crud.yaml'
          prefix: /admin
          security: role: ROLE_ADMIN
      

Integration Tips

  • Dynamic Fields: Use field_options in config to pass dynamic data (e.g., choices for a select field):
    fields:
        - { name: role, type: entity, class: App\Entity\Role, label: 'Role', field_options: { choice_label: 'name' } }
    
  • Reusable CRUDs: Create base templates in templates/base_crud/ to share layouts across multiple CRUDs.
  • API Integration: Combine with Symfony’s Serializer to expose CRUD endpoints as API:
    // UserCrudController.php
    use Symfony\Component\Serializer\Normalizer\NormalizerInterface;
    
    public function __construct(NormalizerInterface $normalizer) {
        $this->normalizer = $normalizer;
    }
    
    public function apiListAction()
    {
        $users = $this->getDoctrine()->getRepository(User::class)->findAll();
        return new JsonResponse($this->normalizer->normalize($users));
    }
    

Gotchas and Tips

Pitfalls

  1. Overwriting Files

    • The --overwrite flag is required to regenerate existing files. Without it, the generator skips updates.
    • Tip: Use git diff before overwriting to review changes:
      git diff HEAD -- src/Controller/UserCrudController.php
      
  2. Field Type Mismatches

    • The generator assumes Doctrine types map to Symfony form types (e.g., stringTextType). Custom mappings may break forms.
    • Fix: Override getFieldType() in a custom form type extension.
  3. Event Subscribers Not Triggering

    • Ensure your EventSubscriber is tagged in services.yaml:
      services:
          App\EventSubscriber\UserCrudSubscriber:
              tags: [dlmapps_tools.crud.event_subscriber]
      
  4. Translation Issues

    • Labels and messages must be translatable. Configure translations in config/packages/translation.yaml:
      frameworks:
          translation:
              paths: ['%kernel.project_dir%/translations']
      

Debugging

  • Generator Logs: Enable debug mode to see what’s being generated:
    php bin/console dlm-apps-tools:crud:generate --debug
    
  • Dry Run: Use --dry-run to preview changes without writing files.

Extension Points

  1. Custom Templates Override the default Twig templates by placing them in:

    templates/crud/[entity_name]/[action].html.twig
    

    Example: templates/crud/user/list.html.twig overrides the list view.

  2. Dynamic Actions Add custom actions by extending the controller and overriding configureActions():

    public function configureActions(ActionsConfiguration $configuration)
    {
        $configuration->add('export', ExportAction::class)
            ->setPath('/export')
            ->setLabel('Export');
    }
    
  3. Field Transformers Transform data before/after form submission by implementing FieldTransformerInterface:

    class PasswordTransformer implements FieldTransformerInterface
    {
        public function transform($value)
        {
            return password_hash($value, PASSWORD_BCRYPT);
        }
    }
    

    Register it in config:

    fields:
        - { name: password, type: password, transformer: App\Transformer\PasswordTransformer }
    
  4. Bulk Actions Enable bulk operations by configuring bulk_actions in the entity settings:

    entities:
        App\Entity\User:
            bulk_actions:
                - { name: 'delete_selected', label: 'Delete Selected' }
    

    Implement the logic in a custom action class.

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