0

Hi I have dynamically added input fields on my add view. When I submit my form I want all them input fields to be concatenated into one string and stored in a single database field.

Im trying to achieve this using the beforeSave method of cakephp but I can't seem to find out how to get the values of a text field within the Model.

function beforeSave($options)
{
    $result = '';
    $bool = true;
    $counter = 0;

    while($bool == true)
    {
    $result = $result + ',' + $this->data['Variable']['selectOptions' + counter];
    }

    return true;
}

Anyone any ideas on how to achieve this?

Thanks in advance.

tereško
  • 58,060
  • 25
  • 98
  • 150
Schokea
  • 708
  • 1
  • 9
  • 28
  • Paste your code please... Though you can get your data in `$this->data` in beforeSave function... – Rikesh Sep 03 '12 at 11:29
  • 2
    It seems obvious to me, that you should never manipulate data in a Model. You should modify the data in a Controller, before sending it to the model. – Kao Sep 03 '12 at 11:29
  • So get the values in the controller stick them into a string and then set a text field in the view with the values and save? – Schokea Sep 03 '12 at 11:41
  • You don't want `'selectOptions' + counter++`? – Ivo Sep 03 '12 at 18:30

4 Answers4

1

In my opinion (from MVC point of view) it would be better to concatenate the fields in controller and then unset unnecessary fields before saving the model...

Greg Motyl
  • 2,478
  • 17
  • 31
0

after get the post values in model you can merge the array values into a single variable like this..

<?php 
   $var = array('test1','test2','test3','test4','test5','test6');
   $new_values = implode(',',$var);
   echo $new_values;
?>

You can retrieve these values after saving to database.

Basith
  • 1,077
  • 7
  • 22
0

this might not be the perfect answer but might give you some head start in that direction

function beforeSave($options = array()) {

    pr($this->data); // <= show data you intend to save
    exit;
}

use foreach to loop the data array ($this->data) and perform concatenation on the values and assign the concatenated string to the feild name

function beforeSave($options = array()) {
foreach  ($this->data['Variable'] as $key=>$value)
{
$feildflag = strstr($key, 'selectOptions');
if($feildflag){
$concatenatedstring .= $value;
}
}
$this->data['Variable']['your_feild_name'] = $concatenatedstring ;
}
Ujwal Abhishek
  • 328
  • 1
  • 6
0

Your dynamic form field should looks like in a foreach loop:

<?php echo $this->Form->input('Model.field][', array());

In your model:

function beforeSave($options)
{
    if(!empty($this->data))
    {
         $this->data['Model']['common_field'] = implode(",", $this->data['Model'['field'];
         unset($this->data['Model']['field']);
    }  
}
Arun Jain
  • 5,476
  • 2
  • 31
  • 52