Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.2 kB
2
Indexable
Never
use Drupal\views\Plugin\views\filter\InOperator;

/**
 * Implements hook_views_data_alter().
 */
function custom_filter_views_data_alter(array &$data) {
  $data['node_field_data']['custom_file_filter'] = [
    'title' => t('Custom File Filter'),
    'filter' => [
      'id' => 'custom_filter_handler',
    ],
  ];
}

/**
 * Custom filter handler for filtering by file name.
 */
class CustomFilterHandler extends InOperator {

  public function getValueOptions() {
    $options = [];

    $user_input = $this->getExposedInput()['custom_filter'];

    $query = \Drupal::database()->select('node__field_attachments', 'fa')
      ->fields('fa', ['entity_id', 'field_attachments_target_id'])
      ->join('file_usage', 'fu', 'fa.field_attachments_target_id = fu.id')
      ->join('file_managed', 'fm', 'fu.fid = fm.fid')
      ->condition('fa.bundle', 'request_form')
      ->condition('fm.filename', '%' . db_like($user_input) . '%', 'LIKE')
      ->execute();

    foreach ($query as $row) {
      $file = \Drupal\file\Entity\File::load($row->field_attachments_target_id);
      if ($file) {
        $options[$file->getFilename()] = $file->getFilename();
      }
    }

    return $options;
  }
}