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

Cube Custom Fields Bundle Laravel Package

cubetools/cube-custom-fields-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation

    composer require cubetools/cube-custom-fields-bundle
    

    Ensure Composer is globally installed and your project is up-to-date.

  2. Enable the Bundle Add the bundle to config/bundles.php (Laravel 5.4+) or AppKernel.php (older versions):

    CubeTools\CubeCustomFieldsBundle\CubeToolsCubeCustomFieldsBundle::class => ['all' => true],
    
  3. Configure Routing Add the routes in routes/web.php (Laravel 5.4+):

    use CubeTools\CubeCustomFieldsBundle\Resources\routes\all.php;
    
  4. Define Custom Fields Create a config/custom_fields.yml file (or use ignore_errors: true if the file is optional):

    custom_fields:
        my_entity:
            - { name: "custom_field_1", type: "text", label: "Custom Field 1" }
            - { name: "custom_field_2", type: "number", label: "Custom Field 2" }
    
  5. First Use Case Use the bundle to dynamically add custom fields to an entity form. For example, in a Symfony form builder:

    use CubeTools\CubeCustomFieldsBundle\Form\Type\CustomFieldsType;
    
    $builder->add('custom_fields', CustomFieldsType::class, [
        'entity' => 'my_entity',
        'mapped' => false,
    ]);
    

Implementation Patterns

Dynamic Form Integration

  • Entity-Specific Custom Fields Use the CustomFieldsType form type to attach custom fields to any entity dynamically. Pass the entity name as a configuration option:

    $builder->add('custom_fields', CustomFieldsType::class, [
        'entity' => 'user_profile',
        'mapped' => true, // Maps fields to the entity
    ]);
    
  • Field Validation Validate custom fields using Symfony’s validation constraints. Define constraints in the YAML config:

    custom_fields:
        my_entity:
            - { name: "email", type: "email", label: "Email", constraints: { NotBlank: {}, Email: {} } }
    
  • Data Persistence Store custom field data in a separate table or as JSON in the entity’s database column. Use Doctrine listeners or repository methods to handle serialization/deserialization:

    // Example: Custom Doctrine listener to handle custom fields
    $entity->setCustomFields(json_encode($customFieldData));
    

Workflows

  1. Admin Panel Integration Use the bundle to add custom fields to admin forms (e.g., SonataAdmin, EasyAdmin). Example for EasyAdmin:

    $builder->add('custom_fields', CustomFieldsType::class, [
        'entity' => 'product',
        'label' => 'Product Custom Fields',
    ]);
    
  2. API Endpoints Expose custom fields via API using Symfony’s serializers or Laravel’s API resources. Example:

    // In a Laravel resource
    public function toArray($request)
    {
        return [
            'custom_fields' => $this->resource->getCustomFields(),
        ];
    }
    
  3. Frontend Integration Use the bundle’s JavaScript assets (if provided) or build custom frontend logic to handle custom fields in forms. Example with Vue.js:

    // Fetch custom fields for an entity
    axios.get(`/api/custom-fields/my_entity`).then(response => {
        this.customFields = response.data;
    });
    

Integration Tips

  • Doctrine Entities Extend your entity to include custom fields. Example:

    /**
     * @ORM\Column(type="json")
     */
    private $customFields = [];
    
    public function getCustomFields(): array
    {
        return $this->customFields;
    }
    
    public function setCustomFields(array $customFields): void
    {
        $this->customFields = $customFields;
    }
    
  • Symfony Forms Customize the CustomFieldsType form type by extending it:

    use CubeTools\CubeCustomFieldsBundle\Form\Type\CustomFieldsType as BaseCustomFieldsType;
    
    class ExtendedCustomFieldsType extends BaseCustomFieldsType
    {
        public function configureOptions(OptionsResolver $resolver)
        {
            $resolver->setDefaults([
                'custom_option' => 'value',
            ]);
        }
    }
    
  • Localization Localize field labels and placeholders by using Symfony’s translation system:

    custom_fields:
        my_entity:
            - { name: "description", type: "textarea", label: "app.custom_fields.description" }
    

    Translations in resources/translations/messages.en.yml:

    app.custom_fields.description: "Product Description"
    

Gotchas and Tips

Pitfalls

  1. YAML Configuration Errors

    • The bundle expects custom_fields.yml to be valid YAML. Use ignore_errors: true in config.yml to avoid crashes if the file is missing or invalid:
      imports:
          { resource: custom_fields.yml, ignore_errors: true }
      
  2. Field Naming Conflicts

    • Avoid naming custom fields the same as existing entity properties to prevent serialization/deserialization issues.
  3. Doctrine Lifecycle Events

    • If custom fields are stored as JSON, ensure proper handling during prePersist and preUpdate events to avoid data loss or corruption.
  4. Form Mapping Issues

    • If mapped: true, ensure the entity has a method to handle custom field data (e.g., setCustomFields). Otherwise, the form submission will fail silently.
  5. Caching

    • Custom field configurations are likely cached. Clear the cache after modifying custom_fields.yml:
      php artisan cache:clear
      

Debugging

  • Check Configuration Verify the custom_fields.yml is correctly loaded. Add debug logs in config.yml:

    imports:
        { resource: custom_fields.yml }
    

    Then check Symfony’s debug toolbar or logs for errors.

  • Form Errors If custom fields don’t appear in the form, ensure:

    • The entity name in the form type matches the YAML config.
    • The bundle is properly registered in bundles.php/AppKernel.php.
  • Database Issues If custom fields aren’t saved, check:

    • The entity’s setCustomFields method is called.
    • The database column (if using JSON) has sufficient size.

Tips

  1. Reusable Field Types Define reusable field types in YAML to avoid repetition:

    custom_fields:
        reusable_type:
            - { name: "reusable_field", type: "text", label: "Reusable Label" }
    

    Then reference them in other entities:

    custom_fields:
        my_entity:
            - { name: "field_1", type: "reusable_type" }
    
  2. Default Values Set default values for custom fields in YAML:

    custom_fields:
        my_entity:
            - { name: "status", type: "choice", label: "Status", choices: { active: "Active", inactive: "Inactive" }, default: "active" }
    
  3. Conditional Fields Use Symfony’s ConditionalFieldBuilder to show/hide fields based on other inputs:

    $builder->add('custom_fields', CustomFieldsType::class, [
        'entity' => 'order',
        'conditional_fields' => [
            'shipping_address' => ['if' => 'is_shipping_same_as_billing', 'is' => true],
        ],
    ]);
    
  4. Field Groups Organize custom fields into groups for better UX:

    custom_fields:
        my_entity:
            - { name: "group_billing", type: "group", label: "Billing Information" }
            - { name: "billing_address", type: "text", label: "Address", group: "group_billing" }
    
  5. Testing Test custom fields with PHPUnit by mocking the bundle’s services or using the CustomFieldsType directly:

    $formFactory = $this->get('form.factory');
    $form = $formFactory->create(CustomFieldsType::class, null, [
        'entity' => 'test_entity',
    ]);
    
  6. Performance For entities with many custom fields, consider lazy-loading or pagination in forms/APIs to improve performance.

  7. Security Sanitize custom field inputs to prevent XSS or SQL injection, especially if fields are rendered directly in templates:

    {{ form_row(form.custom_fields) | escape }}
    
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.
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
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle