Not saving NULL in to DB

How to save NULL values instead of empty strings in a database using ChronoForms.

Overview

The issue occurs because empty form fields are being sent as empty strings, which the database saves as blank values instead of NULL.
Modify the form data before saving by unsetting empty fields from a copy of the data array and then using that modified array as the data source for the save action.

ct ctrlmedia 09 May, 2017
Hi,
I have a connection which uses a chronoform to save to add records to a database.
Everything works fine but the empty field saves as an empty string as far as I can make out. NULL is not in the table if the field is blank.

The DB column looks like this:
Name - Type - Collation - Null - Default
priority - varchar(2) - utf8_general_ci - Yes - NULL



The debug info on the save looks like this:

[save_new_issue] => Array
(
[data] => Array
(
[notes] => zero hours notes
[priority] =>
[title] => Zero Hours Contract




The actual save looks like:
INSERT INTO `table_name` (`notes`, `priority`, `title`) values ( 'zero hours notes', '', 'Zero Hours Contract');





I have also added this function which works, if I change NULL to 5 the value changes to 5.
if($this->data["Issues"]["priority"] == ""){$this->data["Issues"]["priority"] = NULL;}


When the record saves it leaves the field "priority" blank rather than "NULL".
I was wondering if anyone had any suggestions?

Kind Regards
Max_admin Max_admin 09 May, 2017
Answer
1 Likes
Hi Mark,

Just unset the field from the save data array if its empty before the "save data" function:

if($this->data["Issues"]["priority"] == ""){unset($this->data["Issues"]["priority"]);}

does that work ?

Best regards,
Max
Max, ChronoForms developer
ChronoMyAdmin: Database administration within Joomla, no phpMyAdmin needed.
ChronoMails simplifies Joomla email: newsletters, logging, and custom templates.
ct ctrlmedia 09 May, 2017
1 Likes
HI Max,
That has done the trick, thanks again for your help!

Kind Regards
he healyhatman 14 May, 2018
This doesn't work consistently for me.
if($this->data["client_id"] == "") {
unset($this->data["client_id"]);
}

if($this->data["client_name"] == "") {
unset($this->data["client_name"]);
}

For some reason if either is empty it unsets them from the data array, but it still send the client_name to the save_data action. The client_id is correctly unset.
Max_admin Max_admin 20 May, 2018
Hi healyhatman,

Yes, assuming you run this code in a PHP action, the solution is to do the following:
$new_data = $this->data;
if($new_data["client_id"] == "") {
unset($new_data["client_id"]);
}

return $new_data;
Then use {var:php_name} as the data provider of the "Save data" action.

Best regards,
Max
Max, ChronoForms developer
ChronoMyAdmin: Database administration within Joomla, no phpMyAdmin needed.
ChronoMails simplifies Joomla email: newsletters, logging, and custom templates.
This topic is locked and no more replies can be posted.