View source
<?php
namespace Drupal\barcode\Plugin\Field\FieldFormatter;
use Com\Tecnick\Barcode\Barcode;
use Drupal\barcode\Plugin\Field\FieldType\BarcodeBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
abstract class BarcodeFormatterBase extends FormatterBase {
public static function defaultSettings() {
return [
'background' => 'FFFFFF',
'foreground' => '000000',
] + parent::defaultSettings();
}
public function settingsForm(array $form, FormStateInterface $form_state) {
$settings = $this
->getSettings();
$elements['background'] = [
'#type' => 'textfield',
'#title' => $this
->t('Background Color'),
'#default_value' => $settings['background'],
'#maxlength' => 6,
];
$elements['foreground'] = [
'#type' => 'textfield',
'#title' => $this
->t('Foreground Color'),
'#default_value' => $settings['foreground'],
'#maxlength' => 6,
];
return $elements;
}
public function settingsSummary() {
$settings = $this
->getSettings();
if ($settings['background']) {
$summary[] = $this
->t('Custom background color: @background', [
'@background' => $settings['background'],
]);
}
if ($settings['foreground']) {
$summary[] = $this
->t('Custom Foreground color: @foreground', [
'@foreground' => $settings['foreground'],
]);
}
return $summary;
}
protected function generateBarcode(BarcodeBase $field, $background, $foreground) {
$barcode_generator = new Barcode();
return $barcode_generator
->getBarcodeObj($field->type, $field->value, -2, -50, $foreground, [
10,
10,
10,
10,
])
->setBackgroundColor($background);
}
}