我在尝试使用 Yii 中的 TSumColumn::class 计算名为“ore”的列中的数据总和时遇到问题。问题的出现是由于细胞内的额外内容,特别是封装在
<small>(' . Utility::calcoloGiornate($model->ore) . 'gg)</small>.
中
我的目标是从每个单元格中仅提取
Yii::$app->formatter->asDecimal($model->ore)
部分来计算列底部的总和。但是,为了在每个单元格中显示目的而保留 <small>(' . Utility::calcoloGiornate($model->ore) . 'gg)</small>
部分至关重要。
这是当前的列定义:
[
'attribute' => 'ore',
'value' => function ($model, $key, $index, $column) {
return '<span class="font-montserrat bold text-success fs-16">'
. Yii::$app->formatter->asDecimal($model->ore) // only sum this value
. '</span> <small>(' . Utility::calcoloGiornate($model->ore) . 'gg)</small>'; //don't include this value while summing but keep it displayed in the cell
},
'format' => 'html',
'class' => TSumColumn::class,
],
这是我正在使用的 TsumColumn 类:
use kartik\grid\DataColumn;
class TSumColumn extends DataColumn
{
public function getDataCellValue($model, $key, $index)
{
$value = parent::getDataCellValue($model, $key, $index);
if (is_numeric(str_replace(',','.',strip_tags($value)))) {
$this->footer += round(str_replace(',','.',strip_tags($value)),2);
}
return $value;
}
/**
* Renders the footer cell content.
* The default implementation simply renders [[footer]].
* This method may be overridden to customize the rendering of the footer cell.
* @return string the rendering result
* @throws \yii\base\InvalidConfigException
*/
protected function renderFooterCellContent()
{
if($this->footer !== null && trim($this->footer) !== '') {
if($this->format == 'currency') {
return \Yii::$app->formatter->asCurrency($this->footer);
}
return \Yii::$app->formatter->asDecimal($this->footer);
}
return $this->grid->emptyCell;
}
}
我设法通过从 TsumColumn 扩展一个新类并在我的 gridView 表中使用它来解决这个问题。
class SumColumnOneValue extends TSumColumn
{
public function getDataCellValue($model, $key, $index)
{
$value = parent::getDataCellValue($model, $key, $index);
$numericValue = 0;
// Look for content within <span> tags and extract numeric values for summation
preg_match('/<span[^>]*>([\d.,]+)<\/span>/', $value, $matches);
if (isset($matches[1])) {
$numericValue = str_replace(',', '.', $matches[1]);
$this->footer += round($numericValue, 2);
}
return $value;
}
}