0

CiviCRM: v5.57.3 (Currently waiting for a 3rd Party plugin to be updated to be compatible with the latest version.) WordPress: v6.2.2

We have a custom field attached to CiviEvents that lets the team upload an image to be used when outputting the Event on the public front end.

We are building the front end outside of CiviCRM by using API4 to fetch data.

We can retrieve the file details via joining to the File on the custom field.

{
  "id": 1,
  "Events_.Image": 1234,
  "file.id": 1234,
  "file.file_type_id": null,
  "file.mime_type": "image/png",
  "file.uri": "example.png",
  "file.document": null,
  "file.description": null,
  "file.upload_date": "2023-07-05 16:00:00",
  "file.created_id": null

What we are having issues with is taking this information and getting a full URL to be used inside an <img> tag. eg, https://www.example.test/app/uploads/civicrm/custom/example.png.

I'd expect a function along the lines of get_image_url(1234); but cannot find anything within the CiviCRM documentation.

Any guidance is much appreciated.

2 Answers 2

2

With the help of Lars SG's links. I created a, PHP 8, helper function to get a URL based on a file ID provided by the API.


function se_45209_get_entity_image_url( int $entity_id, int $file_id ): string
{
    if ( $file_id === 0 ) {
        return '';
    }

    $file_hash = is_callable( [ 'CRM_Core_BAO_File', 'generateFileHash' ] )
    ? CRM_Core_BAO_File::generateFileHash( $entity_id, $file_id )
    : '';

    return CRM_Utils_System::url(
        path: 'civicrm/file',
        query: "reset=1&id={$file_id}&eid={$entity_id}&fcs={$file_hash}",
        frontend: true
    );
}

Caveat: This does require the CiviCRM plugin to be loaded.

1

Short answer: Use the Attachments API instead, but it isn't available in API 4 yet, so you'll have to use API 3. See this previous question for discussion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.