CakePHP - Retrieving a list of options from another table, to use with form helper/ before Instering

StackOverflow https://stackoverflow.com/questions/21311728

  •  01-10-2022
  •  | 
  •  

Question

Here is Yet another cakePHP question! I have table called blood_groups which has blood_group_id and group fields.. Then I have another table called donors, which has several fields such as name, surname etc. Another field included inside this table is the foreign key 'blood_group_id' which will need to map to the blood_group table on retrieval. in the donor registration view, i want to be able to retrieve the values from the blood_groups table, and display them using the formHelper (with their respective id's).

I have gone through CAKE doc, and I understand that I would need to create the association between my models, but I am struggling to figure this one out. Should I create $hasOne association inside the Donor Model (considering that the Donor table has the fk of the other table). And how would I go about retrieving the options of blood_groups from the blood_groups Model?

Should It work like this?(and are any other prerequisites involved?) : In my DonorController -

$this->set('blood_groups', $this->Donor->Blood_Group->find('all'));

in Views/Donor/add.ctp

echo $this->Form->input('blood_group_id');

Was it helpful?

Solution

Accessing data through associations is fine. But for radios or checkboxes you want to do a find('list). Your model and variable name does not match the CakePHP convention, there should be no underscore.

Properly named this should be already enough to populate the input.

// controller
$this->set('bloodGroups', $this->Donor->BloodGroup->find('list'));
// view
echo $this->Form->input('blood_group_id');

If you don't follow the conventions for some reason:

echo $this->Form->input('blood_group_id', array(
    'options' => $bloodGroups
));

See:

OTHER TIPS

Create one function in BloodGroup Model
function getDonors(){
  $options = array(
       // 'conditions' => array('Donor.blood_group_id'=>$id),
        'joins' => array(
            array(
                'alias' => 'Donor',  
                'table' => 'donors',
                'type' => 'LEFT',
                'conditions' => array(
                    'Donor.blood_group_id = BloodGroup.blood_group_id',
                ),
            )
          ),              
        'fields' => array('Donor.name','Donor.surname','Donor.blood_group_id',
                         'BloodGroup.blood_group_id')
    );
   $returnData = $this->find('all',$options);
   return $returnData;
}

Now from controller call this function

 App::import('model','BloodGroup');
 $BloodGroup = new BloodGroup;
 $donorList = $BloodGroup->getDonors();
 $this->set('donorList',$donorList);

In view file you will get list of donors in $donorList.

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