0

I'm using CakePHP 2 and I have two models: Questions & Topics which are connected via a HABTM relationship. In my 'add' form for questions, I have a variable amount of autocomplete fields which should serve to couple (existing) topics to the Question the user is adding.

What I want is: When I save my Question, that the relations with the selected topics are saved automatically as well. Can someone show me how I can achieve this? Preferably I'd like for cake, by naming my form helper fields correctly, to handle as much of this automatically without me having to perform manual updates in the controller. Is this possible?

Would it look something like this:

<?php echo $this->Form->input('RelatedTopic.0.topic_id'); ?>
<?php echo $this->Form->input('RelatedTopic.1.topic_id'); ?>
..

This is my relation in the Question model:

$hasAndBelongsToMany= array(
  'RelatedTopic' => array(
    'className' => 'Topic',
    'joinTable' => 'questions_topic',
    'foreignKey' => 'question_id',
    'associationForeignKey' => 'topic_id',
  )
);
Kiluminati
  • 73
  • 10

1 Answers1

0

Are you adding new topics related to the question or do you have a predetermined list of topics for the questions?

Colby Guyer
  • 594
  • 3
  • 14
  • Yes, I think I mentioned this is in my question. The list of topics is predetermined and the form shouldn't add any topics, only relate them to the 'Question' model. – Kiluminati Oct 25 '12 at 08:09
  • Use a multi-select or multi-checkbox to get the input then. `echo $this->Form->input('Question.RelatedTopic',array('label'=>'At least one Topic', 'type'=>'select', 'multiple'=>true));` – Colby Guyer Oct 25 '12 at 14:41
  • .. did you read my question? I'm using autocomplete fields. How would an autocomplete multi-select or multi-checkbox input work? – Kiluminati Oct 26 '12 at 09:35
  • It was not clear you were asking for autocompleted on a habtm, especially since you had form inputs. So if you have predetermined values, I would set the values in the controller before a save instead. try to do something like this `$this->data['RelatedTopic'][0]['RelatedTopic']['id']=$firsttopic_id; $this->data['RelatedTopic'][1]['RelatedTopic']['id']=$secondtopic_id; ` – Colby Guyer Oct 26 '12 at 12:53