user2948950
user2948950

Reputation: 137

Database table to make drop down select using cakephp

I have one controller for invoices and another for clients.

I have made some "relationships" in the models of these controllers as below:

Client.php

<?php

  class Client extends AppModel {
      public $hasMany = array(
          'Invoice' => array(
              'className' => 'Invoice',
              'foreignKey' => 'client_id'
           )
      );
   }

?>

Invoice.php

<?php

class Invoice extends AppModel {
    public $belongsTo = array(
        'Client' => array(
            'className' => 'Client',
            'foreignKey' => 'client_id'
        )
    );
}

?>

So I thought that making a drop down with each client would be easy. Although, I can't figure out how to do this.

First off this is what I want as a result:

<select>
  <option value="1">Client Name</option>
</select>

Where value is equal to id in client table and Client Name is equal to name in client table.

I tried placing the following into the invoices controleler:

$client = $this->Client->find('all');

and then the following into my view:

echo $this->Form->select('client_name',client, array(
                'class' => 'form-control',
                'name' => 'client_id'
            ));

But I received the following error:

Call to a member function find() on a non-object    

Directly on page load. What do I need to do to make this work?

Upvotes: 1

Views: 7104

Answers (1)

Kai
Kai

Reputation: 3823

More than likely, your problem is that the Client model is not automatically loaded in the Invoices controller. Since Client has a relationship with Invoice, you can call find on Client like this instead:

$data = $this->Invoice->Client->find('list', array('fields' => array('id', 'name')));
$this->set('clients', $data);

Then in the view,

echo $this->Form->select('Invoice.client_id', $clients);

or

echo $this->Form->input('Invoice.client_id', array('type' => 'select', 'options' => $clients));

This should output a dropdown where the values are the client id's and the visible options in the drop down are the client names. You will want to go by id's rather than client names when associating invoices with the clients.

Upvotes: 4

Related Questions