PHP code example of restruct / silverstripe-simpler

1. Go to this page and download the library: Download restruct/silverstripe-simpler library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

restruct / silverstripe-simpler example snippets


use SilverStripe\View\Requirements;

Requirements::javascript('mymodule/client/dist/js/my-vue-app.js', ['type' => 'module']);

use Restruct\Silverstripe\Simpler\AdminExtension;

AdminExtension::

use Restruct\Silverstripe\Simpler\SimplerModalField;
use Restruct\Silverstripe\Simpler\SimplerModalAction;

// Iframe content (e.g., preview) with extra large modal
SimplerModalField::create('preview', 'Preview')
    ->setIframeSrc('/admin/preview/123')
    ->setIframeHeight('80vh')
    ->setModalSize('xl')  // 'sm', 'lg', 'xl' or custom like '800px', '90vw'
    ->setCloseBtn(false)  // Hide footer close button (default: true)
    ->setButtonIcon('eye')
    ->addExtraClass('btn-outline-info');

// HTML content with custom width
SimplerModalField::create('info', 'Info')
    ->setContent('<p>Some information here</p>')
    ->setModalSize('600px');

// Custom dialog title (different from button text)
SimplerModalField::create('details', 'Show Details')
    ->setDialogTitle('Item Details')
    ->setContent($myHtmlContent);

// CMS action with form fields (form submits directly - no iframe!)
SimplerModalAction::create('translate', 'Translate')
    ->setFieldList(FieldList::create([
        DropdownField::create('lang', 'Language', ['en' => 'English', 'nl' => 'Dutch']),
        TextareaField::create('notes', 'Notes'),
    ]))
    ->setDialogButtonTitle('Start Translation');

// Change from:
use LeKoala\PureModal\PureModal;
use LeKoala\PureModal\PureModalAction;

// To:
use Restruct\Silverstripe\Simpler\SimplerModalField as PureModal;
use Restruct\Silverstripe\Simpler\SimplerModalAction as PureModalAction;

use Restruct\Silverstripe\Simpler\GridFieldToolbarModalAction;

// Extend and override handleAction():
class MyGridFieldAction extends GridFieldToolbarModalAction
{
    public function __construct()
    {
        parent::__construct('myaction', 'Do Something');
        $this->setDialogTitle('Configure Action');
        $this->setSubmitLabel('Apply');
        $this->setButtonIcon('rocket');
        $this->setFieldList(FieldList::create([
            DropdownField::create('Option', 'Choose', $options),
            NumericField::create('Count', 'How many'),
        ]));
    }

    public function handleAction(GridField $gridField, $actionName, $arguments, $data)
    {
        if ($actionName !== 'myaction') {
            return;
        }
        $option = $data['Option'] ?? null;
        $count = (int) ($data['Count'] ?? 1);
        // Do something with the form data...
    }
}

// Add to GridField config:
$config->addComponent(new MyGridFieldAction());

use SilverStripe\Control\HTTPResponse;
use SilverStripe\Control\HTTPResponse_Exception;

// In handleAction():
try {
    // ... do work
} catch (\Exception $e) {
    throw new HTTPResponse_Exception(new HTTPResponse($e->getMessage(), 422));
}

Controller::curr()->getResponse()->addHeader('X-Reload', 'true');

use Restruct\Silverstripe\Simpler\GridFieldModalButton;

class MyDetailButton extends GridFieldModalButton
{
    protected function getButtonLabel(DataObject $record): string
    {
        return 'Details';
    }

    protected function getModalTitle(DataObject $record): string
    {
        return 'Details for ' . $record->Title;
    }

    protected function getModalContent(DataObject $record): string
    {
        return '<p>' . htmlspecialchars($record->Description) . '</p>';
    }

    protected function shouldShowButton(DataObject $record): bool
    {
        return $record->canView();
    }
}

// Add to GridField config:
$config->addComponent(new MyDetailButton());

use Restruct\Silverstripe\Simpler\GridFieldToggleFieldButton;
use Restruct\Silverstripe\Simpler\GridFieldToggleIsActiveButton;

// Simple boolean toggle for IsActive field (pre-configured)
$config->addComponent(GridFieldToggleIsActiveButton::create());

// Generic boolean toggle for any field
$config->addComponent(GridFieldToggleFieldButton::create('IsPublished'));

// Multi-state toggle (cycles through values in order)
$config->addComponent(
    GridFieldToggleFieldButton::create('Status')
        ->setStates([
            'draft' => ['icon' => 'edit', 'title' => 'Submit for Review'],
            'review' => ['icon' => 'eye', 'title' => 'Publish'],
            'published' => ['icon' => 'check-mark', 'title' => 'Archive'],
            'archived' => ['icon' => 'archive', 'title' => 'Reset to Draft'],
        ])
        ->setConfirmMessage('Change status?')
);

GridFieldToggleFieldButton::create('IsActive')
    // Custom state rendering via callback
    ->setStateRenderer(function(DataObject $record, $currentValue) {
        return [
            'icon' => $record->getStatusIcon(),
            'title' => $record->getNextStatusLabel(),
            'buttonClass' => $currentValue ? 'text-success' : 'text-muted',
        ];
    })
    // Visibility check
    ->setShouldShow(fn($record) => $record->canEdit())
    // Custom toggle logic (called before save)
    ->setToggleAction(function(DataObject $record, $newValue) {
        $record->IsActive = $newValue;
        $record->StatusChangedDate = DBDatetime::now();
        $record->StatusChangedBy = Security::getCurrentUser()->ID;
    })
    // Confirmation dialog
    ->setConfirmMessage('Are you sure?')
    // Use writeWithoutVersion() for versioned records (default: true)
    ->setWriteWithoutVersion(true);

use Restruct\Silverstripe\Simpler\Session;

// Instead of: $this->getRequest()->getSession()->get('key')
$value = Session::get('key');
Session::set('key', 'value');
Session::clear('key');
Session::clear_all();
Session::add_to_array('key', 'value');
$all = Session::get_all();

use Restruct\Silverstripe\Simpler\HeadRequirements;

// Import map entries (browsers allow only ONE import map - these accumulate)
HeadRequirements::import_map('vue', 'restruct/silverstripe-simpler:client/dist/js/vue.esm-browser.js');
HeadRequirements::import_map('lodash', 'https://cdn.jsdelivr.net/npm/lodash-es@4/lodash.min.js');

// JavaScript file in <head>
HeadRequirements::javascript('mymodule:client/dist/js/early-script.js');
HeadRequirements::javascript('https://cdn.example.com/lib.js', ['defer' => true]);

// Inline script in <head>
HeadRequirements::custom_script('window.CONFIG = { debug: true }', 'my-config');
js
simpler.modal.title = 'My Dialog';
simpler.modal.bodyHtml = '<p>Hello world!</p>';
simpler.modal.show = true;