I am validating a form with Codeigniter 4. On submission, the first thing I check is if there is anything to update. If there isn't anything to update, warning message stating there is nothing to update appears. The problem is, I have not changed anything but hasChanged returns TRUE stating it has indeed changed. Is there any easy way to echo out what has changed? Here is my code;
public function post_update($post_id)
{
$original_post = $this->model->find($post_id);
if ($this->request->getMethod() === 'post') {
// get the form data
$update_post = $this->request->getPost();
$original_post->fill($update_post);
if (!$original_post->hasChanged()){
return redirect()->back()
->with('warning', 'Nothing to Update')
->withInput();
} else {
$this->model->save($update_post)
}
} // end method
I have echo'd out $original_post before the fill and after the fill. The fields sent are different but what is being sent has not changed, as far as I can see. WOuld like a to know what hasChanged() seems as being changed.
Also, I added the below just before if (!$original_post->hasChanged()
to see what has changed:
echo 'post_id'.$original_post->hasChanged('post_id');echo '</br>';
echo 'post_category_id'.$original_post->hasChanged('post_category_id');echo '</br>';
echo 'post_user_id'.$original_post->hasChanged('post_user_id');echo '</br>';
echo 'post_title'.$original_post->hasChanged('post_title');echo '</br>';
echo 'post_slug'.$original_post->hasChanged('post_slug');echo '</br>';
echo 'post_body'.$original_post->hasChanged('post_body');echo '</br>';
echo 'post_is_publish'.$original_post->hasChanged('post_is_publish');echo '</br>';
echo 'post_image'.$original_post->hasChanged('post_image');echo '</br>';
echo 'post_created_at'.$original_post->hasChanged('post_created_at');echo '</br>';
echo 'post_updated_at'.$original_post->hasChanged('post_updated_at');echo '</br>';
echo $original_post->hasChanged();
In the above, it returns empty (meaning false meaning no change) for everything except echo $original_post->hasChanged();
which comes back as 1 meaning it has changed. How can I find out what changed??? There are no more fields in my table.
How can I find out what changed???
The Entity class provides you with a pair of methods called toArray
and toRawArray
:
public function toArray(bool $onlyChanged = false, bool $cast = true, bool $recursive = false): array
public function toRawArray(bool $onlyChanged = false, bool $recursive = false): array
You can use the first boolean parameter to get only what the Entity thinks has changed. If you're performing any implicit casts using Entity magic, you can use the raw version to bypass them.
I will say that hasChanged
uses strict comparison, which catches a lot of people (myself included) off-guard the first time they use it; you need to be careful that you're not changing the types of data either (e.g. the integer 1 to the string '1') because hasChanged
will catch that.