<?php
/**
 * @ViewsField("basket_user_percent_field")
 */

namespace Drupal\basket\Plugin\views\field;

use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\ResultRow;
use Drupal\Core\Form\FormStateInterface;
use Drupal\views\Views;

class BasketUserPercentField extends FieldPluginBase {
    protected function defineOptions() {
        $options = parent::defineOptions();
        $options['templateTwig'] = ['default' => '{{ percent }} %'];
        return $options;
    }
    public function buildOptionsForm(&$form, FormStateInterface $form_state) {
        $form['templateTwig'] = array(
            '#type'             => 'textarea',
            '#title'            => 'Render template (Twig)',
            '#rows'             => 1,
            '#default_value'    => $this->options['templateTwig'],
            '#description'      => implode('<br/>', [
                '{{ percent }}'
            ])
        );
        parent::buildOptionsForm($form, $form_state);
    }
    public function query(){
        $join = Views::pluginManager('join')->createInstance('standard', [
            'type'          => 'LEFT',
            'table'         => 'basket_user_percent',
            'field'         => 'uid',
            'left_table'    => 'users_field_data',
            'left_field'    => 'uid',
            'operator'      => '=',
        ]);
        $rel = $this->query->addRelationship($this->field, $join, 'users_field_data');
        $this->query->addField($this->field, 'percent', $this->field.'_percent');
    }
    public function clickSort($order){
        $this->query->addOrderBy($this->field, 'percent', $order);
    }
    public function render(ResultRow $values){
        return [
            '#type'         => 'inline_template',
            '#template'     => $this->options['templateTwig'],
            '#context'      => [
                'percent'       => !empty($values->{$this->field.'_percent'}) ? $values->{$this->field.'_percent'} : 0
            ]
        ];
    }
}