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

Crud Generator Bundle Laravel Package

edinaldofox/crud-generator-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require petkopara/crud-generator-bundle
    

    Add to config/bundles.php:

    return [
        // ...
        Petkopara\CrudGeneratorBundle\PetkoparaCrudGeneratorBundle::class => ['all' => true],
    ];
    
  2. First Command Generate a CRUD for an existing entity (e.g., App\Entity\Product):

    php bin/console petkopara:crud:generate Product
    

    This creates:

    • Controller (src/Controller/ProductCrudController.php)
    • Twig templates (templates/ProductCrud/)
    • Routes (config/routes.yaml)
  3. First Use Case Access the generated CRUD at /product/crud (or your configured route). The bundle auto-generates:

    • List view with pagination (default: 10 items/page).
    • Filtering by all entity fields.
    • Sorting by any column.
    • Bulk delete functionality.
    • Bootstrap 3.3.6-styled forms and tables.

Implementation Patterns

Core Workflows

  1. Generating CRUDs

    • Basic Generation:
      php bin/console petkopara:crud:generate EntityName [--format=yml|xml|php]
      
    • Custom Template Path:
      php bin/console petkopara:crud:generate EntityName --template-dir=custom/templates/
      
    • Override Defaults: Use config/packages/petkopara_crud_generator.yaml to set global defaults (e.g., page_size, default_sort).
  2. Extending Generated Code

    • Controller Overrides: Extend the generated controller and override methods like configureList(), configureFields(), or configureActions(). Example:
      // src/Controller/ProductCrudController.php
      class ProductCrudController extends AbstractCrudController
      {
          public function configureFields(string $action): iterable
          {
              return parent::configureFields($action)
                  ->add('price', 'currency', ['currency' => 'USD']);
          }
      }
      
  3. Customizing Fields

    • Use Symfony UX Maker-style field configurations in configureFields():
      ->add('name', 'text', ['attr' => ['placeholder' => 'Product name']])
      ->add('category', 'entity', ['class' => Category::class, 'multiple' => true])
      ->add('isActive', 'checkbox', ['required' => false])
      
  4. Adding Custom Actions

    • Define actions in configureActions():
      public function configureActions(Actions $actions): Actions
      {
          return $actions
              ->add('publish', Button::create('Publish')->setIcon('fas fa-rocket'))
              ->add('publish', Callback::create()->setCallback([$this, 'publishAction']));
      }
      
  5. Handling Associations

    • The bundle auto-detects Doctrine associations (OneToMany, ManyToOne, etc.). Customize with:
      ->add('author', 'entity', ['class' => Author::class, 'property' => 'fullName'])
      
  6. Pagination and Filtering

    • Override configurePagination() and configureFilters():
      public function configurePagination(OptionsResolver $resolver): void
      {
          $resolver->setDefaults(['page_size' => 20]);
      }
      
  7. Bulk Operations

    • Enable bulk actions in configureActions():
      ->add('bulk_delete', BulkAction::create('Delete selected')->setIcon('fas fa-trash'))
      

Integration Tips

  1. Symfony Flex Compatibility

    • Works seamlessly with Symfony Flex. No manual bundle registration needed in AppKernel.php.
  2. Doctrine Integration

    • Requires Doctrine ORM. Ensure your entity uses Doctrine annotations/attributes or YAML/XML mappings.
  3. Twig Customization

    • Override templates by placing them in templates/bundles/PetkoparaCrudGenerator/. The bundle follows Symfony’s template inheritance.
  4. API-First Approach

    • For API endpoints, combine with Symfony’s Serializer and ApiPlatform:
      # config/routes.yaml
      petkopara_crud:
          resource: '.'
          type: petkopara_crud
          prefix: /api
      
  5. Testing

    • Use CrudTestCase (if provided) or mock the controller:
      $client = static::createClient();
      $client->request('GET', '/product/crud');
      $this->assertResponseIsSuccessful();
      

Gotchas and Tips

Pitfalls

  1. Entity Naming Conflicts

    • Avoid generating CRUDs for entities with names conflicting with Symfony’s core components (e.g., User, Role). Prefix with App or use underscores:
      php bin/console petkopara:crud:generate App_User
      
  2. Template Caching

    • Clear cache after customizing templates:
      php bin/console cache:clear
      
  3. Association Loading

    • Lazy-loaded associations (e.g., ManyToOne) may cause NULL values in the UI. Use fetch="EAGER" in Doctrine or customize the query in configureList():
      public function configureList(QueryBuilder $qb): void
      {
          $qb->leftJoin('p.author', 'a');
      }
      
  4. CSRF Protection

    • Bulk actions may trigger CSRF errors. Ensure _csrf_token is included in forms or disable CSRF for bulk endpoints (not recommended for production).
  5. Field Type Mismatches

    • The bundle auto-detects field types, but custom types (e.g., JsonType) may not render correctly. Override configureFields() to specify types explicitly:
      ->add('metadata', 'text', ['attr' => ['class' => 'json-editor']])
      
  6. Route Conflicts

    • Generated routes may conflict with existing ones. Use --route-name to customize:
      php bin/console petkopara:crud:generate Product --route-name=admin_product
      

Debugging Tips

  1. Log Generated SQL Enable Doctrine logging in config/packages/dev/doctrine.yaml:

    doctrine:
        dbal:
            logging: true
            profiling: true
    
  2. Check Generated Code Inspect the generated controller and templates in var/cache/dev/ for errors. Use:

    php bin/console debug:container Petkopara\CrudGeneratorBundle
    
  3. Override Configuration Debug issues by overriding bundle config in config/packages/petkopara_crud_generator.yaml:

    petkopara_crud_generator:
        default:
            page_size: 5
            debug: true  # Shows generated SQL and template paths
    
  4. Template Debugging Use Twig’s dump() in custom templates to inspect variables:

    {% dump app.request.attributes %}
    

Extension Points

  1. Custom Field Types Extend the bundle by creating a custom field type. Example:

    // src/Form/Extension/CustomFieldExtension.php
    use Petkopara\CrudGeneratorBundle\Form\Type\FieldTypeExtensionInterface;
    
    class CustomFieldExtension implements FieldTypeExtensionInterface
    {
        public function getExtendedTypes(): array
        {
            return ['custom_type'];
        }
    
        public function getType(FieldDefinitionInterface $field): string
        {
            return 'text';
        }
    
        public function getOptions(FieldDefinitionInterface $field): array
        {
            return ['attr' => ['class' => 'custom-class']];
        }
    }
    

    Register the service in config/services.yaml:

    services:
        App\Form\Extension\CustomFieldExtension:
            tags:
                - { name: petkopara_crud_generator.field_type_extension }
    
  2. Event Listeners Hook into CRUD events (e.g., prePersist, postDelete) via Symfony’s event dispatcher:

    // src/EventListener/CrudListener.php
    use Petkopara\CrudGeneratorBundle\Event\CrudEvent;
    
    class CrudListener
    {
        public function onPrePersist(CrudEvent $event)
        {
            $data = $event->getData();
            $data->setCreatedAt(new \DateTime());
        }
    }
    

    Register the listener:

    services:
        App\EventListener\CrudListener:
            tags:
                - { name: kernel.event_listener, event: petkopara_crud.pre_persist, method: onPrePersist }
    
  3. Custom Actions Create reusable actions by extending AbstractAction:

    // src/Action/CustomAction.php
    
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