/** * Update grid available custom columns and save * * @param array $columns New columns informations * @return this */ public function updateCustomColumns(array $columns, $mustSave = true) { $this->loadColumns(); $helper = $this->_getHelper(); if (!is_null($this->_typeModel)) { $typeCode = $this->_typeModel->getCode(); } else { return $this; } $availableColumns = $this->getAvailableCustomColumns(); $availableCodes = array_keys($availableColumns); // Requested codes $customCodes = !is_null($typeCode) ? $columns : array(); // Codes of the same grid type that are already used $usedCodes = array(); // IDs that should be removed $removedIds = array(); foreach ($this->_originIds[self::GRID_COLUMN_ORIGIN_CUSTOM] as $columnId) { if (!is_null($typeCode)) { $parts = explode('/', $this->_columns[$columnId]['index']); if ($typeCode == $parts[0] && in_array($parts[1], $customCodes) && in_array($parts[1], $availableCodes)) { $usedCodes[] = $parts[1]; } else { $removedIds[] = $columnId; } } else { $removedIds[] = $columnId; } } // Add new columns whenever needed $newCodes = array_intersect($availableCodes, array_diff($customCodes, $usedCodes)); $columnsGroups = $this->getCustomColumnsGroups(); foreach ($newCodes as $code) { $newColumnId = $this->_getNextCustomColumnId(); $columnModel = $availableColumns[$code]; if (isset($columnsGroups[$columnModel->getGroupId()]) && $this->_getConfigHelper()->getAddGroupToCustomColumnsDefaultHeader()) { $header = $helper->__('%s (%s)', $columnModel->getName(), $columnsGroups[$columnModel->getGroupId()]); } else { $header = $columnModel->getName(); } $this->_columns[$newColumnId] = array('grid_id' => $this->getId(), 'id' => $newColumnId, 'index' => $typeCode . '/' . $code, 'width' => '', 'align' => self::GRID_COLUMN_ALIGNMENT_LEFT, 'header' => $header, 'order' => $this->_getNextOrder(), 'origin' => self::GRID_COLUMN_ORIGIN_CUSTOM, 'is_visible' => 1, 'filter_only' => 0, 'is_system' => 0, 'missing' => 0, 'store_id' => null, 'renderer_type' => null, 'renderer_params' => null, 'allow_edit' => 0, 'custom_params' => null); $this->_originIds[self::GRID_COLUMN_ORIGIN_CUSTOM][] = $newColumnId; } // Remove necessary IDs foreach ($removedIds as $columnId) { unset($this->_columns[$columnId]); } // Recompute max order, as it may have now changed $this->_recomputeMaxOrder(); return $mustSave ? $this->save() : $this->setDataChanges(true); }