There may be a type where you compare $date1 to $date2. You typed $tdate1 < $date2 but $tdate1 doesn't exists. Try to fix that and see if it works.
Meanwhile I try to reproduce your use case in a dev environment to help you out. Feel free to tell me if it is ok for you.
Hope it helps. Take care.
UPDATE 1:
Eureka! This is it! Basically you needed to use onContentAfterSaveonContentAfterSave
rather then onContentBeforeSaveonContentBeforeSave
and use the FieldsHelperFieldsHelper
in conjuction with the FieldsModelFieldFieldsModelField
.
Here is the code:
<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
class plgContentAlertcustomfieldhandler extends JPlugin
{
public function onContentAfterSave($context, &$article, $isNew)
{
if ($context === 'com_content.article') {
$custom_fields = FieldsHelper::getFields($context, $article, true);
$custom_fields_by_name = \Joomla\Utilities\ArrayHelper::pivot($custom_fields, 'name');
$date1 = strtotime($custom_fields_by_name['date1']->value);
$date2 = strtotime($custom_fields_by_name['date2']->value);
if ($date1 < $date2) {
//define the value you want to assign
$your_custom_field_value = 'alert';
JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_fields/models');
/**
* @var FieldsModelField $model_field
*/
$model_field = JModelLegacy::getInstance('Field', 'FieldsModel', ['ignore_request' => true]);
//set the value using field model instead to make change permanent in db
$model_field->setFieldValue(
$custom_fields_by_name['alert']->id,
$article->id,
$your_custom_field_value
);
}
}
return true;
}
}
Have a great day. Happy coding!UPDATE:
UPDATE 2: SecondSecond version of the code toggling on and off the checkbox when your requirement is not met.
<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
class plgContentAlertcustomfieldhandler extends JPlugin
{
public function onContentAfterSave($context, &$article, $isNew)
{
if ($context === 'com_content.article') {
$custom_fields = FieldsHelper::getFields($context, $article, true);
$custom_fields_by_name = \Joomla\Utilities\ArrayHelper::pivot($custom_fields, 'name');
$date1 = strtotime($custom_fields_by_name['date1']->value);
$date2 = strtotime($custom_fields_by_name['date2']->value);
$your_custom_field_value = '';
if ($date1 < $date2) {
//define the value you want to assign
$your_custom_field_value = 'alert';
}
JModelLegacy::addIncludePath(JPATH_ADMINISTRATOR . '/components/com_fields/models');
/**
* @var FieldsModelField $model_field
*/
$model_field = JModelLegacy::getInstance('Field', 'FieldsModel', ['ignore_request' => true]);
//set the value using field model instead to make change permanent in db
$model_field->setFieldValue(
$custom_fields_by_name['alert']->id,
$article->id,
$your_custom_field_value
);
}
return true;
}
}