CakePHP 3: How to update foreignKey? - cakephp

I use BlueImp jQuery plugin to upload multiple images in follow scenario:
User open add or edit Albums page, select images and procces upload via ajax method. This work fine, image data (name, size, model, field,..) are stored in related images table without foreign key.
Ajax return id of recent uploaded image, and js create (captions, position) inputs for that file.
User fill other form fields, and click submit.
Problem, if user create new album or edit/update exist one wich not contain images, application does not update foriegn key for new images. But if album contain images, and user add new one to album, after save post cakephp add / update foreign key to new images records.
Debug output:
// first time add images, does not update FK
[
'name' => 'A4',
'images' => [
(int) 116 => [
'caption' => '',
'position' => '1',
'id' => '116'
]
],
'id' => '4',
'user_id' => '1',
'active' => '1'
]
// album has one image, we add new one, CakePHP Update FK for new images
[
'name' => 'A4',
'images' => [
(int) 117 => [
'caption' => '',
'position' => '1',
'id' => '117'
],
(int) 118 => [
'caption' => '',
'position' => '2',
'id' => '118'
]
],
'id' => '4',
'user_id' => '1',
'active' => '1'
]
AlbumsController add method:
public function add()
{
$album = $this->Albums->newEntity();
if ($this->request->is('post')) {
$album = $this->Albums->patchEntity($album, $this->request->data,['associated' => ['Images']]);
if ($this->Albums->save($album)) {
$this->Flash->success(__('The album has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The album could not be saved. Please, try again.'));
}
}
$users = $this->Albums->Users->find('list', ['limit' => 200]);
$this->set(compact('album', 'users'));
$this->set('_serialize', ['album']);
}
Albums Table:
$this->hasMany('Images', [
'foreignKey' => 'foreign_key',
'conditions' => [
'Images.model' => 'Albums',
'Images.field' => 'upload'
],
'sort' => ['Images.position' => 'ASC']
]);
Images Table:
$this->belongsTo('Albums', [
'foreignKey' => 'foreign_key',
'joinType' => 'INNER'
]);
I use same approach in the cakephp 2 apps, and work without problems.
Video: http://screencast-o-matic.com/watch/cDhYYOinCX
Q: How to update foreignKey?

I'm not sure is this correct way, but it's work for me.
AlbumsTable
public function afterSave(Event $event, Entity $entity, ArrayObject $options)
{
if (isset($entity)) {
$images = TableRegistry::get('Images');
$images->query()
->update()
->set(['foreign_key' => $entity->id])
->where([
'foreign_key IS NULL',
'model' => 'Albums'
])
->execute();// conditions
}
}

Related

Unable to save associated (hasOne) data

I am creating a simple API with CakePHP 4, and I am having some issues saving some POST data. This is a new project, so the models are newly baked, based on my 3 tables: elaborations, details, jobs
The ElaborationTable table has these relations:
$this->hasOne('Details', [ // this (and the next) is the only thing that I've manually changed here: hasOne instead of hasMany
'foreignKey' => 'elaboration_id',
]);
$this->hasOne('Jobs', [
'foreignKey' => 'elaboration_id',
]);
While both DetailsTable and JobsTable have this:
$this->belongsTo('Elaborations', [
'foreignKey' => 'elaboration_id',
'joinType' => 'INNER',
]);
In my controller, this is what I'm using to retrieve the POST data and save it to each database table:
$data = $this->request->getData();
$data['user_id'] = $this->Auth->user('id');
$elaboration = $this->Elaborations->newEntity($data, [
'associated' => [
'Details',
'Jobs'
]
]);
Finally, my POST data is something like this:
APP/Controller/ElaborationsController.php (line 85)
[
'detail' => [
'regione' => 'Lazio',
'provincia' => 'RM',
'comune' => 'Roma',
],
'job' => [
'serramenti' => '1',
],
'user_id' => (int) 2,
]
Now, the user_id field gets saved in my elaborations table, no errors are issued, but still the details and jobs tables remains empty, no data is saved.
What am I doing wrong?

How to insert a new record in an associated belongsTo table instead of editing the associated one

In a edit-template, I created 2 forms. The first to edit a record from 'Table1' and a second form to add an record to the associated (belongsTo) table 'Table2'. I don't want to edit the associated record but add a new one in Table2 and change the bindingkey of the record from 'Table1'.
In the controller I use patchEntity(), but this way the original linked record in 'Table2' is edited.
The code for the second form look like this.
<?= $this->Form->create($machine, ['url' => ['action' => 'edit_foto']]);?>
<?= $this->Form->controls([
'id' => ['type' => 'hidden'],
'foto.omschrijving' => [
'type' => 'text',
'label' => __('naam van de machine'),
'value' => $result->type_machine
], []);?>
<?= $this->Form->button(__('save'), ['type' => 'submit']); ?>
<?= $this->Form->end(); ?>
In the controller for 'Table1' I use something like this.
public function editFoto($id) {
$data = $this->getRequest()->getData();
$machine = $this->Machines->get($id, [
'contain' => [
'Foto'
]
]);
if ($this->request->is([
'patch',
'post',
'put'
])) {
$machine = $this->Machines->patchEntity($machine, $data);
if ($this->Machines->save($machine)) {
$this->Flash->success(__('Machine {naam} has been saved.', [
'naam' => $machine['naam']
]));
return $this->redirect(['action' => 'edit', $id]);
}
}
}
How can I prevent the controller from editing the original record and instead force to add a new record in 'Table2' and change the bindingkey in 'Table1'?
Help is much appreciated.
added information:
the data send by the form looks like:
[
'id' => '87',
'foto' => [
'omschrijving' => 'WAKER 135 - ter - testje',
'foto' => [
'tmp_name' => 'C:\xampp\tmp\php6CFD.tmp',
'error' => (int) 0,
'name' => 'MAKITA DTD153RTJ accuschroevendraaier.jpg',
'type' => 'image/jpeg',
'size' => (int) 188971
],
'dir_id' => '5c9dd428cc4ef'
]
]
Instead of
$machine = $this->Machines->patchEntity($machine, $data);
$this->Machines->save($machine);
you should use
$machine = $this->Machines->newEntity($data, [
'associated' => ['Fotos']
]);
$this->Machines->save($machine);
to save the data. If the associations between Table1 and Table2 are correct in the models, this will also update the binding keys.
Make sure, the format of the ids in FormHelper is correct. See the docs, how to handle Saving With Associations. You can see this in $data. When submitting the form, $data should be in the following format:
$data = [
'id' => '...',
'foto' => [
// ... model data
],
];

how to save belongstomany checkboxes in cakephp

I have a set of checkboxes with a belongs to many relationship. I couldnt use a multiple checkbox option for various reasons. The table Tutors has a belongsToMany relationship with subjects table. I get the correct checkboxes checked when it loads and when I update the checboxes I get the correct checkbox data returned but how do i save this? The docs say i need to put the id's in an array for the correct Subjects to be checked . I tried a few things but I couldnt save the data. I dont get an error, just not saving.
//view
foreach ($subjects as $key => $item) {
$sub=$item->name;
$val=0;
foreach ($tutor->subjects as $key2 => $item2) {
$sub2=$item2->name;
if ($sub==$sub2){
$val=1;
break;
}
}
echo $this->Form->hidden('subjects.'.$key.'.id', ['value'=>$item->id]);
echo $this->Form->input('subjects.'.$key.'.checkedvalue', ['label'=>$sub,
'checked'=> $val,'type'=>'checkbox']);
}
//controller
public function edittest5($id = null)
{
$tutor = $this->Tutors->get($id, [
'contain' => ['AvailabilityForTutors','Subjects']
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$tutor = $this->Tutors->patchEntity($tutor, $this->request->data(),['associated' => ['AvailabilityForTutors','Subjects']] );
// $tutor->dirty('availability_for_tutors', true);
debug($tutor);
$this->Tutors->save($tutor,[
// 'atomic'=>false,
'validate' => false,
'associated' => ['Subjects']
]);
return $this->redirect(['action' => 'edittest5',$id]);
}
$subjects = $this->Tutors->Subjects->find('all', ['limit' => 200]);
returned data
'first_name' => 'drew',
'subjects' => [
(int) 0 => [
'id' => '1',
'checkedvalue' => '1'
],
(int) 1 => [
'checkedvalue' => '0'
],
(int) 2 => [
'checkedvalue' => '0'
],
(int) 3 => [
'checkedvalue' => '0'
],
(int) 4 => [
'id' => '5',
'checkedvalue' => '1'

CakePHP - Add custom values to User Object

I have added 4 more columns to my CakePHP Users table and I am trying to figure out how I can include these columns in the $this->Auth->user() object.
I've added the column information to my Users Model and Entity but still no joy. Currently my user object looks like this;
[
'id' => (int) 1,
'username' => 'admin',
'name' => 'Web Admin',
'email' => 'webteam#',
'role' => 'admin',
'created' => object(Cake\I18n\Time) {
'time' => '2016-02-09T16:04:46+00:00',
'timezone' => 'UTC',
'fixedNowTime' => false
},
'modified' => object(Cake\I18n\Time) {
'time' => '2016-02-12T08:53:16+00:00',
'timezone' => 'UTC',
'fixedNowTime' => false
}
]
Where is this object created and is there a way I can add my custom values to it, without editing core CakePHP files?
Thanks for your help .
By default the built-in authenticators will fetch all fields in the tables schema.
You most probably just forgot to clear your cache (tmp/cache/models), which you should do whenever you make changes to your schemas.
In case one would want to specify what fields are being fetched, a custom finder would be needed.
See Cookbook > Controllers > Components > Authentication > Customizing Find Query
$this->loadComponent('Auth', [
'authenticate' => [
'Form' => [
'finder' => 'auth'
]
],
]);
In your UsersTable class
public function findAuth(\Cake\ORM\Query $query, array $options)
{
return $query
->select(['id', 'username', 'password', 'column_x', 'column_y']);
}
It should be noted that the fields required for authentication must always be included, ie like username and password!

CakePHP 3: Upload multiple files and save file names in associated model?

I need to create the upload process where the user can upload multiple files at once, using the file field with html5 multiple attr. Name of the file must be saved in the associated model.
I can run successfully upload one file and save the file name in the photos table, across the field:
echo $this->Form->file('photos.name');
But if I want to enable upload more photos with
echo $this->Form->input('title'); // post title
echo $this->Form->input('maintext'); // post main text,
... etc
echo $this->Form->file('photos[].name',['multiple'=>true]);
I get into the problem, and try to understand where I make mistakes, but without success.
PostsController:
public function add()
{
$post = $this->Posts->newEntity();
if ($this->request->is('post')) {
$post = $this->Posts->patchEntity($post, $this->request->data);
if ($this->Posts->save($post)) {
$this->Flash->success(__('The post has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The post could not be saved. Please, try again.'));
}
}
$this->set(compact('post'));
$this->set('_serialize', ['post']);
}
PostsTable:
$this->addBehavior('Upload');
$this->hasMany('Photos', [
'foreignKey' => 'post_id'
]);
UploadBehavior
All standard callbacks where I currently perform debug $data / $entity, but only in beforeMarshal i use:
$data = Hash::get($data,'name');
debug($data);
// debug output
[
'name' => 'HPIM3869.JPG',
'type' => 'image/jpeg',
'tmp_name' => 'C:\xampp\tmp\phpF02D.tmp',
'error' => (int) 0,
'size' => (int) 1295448
],
...
In beforeSave and afterSave
My form is OK, the data properly come in before Marshal method, if I upload 3 files, I also see the same number of debug outputs, but in beforSave and afterSave debug only show the first file like this:
debug($entity);
object(App\Model\Entity\Photos) {
'name' => [
'name' => 'HPIM3435.JPG',
'type' => 'image/jpeg',
'tmp_name' => 'C:\xampp\tmp\php5839.tmp',
'error' => (int) 0,
'size' => (int) 1517410
],
'post_id' => (int) 469,
'created' => object(Cake\I18n\Time) {
'time' => '2015-10-07T09:22:44+0200',
'timezone' => 'Europe/Berlin',
'fixedNowTime' => false
},
'modified' => object(Cake\I18n\Time) {
'time' => '2015-10-07T09:22:44+0200',
'timezone' => 'Europe/Berlin',
'fixedNowTime' => false
},
'[new]' => true,
'[accessible]' => [
'*' => true
],
'[dirty]' => [
'name' => true,
'post_id' => true,
'created' => true,
'modified' => true
],
'[original]' => [],
'[virtual]' => [],
'[errors]' => [],
'[repository]' => 'Photos'
}
Edit:
In the purpose of the test, I create such a form:
echo $this->Form->input('name',['value'=>'zzz']);
echo $this->Form->input('photos.0.name',['value'=>'zzz']);
echo $this->Form->input('photos.1.name',['value'=>'hhh']);
echo $this->Form->input('photos.2.name',['value'=>'fff']);
Also it only be saved the first result.
I need help to understand how to save multiple form data. Where I go wrong?
I think your field should be like this
echo $this->Form->file('photos.name.',['multiple'=>true]); //note dot notation at end of name. It will generate input name as array

Resources