Search code examples
phpcakephpformhelper

Converting an array into a usable string - cakePHP


I'm working on a simple cakePHP form. I have a variable $user_name that's populated from my SQL tables.

I've affirmed with

    echo '<pre>';
    print_r($user_name);
    echo '</pre>';

That the $user_name is correctly populated. I'm trying to use the variable that I've populated to auto-fill the following form field

    echo $this->Form->input($modelNameField . '.name_of_customer', array('readonly'=> 'readonly','label'=> 'Customer Name', 'type'=> 'text', 'value'=> $user_name));

However, the field remains blank. Any suggestions?

Declaration for $user_name

         App::import('model','customerInfo');            
         $customerInfos = new customerInfo();        
         $user_name = array();
         $user_name =  $customerInfos->get_name($id); 

--

The get_name method

         public function get_name($id)
     {
    return $this->find('first', array('fields' =>array('usr_name'),'conditions'=>array("customerInfo.id"=>$id)));
     }

--

The print out from print_r($user_name); for $id =1 is

         Array
         (
         [CustomerInfo] => Array
         (
          [usr_name] => Ted Jones
         )

         )

Solution

  • This is a pretty basic question.

    The value option of the form helper needs to be a string, inputs don't know what to do with something like an array.

    Your array has this structure

    $user_name = array (
                   'CustomerInfo' => array(
                       'usr_name' => 'Ted Jones'
                   )
                 );
    

    So the string value you want is in $user_name['CustomerInfo']['usr_name']. The form helper has no way of knowing that the string you wanted to put as value was in that part of that array.

    Don't know why you tried doing an array_pop before doing an index definition. Accessing values inside an array in php is quite simple, so try to do the simple approach first and go for the array_ php functions if it's something more complicated.

    For future reference, if you have an array or a variable and you want to use a value inside of it, do a debug or print_r to know how to access it. And if it's a matter of what types of data an option can take, the cake docs are a very good reference.