User setting update now create setting if it doesn't exists yet instead of returning an error

This commit is contained in:
osaajani 2023-09-17 16:12:31 +02:00
parent 9aa3eca812
commit fb3f9425d1
3 changed files with 43 additions and 4 deletions

View File

@ -35,6 +35,18 @@ namespace controllers\internals;
return $settings_array;
}
/**
* Get a user setting by his name for a user.
*
* @param int $id_user : user id
*
* @return array
*/
public function get_by_name_for_user(int $id_user, string $name)
{
return $this->get_model()->get_by_name_for_user($id_user, $name);
}
/**
* Update a setting by his name and user id.
*

View File

@ -75,6 +75,20 @@ namespace controllers\publics;
$setting_value = json_encode($setting_value);
}
// If setting dont exists yet, create it, else update
$setting = $this->internal_setting->get_by_name_for_user($_SESSION['user']['id'], $setting_name);
if (!$setting)
{
$success = $this->internal_setting->create($_SESSION['user']['id'], $setting_name, $setting_value);
if (false === $success)
{
\FlashMessage\FlashMessage::push('danger', 'Impossible de mettre à jour ce réglage.');
return $this->redirect(\descartes\Router::url('Setting', 'show'));
}
}
else
{
$update_setting_result = $this->internal_setting->update_for_user($_SESSION['user']['id'], $setting_name, $setting_value);
if (false === $update_setting_result)
{
@ -82,6 +96,7 @@ namespace controllers\publics;
return $this->redirect(\descartes\Router::url('Setting', 'show'));
}
}
$settings = $this->internal_setting->gets_for_user($_SESSION['user']['id']);
$_SESSION['user']['settings'] = $settings;

View File

@ -27,6 +27,18 @@ namespace models;
return $this->_update($this->get_table_name(), ['value' => $value], ['id_user' => $id_user, 'name' => $name]);
}
/**
* Get a user setting by his name for a user.
*
* @param int $id_user : user id
*
* @return array
*/
public function get_by_name_for_user(int $id_user, string $name)
{
return $this->_select_one($this->get_table_name(), ['name' => $name, 'id_user' => $id_user]);
}
/**
* Return table name.
*/