In articles, I have created a series of custom fields, including two date fields and a checkboxes field. Now, through a plugin in the onContentBeforeSave
event I need to verify that if date 1 is less than date 2 then set the value of the checkbox field. For this I try the following
<?php
defined( '_JEXEC' ) or die( 'Restricted access' );
class plgContentAlertcustomfieldhandler extends JPlugin
{
public function onContentBeforeSave($context, &$article, $isNew, $data)
{
if ($context === 'com_content.article') {
$date1 = strtotime($data['com_fields']['date1']);
$date2 = strtotime($data['com_fields']['date2']);
if ($date1 < $date2) {
$data['com_fields']['alert'][0] = 'alert';
}
}
return true;
}
}
I try to set the value in this line:
$data['com_fields']['alert'][0] = 'alert';
This custom field has only one checkbox, defined with the name Alert and with the value alert.
Update 1:
I am trying $data['com_fields']['alert'] = true;
but I am getting the same result.
Update 2:
If I manually set a value to the checkbox, debugging I can verify that the value assigned to alert in $data
is
array (
0 => 'alert',
)
I try to apply this same value programmatically as follows
$data['com_fields']['alert'] = ['alert'];
But the value is not persisted, at the end of the process of saving and refreshing the view the checkbox remains unchecked
Update 3
Following the process of saving through debugging I identify that if I programmatically assign the value to the custom field through $data ['com_fields']['alert'] = ['alert'];
when arriving to the save
method in libraries/src/MVC/Model/AdminModel.php
in the argument $data
the value of alert
is false
, while if I set a value manually when arriving at this method in$data
the value of the alert
field is [0 => 'alert']
and consequently the value of the checkbox is assigned.
Update 4
The typo error pointed out by alexandreelise is now repaired. The problem still persists.
Update 5
Using debug I managed to identify that it doesn't matter which field within $ data['com_fields']
I modify in the onContentBeforeSave
event once it delegates to the trigger
method of the JEventDispatcher
class located at libraries/joomla/event/dispatcher.php
the argument $args
that includes in the index 3 the data to be persisted including those of com_fields
retain the values set by the user even if they have been programmatically modified as in the example I described. Eventually this data is passed to libraries/src/MVC/Model/AdminModel.php
in the save
method that has the argument $data
the data to be inserted preserves the values set by the user. Right now I think that maybe the solution is to try to modify these values in another event maybe before onContentBeforeSave
. Thanks again for any ideas
I appreciate your advice