Announcement

Collapse
No announcement yet.

Attachment API - save file and link to record

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Attachment API - save file and link to record

    I want to create a new record with an associated attachment which is based on a file in the file system. I've been trying to find how attachments are handled for a standard upload, but I don't understand what is going on.

    I want to:
    a) Create new record
    b) Create a new attachment record and save
    c) Copy a pre-existing file to the attachments file repository
    d) Set the attachment field value on the record and save

    I seem to be able to to all except c). where would I find the correct method for storing a file into the file repository (default upload dir)

  • #2
    Attachments are somewhat difficult to understand. Here is some code I wrote that downloads an image from a url, adds the image to an attachment, and relates the attachment to another object.
    PHP Code:
      public function getAndRelateMedia($message$data) {
        
    $numMedia = (int)($data->NumMedia);
        if(
    $numMedia <= 0) return;

        for(
    $i 0$i min($numMedia10); $i++) {
          
    $typeName "MediaContentType{$i}";
          
    $type $data->$typeName;
          if(!
    in_array($type, array("image/gif""image/png""image/jpg""image/jpeg"))) {
            continue;
          }

          
    $urlName "MediaUrl{$i}";
          
    $url $data->$urlName;

          
    $attachment $this->em->getNewEntity('Attachment');
          
    $attachment->set('contents'file_get_contents($url));
          
    $attachment->set('name'"Media {$i}");
          
    $attachment->set('type'$type);
          
    $attachment->set('role'"Inline Attachment");
          
    $this->em->saveEntity($attachment);

          
    $this->em->getRDBRepository("MessageC")->getRelation($message"media")->relate($attachment);
        }
      }
    ​ 
    file_get_contents can open files on your system as well, which may be what you need to use for part c.

    Comment

    Working...
    X