0

This question follows this one

$entry = ee('Model')->get('ChannelEntry')
->filter('entry_id', $entry_id)
->first();

$entry->$field_id_5; // NULL

$field_id_5 is a grid field that stores images.

How am I supposed to get what I need to build the urls to the images ?

1
  • Hmm. Good question. I guess about now that documentation of the EE models would be very handy... ;) – JCOGS Design Sep 7 '19 at 13:58
2

You've probably already found a workaround to this, but thought I'd throw in my 2¢ for others that are trying to get models to work.

Models seem to be decent to use if you're doing simple things with simple fields. For my needs, I've usually found it lacking (like the case with these grid fields, category filtering, etc.) and after my scouring of docs and source code, I can't honestly recommend using Channel Entry Models for anything. If someone does know the correct way using Channel Entry Models, please provide an answer so we can upvote it.

That said, I've taken to the alternative—querying the database using EE's Active Record. So in your case, you can get the field by using

$query = ee()->db->where('entry_id', $entry_id)->get('channel_grid_field_5');

// Check if we actually have any results
if (!$query->num_rows()){
    return; // Or however you want to handle this
}

// Iterate over every possible row
$images = [];
foreach($query->result_array() as $row){
    // The particular column name for one of my grid fields is 10. You'll
    // need to figure out which one(s) you need to reference for your needs.
    $images[] = $row['col_id_10'];
} 

Now that you have your array of images, you need to parse them to derive your URL. They will yield something like {filedir_8}best_puppy.jpg. You can either hardcode what {filedir_X} is supposed to be or run another database query against the upload_prefs table:

$image_urls = [];
foreach($images as $image){

    // Extract the directory id from image path
    $filedir_id = preg_replace('/^\{\w_(\d+)\}.+$/', '$1', $image);

    // Get the url path from the table
    $filedir_query = ee()->db->select('url')->where('id', $filedir_id)->get('upload_prefs');
    if (!$filedir_query->num_rows()){
        return;
    }

    // Extract the actual path since it's prepended by `{base_url}`
    $path = str_replace('{base_url}', '', $filedir_query->row_array()['url']);
    // Extract the file name
    $filename = preg_replace('/\{filedir_\d+\}(.+)/', '$1', $image);

    // Prepend the protocol, domain, and path to the filename
    $image_urls[] = "https://cdn.example.com/$path$filename";
}

Voila! Your very own URL to the file.

Relevant Resources

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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