I have a Course model and a User model joined by Subscription. I want to create a postLink form helper on the Courses index page that would automatically subscribe the user to that, but I don't know how to pass the parameters correctly. In essence, I want the user to click Subscribe, and have a subscriptions/add form automatically submitted so that the join table has another record.
My specific question is: How do I use a model in another model's view?
Here's the Courses index.ctp array from print_r:
Array
(
[0] => Array
(
[Course] => Array
(
[id] => 1
[name] => Flying
[created] => 2014-01-27 19:05:43
[modified] => 2014-01-27 19:05:43
)
[Subscription] => Array
(
[0] => Array
(
[id] => 2
[user_id] => 2
[course_id] => 1
)
)
)
)
Here's my bad postLink in the Course index.ctp view:
<?php
echo $this->Form->postLink(__('Subscribe'),
array( 'controller' => 'Subscriptions',
'action' => 'add' ),
null,
__('Are you sure you want to subscribe to # %s?',
$course['Course']['name']));
?>
Assuming they're associated, you can do like you would in the Controller - just don't include the model you're actually in, since $this is already that model:
$this->AssociatedModel->save($data);
Related
I have a BlogPost model that has a belongsToMany relationship called images, this relationship uses a link table to associate the blog post id with the image id.
When pulling in the data for a blog post, the images property looks like this:
[images] => Array
(
[0] => Array
(
[id] => 8304
[original] => /img/blog/2017/5/wifiradio_original_59089cae673db.png
[large] => /img/blog/2017/5/wifiradio_large_59089cae673db.jpg
[medium] => /img/blog/2017/5/wifiradio_medium_59089cae673db.jpg
[small] => /img/blog/2017/5/wifiradio_small_59089cae673db.jpg
[name] => wifiradio.png
[alt] => wifiradio.png
[created_at] => 2017-05-02 14:50:22
[updated_at] => 2017-05-02 14:50:22
[pivot] => Array
(
[blog_post_id] => 47749
[image_id] => 8304
[id] => 136949
[type] => featured
)
)
)
)
The array key is not useful as the numeric value, i would like the array key to be the value of pivot->type.
Laravels keyBy method almost does what I need but I can not get it to work directly on the data returned.
Is it possible to use keyBy from within the model so that data is always returned in a useable format?
I solved this by formatting the array within the controller.
Here's the function I created if anyone has a similair problem:
public function formatPosts($posts){
foreach($posts as $post){
$images = collect($post->images);
unset($post->images);
$post->images = $images->keyBy('pivot.type');
}
return $posts;
}
I have model for
user(id,name)
section(id,name)
section_users(id,user_id,section_id)
The admin adds all the users and sections separately. Once theses are added I want the admin to selects the section and add all the users in it in section_users
I have a select input with multiple set to true. How do i save this data the cakephp way along with validation.
<?php echo $this->Form->input("section_id"); ?>
<?php echo $this->Form->input("user_id", array('multiple'=>'checkbox')); ?>
This generates
Array
(
[section_id] => 1
[user_id] => Array
(
[0] => 3
[1] => 4
)
)
I know i can loop and convert to this and use saveAll or saveMany but what is the cakephp way/right way to do it.
Array
(
[0] => Array
(
[section_id] => 1
[user_id] => 3
)
[1] => Array
(
[section_id] => 1
[user_id] => 4
)
)
As already mentioned, this is exaplained in the docs, please read them, and in case you don't understand them (which would be understandable as the HABTM section is a little confusing and requires some trial & error), tell us what exactly you are having problems with.
http://book.cakephp.org/2.0/en/models/saving-your-data.html#saving-related-model-data-habtm
Based on the examples shown, the format for saving multiple X to Y should be
Array
(
[Section] => Array
(
[id] => 1
)
[User] => Array
(
[User] => Array(3, 4)
)
)
The corresponding form could look like this:
<?php echo $this->Form->create('User'); ?>
<?php echo $this->Form->input('Section.id'); ?>
<?php echo $this->Form->input('User', array('multiple' => 'checkbox')); ?>
<?php echo $this->Form->end('Add Users'); ?>
And the data would be saved via the Section model, that way its modified column is being updated properly.
public function addUsersToSection($id) {
// ...
if($this->request->is('post')) {
if($this->Section->save($this->request->data)) {
// ...
} else {
// ...
}
} else {
$options = array(
'conditions' => array(
'Section.' . $this->Section->primaryKey => $id
)
);
$this->request->data = $this->Section->find('first', $options);
}
$users = $this->Section->User->find('list');
$this->set(compact('users'));
}
Another way would be to restructure the array as shown by Vinay Aggarwal, that works fine, the only difference is that it requires saving through the join model, and consequently it doesn't update the Section models modified column.
CakePHP has the saveMany function, as mentioned in the documentation:
Model::saveMany(array $data = null, array $options = array())¶
This is HABTM relation, first of all you need have relation setup in SectionUser model. Then you can use saveAll() method to save all records at once.
Array
(
[0] => Array
(
[user_id] => 33
[section_id] => 9
)
[1] => Array
(
[user_id] => 33
[section_id] => 10
)
)
Make sure your data array is in above given format.
$this->SectionUser->saveAll($data);
At first sorry for my English.
I've got a problem in associative models in CakePHP. When I bind more than two models, for example
$this->Album->bindModel(
array(
'hasMany'=>array(
'Photo'=>array(
'className'=>'Photo'
),
'Album'=>array(
'className'=>'Album'
)
)
)
);
I have:
Array
(
[Album] => Array
(
[id] => 22
[f_name] => Some album
[0] => Array
(
[id] => 19
[f_name] => Another album
[id_parent] => 22
[Photo] => Array
(
....
Is it any way to set a key in parent table? I mean I don't want to have "0" as a key, there can be "Album1", "Album2" and so on.
The problem likely stems from binding a model to itself under the same name. Album hasMany Album probably trips up Cake somewhere. Use a unique name for the association, like Album hasMany SubAlbum.
I am playing around with a quotes database relating to a ski trip I run. I am trying to list the quotes, but sort by the person who said the quote, and am struggling to get the paginate helper to let me do this.
I have four relevant tables.
quotes, trips, people and attendances. Attendances is essentially a join table for people and trips.
Relationships are as follows;
Attendance belongsTo Person hasMany Attendance
Attendance belongsTo Trip hasMany Attendance
Attendance hasMany Quote belongs to Attendance
In the QuotesController I use containable to retrieve the fields from Quote, along with the associated Attendance, and the fields from the Trip and Person associated with that Attendance.
function index() {
$this->Quote->recursive = 0;
$this->paginate['Quote'] = array(
'contain' => array('Attendance.Person', 'Attendance.Trip'));
$this->set('quotes', $this->paginate());
}
This seems to work fine, and in the view, I can echo out
foreach ($quotes as $quote) {
echo $quote['Attendance']['Person']['first_name'];
}
without any problem.
What I cannot get to work is accessing/using the same variable as a sort field in paginate
echo $this->Paginator->sort('Name', 'Attendance.Person.first_name');
or
echo $this->Paginator->sort('Location', 'Attendance.Trip.location');
Does not work. It appears to sort by something, but I'm not sure what.
The $quotes array I am passing looks like this;
Array
(
[0] => Array
(
[Quote] => Array
(
[id] => 1
[attendance_id] => 15
[quote_text] => Hello
)
[Attendance] => Array
(
[id] => 15
[person_id] => 2
[trip_id] => 7
[Person] => Array
(
[id] => 2
[first_name] => John
[last_name] => Smith
)
[Trip] => Array
(
[id] => 7
[location] => La Plagne
[year] => 2000
[modified] =>
)
)
)
I would be immensely grateful if someone could suggest how I might be able to sort by the the first_name of the Person associated with the Quote. I suspect my syntax is wrong, but I have not been able to find the answer. Is it not possible to sort by a second level association in this way?
I am pretty much brand new with cakephp so please be gentle.
Thanks very much in advance.
I've had the similar problem awhile back. Not with sort though. Try putting the associated table in another array.
echo $this->Paginator->sort('Name', 'Attendance.Person.first_name');
change to:
echo $this->Paginator->sort('Name', array('Attendance' => 'Person.first_name'));
Hope this helps
i'm also looking for help with this.
so far i've found that you can sort multi level associations in controller's pagination options after using the linkable plugin https://github.com/Terr/linkable.
but it breaks down when you try to sort form the paginator in the view. i'm using a controller for magazine clippings. each clipping belongs to an issue and each issue belongs to a publication.
$this->paginate = array(
"recursive"=>0,
"link"=>array("Issue"=>array("Publication")),
"order"=>array("Publication.name"=>"ASC",
"limit"=>10);
after debugging $this->Paginator->params->paging->Clipping in the view, you can see that the sort is described in two separate places, "defaults" and "options". the sort info needs to be present in both for it to work in the view.
here is after setting order in controller:
[Clipping] => Array
(
[page] => 1
[current] => 10
[count] => 6685
[prevPage] =>
[nextPage] => 1
[pageCount] => 669
[defaults] => Array
(
[limit] => 10
[step] => 1
[recursive] => 0
[link] => Array
(
[Issue] => Array
(
[0] => Publication
)
)
[order] => Array
(
[Publication.name] => ASC
)
[conditions] => Array
(
)
)
[options] => Array
(
[page] => 1
[limit] => 10
[recursive] => 0
[link] => Array
(
[Issue] => Array
(
[0] => Publication
)
)
[order] => Array
(
[Publication.name] => ASC
)
[conditions] => Array
(
)
)
)
and here is after using $this->Paginator->sort("Publication","Publication.name");.
notice the options array is empty.
[Clipping] => Array
(
[page] => 1
[current] => 10
[count] => 6685
[prevPage] =>
[nextPage] => 1
[pageCount] => 669
[defaults] => Array
(
[limit] => 10
[step] => 1
[recursive] => 0
[link] => Array
(
[Issue] => Array
(
[0] => Publication
)
)
[order] => Array
(
[Publication.name] => DESC
)
[conditions] => Array
(
)
)
[options] => Array
(
[page] => 1
[limit] => 10
[recursive] => 0
[link] => Array
(
[Issue] => Array
(
[0] => Publication
)
)
[order] => Array
(
)
[conditions] => Array
(
)
)
does one really need to modify the paginator class to make this work?
UPDATE:
i found out the problem:
in the core cake controller paginator merges default and options to create the find query.
but the options array is empty when using linkable to sort. because options is listed after default it overrides default and the empty array replaces the default array of options.
solution to this is extending the paginate function inside of app_controller.php and unsetting the options array order value if it is empty:
(line 1172 in cake/libs/controller/controller.php)
if(empty($options["order"])){
unset($options["order"]);
}
then the options will not be overwritten by thte blank array.
of course this should not be changed inside of controller.php, but put it in app_controller.php and move it to your app folder.
On CakePHP 3 this problem can be solved by adding 'sortWhitelist' params to $this->paginate on your controller.
$this->paginate = [
// ...
'sortWhitelist' => ['id', 'status', 'Attendance.Person.first_name']
];
And then in your view:
echo $this->Paginator->sort('Name', 'Attendance.Person.first_name');
This is noted in the docs:
This option is required when you want to sort on any associated data, or computed fields that may be part of your pagination query:
However that could be easily missed by tired eyes, so hope this helps someone out there!
I'm developing a simple application with CakePhp, and need some help on creating a multi-record edit form using some related data.
The application I'm developing is pretty straightforward, its main purpose is managing students records: updating, deleting, changing a student from one group to another, the usual suspects.
The relevant tables of the database are:
group = (id, teacher, classroom, etc)
groups_students=(groupID, studentID, since, until)
students = (id, name, last_name, etc)
assitance = (id, assitance, date)
assistance_students (studentID, assitanceID, meta_information )
As you might have gathered from the tables above, the application is supposed to aid in recording assitance. Which is where I'm having some issues.
What I want to do is this:
Have the user select a group
In de detail group, I'll have an action called "Register Assistance"
Register assitance should redirect to a view in wich for every student belonging to that group, the user can see the student's assitance, edit them, and save. Something like this:
In which A stands for "Absent" and P for "Present" and the user can edit everyone, and the save.
I just don't know how to go about that? How do I manage that? I've managed to create a multi-edit form for the assitance, but adding the related data is a pain, I don't know if I should query the students from the groups controllers and then pass that to the action to register assitance, or manage all the logic inside the assitance controller?
Any help would be great,
thanks!
Edit: Here's the output of $this->Student->find('first');
Array (
[Alumno] => Array (
[id] => 14
[tipo] => dni
[dni] => 2321312312
[apellido] => COQUITO
[nombre] => Pepe
[carrera] => Composición Musical
[creado] => 2011-01-08 17:59:00
[modificado] => 2011-01-08 17:59:00
)
)
The output is in spanish. Alumno = Student, nombre= first name, apellido= last_name.
Well, I managed to find a solution to this. I was waiting to see if anyone found something better, as I'm pretty sure my solution is far from the best, but here it goes, in case someone finds this question in the future.
My issue was that I needed, for every group I selected to register assitance:
Every student that belonged to that group
All the assitances of the students belonging to that group
Now, in order to make use of the Form helper to edit those assitences (and after, the saveAll() method), I needed $this->data to have ann array like this:
Array
(
[Assitance] => Array
(
[5] => Array
(
[id] => 5
[date] => 2011-01-09
[assitance] => A
[updated] => 2011-01-16 21:32:00
[created] => 2011-01-16 21:32:00
)
[6] => Array
(
[id] => 6
[date] => 2011-03-09
[assitance] => A
[updated] => 2011-01-16 21:32:00
[created] => 2011-01-16 21:32:00
)
)
)
at the same time, though, I needed each student linked to his or her assitances, to be able to loop trough them, and display the edit forms for every assitance in a table like the one in the question:
What I ended up doing is this
First, I query all the students belonging to the selected group.
For each student get all his/her assitances .
so, for each student, I ended up having an array like this:
Array
(
[Student] => Array
(
[id] => 12
[last_name] => LASARTE
[name] => Julia
[created] => 2011-01-08 16:35:00
[updated] => 2011-01-08 16:35:00
[assitance] => Array
(
[0] => Array
(
[Assitance] => Array
(
[id] => 4
[date] => 2011-01-09
[assitance] => z
[updated] => 2011-01-16 20:51:00
[created] => 2011-01-16 20:51:00
)
[assitance_studenty] => Array
(
[id] => 2
[student_id] => 12
[assitance_id] => 4
[comision] => 0
)
)
)
)
)
)
Now, with that, I have the information I need in order to display the table and create the forms, but I still need the assitances data in $this->data, so the form helper can create the from displaying the correct information, and afterwars, saveAll() updates the rows in the database correctly.
What I needed to do was turn the array of $students into an structure like the one at the beginning of the post. Enter the Set Class:
$formated_students = Set::combine($students, '{n}.students.id', '{n}.students');
$assitance = Set::extract('/presentes/Assistance', $formated_students);
$this->data['Assistance'] = Set::combine($assistance, '{n}.Assistance.id', '{n}.Assistance');
I'm pretty sure the first to lines (formating the students array in order to extract the assitance) can be done with just one Set::extract or Set::classicExtract, but this worked and regular expressions are really not my thing, so.
After that, It's just a matter of looping trough the data and making the table:
<?php
echo $form->create('Assistance', array('url' => array('controller' => 'Comisions', 'action' => 'register_assitance')));
foreach ($students as $student) { ?>
<tr><td>><?php echo $student['students']['last_name'].", ".$student['students']['name']; ?></td>
<?php foreach ($student['students']['assitance'] as $asstiance) { ?>
<td><?php echo $form->input('Assistance.'.$assitance['Assistance']['id'].'.id');
echo $form->input('Assistance.'.$assitance['Assistance']['id'].'.assistance', array( 'label' => false, 'size' => 1)) ?></td>
<?php } ?>
</tr>
<?php } ?>