Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save flocondetoile/4bf64bef3bdc9492f5dc80a246c612a1 to your computer and use it in GitHub Desktop.
Save flocondetoile/4bf64bef3bdc9492f5dc80a246c612a1 to your computer and use it in GitHub Desktop.
/**
* {@inheritdoc}
*/
public function blockForm($form, FormStateInterface $form_state) {
$form['header'] = array(
'#type' => 'fieldset',
'#title' => t('Header'),
);
$form['header']['subtitle'] = array(
'#type' => 'textfield',
'#tree' => TRUE,
'#title' => t('Subtitle'),
'#default_value' => $this->configuration['header']['subtitle'],
);
$form['header']['title'] = array(
'#type' => 'text_format',
'#tree' => TRUE,
'#title' => t('Title'),
'#default_value' => $this->configuration['header']['title']['value'],
'#format' => $this->configuration['header']['title']['format'],
);
$form['header']['fid'] = array(
'#title' => t('Background image'),
'#type' => 'managed_file',
'#default_value' => !empty($this->configuration['header']['fid']) ? $this->configuration['header']['fid'] : NULL,
'#upload_location' => 'public://images/block',
);
return $form;
}
/**
* {@inheritdoc}
*/
public function blockSubmit($form, FormStateInterface $form_state) {
// Get old value.
$element = $form['settings']['header']['fid'];
$fid_old = isset($element['#default_value']) ? $element['#default_value'] : array();
$fid = $form_state->getValue(array('header', 'fid'), array());
if (!empty($fid) && $fid != $fid_old) {
$fid = reset($fid);
$file = file_load($fid);
$file->status = FILE_STATUS_PERMANENT;
$file->save();
\Drupal::service('file.usage')->add($file, 'mycustom_block', 'block', 1);
}
if (!empty($fid_old) && $fid != $fid_old) {
// Value has changed - delete old file.
$fid_old = reset($fid_old);
$file = file_load($fid_old);
if ($file) {
// Delete file usage and let garbage colector take care of actual file.
\Drupal::service('file.usage')->delete($file, 'mycustom_block', 'block', 1);
}
}
$this->configuration['header']['subtitle'] = $form_state->getValue(array('header', 'subtitle'), '');
$this->configuration['header']['title'] = $form_state->getValue(array('header', 'title'), '');
$this->configuration['header']['fid'] = $form_state->getValue(array('header', 'fid'), array());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment