0

I got a little "problem" with CakePHP. My code is working fine, but I am looking for a way to shorten the code.

I have a model called "Document" and it "belongsTo" several "User"s.

  • creator
  • editor
  • responsiblePerson

In my Controller I use the following code to load a list of all the available users:

$creators= $this->Document->Creator->find('list');
$editors= $this->Document->Editor->find('list');
$responsiblepersons= $this->Document->Responsibleperson->find('list');
$this->set(compact('creators','editors','responsiblepersons');

Now I can use this code in my views:

echo $this->Form->input($creator_id);
echo $this->Form->input($editor_id);
echo $this->Form->input($responsibleperson_id);

This is working fine, but is it really necessary to find all 3 lists? In my controller $creators, $editors & $responsiblepersons contain all the same elements. Overall one "Document" is connected to 6 different "User"s, so this is really bloating my code.

Any idea? Thanks!

2
  • 1
    are creator, editor and responsiblePerson aliases to the same model? Commented Jan 22, 2015 at 19:37
  • Yes, they are all User-models Commented Jan 23, 2015 at 9:43

1 Answer 1

1

If they all are associated with the same table and model than just do:

$users = $this->Document->Creator->find('list');

And use the same list everywhere where you need the same list in the views.

Sign up to request clarification or add additional context in comments.

2 Comments

Same table and model yes, but 3 different fields. creator_id, editor_id and responsibleperson_id. So I need something like this $this->Form->input('creator_id',$users)
Check the documentation. book.cakephp.org/2.0/en/core-libraries/helpers/form.html 2nd arg of input() is an options array. 'type' => 'select', 'options' => $list is needed for a select input.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.