Question

In my Users controller, I find the number of forms that the user has created by querying the 'Forms' table and store it in an array. But how to use the array variables in the view file.

Normally, I would set the variable in the controller using set function and use it in the view file as such. But how to set an array in the controller? I get the values in the controller(did an echo).

My controller code is:

function users(){

   $this->set('users',$this->User->find('all'));
   $users=$this->User->find('all');
   foreach($users as $user):

     $id=$user['User']['id'];
     $userFormCount[$id]=$this->Form->find('count',array('conditions'=>array('Form.created_by'=>$user['User']['id'])));
     $userFormCount[$id]=$this->Form->find('count',array('conditions'=>array('Form.created_by'=>$user['User']['id'])));      
     echo "users : ".$id."  ".$userFormCount[$id];

   endforeach;
}

My view file:

<?php foreach($users as $user):?>

   <tr>
  <td class="people_profile">

         <a href="/users/angeline"><?php echo $user['User']['name'];?></a>
      </td>

     <td>
    <?php 
    $id=$user['User']['id'];
    echo $userFormCount[$id]." ";?>forms,   //need the array value here.
    0 reports,
    0 badges
  </td>
 </tr>
<?php endforeach;?>

Since I have stored the value in a varaible $userFormCount in the controller, I do not get the value in the view file. but how to set and get an array value?

Was it helpful?

Solution

First of all you should avoid repeating your function calls.

First two lines of your function can be replaced by:

$users=$this->User->find('all');
$this->set('users', $users);

Next you can alter your object before passing it to view and add the property you are calculating to that object.

function users(){

    $users=$this->User->find('all');

    // notice the & here
    foreach($users as & $user):

       // you are repeating the same line here as well, that's not necessary
       $user['User']['custom_field'] = $this->Form->find('count', 
           array('conditions'=>array('Form.created_by'=>$user['User']['id'])));
    endforeach;

    $this->set('users', $users);
}

and you can then use it in your view like any other field that you get from the database. To improve it even firther you may want to consider moving this code to a afterFind callback in your User model, at least if this custom values are used more then once.

OTHER TIPS

You already know how to set an array value :-)

In this code you are setting the array 'users'

$this->set('users',$this->User->find('all'));

So you can do the same for the other array:

$this->set('userFormCount',$userFormCount);

...and read it in the same way as your users variable.

But please look at RaYell's answer, because it explains how to make your current code better.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top