1

I'm trying to create single edit form based on contacts that allows me to update/add skill levels for all the skills even if the contact doesn't already have a rating.

Something like:

Edit Contact

Name   [TextBox: John Doe]

Skills
C#              [TextBox: empty]
C/C++           [TextBox: empty]
Data Analysis   [TextBox: 5]
Graphic Design  [TextBox: empty]
Javascript      [TextBox: 8]
Photography     [TextBox: empty]
HTML            [TextBox: empty]
Json            [TextBox: empty]
Jquery          [TextBox: empty]

My tables are configured like this:

Contacts

TABLE `contacts` (
  `id` bigint(20) NOT NULL,
  `name` varchar(100) NOT NULL
)

(1, 'John Doe')

$this->belongsToMany('Skills', [
    'foreignKey' => 'contact_id',
    'targetForeignKey' => 'skill_id',
    'joinTable' => 'contacts_skills', (Tried with and without)
    'through' => 'ContactsSkills',    (Tried with and without)
]);

Skills

TABLE `skills` (
  `id` bigint(20) NOT NULL,
  `name` text NOT NULL
)

(1,'C#'),
(2,'C/C++'),
(3,'Data Analysis'),
(4,'Graphic Design'),
(5,'Javascript'),
(6,'Photography'),
(7,'HTML'),
(8,'Json'),
(9,'Jquery')

$this->belongsToMany('Contacts', [
    'foreignKey' => 'skill_id',
    'targetForeignKey' => 'contact_id',
    'joinTable' => 'contacts_skills', (Tried with and without)
    'through' => 'ContactsSkills',    (Tried with and without)
]);

ContactsSkills

TABLE `contacts_skills` (
  `id` bigint(20) NOT NULL,
  `contact_id` bigint(20) NOT NULL,
  `skill_id` bigint(20) NOT NULL,
  `level` tinyint(1) DEFAULT NULL
)

(1,1,3,5),
(2,1,5,8)

$this->belongsTo('Contacts', [
    'foreignKey' => 'contact_id',
    'joinType' => 'INNER',
]);
$this->belongsTo('Skills', [
    'foreignKey' => 'skill_id',
    'joinType' => 'INNER',
]);

I've already dug though the documentation: https://book.cakephp.org/4/en/orm/saving-data.html https://book.cakephp.org/4/en/views/helpers/form.html (where I learned about _joinData) NOTE: The multiple select element doesn't work for _joinData.

And many more.  : )

I've tried just about every combination of associations to connect the three tables together, to no avail.

I know I can use _joinData to get the skills that already have a level:

echo $this->Form->control('skills.0._joinData.level');
echo $this->Form->control('skills.1._joinData.level', ['label' => ?????]);
            

though I'm having issues setting the label to the skill name.

My assumption is that I have to iterate the skills table and build the controls that way, but I don't know how to reference the join table from within the iteration.

Any suggestions?

Michael Coury
  • 191
  • 1
  • 8

0 Answers0