In Drupal 8 seems one has to create 2 or 3 files plus folder structures to do even the simplest of tasks. So I am trying to figure out how to do a simple hack without all the overhead.

I have a node type for which I attached images. There is a parent node for which I want to display one of the images from the children. I created an Image field for the parent.

So literally, all I need to do is query the database, grab a child's image at random (in every view, each time the parent is viewed, I want the image re-assigned randomly), and rewrite the parent's image field accordingly. This was so easy in Drupal 7...

Does anyone have an idea of how to do this in Drupal 8 in the simplest possible manner, ideally editing just one file?



You can use hooks the same way as in Drupal 7, if you want to change the content of the node before rendering, you can put a hook in your module or theme:

module/theme_preprocess(&$variables, $hook) {
   if ($hook == 'node') {

check if you are in the right node and change it.

The simplest solution for your problem would be to put all children images in the node display and then hide the images you don't want:


So you don't need to lookup the children image yourself.

  • Interesting. I just read about twig, and seems twig allows you to specify a filter which perhaps would also be a way to accomplish this. I understand the preprocess approach you mention. Would it also make sense to edit the field directly in the appropriate twig template file? – Brian Huether Oct 13 '15 at 9:18
  • Will that work though if View s is doing the rendering? Wouldn't I need to use a Views specific hook? – Brian Huether Oct 13 '15 at 11:12
  • Yes, you can do the same with twig, in my project i do lot of image handling in php, twigs and jquery. You can do the task with all of them, but php in a hook seems to be the simpliest way to do it. – 4k4 Oct 13 '15 at 11:19
  • I created a module and the associated yml and module file. I have tried mymodule_preprocess, mymodule_preprocess_views_view, but the functions are not being called. The module is enabled and I cleared cache. Is there any obvious reason why these functions would not be called? – Brian Huether Oct 13 '15 at 11:21
  • This depends how you configure the format in view, if you show content, then you can use a node hook, if you show fields you can use a field hook. – 4k4 Oct 13 '15 at 11:27

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.