# Entity Builder AG-Grid

The `eb_aggrid` module provides an AG-Grid-based spreadsheet interface for Entity Builder.

**Project Page:** [https://www.drupal.org/project/eb_aggrid](https://www.drupal.org/project/eb_aggrid)

## Overview

eb_aggrid is a grid provider for eb_ui that offers an Excel-like interface for creating and managing Entity Builder definitions. It registers itself via the `hook_eb_ui_grid_provider_info` hook.

## Requirements

- Drupal 11+
- PHP 8.3+
- eb module (core)
- eb_ui module (provides GridProviderManager)
- AG-Grid Community library (33.0.0) - installed via [Asset Packagist](https://asset-packagist.org/)

## Installation

### Step 1: Configure Asset Packagist (if not already done)

The AG-Grid library is installed via [Asset Packagist](https://asset-packagist.org/).
Add the following to your project's root `composer.json`:

```json
{
  "repositories": [
    {
      "type": "composer",
      "url": "https://asset-packagist.org"
    }
  ],
  "extra": {
    "installer-types": ["npm-asset", "bower-asset"],
    "installer-paths": {
      "web/libraries/{$name}": [
        "type:drupal-library",
        "type:npm-asset",
        "type:bower-asset"
      ]
    }
  }
}
```

You also need the composer-installers-extender package:

```bash
composer require oomphinc/composer-installers-extender
```

### Step 2: Install the Module and AG-Grid Library

```bash
# Install the eb_aggrid module
composer require drupal/eb_aggrid

# Install the AG-Grid library
composer require npm-asset/ag-grid-community:33.0.0
```

This installs the library to `web/libraries/ag-grid-community`.

### Step 3: Enable the Modules

```bash
drush en eb_ui eb_aggrid -y
drush cr
```

### Step 4: Verify Installation

Navigate to `/admin/config/development/eb` to use the spreadsheet interface.

### Quick Install (if Asset Packagist is already configured)

```bash
composer require drupal/eb_aggrid npm-asset/ag-grid-community:33.0.0
drush en eb_ui eb_aggrid -y && drush cr
```

## Architecture

```
eb_aggrid (Standalone module)
├── EbAggridForm (main spreadsheet interface)
├── EbAggridApiController (plugin settings endpoints)
├── EbAggridSettingsForm (grid configuration)
├── EbAggridHooks (provider registration)
├── GridProviderAccess (route priority)
├── FieldTypeFormSchemaBuilder (settings form schemas)
└── JS/CSS assets for AG-Grid
```

### Provider Registration

```php
// src/Hook/EbAggridHooks.php
#[Hook('eb_ui_grid_provider_info')]
public function gridProviderInfo(): array {
  return [
    'aggrid' => [
      'id' => 'aggrid',
      'label' => $this->t('AG-GRID Spreadsheet'),
      'form_class' => '\Drupal\eb_aggrid\Form\EbAggridForm',
      'library' => 'eb_aggrid/grid',
      'theme_class' => 'ag-theme-quartz',
    ],
  ];
}
```

## Features

### Grid Interface

Tabbed spreadsheet with five sheets:

| Tab | Purpose |
|-----|---------|
| **Bundles** | Content types, vocabularies, media types |
| **Fields** | Field definitions with widgets and formatters |
| **Field Groups** | Visual grouping (requires eb_field_group) |
| **Displays** | Form and view display configurations |
| **Menus** | Custom menu definitions |

### Source View

When eb_aggrid is active, a "Source" link appears for YAML editing:

- Uses eb_ui's EbUiYamlForm
- Follows Webform pattern (visual + source editing)
- Syncs changes between grid and YAML

### UX Enhancements

- **Field Name Auto-generation**: "Author Name" → "field_author_name"
- **Combined Target Column**: "Content: Article" for entity references
- **Field Type Labels**: Human-readable names from Drupal
- **Smart Default Settings**: Auto-populate based on field type

### Settings Modal

Form-based editing instead of raw JSON:

- **Entity Reference**: Target type dropdown, bundle checkboxes
- **Text Fields**: Allowed text formats
- **Image/File**: Extensions, max size, alt/title options
- **Number**: Min/max values, precision, scale
- **List**: Allowed values key-value editor
- **Boolean**: On/Off labels

### Widget/Formatter Settings

Server-side rendered using Drupal's native `settingsForm()`:

- Full Form API support
- Third-party module integration
- Same forms as "Manage form display" UI

## API Endpoints

### POST /eb/api/plugin-settings/{plugin_type}/{plugin_id}

Renders widget or formatter settings forms.

**Parameters:**
- `plugin_type`: `widget` or `formatter`
- `plugin_id`: Plugin ID (e.g., `string_textfield`)

**Request Body:**
```json
{
  "field_type": "entity_reference",
  "current_settings": {"match_operator": "CONTAINS"},
  "entity_type": "node",
  "bundle": "article"
}
```

**Response:**
```json
{
  "success": true,
  "hasSettings": true,
  "html": "<div class=\"eb-plugin-settings-form\">...</div>"
}
```

### POST /eb/api/format-settings/{format_type}

Renders field_group format settings forms.

**Parameters:**
- `format_type`: `fieldset`, `details`, `tabs`, etc.

## Configuration

Navigate to `/admin/config/development/eb/eb_aggrid/settings`:

| Setting | Default | Description |
|---------|---------|-------------|
| `validation_debounce_ms` | 500 | Validation delay (ms) |
| `sync_debounce_ms` | 150 | Grid sync delay (ms) |
| `max_json_depth` | 10 | Maximum JSON nesting |
| `max_content_size` | 5 | Maximum payload size (MB) |
| `debug_mode_enabled` | false | Allow debug mode |
| `theme_class` | ag-theme-quartz | AG-Grid theme |

## Debug Mode

Enable debug mode to inspect grid row data:

1. Enable in settings (`/admin/config/development/eb/eb_aggrid/settings`)
2. Add `?eb_debug=1` to URL
3. Click magnifying glass on any row

Shows:
- Core Fields
- Settings
- Raw Data (copyable JSON)

## JavaScript Files

| File | Purpose |
|------|---------|
| `eb_aggrid.js` | Main initialization |
| `eb_aggrid.grid.js` | AG-Grid configuration |
| `eb_aggrid.columns.js` | Column definitions |
| `eb_aggrid.modals.js` | Modal dialogs |
| `eb_aggrid.settings-forms.js` | Settings form rendering |
| `eb_aggrid.debug.js` | Debug panel |
| `eb_aggrid.validation.js` | Client-side validation |
| `eb_aggrid.import.js` | Import functionality |

## Keyboard Shortcuts

| Shortcut | Action |
|----------|--------|
| Ctrl+Z | Undo |
| Ctrl+Y | Redo |
| Ctrl+Shift+N | Add new row |
| Delete | Remove selected rows |
| Ctrl+D | Duplicate row |
| Arrow keys | Navigate cells |
| Enter | Start editing |
| Escape | Cancel editing |
| Tab | Move to next cell |

## Security

- **CSRF Protection**: X-CSRF-Token required
- **XSS Sanitization**: All input sanitized
- **Content Size Limits**: Configurable
- **Nesting Depth Limits**: Configurable
- **Permission-based Debug**: Admin only

## Testing

```bash
# Unit tests
vendor/bin/phpunit -c /var/www/html/phpunit.xml \
  web/modules/custom/eb_aggrid/tests/src/Unit/

# Kernel tests
vendor/bin/phpunit -c /var/www/html/phpunit.xml \
  web/modules/custom/eb_aggrid/tests/src/Kernel/

# Functional tests
vendor/bin/phpunit -c /var/www/html/phpunit.xml \
  web/modules/custom/eb_aggrid/tests/src/Functional/
```

## Troubleshooting

### Grid Not Loading

1. Verify the AG-Grid library is installed:
   ```bash
   ls web/libraries/ag-grid-community
   ```
2. Check browser console for JavaScript errors
3. Verify AG-Grid library is loading (check Network tab for 404 errors)
4. Clear Drupal cache: `drush cr`

### Library Not Found

If you see errors about missing AG-Grid files:

1. Ensure Asset Packagist is configured (see Installation Step 1)
2. Install the library: `composer require npm-asset/ag-grid-community:33.0.0`
3. Verify the library path matches the module's expectations

### Settings Modal Issues

1. Ensure field type is selected
2. For entity reference, select target type first
3. Check browser console

### Debug Mode Not Working

1. Enable in settings
2. Add `?eb_debug=1` to URL
3. Verify admin permission

## Related Modules

- **eb_ui**: Base UI module with shared API endpoints
- **eb**: Core Entity Builder functionality
- **eb_field_group**: Field group support extension
