2

I have a html form to save projects in cakephp. i want to restrict the user to save same project name. If any body type the same project name for that i applied the 'unique' validation in model but if anybody enter the same name with spaces before or after the project name it accepts it and store into the database.THat is the issue. I want to remove that extra spaces before save.

Please help.

Amandeep Kaur
  • 107
  • 2
  • 10

4 Answers4

8

The best place to remove whitespace from user input i.e. trim() is in the beforeFilter() callback at the Controller level. For PHP5+ the array function array_walk_recursive() makes this job very easy.

For example:

public function beforeFilter()
{
    parent::beforeFilter();

    // remove leading and trailing whitespace from posted data
    if (!function_exists('trimItem')) {
        function trimItem(&$item,$key){
            if (is_string($item)){
                $item = trim($item);    
            }
        }
    }       
    array_walk_recursive($this->request->data, 'trimItem');                     
}

Drop this code into AppController and user input will be trimmed on all forms

Hope this helps

SyntaxGoonoo
  • 900
  • 8
  • 10
  • This approach works great. You could even improve it by using closure functions. `// remove leading and trailing whitespace from posted data array_walk_recursive($this->request->data, function (&$value,$key) { if (is_string($value)) { $value = trim($value); } });` sorry for bad code format in comments. – Matthias Lill Jan 25 '16 at 09:06
3

use trim which will trim your string from both sides

ref : http://php.net/manual/en/function.trim.php

trim($str);
Prasanth Bendra
  • 31,145
  • 9
  • 53
  • 73
3

Just as an addition to @Prasantn Bebdra's answer and since the asker doesn't know where and how to use trim().

To trim all the data that is comming from POST in your controller (just before the call to Model->save()) do:

foreach ($this->data as $key => $value) {
    $this->data[$key] = trim($value);
}

You can also use this in the Model by utilizing one of it's callbacks for example beforeValidate() or beforeSave() where in your case it should be better to use beforeValidate since you'd probably also want to validate this data afterwards.

You should also notify the user that the input will be trimmed and maybe also do such trimming on the client-side (before the POST) - check this StackOverflow answer out.

Community
  • 1
  • 1
Borislav Sabev
  • 4,776
  • 1
  • 24
  • 30
  • thanks for your reply @Borislav Sabev..its very useful post for me.i used this in my model by using call back beforeValidate().. – Amandeep Kaur Jan 31 '13 at 07:12
0

Through my research, I think the best solution if your data is in array format then try this => Stackoverflow: How to trim white spaces of array values in php

While, if your data is not an array then you can simply use:

$data = trim($data);
Marwan Salim
  • 682
  • 7
  • 14