/** * Updates the weight fields of other rows according to the new and old weight paased in. * And returns the new weight be used. If old-weight not present, Creates a gap for a new row to be inserted * at the specified new weight * * @param string $daoName full name of the DAO * @param integer $oldWeight * @param integer $newWeight * @param array $fieldValues field => value to be used in the WHERE * @param string $weightField field which contains the weight value, * defaults to 'weight' * @return bool */ static function updateOtherWeights($daoName, $oldWeight, $newWeight, $fieldValues = null, $weightField = 'weight') { $oldWeight = (int) $oldWeight; $newWeight = (int) $newWeight; // max weight is the highest current weight $maxWeight = CRM_Utils_Weight::getMax($daoName, $fieldValues, $weightField); if (!$maxWeight) { $maxWeight = 1; } if ($newWeight > $maxWeight) { //calculate new weight, CRM-4133 $calNewWeight = CRM_Utils_Weight::getNewWeight($daoName, $fieldValues, $weightField); //no need to update weight for other fields. if ($calNewWeight > $maxWeight) { return $calNewWeight; } $newWeight = $maxWeight; if (!$oldWeight) { return $newWeight + 1; } } elseif ($newWeight < 1) { $newWeight = 1; } // if they're the same, nothing to do if ($oldWeight == $newWeight) { return $newWeight; } // if oldWeight not present, indicates new weight is to be added. So create a gap for a new row to be inserted. if (!$oldWeight) { $additionalWhere = "{$weightField} >= {$newWeight}"; $update = "{$weightField} = ({$weightField} + 1)"; CRM_Utils_Weight::query('UPDATE', $daoName, $fieldValues, $update, $additionalWhere); return $newWeight; } else { if ($newWeight > $oldWeight) { $additionalWhere = "{$weightField} > {$oldWeight} AND {$weightField} <= {$newWeight}"; $update = "{$weightField} = ({$weightField} - 1)"; } elseif ($newWeight < $oldWeight) { $additionalWhere = "{$weightField} >= {$newWeight} AND {$weightField} < {$oldWeight}"; $update = "{$weightField} = ({$weightField} + 1)"; } CRM_Utils_Weight::query('UPDATE', $daoName, $fieldValues, $update, $additionalWhere); return $newWeight; } }