![]() |
I would like to convert all my POST values from '' to NULL automatically with a Codeigniter validation rule. Is it possible?
Here is my helper, which is working fine with text and numbers : PHP Code: function empty2null($value) Can I define it as a validation rule (prepping?) somewhere? How to do this? Afterwards I would like to send it as a proper NULL value to Doctrine. I tried to implement it as a classic rules, but this custom function is not triggered when the POST value is empty. Thank you
@b126,
You should be able to use a PHP function such as isset() (scroll down page to See Also for other suggestions- http://php.net/manual/en/function.isset.php). return isset($value)? null : $value; (02-27-2019, 01:10 PM)php_rocs Wrote: @b126, Hi, Thank you but it’s not a question of isset(), or empty() or ===‘’. It’s a question on how to trigger this conversion automatically while posting the form data or during the validation. Unfortunately, it seems that CI posts empty string if you do not put anything in your input field, like it is the case for optional fields for example. So when a user leave a blank field for an optional input like « distance », the input->post(‘distance’) value posted is ‘’. When you convert ‘’ to an integer in php, it becomes 0. You will then record 0 in your database instead of NULL. The same is for empty strings. You will save ‘’ in your database instead of null. In Laravel, you can use the ConvertEmptyStringsToNull middleware. In Symfony, I think you can use empty_data option. So I wonder if there was an equivalent in Codeigniter.
(02-28-2019, 12:25 PM)dave friend Wrote: That sounds like a good approach. I'd like to see the implementation. I did it and it’s working fine, with strings, and also with numeric values. Here is my /application/core/MY_Input.php PHP Code: class MY_Input extends CI_Input {
(02-28-2019, 12:45 PM)b126 Wrote: I did it and it’s working fine, with strings, and also with numeric values. One thing to be aware of is your code introduces a bug when you ask CI_Input::post() to return the entire $_POST array. i.e. PHP Code: $data = $this->input->post(); That might not be something you ever do, but future code maintenance or changes might run up against this. It's an easy thing to forget and a hard thing to point out to someone else coming to the project. I think you have to either override _fetch_from_array() - which is not as trivial as what you've done - or, you could do the following PHP Code: public function post($index = NULL, $xss_clean = NULL) Have you considered that you might want to trim the input in case somebody enters a string with empty spaces? |
Welcome Guest, Not a member yet? Register Sign In |