Winter CMS resources and help articles

Simple and to the point. Optimized by the community.

Formwidget to wrap another formwidget with a prefix/suffix zone.

0
by mjauvin, last modified on June 15th, 2023

Create the following folders in your plugin's root folder:

formwidgets
formwidgets/wrapper
formwidgets/wrapper/assets
formwidgets/wrapper/assets/css
formwidgets/wrapper/partials

Add this file in the formwidgets folder

Wrapper.php:

use Backend\Classes\FormWidgetBase;

class Wrapper extends FormWidgetBase
{   
    protected $defaultAlias = 'wrapper';

    public $prefix;
    public $suffix;
    public $targetType;

    public function init()
    {   
        $this->fillFromConfig([
            'prefix',
            'suffix',
            'targetType',
        ]);
    }

    protected function loadAssets()
    {   
        $this->addCss('css/wrapper.css');
    }

    public function render()
    {   
        $this->prepareVars();
        return $this->makePartial('wrapper');
    }

    protected function prepareVars()
    {   
        $this->vars['prefix'] = $this->prefix;
        $this->vars['suffix'] = $this->suffix;

        $this->vars['fieldContent'] = $this->getParentForm()->makePartial( 'field_' . $this->config->targetType, [
            'field' => $this->formField,
            'formModel' => $this->model,
        ]);
    }
}

Add this file in the formwidgets/wrapper/partials folder

_wrapper.php:

<div class="wrapper">
<?php if ($prefix) : ?>
  <span class="prefix"><?= $prefix ?></span>
<?php endif ?>
  <?= $fieldContent ?>
<?php if ($suffix) : ?>
  <span class="suffix"><?= $suffix ?></span>
<?php endif ?>
</div>

Add this file in the formwidgets/wrapper/assets/css folder

wrapper.css:

.wrapper {
    display: inline-flex;
    justify-content: center;
    align-items: center;
}       

.prefix,
.suffix {
    width: fit-content;
    height:38px;
    padding: 0.5em;
    border: 1px solid #DDD;
    background-color: #eee;
    z-index: 1;
}           

.prefix {
    border-right: none;
    border-top-left-radius: 10px;
    border-bottom-left-radius: 10px;
    margin-right: -0.25em;
}

.suffix {
    border-left: none;
    border-top-right-radius: 10px;
    border-bottom-right-radius: 10px;
    margin-left: -0.25em;
}

Add this to your Plugin.php file:

    public function registerFormWidgets()
    {
        return [
            FormWidgets\Wrapper::class => 'wrapper',
        ];
    }

You can now create fields like this:

fields:
  myWrappedEmailField:
    type: wrapper
    targetType: email
    prefix: MyPrefix
    suffix: MySuffix

Discussion

0 comments

We use cookies to measure the performance of this website. Do you want to accept these cookies?