The following code has been written to convert centimeters to inches and inches to centimeters;
// Check if it's the correct type; suspect or victim.
// @todo The type is in $node->bundle() and you can use the in_array() function.
if (!in_array($node->bundle(), ['suspect', 'victim'])) {
return;
}
// Convert if centimeters are filled but inches are not.
if (!$node->get('field_height_in_centimeter')->isEmpty() && $node->get('field_height_in_inch')->isEmpty()) {
// Get centimeters.
// @todo The value can be retrieved from $node by getting the value from the field.
$centimeter = (int) $node->get('field_height_in_centimeter')->getValue()[0]['value'];
// Convert them to inches using constant INCH_IN_CENTIMETER.
// @todo You can calculate the value. Use '/' to divide a value and '*' to multiply it. Use function round() to make sure it doesn't have any decimals.
$inch = (int) round($centimeter / self::INCH_IN_CENTIMETER);
// Set inches.
// @todo The value can be set in $node like you retrieved the value.
$node->set('field_height_in_inch', $inch);
}
// Convert if inches are filled but centimeters are not.
elseif (!$node->get('field_height_in_inch')->isEmpty() && $node->get('field_height_in_centimeter')->isEmpty()) {
// Get inches.
// @todo The value can be retrieved from $node by getting the value from the field.
$inch = (int) $node->get('field_height_in_inch')->getvalue()[0]['value'];
// Convert them to centimeters using constant INCH_IN_CENTIMETER.
// @todo You can calculate the value. Use '/' to divide a value and '*' to multiply it. Use function round() to make sure it doesn't have any decimals.
$centimeter = (int) round($inch * self::INCH_IN_CENTIMETER);
// Set centimeters.
// @todo The value can be set in $node like you retrieved the value.
$node->set('field_height_in_centimeter', $centimeter);
}