Skip to content
Snippets Groups Projects

imp: I-6004 sort by balance

Merged simon requested to merge imp-I-6004-sort-by-balance into 1.x
Compare and
2 files
+ 56
67
Preferences
File browser
Compare changes
@@ -3,7 +3,7 @@
namespace Drupal\accounting\Plugin\views\field;
use Drupal\views\ResultRow;
use Drupal\views\Plugin\views\field\FieldPluginBase;
use Drupal\views\Plugin\views\field\NumericField;
/**
* A handler to provide display for the balance.
@@ -12,49 +12,35 @@ use Drupal\views\Plugin\views\field\FieldPluginBase;
*
* @ViewsField("accounting_account_view_account_balance")
*/
class AccountingAccountViewAccountBalance extends FieldPluginBase {
class AccountingAccountViewAccountBalance extends NumericField {
/**
* {@inheritdoc}
*/
public function render(ResultRow $values) {
$empty = [
'#markup' => '',
'#cache' => [
'tags' => \Drupal::entityTypeManager()->getDefinition('accounting_account')->getListCacheTags(),
],
public function query() {
$this->ensureMyTable();
// Add a subquery to the query that will find the download count.
$subQuery = \Drupal::database()->select('journal_entry_line', 'journal_entry_line');
$subQuery->addField('journal_entry_line', 'accounting_account_id');
$subQuery->addExpression("SUM(debit - credit)", 'balance');
$subQuery->condition('state', 'valid');
$subQuery->groupBy("journal_entry_line.accounting_account_id");
// Add the subquery to as a component of a join.
$joinDefinition = [
'table formula' => $subQuery,
'field' => 'accounting_account_id',
'left_table' => 'accounting_account',
'left_field' => 'id',
'adjust' => TRUE,
];
if (!$this->getEntity($values)) {
return $empty;
}
if (get_class($this->getEntity($values)) == 'Drupal\accounting\Entity\AccountingAccount') {
return [
'#markup' => $this->getEntity($values)->getBalance()['balance_sign'],
'#cache' => [
'tags' => \Drupal::entityTypeManager()->getDefinition('journal_entry_line')->getListCacheTags(),
],
];
}
elseif (get_class($this->getEntity($values)) == 'Drupal\accounting\Entity\JournalEntry') {
return [
'#markup' => $this->getEntity($values)->getBalance()['balance_sign'],
'#cache' => [
'tags' => \Drupal::entityTypeManager()->getDefinition('journal_entry_line')->getListCacheTags(),
],
];
}
return $empty;
}
// Create a join object and create a relationship between the main query and the subquery.
$join = \Drupal::service('plugin.manager.views.join')->createInstance('standard', $joinDefinition);
$this->query->addRelationship('journal_entry_line', $join, 'accounting_account');
/**
* {@inheritdoc}
*/
public function query() {
// This function exists to override parent query function.
// Do nothing.
// Add the field to the Views interface.
$this->field_alias = $this->query->addField(NULL, 'COALESCE(balance, 0)', 'balance');
}
}