You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
$this->Session->setFlash(__('The message has been saved'));
259
+
} catch (Exception $e) {
260
+
$this->Session->setFlash($e->getMessage());
261
+
}
262
+
}
263
+
}
264
+
}
265
+
266
+
In the above example, we are calling our custom `createWithAttachments` method on the `Post` model. This will allow us to unify the Post creation logic together in one place. That method is outlined below:
267
+
268
+
<?php
269
+
class Post extends AppModel {
270
+
/* the rest of your model here */
271
+
272
+
public function createWithAttachments($data) {
273
+
// Sanitize your images before adding them
274
+
$images = array();
275
+
if (!empty($data['Image'][0])) {
276
+
foreach ($data['Image'] as $i => $image) {
277
+
if (is_array($data['Image'][$i])) {
278
+
// Force setting the `model` field to this model
279
+
$image['model'] = 'Post';
280
+
281
+
// Unset the foreign_key if the user tries to specify it
282
+
if (isset($image['foreign_key'])) {
283
+
unset($image['foreign_key'])
284
+
}
285
+
286
+
$images[] = $image;
287
+
}
288
+
}
289
+
}
290
+
$data['Image'] = $images;
291
+
292
+
// Try to save the data using Model::saveAll()
293
+
$this->create();
294
+
if ($this->saveAll($data)) {
295
+
return true;
296
+
}
297
+
298
+
// Throw an exception for the controller
299
+
throw new Exception(__("This post could not be saved. Please try again"));
300
+
}
301
+
}
302
+
303
+
The above model method will:
304
+
305
+
- Ensure we only try to save valid images
306
+
- Force the foreign_key to be unspecified. This will allow saveAll to properly associate it
307
+
- Force the model field to `Post`
308
+
309
+
Now that this is set, we just need a view for our controller. A sample view for `View/Posts/add.ctp` is as follows (fields not necessary for the example are omitted):
The one important thing you'll notice is that I am not referring to the `Attachment` model as `Attachment`, but rather as `Image`; when I initially specified the `$hasMany` relationship between an `Attachment` and a `Post`, I aliased `Attachment` to `Image`. This is necessary for cases where many of your Polymorphic models may be related to each other, as a type of *hint* to the CakePHP ORM to properly reference model data.
319
+
320
+
I'm also using `Model.{n}.field` notation, which would allow you to add multiple attachment records to the Post. This is necessary for `$hasMany` relationships, which we are using for this example.
321
+
322
+
Once you have all the above in place, you'll have a working Polymorphic upload!
323
+
249
324
Please note that this is not the only way to represent file uploads, but it is documented here for reference.
0 commit comments