fire event to attach customfields rules to form grid

@param Grid $grid
@return boolean
180160
public function handle(Grid $grid)
    {
        $name      = $grid->name;
        $extension = app('antares.extension')->getActualExtension();

        if (is_null($name) or is_null($extension)) {
            return false;
        }
        $namespace = $extension . '.' . $name;
        if (is_null(app('antares.memory')->make('registry')->get($namespace))) {
            return false;
        }
        $gridRules = !is_array($grid->rules) ? [] : $grid->rules;
        $rules     = array_merge($gridRules, $this->getRulesForCustomFields($namespace));
        $grid->rules($rules);
        return true;
    }
1124037
public function onSubmitForm(Fluent $rules, Fluent $attributes)
    {
        $name = $attributes->get('name');
        if (is_null($name)) {
            return;
        }
        $brand      = antares('memory')->get('brand.default');
        $collection = Foundation::make('antares.customfields.model.view')->query()->where('namespace', $name)->where('brand_id', $brand)->get();
        if ($collection->isEmpty()) {
            return;
        }
        $collection->each(function($item) use(&$rules) {

            $validators = [];
            $item->config->each(function($config) use(&$validators) {
                $name          = $config->validator->name;
                $name == 'regex' && $config->value = implode('', ['[', $config->value, ']']);
                $rule          = ((!is_null($config->value) ? ':' . $config->value : ''));
                $validators[]  = $name . $rule;
            });
            $rules->{$item->name} = $validators;
        });
    }
1136649
public function getFields(GridField $grid, DataObjectInterface $record)
    {
        $cols   = $this->getDisplayFields($grid);
        $fields = new FieldList();

        /** @var DataList $list */
        $list   = $grid->getList();
        $class  = $list ? $list->dataClass() : null;

        foreach ($cols as $col => $info) {
            $field = null;

            if ($info instanceof Closure) {
                $field = call_user_func($info, $record, $col, $grid);
            } elseif (is_array($info)) {
                if (isset($info['callback'])) {
                    $field = call_user_func($info['callback'], $record, $col, $grid);
                } elseif (isset($info['field'])) {
                    if ($info['field'] == LiteralField::class) {
                        $field = new $info['field']($col, null);
                    } else {
                        $field = new $info['field']($col);
                    }
                }

                if (!$field instanceof FormField) {
                    throw new Exception(sprintf(
                        'The field for column "%s" is not a valid form field',
                        $col
                    ));
                }
            }

            if (!$field && $list instanceof ManyManyList) {
                $extra = $list->getExtraFields();

                if ($extra && array_key_exists($col, $extra)) {
                    $field = Injector::inst()->create($extra[$col], $col)->scaffoldFormField();
                }
            }

            if (!$field) {
                if (!$this->displayFields) {
                    // If setDisplayFields() not used, utilize $summary_fields
                    // in a way similar to base class
                    //
                    // Allows use of 'MyBool.Nice' and 'MyHTML.NoHTML' so that
                    // GridFields not using inline editing still look good or
                    // revert to looking good in cases where the field isn't
                    // available or is readonly
                    //
                    $colRelation = explode('.', $col);
                    if ($class && $obj = DataObject::singleton($class)->dbObject($colRelation[0])) {
                        $field = $obj->scaffoldFormField();
                    } else {
                        $field = new ReadonlyField($colRelation[0]);
                    }
                } elseif ($class && $obj = DataObject::singleton($class)->dbObject($col)) {
                    $field = $obj->scaffoldFormField();
                } else {
                    $field = new ReadonlyField($col);
                }
            }

            if (!$field instanceof FormField) {
                throw new Exception(sprintf(
                    'Invalid form field instance for column "%s"',
                    $col
                ));
            }

            // Add CSS class for interactive fields
            if (!($field->isReadOnly() || $field instanceof LiteralField)) {
                $field->addExtraClass('editable-column-field');
            }

            $fields->push($field);
        }

        return $fields;
    }
1265473
public function handleAction(GridField $gridField, $actionName, $arguments, $data)
    {
        switch ($actionName) {
            case 'addto':
                if (isset($data['relationID']) && $data['relationID']) {
                    $gridField->State->GridFieldAddRelation = $data['relationID'];
                }
                break;
        }
    }
617970
protected function getExportColumnsForGridField(GridField $gridField)
    {
        if ($this->exportColumns) {
            return $this->exportColumns;
        }

        /** @var GridFieldDataColumns $dataCols */
        $dataCols = $gridField->getConfig()->getComponentByType(GridFieldDataColumns::class);
        if ($dataCols) {
            return $dataCols->getDisplayFields($gridField);
        }

        return DataObject::singleton($gridField->getModelClass())->summaryFields();
    }
722646
public function getHTMLFragments($grid)
    {
        $dataClass = $grid->getList()->dataClass();
        $obj = singleton($dataClass);

        if (!$obj->canCreate()) {
            return "";
        }

        $text_field = TextField::create("gridfieldaddbydbfield")
            ->setAttribute(
                "placeholder",
                _t(
                    "GridFieldAddLineItem.TypeToAdd",
                    "Type to add by {Filters} or {Title}",
                    "Inform the user what to add based on",
                    [
                        "Filters" => implode(", ", $this->getFilterFields()),
                        "Title" => $this->getCreateField()
                    ]
                )
            )->addExtraClass("relation-search no-change-track")
            ->setAttribute(
                'data-search-url',
                Controller::join_links($grid->Link('search'))
            );

        $find_action = GridField_FormAction::create(
            $grid,
            'gridfield_relationfind',
            _t('GridField.Find', "Find"),
            'find',
            'find'
        );
        $find_action->setAttribute('data-icon', 'relationfind');

        $add_action = GridField_FormAction::create(
            $grid,
            'gridfield_lineitemadd',
            _t("GridFieldAddLineItem.Add", "Add"),
            'add',
            'add'
        );
        $add_action->addExtraClass('btn btn-primary font-icon-plus-circled');
        $add_action->addExtraClass('action_gridfield_relationadd');

        // Start thinking about rending this back to the GF
        $fields = ArrayList::create();

        $fields->push($text_field);
        $fields->push($find_action);
        $fields->push($add_action);

        $forTemplate = ArrayData::create([]);
        $forTemplate->Fields = $fields;

        return [
            $this->targetFragment => $forTemplate->renderWith(AddLineItem::class)
        ];
    }
1372301
public function handleMoveToPage(GridField $grid, $request)
    {
        if (!$paginator = $grid->getConfig()->getComponentByType('GridFieldPaginator')) {
            $this->httpError(404, 'Paginator component not found');
        }

        $move = $request->postVar('move');
        $field = $this->getSortField();

        $list = $grid->getList();
        $manip = $grid->getManipulatedList();

        $existing = $manip->map('ID', $field)->toArray();
        $values = $existing;
        $order = array();

        $id = isset($move['id']) ? (int)$move['id'] : null;
        $to = isset($move['page']) ? $move['page'] : null;

        if (!isset($values[$id])) {
            $this->httpError(400, 'Invalid item ID');
        }

        $this->populateSortValues($list);

        $page = ((int)$grid->getState()->GridFieldPaginator->currentPage) ?: 1;
        $per = $paginator->getItemsPerPage();

        if ($to == 'prev') {
            $swap = $list->limit(1, ($page - 1) * $per - 1)->first();
            $values[$swap->ID] = $swap->$field;

            $order[] = $id;
            $order[] = $swap->ID;

            foreach ($existing as $_id => $sort) {
                if ($id != $_id) $order[] = $_id;
            }
        } elseif ($to == 'next') {
            $swap = $list->limit(1, $page * $per)->first();
            $values[$swap->ID] = $swap->$field;

            foreach ($existing as $_id => $sort) {
                if ($id != $_id) $order[] = $_id;
            }

            $order[] = $swap->ID;
            $order[] = $id;
        } else {
            $this->httpError(400, 'Invalid page target');
        }

        $this->reorderItems($list, $values, $order);

        return $grid->FieldHolder();
    }
61745
public function hasCustomField($key)
    {
        if($key !== 'customFields' && !array_key_exists($key, $this->getAttributes())) {
            if(isset($this->customFields->$key)) {
                return true;
            }
        }
        return false;
    }
139163
public function allButtons($grid ='')
    {
        $buttons = parent::allButtons($grid);
        if(\Yii::$app->user->checkAccess('read::' . $this->getCompatibilityId())) {
            $buttons['tag'] = [
                'text' => 'Assign to tag', 
                'url' => '#assign-all-tag', 
                'options' => [
                    'data-toggle' => "modal",
                    'data-pjax' => 0,
                    'role' => "button",
                ]
            ];
        }
        return $buttons;
    }
1339514
public function augmentColumns($gridField, &$columns)
    {
        if (!in_array('Reorder', $columns) && $gridField->getState()->VersionedGridFieldOrderableRows->enabled) {
            array_unshift($columns, 'Reorder');
        }
    }
275172
public function prepareViewModel(Datagrid $grid)
    {
        $viewModel = $this->getViewModel();

        $viewModel->setVariable('gridId', $grid->getId());
        $viewModel->setVariable('title', $this->getTitle());
        $viewModel->setVariable('parameters', $grid->getParameters());
        $viewModel->setVariable('overwriteUrl', $grid->getUrl());

        $viewModel->setVariable('templateToolbar', $this->getToolbarTemplate());
        foreach ($this->getToolbarTemplateVariables() as $key => $value) {
            $viewModel->setVariable($key, $value);
        }
        $viewModel->setVariable('rendererName', $this->getName());

        $options = $this->getOptions();
        $generalParameterNames = $options['generalParameterNames'];
        $viewModel->setVariable('generalParameterNames', $generalParameterNames);

        $viewModel->setVariable('columns', $this->getColumns());

        $viewModel->setVariable('rowStyles', $grid->getRowStyles());

        $viewModel->setVariable('paginator', $this->getPaginator());
        $viewModel->setVariable('data', $this->getData());
        $viewModel->setVariable('filters', $this->getFilters());

        $viewModel->setVariable('rowClickAction', $grid->getRowClickAction());
        $viewModel->setVariable('massActions', $grid->getMassActions());

        $viewModel->setVariable('isUserFilterEnabled', $grid->isUserFilterEnabled());

        /*
         * renderer specific parameter names
         */
        $optionsRenderer = $this->getOptionsRenderer();
        $viewModel->setVariable('optionsRenderer', $optionsRenderer);
        if ($this->isExport() === false) {
            $parameterNames = $optionsRenderer['parameterNames'];
            $viewModel->setVariable('parameterNames', $parameterNames);

            $activeParameters = [];
            $activeParameters[$parameterNames['currentPage']] = $this->getCurrentPageNumber();
            {
                $sortColumns = [];
                $sortDirections = [];
            foreach ($this->getSortConditions() as $sortCondition) {
                $sortColumns[] = $sortCondition['column']->getUniqueId();
                $sortDirections[] = $sortCondition['sortDirection'];
            }

                $activeParameters[$parameterNames['sortColumns']] = implode(',', $sortColumns);
                $activeParameters[$parameterNames['sortDirections']] = implode(',', $sortDirections);
            }
            $viewModel->setVariable('activeParameters', $activeParameters);
        }

        $viewModel->setVariable('exportRenderers', $grid->getExportRenderers());
    }
750028
public function handle(Fluent $model, Grid $grid)
    {
        $grid->fieldset(function(Fieldset $fieldset) {
            $fieldset->legend(trans('antares/notifications::logs.form.notifications_config_legend'));

            $fieldset->control('input:text', 'days')
                    ->label('')
                    ->field(function() {
                        $memory = app('antares.memory')->make('primary');
                        return '<div class="col-group"><div class="col-dt-16 col-16 col-mb-16">' . trans('antares/notifications::logs.form.notifications_config_days_label', ['x' => '<input class="w50" type="number" name="days" value="' . $memory->get('notifications_remove_after_days', '') . '" size="2" max-length="2"  />']) . '</div><div class="col-dt-16 col-16 col-mb-16 "><div class="input-field__desc">' . trans('antares/notifications::logs.form.notifications_config_days_help') . '</div></div></div>';
                    });
        });
        $grid->rules(array_merge($grid->rules, [
            'days' => ['numeric'],
        ]));
    }
1242828
public function beforeFieldRender($event)
    {
        $clientOptions = $this->getFieldClientOptions($event->getTarget());
        if (!empty($clientOptions)) {
            $this->attributes[] = $clientOptions;
        }
    }
358556
public function initialize(Grid $grid)
    {
        $this->grid = $grid;
        if (method_exists($this, 'initializeComponents')) {
            $this->initializeComponents($grid);
        }
    }
1098174
protected function submitGrid(GridInterface $grid, Request $request)
    {
        return $this->submitForm($this->buildForm(GridType::class, null, ['grid' => $grid]), $request);
    }
1188324
public function handle(FormBuilder $formBuilder)
    {
        $grid      = $formBuilder->grid;
        $fieldsets = $grid->fieldsets();
        if (empty($fieldsets)) {
            return false;
        }
        if (!isset($grid->name) or is_null($grid->name)) {
            return false;
        }

        $extension = app('antares.extension')->getActualExtension();
        $memory    = app('antares.memory')->make('registry');
        $namespace = $extension . '.' . $grid->name;
        if (is_null($memory->get($namespace))) {
            $memory->push($namespace, $namespace);
            $memory->finish();
            return false;
        }

        /* @var $formHandler FormHandler */
        $formHandler = app('Antares\Customfields\Events\FormHandler');
        $formHandler->onViewForm($grid->row(), $formBuilder, $namespace);
    }
224008
public function getCMSFields()
    {
        // PHP 5.3 only
        $self = $this;
        $this->beforeUpdateCMSFields(function (FieldList $fields) use ($self) {
            $fields->removeFieldsFromTab(
                'Root.Main',
                array('KeyValuePairs', 'SortBy', 'SortByDirection')
            );
            // Don't put the GridField for documents in until the set has been created
            if (!$self->isInDB()) {
                $fields->addFieldToTab(
                    'Root.Main',
                    LiteralField::create(
                        'GridFieldNotice',
                        '<p class="message warning">' . _t(
                            'DMSDocumentSet.GRIDFIELD_NOTICE',
                            'Managing documents will be available once you have created this document set.'
                        ) . '</p>'
                    ),
                    'Title'
                );
            } else {
                $fields->removeByName('DocumentSetSort');
                // Document listing
                $gridFieldConfig = GridFieldConfig::create()
                    ->addComponents(
                        new GridFieldButtonRow('before'),
                        new GridFieldToolbarHeader(),
                        new GridFieldFilterHeader(),
                        new GridFieldSortableHeader(),
                        new GridFieldDataColumns(),
                        new DMSGridFieldEditButton(),
                        // Special delete dialog to handle custom behaviour of unlinking and deleting
                        new GridFieldDeleteAction(true),
                        new GridFieldDetailForm()
                    );

                if (class_exists('GridFieldPaginatorWithShowAll')) {
                    $paginatorComponent = new GridFieldPaginatorWithShowAll(15);
                } else {
                    $paginatorComponent = new GridFieldPaginator(15);
                }
                $gridFieldConfig->addComponent($paginatorComponent);

                if (class_exists('GridFieldSortableRows')) {
                    $gridFieldConfig->addComponent(new GridFieldSortableRows('DocumentSort'));
                } elseif (class_exists('GridFieldOrderableRows')) {
                    $gridFieldConfig->addComponent(new GridFieldOrderableRows('DocumentSort'));
                }

                // Don't show which page this is if we're already editing within a page context
                if (Controller::curr() instanceof CMSPageEditController) {
                    $fields->removeByName('PageID');
                } else {
                    $fields->fieldByName('Root.Main.PageID')->setTitle(_t('DMSDocumentSet.SHOWONPAGE', 'Show on page'));
                }

                // Don't show which page this is if we're already editing within a page context
                if (Controller::curr() instanceof CMSPageEditController) {
                    $fields->removeByName('PageID');
                } else {
                    $fields->fieldByName('Root.Main.PageID')->setTitle(_t('DMSDocumentSet.SHOWONPAGE', 'Show on page'));
                }

                $gridFieldConfig->getComponentByType('GridFieldDataColumns')
                    ->setDisplayFields($self->getDocumentDisplayFields())
                    ->setFieldCasting(array('LastEdited' => 'Datetime->Ago'))
                    ->setFieldFormatting(
                        array(
                            'FilenameWithoutID' => '<a target=\'_blank\' class=\'file-url\''
                                . ' href=\'$Link\'>$FilenameWithoutID</a>',
                            'ManuallyAdded' => function ($value) {
                                if ($value) {
                                    return _t('DMSDocumentSet.MANUAL', 'Manually');
                                }
                                return _t('DMSDocumentSet.QUERYBUILDER', 'Query Builder');
                            }
                        )
                    );

                // Override delete functionality with this class
                $gridFieldConfig->getComponentByType('GridFieldDetailForm')
                    ->setItemRequestClass('DMSGridFieldDetailForm_ItemRequest');
                $gridField = GridField::create(
                    'Documents',
                    false,
                    $self->Documents(),
                    $gridFieldConfig
                );
                $gridField->setModelClass('DMSDocument');
                $gridField->addExtraClass('documents');

                $gridFieldConfig->addComponent(
                    $addNewButton = new DMSGridFieldAddNewButton('buttons-before-left'),
                    'GridFieldExportButton'
                );
                $addNewButton->setDocumentSetId($self->ID);

                $fields->removeByName('Documents');
                $fields->addFieldsToTab(
                    'Root.Main',
                    array(
                        $gridField,
                        HiddenField::create('DMSShortcodeHandlerKey', false, DMS::inst()->getShortcodeHandlerKey())
                    )
                );
                $self->addQueryFields($fields);
            }
        });
        $this->addRequirements();
        return parent::getCMSFields();
    }