I'm writing a PHP script that goes through the users, and reads and writes some custom user fields.
The reading part is done, by the use of the FieldsHelper. It works nicely. However, trying to write back some data into these custom user fields seems trickier...
I tried multiple ways of writing into the fields but none of them worked. It showed a 404 error page...
<?php
define('_JEXEC', 1);
if (file_exists(__DIR__ . '/defines.php')) {
include_once __DIR__ . '/defines.php';
}
if (!defined('_JDEFINES')) {
define('JPATH_BASE', __DIR__);
require_once JPATH_BASE . '/includes/defines.php';
}
require_once JPATH_BASE . '/includes/framework.php';
// Load the fields helper
JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php');
// Instantiate the application.
$app = JFactory::getApplication('site');
jimport('joomla.plugin.helper');
// JFactory
require_once (JPATH_BASE .'/libraries/joomla/factory.php');
// Read & write custom fields
ReadWriteCustomFields();
function ReadWriteCustomFields() {
// query users
$db = JFactory::getDBO();
$query = "SELECT id FROM #__users" ;
$db->setQuery($query);
$rows = $db->loadObjectList();
$model = JModelLegacy::getInstance('Field', 'FieldsModel', array('ignore_request' => true));
//run through users
foreach ($rows as $row) {
//get the user object
$user = JUser::getInstance($row->id);
//get custom fields
$customFields = FieldsHelper::getFields('com_users.user', $user, true);
if($customFields[1]->value == "") {
// write into custom field
//$customFields[1]->value = "TRIED THIS";
$model->setFieldValue($customFields[1]->id, $user->id, "AND ALSO THIS");
$model->setFieldValue(1, $user->id, "AND ALSO THIS");
}
}
}
?>