knowledge-8.x-1.x-dev/src/Plugin/views/field/CompetencyPercentage.php
src/Plugin/views/field/CompetencyPercentage.php
<?php
namespace Drupal\knowledge\Plugin\views\field;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\Entity\Role;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;
/**
* Field handler to present the name of the last comment poster.
*
* @ingroup views_field_handlers
*
* @ViewsField("knowledge_competency_percentage")
*/
class CompetencyPercentage extends FieldPluginBase {
/**
* The role field prefix.
*
* @var string
*/
protected $prefix;
/**
* {@inheritdoc}
*/
public function query() {
$this->ensureMyTable();
$scope = $this->options['scope'];
switch ($scope) {
case 3:
$prefix = 'publisher_';
break;
case 2:
$prefix = 'contributor_';
break;
case 1:
$prefix = 'candidate_';
break;
case 0:
default:
$prefix = '';
break;
}
$correct = $prefix . 'correct';
$total = $prefix . 'total';
$this->prefix = $prefix;
/** @var \Drupal\views\Plugin\views\query\Sql $query */
$query = $this->query;
$query->addField(NULL, "(\"$this->tableAlias\".\"$correct\" / \"$this->tableAlias\".\"$total\")", $this->tableAlias . '_' . $prefix . $this->field);
}
/**
* {@inheritdoc}
*/
public function render(ResultRow $values) {
$prefix = $this->prefix;
$field = $this->tableAlias . '_' . $prefix . $this->field;
$percent = $values->$field * 100;
return $this->sanitizeValue($percent . '%');
}
/**
* {@inheritdoc}
*/
public function buildOptionsForm(&$form, FormStateInterface $form_state) {
$candidate = Role::load('knowledge_candidate');
$contributor = Role::load('knowledge_contributor');
$publisher = Role::load('knowledge_publisher');
$form['scope'] = [
'#type' => 'radios',
'#title' => $this->t('Scope'),
'#default_value' => $this->options['scope'],
'#options' => [
0 => $this->t('Total'),
1 => $candidate->label(),
2 => $contributor->label(),
3 => $publisher->label(),
],
];
parent::buildOptionsForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
protected function defineOptions() {
$options = parent::defineOptions();
$options['scope'] = [
'default' => 0,
];
return $options;
}
}
