=============== LIBRARY RULES =============== From library maintainers: - Use admin plugin ### Basic CRUD Setup Example Source: https://github.com/skie/admin-docs/blob/main/docs/Settings.md A straightforward example of setting up the essential CRUD operations (Index, Add, Edit, Delete) for an admin interface using method chaining. ```php $settings->withIndex() ->withAdd() ->withEdit() ->withDelete(); ``` -------------------------------- ### Add Action Configuration Example Source: https://github.com/skie/admin-docs/blob/main/docs/Actions.md Demonstrates the basic setup for an AddAction, including setting the templateizer and customizing the query finder to load related data. ```php $addAction = new AddAction(); $addAction ->setTemplateizer($this->templateizer) ->setGetFinder(function($query) { return $query->contain(['Tags']); }); ``` -------------------------------- ### Setup Wizard Action in PHP Source: https://github.com/skie/admin-docs/blob/main/docs/Wizard.md Demonstrates the initial setup of a WizardAction, including setting its name, type, templateizer, and adding the first step. This is the foundational step for creating a wizard flow. ```php use CakeDC\Admin\Settings\SettingsExt; use CakeDC\Admin\Wizard\Action\WizardAction; use CakeDC\Admin\Wizard\Action\WizardStepAction; class UserWizard extends SettingsExt { public function initialize(): void { $this->setPageTitle([ 'wizard' => __('User Wizard'), ]); parent::initialize(); } public function loadDefaultActions(): void { $wizard = new WizardAction(); $wizard->setTemplateizer($this->templateizer) ->setName('wizard') ->setCrudAction('wizard') ->setType('wizard'); // Add steps $wizard->addStep((new WizardStepAction('step1')) ->setIcon('fa fa-user') ->setTitle('Step 1')); $this->getActionsList()->add($wizard); } } ``` -------------------------------- ### ProductSettings Example Class Configuration (PHP) Source: https://github.com/skie/admin-docs/blob/main/docs/Settings.md An example of extending `SettingsExt` to configure product settings, including page titles, CSV export, removing delete actions, defining fields, and setting up search. ```php class ProductSettings extends SettingsExt { public function initialize(): void { $this->setPageTitle(['index' => 'Products']); parent::initialize(); } public function loadDefaultActions(): void { parent::loadDefaultActions(); $this->withCsv()->removeDelete(); } public function fieldsBuilder(string $page): iterable { yield StringField::new('name')->setEditable(true); yield NumericField::new('price'); } public function searchBuilder(string $page, ServerRequest $request): ?BaseSearch { return new DefaultSearch(['name', 'price']); } } ``` -------------------------------- ### PHP Basic Page Link Setup Source: https://github.com/skie/admin-docs/blob/main/docs/Actions/Links.md Demonstrates the basic setup for a PageLink, including setting an icon, label, CSS class, and associating it with a CRUD operation like INDEX. ```php $link = new PageLink(); $link->setIcon('fa-list') ->setLabel('List Items') ->setCssClass('btn btn-primary') ->setCrudLink(Page::INDEX); ``` -------------------------------- ### View-Only Interface with Export Example Source: https://github.com/skie/admin-docs/blob/main/docs/Settings.md An example configuring a read-only interface with brief view capabilities and CSV export functionality. ```php $settings->withIndex() ->withView() ->withBriefView() ->withCsv(); ``` -------------------------------- ### Show All Actions for Users Settings Source: https://github.com/skie/admin-docs/blob/main/docs/ShowSettingCommand.md Displays all available actions and their associated configurations for a specified Settings class, using 'Users' as an example. ```bash bin/cake setting_ext show Users ``` -------------------------------- ### Label Formatting Example Source: https://github.com/skie/admin-docs/blob/main/docs/Fields.md Shows the basic setup for applying a custom label formatter to a field, including getting the formatted label. ```php $field->setLabelFormatter(new CustomLabelFormatter()); $field->getFormattedLabel($view); // Get formatted label ``` -------------------------------- ### Tab Layout PHP Examples Source: https://github.com/skie/admin-docs/blob/main/docs/Fields.md Provides examples for creating tabs to organize content. Shows basic tab creation and dynamic tabs using HTMX for loading content asynchronously. ```php // Basic tab yield FormField::addTab('Details') ->setIcon('info-circle'); // Dynamic tab with HTMX yield FormField::addTab('Related Items') ->setCustomOption(FormField::OPTION_TAB_IS_HTMX, true) ->setCustomOption(FormField::OPTION_TAB_HTMX_URL, [ 'action' => 'relatedItems', 'id' => $entity->id ]); ``` -------------------------------- ### Custom Widget Initialization Example Source: https://github.com/skie/admin-docs/blob/main/docs/Fields/WidgetField.md An example demonstrating dynamic initialization of a Stat Widget, fetching data from an API service to set its value, description, and icon. ```php use CakeDC\Admin\Settings\Field\StatWidgetField; use CakeDC\Admin\Settings\Widget\StatWidget; yield StatWidgetField::new( StatWidget::new('API Status') ->setColor('bg-info') ) ->setInitializer(function ($field, ?string $key) { $status = $this->apiService->getStatus(); $field->getWidget() ->setValue($status['code']) ->setDescription($status['message']) ->setDescriptionIcon( $status['online'] ? 'fas fa-check' : 'fas fa-times' ); }); ``` -------------------------------- ### PHP Related Link Example Source: https://github.com/skie/admin-docs/blob/main/docs/Actions/Links.md Illustrates the setup for a RelatedLink, showing how to define the related table URL, specify the foreign key name, and set the linking mode. ```php $link = new RelatedLink(); $link->setRelatedTableUrl(['controller' => 'Posts']) ->setForeignKeyName('post_id') ->setMode(RelatedLink::MODE_FOREIGN_KEY); ``` -------------------------------- ### Complete Builder Example Source: https://github.com/skie/admin-docs/blob/main/docs/Fields/Builder.md A comprehensive example demonstrating a Builder field with multiple blocks, nested fields, validation rules, and container patterns. ```php yield BuilderField::new('data', 'Page Content') ->hideOnIndex() ->addBlock('text', 'Text Block', function ($block) { $block ->addField( CollectionField::new('tags', 'Tags') ->setAllowAdd(true) ->setAllowDelete(true) ->setMax(5) ->addNestedField( StringField::new('tag', 'Tag') ) ) ->addField( TextField::new('content', 'Content') ->setRequired(true) ->addValidationRule('notEmptyString', 'Content required') ) ->setFormatter(new TextBlockFormatter()); }) ->setContainerPattern(function() { yield FormField::addRow(); yield BuilderPlaceholderField::new(); }); ``` -------------------------------- ### Chart Dashboard Example Source: https://github.com/skie/admin-docs/blob/main/docs/Fields/WidgetField.md An example showcasing how to display different types of Chart Widgets (line and pie) on a dashboard with responsive configurations. ```php use CakeDC\Admin\Settings\Field\FormField; use CakeDC\Admin\Settings\Field\ChartWidgetField; use CakeDC\Admin\Settings\Widget\ChartWidget; yield FormField::addRow(); yield FormField::addColumn(6); yield ChartWidgetField::new( ChartWidget::new('line') ->setHeading('Monthly Sales') ->setDescription('Last 6 months performance') ->setOptions([ 'responsive' => true, 'maintainAspectRatio' => false ]) ->setMaxHeight('300px') ) ->setInitializer(function ($field, ?string $key) { $field->getWidget()->setData([ 'labels' => ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun'], 'datasets' => [[ 'label' => 'Sales', 'data' => [4500, 5200, 4800, 5900, 6100, 5800], 'borderColor' => '#3B82F6', 'fill' => false ]] ]); }); yield FormField::addColumn(6); yield ChartWidgetField::new( ChartWidget::new('doughnut') ->setHeading('Traffic Sources') ->setType('pie') ->setDescription('Current month breakdown') ->setOptions([ 'responsive' => true, 'maintainAspectRatio' => false, 'cutout' => '70%' ]) ->setMaxHeight('300px') ) ->setInitializer(function ($field, ?string $key) { $field->getWidget()->setData([ 'labels' => ['Direct', 'Organic', 'Referral', 'Social'], 'datasets' => [[ 'data' => [30, 40, 15, 15], 'backgroundColor' => [ '#3B82F6', '#10B981', '#F59E0B', '#EF4444' ] ]] ]); }); ``` -------------------------------- ### View Action Configuration Example Source: https://github.com/skie/admin-docs/blob/main/docs/Actions.md Demonstrates how to instantiate and configure a ViewAction, including setting associations, templateizer, and query customization for loading records with related data. ```php $viewAction = new ViewAction(); $viewAction ->setAssociations(['MoviesCasts', 'Genres']) ->setTemplateizer($this->templateizer) ->setGetFinder(function($query) { return $query->contain(['Tags']); }); ``` -------------------------------- ### Create Custom Processor Example Source: https://github.com/skie/admin-docs/blob/main/docs/Processors.md Demonstrates how to create a custom processor by extending the BaseProcessor class. ```php use CakeDC\Admin\Controller\Processor\BaseProcessor; class CustomProcessor extends BaseProcessor { public $action = 'custom'; public function execute(?string $key = null) { // Custom logic here } } ``` -------------------------------- ### Custom Action Implementation Example Source: https://github.com/skie/admin-docs/blob/main/docs/Settings.md Shows how to integrate custom action classes for 'Add' and 'Edit' functionalities, allowing for specialized behavior beyond defaults. ```php $settings->withAdd(new CustomAddAction()) ->withEdit(new CustomEditAction()); ``` -------------------------------- ### Show Specific Action for Users Settings Source: https://github.com/skie/admin-docs/blob/main/docs/ShowSettingCommand.md Retrieves configuration details for a particular action, such as 'index', within the UsersSettings class. This helps in analyzing the setup for a single operation. ```bash bin/cake setting_ext show Users --action index ``` -------------------------------- ### Advanced Listing Configuration Example Source: https://github.com/skie/admin-docs/blob/main/docs/Settings.md Demonstrates configuring advanced features for the listing page, including inline editing, table actions, bulk operations, and CSV export. ```php $settings->withIndex() ->withInlineEdit() ->withTableActions() ->withBulk() ->withCsv(); ``` -------------------------------- ### Setup Builder Field Source: https://github.com/skie/admin-docs/blob/main/docs/Fields/Builder.md Demonstrates the basic setup of a Builder field within CakeDC Admin settings, including namespace and field instantiation. ```php use CakeDC\Admin\Settings\Field\BuilderField; class PagesSettings extends SettingsExt { public function fieldsBuilder(string $page): iterable { yield BuilderField::new('content', 'Page Content') ->hideOnIndex() ->setUnlocked(true); } } ``` -------------------------------- ### URL Formatting: Basic URL Field Example Source: https://github.com/skie/admin-docs/blob/main/docs/Fields/Formatters.md An example of setting up a basic URL format for a field, specifying the action to link to. This is a common use case for creating simple internal links. ```PHP $field = new Field('title'); $field->setUrlFormat(UrlFormat::new() ->setUrl(['action' => 'view']) ); ``` -------------------------------- ### Common Use Case: Form Configuration Check Source: https://github.com/skie/admin-docs/blob/main/docs/ShowSettingCommand.md An example demonstrating how to check the form configuration, including buttons and fields, for a specific action like 'add' within the UsersSettings class. ```bash bin/cake setting_ext show Users --action add ``` -------------------------------- ### Basic Field Formatting Setup Source: https://github.com/skie/admin-docs/blob/main/docs/Fields.md Demonstrates how to set up a field with multiple formatters applied sequentially. This includes escaping, number formatting, and currency formatting. ```php $field = Field::new('price') ->appendFormatter(new EscapeFormatter()) ->appendFormatter('Number', ['precision' => 2]) ->appendFormatter(new CurrencyFormatter(['symbol' => '$'])); ``` -------------------------------- ### Get and Configure Current Action Source: https://github.com/skie/admin-docs/blob/main/docs/Settings.md Demonstrates retrieving the current action object and configuring its properties, such as setting default paginator limits for an IndexAction. ```php // Get current action $action = $this->getCurrentAction(); // Check action type if ($action instanceof IndexAction) { // Configure index specific options $action->setDefaultPaginatorLimit(25); } ``` -------------------------------- ### Add Many Action Configuration Example Source: https://github.com/skie/admin-docs/blob/main/docs/Actions.md Shows how to configure an AddManyAction for creating multiple records, including setting the templateizer and customizing the query finder. ```php $addManyAction = new AddManyAction(); $addManyAction ->setTemplateizer($this->templateizer) ->setGetFinder(function($query) { return $query->contain(['Tags']); }); ``` -------------------------------- ### Edit Action Configuration Example Source: https://github.com/skie/admin-docs/blob/main/docs/Actions.md Illustrates the configuration for an EditAction, allowing modification of existing records by setting the templateizer and query finder. ```php $editAction = new EditAction(); $editAction ->setTemplateizer($this->templateizer) ->setGetFinder(function($query) { return $query->contain(['Tags']); }); ``` -------------------------------- ### Create Table Report using CakeDC Admin Source: https://github.com/skie/admin-docs/blob/main/docs/Reports/TableReports.md Demonstrates extending `CakeDCAdminReportTableReport` and implementing `initialize()` for basic report setup, including setting the report title and description. ```php use CakeDC\Admin\Report\TableReport; use CakeDC\Admin\Settings\Field\StringField; use CakeDC\Admin\Settings\Field\NumericField; use CakeDC\Admin\Settings\Field\Formatter\CurrencyFormatter; use CakeDC\Admin\Report\Field\ComputeField; class ProductsReport extends TableReport { public function initialize(): void { parent::initialize(); $this->setTitle('Products Report'); $this->setDescription('List of all products with prices'); } public function defineFields(): void { $this->addField(StringField::new('name') ->setLabel('Product Name')); $this->addField(NumericField::new('price') ->setLabel('Price') ->appendFormatter( (new CurrencyFormatter()) ->setCurrencyPrefix('$') ->setDecimalsCount(2))); } public function defineTotalFields(): void { $this->addTotalField(ComputeField::new('total_price') ->setLabel('Total Price') ->setOperation(ComputeField::OPERATION_SUM) ->setField('price') ->appendFormatter( (new CurrencyFormatter()) ->setCurrencyPrefix('$') ->setDecimalsCount(2))); } } ``` -------------------------------- ### Setup Toggle Section with Rules Source: https://github.com/skie/admin-docs/blob/main/docs/Fields/ToggleSection.md Demonstrates how to initialize a ToggleSectionStart object, define a rule for its visibility, and set the operation type. It also shows how to yield subsequent fields that belong to this section. ```php use CakeDC\Admin\Settings\Field\Layout\ToggleSectionStart; use CakeDC\Admin\Rules\RuleFactory; // Show fields only when checkbox is checked yield (new ToggleSectionStart()) ->setRule(RuleFactory::equals('show_address', true)) ->setOperation(ToggleSectionStart::OPERATION_SHOW); // Fields inside the toggle section yield TextField::new('street', 'Street Address'); yield TextField::new('city', 'City'); yield TextField::new('postal_code', 'Postal Code'); ``` -------------------------------- ### Bulk Links Source: https://github.com/skie/admin-docs/blob/main/docs/Actions.md Provides an example for adding actions that operate on multiple records simultaneously. It demonstrates adding a `BulkLink` for batch operations. ```php public function loadDefaultLinks(ActionCollection $actions) { $this->bulkLinks->add(new BulkLink()); } ``` -------------------------------- ### Basic AutocompleteField Setup (PHP) Source: https://github.com/skie/admin-docs/blob/main/docs/Fields/Autocomplete.md Demonstrates the basic instantiation and configuration of the AutocompleteField component in PHP. It sets the field's label, the URL for data fetching, and the property names for ID and display values. ```php AutocompleteField::new('user_id') ->setLabel('User') ->setAutocompleteUrl('/admin/users/autocomplete') ->setIdName('id') ->setValueName('name'); ``` -------------------------------- ### Custom Action Creation Example Source: https://github.com/skie/admin-docs/blob/main/docs/Actions.md Demonstrates how to create a custom action by extending the base PageAction class, setting its label, type, processor class, and defining default links. ```php use CakeDC\Admin\Settings\Action\PageAction; use CakeDC\Admin\Settings\ActionCollection; use CakeDC\Admin\Action; class CustomAction extends PageAction { public function __construct() { parent::__construct(); $this->setLabel('Custom Action'); $this->setType(Action::TYPE_CRUD); $this->setProcessorClass(CustomProcessor::class); } public function loadDefaultLinks(ActionCollection $actions) { // Add default links/buttons } } ``` -------------------------------- ### Column Layout PHP Examples Source: https://github.com/skie/admin-docs/blob/main/docs/Fields.md Demonstrates how to define columns for responsive layout. Supports specifying numeric widths (e.g., 6/12) or using custom Bootstrap classes for flexible column arrangements. ```php // Column with numeric width (6/12) yield FormField::addColumn(6) ->setLabel('Left Column'); // Column with custom Bootstrap classes yield FormField::addColumn('col-md-8 offset-md-2'); ``` -------------------------------- ### PHP Link URL Building Strategies Source: https://github.com/skie/admin-docs/blob/main/docs/Actions/Links.md Explains and provides examples for different URL building strategies for links, including default, related (foreign key), and custom URL builders. ```php // Default URL builder $link->defaultUrlBuilder($request, $entity); // Related URL builder with foreign key $link->relatedUrlBuilder($request, $entity); // Custom URL builder $link->setUrlBuilder(function($request, $entity) { return Router::url(['action' => 'custom', $entity->id]); }); ``` -------------------------------- ### Initialize HTMX Functionality Source: https://github.com/skie/admin-docs/blob/main/docs/HtmxManagement.md Demonstrates the core JavaScript function responsible for initializing HTMX across different UI contexts, including tabbed interfaces and standard elements, along with pagination setup. ```javascript initializeHtmx(root, isTab) { initializeTabHtmx(rootElement); initializeNonTabHtmx(rootElement); initializeNonHtmxElements(rootElement, isTab); initializePagination(rootElement, isTab); } ``` -------------------------------- ### Generate Core Settings with bake Source: https://github.com/skie/admin-docs/blob/main/docs/Intro.md Commands for generating core framework settings, including model-specific settings, all model settings, admin controllers, and base AppSettings classes. These commands streamline the setup of application configurations. ```APIDOC bake setting_ext model - Generates model-specific settings. - Usage: bake setting_ext model bake setting_ext all - Generates settings for all models. - Usage: bake setting_ext all bake setting_ext controller - Generates admin controllers. - Usage: bake setting_ext controller bake app_settings - Generates the base AppSettings class. - Usage: bake app_settings bake setting name - Generates an individual settings class for a given name. - Parameters: - name: The name of the settings class to generate. - Usage: bake setting ``` -------------------------------- ### KeyValueField PHP Example Source: https://github.com/skie/admin-docs/blob/main/docs/Fields.md Demonstrates the creation and configuration of a KeyValueField for displaying key-value pairs in a table format. Allows customization of add, delete, edit, and label options. ```php KeyValueField::new('key_value') ->setLabel('Key Value') ->setAllowAdd(true) ->setAllowDelete(true) ->setEditableKeys(true) ->setEditableValues(true) ->setReorderable(false) ->setKeyLabel(__('Key')) ->setValueLabel(__('Value')); ``` -------------------------------- ### Common Use Case: Index Page Structure Source: https://github.com/skie/admin-docs/blob/main/docs/ShowSettingCommand.md Shows how to analyze the structure of an index page, including table configuration, available actions, and link configurations, for the UsersSettings class. ```bash bin/cake setting_ext show Users --action index ``` -------------------------------- ### Report Registration Example Source: https://github.com/skie/admin-docs/blob/main/docs/Actions.md Example demonstrating how to register report implementations with default or customized settings within a CakePHP SettingsExt class. ```php use CakeDC\Admin\Settings\SettingsExt; use App\Report\SalesReport; use App\Report\InventoryReport; class CustomersSettings extends SettingsExt { // Constants for report identifiers const SALES_REPORT = 'sales_report'; const INVENTORY_REPORT = 'inventory_report'; public function loadDefaultActions(): void { parent::loadDefaultActions(); // Register reports with default settings $this->addReport(new SalesReport(), self::SALES_REPORT); // Report with customized settings $this->addReport(new InventoryReport(), self::INVENTORY_REPORT, [ 'templatePlugin' => 'MyPlugin', 'templatePath' => 'Admin/CustomReports', ]) ->setLabel('Inventory Analysis'); } } ``` -------------------------------- ### Disable Record Creation Example Source: https://github.com/skie/admin-docs/blob/main/docs/Settings.md A simple example demonstrating how to remove the 'Add' action, thereby disabling record creation functionality. ```php $settings->removeAdd(); ``` -------------------------------- ### Basic Usage of setting_ext show Source: https://github.com/skie/admin-docs/blob/main/docs/ShowSettingCommand.md Demonstrates the fundamental command structure for displaying Settings class configurations, requiring the settings name. The command targets a specific Settings class, identified by its name without the 'Settings' suffix. ```bash bin/cake setting_ext show [options] ``` -------------------------------- ### Dashboard Statistics Example Source: https://github.com/skie/admin-docs/blob/main/docs/Fields/WidgetField.md An example of arranging multiple Stat Widgets within a dashboard layout using columns and rows for better presentation. ```php use CakeDC\Admin\Settings\Field\FormField; use CakeDC\Admin\Settings\Field\StatWidgetField; use CakeDC\Admin\Settings\Widget\StatWidget; yield FormField::addRow(); yield FormField::addColumn(6); yield StatWidgetField::new( StatWidget::new('Total Users') ->setDescription('12% increase') ->setDescriptionIcon('fas fa-arrow-up') ->setColor('bg-success') ) ->setInitializer(function ($field, ?string $key) { $field->getWidget()->setValue('1234'); }); yield FormField::addColumn(6); yield StatWidgetField::new( StatWidget::new('Active Sessions') ->setDescription('5% decrease') ->setDescriptionIcon('fas fa-arrow-down') ->setColor('bg-warning') ) ->setInitializer(function ($field, ?string $key) { $field->getWidget()->setValue('892'); }); ``` -------------------------------- ### JavaScript Post-Select Callback Example Source: https://github.com/skie/admin-docs/blob/main/docs/Fields/Autocomplete.md An example JavaScript function that handles user selection from an autocomplete field. It logs the selection data and redirects the user if a URL is provided in the data. ```javascript App.handleUserSelection = function(id, value, field, data) { console.log('Selected user:', { id, value, field, data }); if (data && data.url) { window.location.href = data.url; } }; ``` -------------------------------- ### List Actions Only for Users Settings Source: https://github.com/skie/admin-docs/blob/main/docs/ShowSettingCommand.md Displays a simplified table containing only the names of all available actions for the UsersSettings class, useful for a quick overview. ```bash bin/cake setting_ext show Users --only-actions ``` -------------------------------- ### LinkButtonField PHP Example Source: https://github.com/skie/admin-docs/blob/main/docs/Fields.md Example of creating a LinkButtonField, which renders as a clickable button or link. It uses the Link class to define the button's text, URL, and optional icon. ```php LinkButtonField::new( Link::new('View Details') ->setUrl(['action' => 'view', $id]) ->setIcon('eye') ); ``` -------------------------------- ### Basic Usage: Creating a Navigation Menu (PHP) Source: https://github.com/skie/admin-docs/blob/main/docs/AdminMenuBuilder.md Demonstrates the fundamental steps to initialize a MenuBuilder and add top-level menu items, including those with sub-items. This example showcases the use of MenuItem::new() and setUrl() for defining navigation links. ```php use CakeDC\Admin\Menu\MenuBuilder; use CakeDC\Admin\Menu\MenuItem; // Create menu builder $menu = new MenuBuilder(); // Add a main menu item $menu->addItem( MenuItem::new('Dashboard') ->setIcon('fas fa-tachometer-alt') ->setUrl(['plugin' => 'CakeDC/Admin', 'controller' => 'Dashboard', 'action' => 'index']) ); // Add another item with sub-items $menu->addItem( MenuItem::new('Content') ->setIcon('fas fa-folder') ->addSubItem( MenuItem::new('Articles') ->setUrl(['controller' => 'Articles', 'action' => 'index']) ) ->addSubItem( MenuItem::new('Categories') ->setUrl(['controller' => 'Categories', 'action' => 'index']) ) ); ``` -------------------------------- ### Configure Existing Actions (Associations) Source: https://github.com/skie/admin-docs/blob/main/docs/BestPractices.md Shows an alternative method for configuring actions by retrieving an action instance (e.g., `ViewAction`) from the action list and setting its properties, such as associations for related data. ```php /** @var \CakeDC\Admin\Settings\Action\ViewAction $viewAction */ $viewAction = $this->getActionsList()->byName(Page::VIEW); $viewAction->setAssociations([ 'Users', ]); ``` -------------------------------- ### Common Use Case: Field Configuration Debugging Source: https://github.com/skie/admin-docs/blob/main/docs/ShowSettingCommand.md Illustrates debugging field behavior or configuration by showing detailed properties for a specific field, such as 'password', within an action like 'edit' for the UsersSettings class. ```bash bin/cake setting_ext show Users --action edit --field password ``` -------------------------------- ### Initialize Settings with SettingsExt initialize Source: https://github.com/skie/admin-docs/blob/main/docs/Settings.md The `initialize` method is an optional configuration method used to set up initial settings for the admin interface, such as page titles, model relationships, and default values. ```php public function initialize(): void { $this->setPageTitle([ 'index' => 'Products', 'add' => 'Add Product', ]); parent::initialize(); } ``` -------------------------------- ### Render Column Headers Source: https://github.com/skie/admin-docs/blob/main/docs/Reports/Helpers.md Renders column headers with bold text, gray background, and proper cell styling, starting at a specified row. It takes the sheet object, starting row, and field definitions as input. ```PHP // Render column headers starting at a specific row $currentRow = $this->Excel->renderColumnHeaders( $sheet, $startRow, $fields ); ``` -------------------------------- ### Add and Configure Actions Source: https://github.com/skie/admin-docs/blob/main/docs/Settings.md Illustrates how to add new custom actions, either with default configuration or with specific callback-based customizations, and how to modify existing actions. ```php // Add custom action $this->addAction(new CustomAction()); // Add custom action with configuration $this->addAction(new CustomAction(), function(CustomAction $action) { $action->setTitle('Custom Action'); }); // Configure action $this->configureAction('index', function(IndexAction $action) { $action->setTitle('User List'); $action->setDefaultPaginatorLimit(25); }); // Get specific action by name $indexAction = $this->getActionsList()->byName('index'); // Get specific action by type $indexAction = $this->getActionsList()->byType(Page::ADD); ``` -------------------------------- ### Full CellField Configuration Example Source: https://github.com/skie/admin-docs/blob/main/docs/Fields/Extended Cell Field Example.md A comprehensive example demonstrating the chaining of CellField configuration methods, including setting the cell name, action, custom options, template, and visibility. ```php setAction('customDisplay') // Specify a custom action method ->setOptions([ 'count' => 5, 'title' => 'My Boxes' ]) ->setTemplate('custom_box') // Use a custom template ->setDefaultColumns('col-md-12') // Set default column classes ->hideOnForms() // Hide on form views ->hideOnIndex(); // Hide on index views ?> ``` -------------------------------- ### MenuItem: Creating Menu Items (PHP) Source: https://github.com/skie/admin-docs/blob/main/docs/AdminMenuBuilder.md Illustrates two ways to create a MenuItem instance: using the constructor directly or utilizing the recommended static factory method `MenuItem::new()`. The factory method simplifies the instantiation process. ```php // Using constructor $item = new MenuItem('Users'); // Using static factory method (recommended) $item = MenuItem::new('Users'); ``` -------------------------------- ### JavaScript Dynamic Empty State Callback Example Source: https://github.com/skie/admin-docs/blob/main/docs/Fields/Autocomplete.md An example JavaScript function that generates HTML for an empty autocomplete state. It accepts the search query and a context object, allowing for dynamic content like buttons with inline actions. ```javascript function renderEmptyUser(query, ctx) { // ctx contains additional info (field, parent, context, etc.) return `
No user found for "${query}".
`; } function openAddUserModal(name) { // Your modal logic here alert('Open modal to add: ' + name); } ``` -------------------------------- ### Product Inventory Report Class Example Source: https://github.com/skie/admin-docs/blob/main/docs/Reports/TableReports.md An example of extending `CakeDC\Admin\Report\TableReport` to define a product inventory report. It covers initializing report properties, defining various fields (string, numeric, date) with formatters and alignment, and setting up total fields with aggregation operations. ```php use CakeDC\Admin\Report\TableReport; use CakeDC\Admin\Settings\Field\StringField; use CakeDC\Admin\Settings\Field\NumericField; use CakeDC\Admin\Settings\Field\DateField; use CakeDC\Admin\Settings\Field\FieldCollection; use CakeDC\Admin\Settings\Field\Formatter\NumericFormatter; use CakeDC\Admin\Settings\Field\Formatter\CurrencyFormatter; use CakeDC\Admin\Report\Field\Formatter\NumericExcelFormatter; use CakeDC\Admin\Report\Field\Formatter\CurrencyExcelFormatter; use CakeDC\Admin\Report\Field\Formatter\DateExcelFormatter; use CakeDC\Admin\Report\Field\ComputeField; class ProductInventoryReport extends TableReport { public function initialize(): void { parent::initialize(); $this->setTitle('Product Inventory'); $this->setDescription('Current inventory levels for all products'); $this->setPageOrientation(self::ORIENTATION_LANDSCAPE); $this->setTotalLabel('Inventory Totals'); } public function defineFields(): void { $this->addField(StringField::new('sku') ->setLabel('SKU')); $this->addField(StringField::new('name') ->setLabel('Product Name')); $this->addField(StringField::new('category') ->setLabel('Category')); $this->addField(NumericField::new('stock') ->setLabel('In Stock') ->appendFormatter( (new NumericFormatter()) ->setDecimalsCount(0) ) ->appendFormatter( (new NumericExcelFormatter()) ->setDecimalsCount(0) ) ->setTextAlign('right')); $this->addField(NumericField::new('reorder_level') ->setLabel('Reorder Level') ->appendFormatter( (new NumericFormatter()) ->setDecimalsCount(0) ) ->appendFormatter( (new NumericExcelFormatter()) ->setDecimalsCount(0) ) ->setTextAlign('right')); $this->addField(NumericField::new('price') ->setLabel('Unit Price') ->appendFormatter( (new CurrencyFormatter()) ->setCurrencyPrefix('$') ->setDecimalsCount(2) ) ->appendFormatter(new CurrencyExcelFormatter()) ->setTextAlign('right')); $this->addField(DateField::new('last_ordered') ->setLabel('Last Ordered') ->setFormat('Y-m-d') ->appendFormatter(new DateExcelFormatter('yyyy-mm-dd'))); } public function defineTotalFields(): void { $this->addTotalField(ComputeField::new('total_stock') ->setLabel('Total Stock') ->setOperation(ComputeField::OPERATION_SUM) ->setField('stock') ->appendFormatter( (new NumericFormatter()) ->setDecimalsCount(0) ) ->appendFormatter( (new NumericExcelFormatter()) ->setDecimalsCount(0) )); $this->addTotalField(ComputeField::new('total_value') ->setLabel('Total Value') ->setOperation(ComputeField::OPERATION_SUM) ->appendFormatter( (new CurrencyFormatter()) ->setDecimalsCount(2) ) ->appendFormatter(new CurrencyExcelFormatter())); } } ``` -------------------------------- ### PHP: Configure Custom Index and Dashboard Actions Source: https://github.com/skie/admin-docs/blob/main/docs/Actions.md Demonstrates setting up custom 'cheapest' and 'expensive' index actions with specific query builders and ordering. It also shows how to create a dashboard action with tab links pointing to these custom index views. ```php use Cake\Database\Query\SelectQuery; use CakeDC\Admin\Settings\Action\DashboardAction; use CakeDC\Admin\Settings\Action\IndexAction; use CakeDC\Admin\Settings\Action\IndexLink; use CakeDC\Admin\Settings\SettingsExt; class UserSettings extends SettingsExt { public function loadDefaultActions() { parent::loadDefaultActions(); $cheapestAction = (new IndexAction()) ->setTemplateizer($this->templateizer) ->setTemplateName('index') ->setName('cheapest') ->setQueryBuilder(function (SelectQuery $query, $key) { return $query ->where(['budget <' => 100000]) ->orderBy(['budget' => 'ASC']); }); $this->getActionsList()->add($cheapestAction); $expensiveAction = (new IndexAction()) ->setTemplateizer($this->templateizer) ->setTemplateName('index') ->setName('expensive') ->setQueryBuilder(function (SelectQuery $query, $key) { return $query ->where(['budget >' => 10000000]) ->orderBy(['budget' => 'DESC']); }); $this->getActionsList()->add($expensiveAction); $dashboardAction = (new DashboardAction()) ->setTemplateizer($this->templateizer) ->setTemplateName('dashboard') ->setName('dashboard'); $dashboardAction->getTabsLinks()->add( (new IndexLink()) ->setLabel('Cheapest Movies') ->setCrudLink('cheapest') ); $dashboardAction->getTabsLinks()->add( (new IndexLink()) ->setLabel('Expensive Movies') ->setCrudLink('expensive') ); $this->getActionsList()->add($dashboardAction); return $this; } } ``` -------------------------------- ### Action Template Elements Configuration Source: https://github.com/skie/admin-docs/blob/main/docs/Actions.md Example of setting template elements for actions, such as prefixes or postfixes, to customize rendering within templates. ```php $action->setTemplateElements([ Action::ELEMENT_PREFIX => 'prefix_element', Action::ELEMENT_POSTFIX => 'postfix_element' ]); ``` -------------------------------- ### PHP User Wizard Implementation Source: https://github.com/skie/admin-docs/blob/main/docs/Wizard.md This snippet defines a `UserWizard` class in PHP, extending `SettingsExt`. It configures a multi-step wizard with actions for account setup, personal information (conditionally displayed), and confirmation. It also includes methods for building specific fields for each wizard step. ```php class UserWizard extends SettingsExt { public function initialize(): void { $this->setPageTitle([ 'wizard' => __('User Wizard'), ]); parent::initialize(); } public function loadDefaultActions(): void { $wizard = new WizardAction(); $wizard->setTemplateizer($this->templateizer) ->setName('wizard') ->setCrudAction('wizard') ->setType('wizard'); // Account Setup Step $wizard->addStep((new WizardStepAction('account')) ->setIcon('fa fa-user') ->setTitle('Account Setup') ); // Personal Info Step (Conditional) $wizard->addStep((new WizardStepAction('personal')) ->setIcon('fa fa-table') ->setTitle('Personal Information') ->setCondition(function(array $data) { return $data['account']['email'] !== 'superadmin@example.com'; }) ->setProcessCallback(function(array $data, WizardContext $context, Controller $controller, WizardProcessor $processor) { $controller->Flash->success('Personal Info Saved'); return true; }) ); // Confirmation Step $wizard->addStep((new WizardStepAction('confirm')) ->setIcon('fa fa-check') ->setTitle('Review Information') ->setProcessCallback(function(array $data, WizardContext $context, Controller $controller, WizardProcessor $processor) { $controller->Flash->success('Confirmed'); return true; }) ); // Final Processing $wizard->setFinalCallback(function(array $data, WizardContext $context, Controller $controller, WizardProcessor $processor) { $controller->Flash->success('Wizard Completed'); return $controller->redirect('/admin/pages'); }); $this->getActionsList()->add($wizard); } public function fieldsBuilder(string $page): iterable { return match($page) { 'account' => $this->buildAccountFields(), 'personal' => $this->buildPersonalFields(), 'confirm' => $this->buildConfirmFields(), default => [], }; } protected function buildAccountFields(): iterable { yield StringField::new('username') ->setRequired(true); yield EmailField::new('email') ->setRequired(true); yield PasswordField::new('password') ->setRequired(true); } protected function buildPersonalFields(): iterable { yield StringField::new('first_name') ->setRequired(true); yield StringField::new('last_name') ->setRequired(true); yield StringField::new('role') ->setDefaultValue('user'); } protected function buildConfirmFields(): iterable { yield CellField::new('Wizard') ->setAction('preview'); } } ``` -------------------------------- ### Create Block Formatter Source: https://github.com/skie/admin-docs/blob/main/docs/Fields/Builder.md Provides an example of creating a custom formatter for a block, defining how block data is rendered into HTML. ```php class HeaderBlockFormatter implements FormatterInterface { public function format(FieldInterface $field, EntityInterface $data, View $view): string { $level = $data['level'] ?? 'h2'; $title = $data['title'] ?? ''; return sprintf( '<%1$s class="block-header">%2$s', h($level), h($title) ); } } ``` -------------------------------- ### Applying Formatter Chain Source: https://github.com/skie/admin-docs/blob/main/docs/Fields/Formatters.md Shows how to execute the entire chain of applied formatters to get the final formatted value for an entity. ```php $field->getFormattedValue($entity, $view); // Applies all formatters in chain ``` -------------------------------- ### Custom Formatter Implementation Source: https://github.com/skie/admin-docs/blob/main/docs/Fields.md Provides an example of creating a custom formatter by extending the BaseFormatter class and implementing the format method. ```php use CakeDC\Admin\Settings\Field\Formatter\BaseFormatter; class CustomFormatter extends BaseFormatter { public function format(FieldInterface $field, EntityInterface $entity, View $view) { $value = $field->getValue(); // Transform value return $transformedValue; } } ``` -------------------------------- ### Build Admin Menu Structure Source: https://github.com/skie/admin-docs/blob/main/docs/AdminMenuBuilder.md Demonstrates creating a `MenuBuilder` instance and adding menu items with sub-items and icons for an admin interface. ```php $menu = new MenuBuilder(); // Movies Management $menu->addItem( MenuItem::new('Movies') ->setIcon('fas fa-film') ->addSubItem( Movies::getMenuItem('dashboard', 'Movies Dashboard') ->setIcon('fas fa-list') ) ->addSubItem( Movies::getMenuItem('index', 'Movies List') ->setIcon('fas fa-list') ) ->addSubItem( Genres::getMenuItem() ->setIcon('fas fa-theater-masks') ) ->addSubItem( Keywords::getMenuItem() ->setIcon('fas fa-tags') ) ); ``` -------------------------------- ### Conditional Formatter Application Source: https://github.com/skie/admin-docs/blob/main/docs/Fields/Formatters.md Provides an example of applying a formatter only when a specific condition is met, such as checking if a URL formatter is already configured. ```php if ($field->hasUrlFormatter()) { $field->appendFormatter(new UrlFormatter([ 'url' => ['controller' => 'Products', 'action' => 'view'] ])); } ``` -------------------------------- ### Add Multiple Steps to Wizard in PHP Source: https://github.com/skie/admin-docs/blob/main/docs/Wizard.md Illustrates how to add several distinct steps to a wizard. Each step can be configured with an icon and a title, defining the user interface for each stage of the process. ```php // Step 1 $wizard->addStep((new WizardStepAction('account')) ->setIcon('fa fa-user') ->setTitle('Account Setup') ); // Step 2 $wizard->addStep((new WizardStepAction('profile')) ->setIcon('fa fa-table') ->setTitle('Profile Setup') ); // Step 3 $wizard->addStep((new WizardStepAction('overview')) ->setIcon('fa fa-check') ->setTitle('Overview') ); ``` -------------------------------- ### Show Specific Field for Users Settings Source: https://github.com/skie/admin-docs/blob/main/docs/ShowSettingCommand.md Provides detailed configuration for a specific field, like 'email', within a given action ('edit') of the UsersSettings class. This is useful for debugging field-level properties. ```bash bin/cake setting_ext show Users --action edit --field email ``` -------------------------------- ### ActiveSimpleTableField Custom Actions Example Source: https://github.com/skie/admin-docs/blob/main/docs/Fields.md Demonstrates how to add custom top and row actions to the ActiveSimpleTableField, such as 'Add Institution' or 'View Details'. ```php $addLink = new AddRelatedLink(); $addLink->setLabel(__('Add Institution')); $addLink->setCssClass('btn btn-primary'); $viewLink = new ViewTableLink(); $viewLink->setLabel(__('View Details')); yield ActiveSimpleTableField::new('institutions') ->setLabel(__('Institutions')) ->setTableColumns($columns) ->setRelatedModel('Institutions') ->addTopAction($addLink) ->addTableAction($viewLink) ->addTableAction(new EditTableLink()) ->addTableAction(new DeleteRelatedTableLink()); ``` -------------------------------- ### Panel Navigation Configuration Methods Source: https://github.com/skie/admin-docs/blob/main/docs/LayoutQuickReference.md Details the available configuration methods for the Panel Navigation component, allowing developers to customize its behavior, such as sticky positioning, scroll offsets, scroll spy functionality, panel inclusion, and depth limits. ```APIDOC PanelNavigation: setStickyTop(bool $enable): PanelNavigation Enables fixed positioning of the navigation at the top of the viewport. setOffset(int $offset): PanelNavigation Sets the pixel offset for scrolling to sections. setScrollSpy(bool $enable): PanelNavigation Enables automatic highlighting of the current visible section during scrolling. setIncludeRelatedPanels(bool $include): PanelNavigation Includes or excludes related panels from the navigation. setMaxDepth(int $depth): PanelNavigation Limits the navigation to specific nesting depths. ``` -------------------------------- ### Configure Report Action and Engines Source: https://github.com/skie/admin-docs/blob/main/docs/Reports/Index.md Demonstrates how to set up a ReportAction for a specific report, assign a report class, and configure available output engines like PDF and Excel. It also shows how to disable specific engines. ```php use CakeDC\Admin\Settings\Action\ReportAction; use CakeDC\Admin\Report\Engine\PdfEngine; use CakeDC\Admin\Report\Engine\ExcelEngine; use App\Report\SalesReport; // Create report action $reportAction = new ReportAction(); $reportAction ->setName('sales_report') ->setLabel('Sales Report') ->setReport(new SalesReport()); // Configure available engines $reportAction->enableEngine('pdf', PdfEngine::class, [ 'download' => true, ]); $reportAction->enableEngine('excel', ExcelEngine::class); // Disable an engine if needed $reportAction->disableEngine('html'); // Add to actions list $this->getActionsList()->add($reportAction); ```