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

Attachment Admin Bundle Laravel Package

c33s/attachment-admin-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Bundle Require the package via Composer:

    composer require c33s/attachment-admin-bundle
    

    Register the bundle in config/bundles.php:

    return [
        // ...
        C33s\AttachmentAdminBundle\C33sAttachmentAdminBundle::class => ['all' => true],
    ];
    
  2. Enable Propel ORM (if not already) The bundle assumes Propel is used. Ensure propel/propel-bundle is installed and configured.

  3. Generate a Model with Attachments Use the c33s:attachment:generate command to scaffold attachment fields for an existing model:

    php bin/console c33s:attachment:generate App\Entity\YourModel
    

    This creates:

    • A Attachment table (if missing).
    • A YourModelAttachment join table (if missing).
    • A YourModelAdmin class extending SonataAdminBundle with attachment fields.
  4. First Use Case: Upload Files

    • Navigate to the generated admin panel (e.g., /admin/your_model).
    • Use the file upload field to attach files to records.

Implementation Patterns

Workflow: Integrating with Existing Admins

  1. Extend an Existing Sonata Admin Override the default admin class to customize attachment behavior:

    use C33s\AttachmentAdminBundle\Admin\AttachmentAdmin;
    
    class YourModelAdmin extends AttachmentAdmin
    {
        protected function configureFormFields(FormMapper $formMapper)
        {
            $formMapper
                ->add('attachments', 'c33s_attachment', [
                    'label' => 'Attachments',
                    'required' => false,
                    'multiple' => true,
                ]);
        }
    }
    
  2. Dynamic Attachment Fields Use the c33s_attachment form type to dynamically attach files to any model:

    # config/sonata_admin.yml
    sonata_admin:
        templates:
            form:
                - 'C33sAttachmentAdminBundle:Form:field_c33s_attachment.html.twig'
    
  3. Validation and Constraints Add validation rules to the attachment field:

    $formMapper->add('attachments', 'c33s_attachment', [
        'constraints' => [
            new File\FileType(['mime_types' => ['image/jpeg', 'application/pdf']]),
            new File\MaxSize(['maxSize' => '1024k']),
        ],
    ]);
    
  4. Batch Processing Use the AttachmentManager service to handle bulk operations:

    $attachmentManager = $this->get('c33s_attachment.manager');
    $attachments = $attachmentManager->findBy(['objectId' => $model->getId()]);
    
  5. Custom Storage Backends Override the default storage (e.g., switch from filesystem to S3):

    # config/packages/c33s_attachment_admin.yaml
    c33s_attachment_admin:
        storage:
            adapter: 'aws' # or 'local', 'ftp', etc.
            options:
                bucket: 'your-bucket'
                region: 'us-east-1'
    

Gotchas and Tips

Pitfalls

  1. Propel Dependency

    • The bundle only works with Propel ORM. If using Doctrine, this bundle is incompatible.
    • Ensure your schema.xml includes the Attachment and join tables. Run:
      php bin/console propel:schema:update --force
      
  2. Admin Route Conflicts

    • If extending SonataAdminBundle, ensure the admin class name follows conventions (e.g., YourModelAdmin).
    • Override the route name if conflicts arise:
      class YourModelAdmin extends AttachmentAdmin
      {
          public function getRouteName()
          {
              return 'custom_your_model_admin';
          }
      }
      
  3. File Upload Limits

    • PHP’s upload_max_filesize and post_max_size may block large uploads. Adjust in php.ini or .htaccess:
      upload_max_filesize = 20M
      post_max_size = 25M
      
  4. Permission Issues

    • Ensure the web server user (e.g., www-data) has write permissions to the upload directory (default: var/uploads/).
    • For S3/AWS, configure IAM roles with proper permissions.
  5. Translation Missing

    • The bundle uses basic translations. Extend the translation catalog if needed:
      php bin/console translation:update --force fr
      

Debugging Tips

  1. Check Database Schema Verify the Attachment and join tables exist:

    SELECT * FROM attachment;
    SELECT * FROM your_model_attachment;
    
  2. Enable Debug Mode Temporarily set APP_DEBUG=1 in .env to see detailed errors.

  3. Log Uploads Add logging to track uploads:

    $this->get('logger')->info('Attachment uploaded', ['file' => $file->getClientOriginalName()]);
    
  4. Clear Cache After generating admins or updating config:

    php bin/console cache:clear
    

Extension Points

  1. Customize the Upload Form Override the Twig template:

    # templates/YourModelAdmin/attachment_field.html.twig
    {% extends 'C33sAttachmentAdminBundle:Form:field_c33s_attachment.html.twig' %}
    {% block attachment_widget %}
        {{ parent() }} <!-- Customize here -->
    {% endblock %}
    
  2. Add Metadata to Attachments Extend the Attachment model to store extra fields (e.g., title, description):

    <!-- schema.xml -->
    <table name="attachment" phpName="Attachment">
        <column name="title" type="VARCHAR" size="255" required="false" />
    </table>
    
  3. Hook into Lifecycle Events Use Propel listeners to trigger actions on attachment changes:

    $attachment->save();
    $this->get('event_dispatcher')->dispatch(
        'attachment.pre_save',
        new AttachmentEvent($attachment)
    );
    
  4. API Integration Expose attachments via API using FOSRestBundle or API Platform:

    # config/serializer/Attachment.yaml
    App\Entity\Attachment:
        attributes:
            url:
                accessor:
                    getter: getUrl
                    serializer_name: 'serializer.group.default'
    
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