I would like to have a multi image upload in my form with an option to sort images and provide optional title/alt. This functoonality is present in the image widget field widget plugin and so instead of writing a lot of new code I am wondering if there is a simple way to use it as form element somehow?

  • I do not think there is a simple way to do this without writing a lot of duplicate code. You could re-use parts of the tabledrag API to do sorting, which might not be "a lot" of code, but there is still code to be written. Create a form array with a key, which contains an indexed array of form children being your image widget. Wrap this in a conditional to check some form state that adds a new form child. Add a button that calls a PHP ajax callback, return the form array with only the key. Probably not suitable for a comment, but I'm tired and don't feel like writing out code for you. – mradcliffe Feb 3 '17 at 2:04

I agree with @mradcliffe, that there is probably no simple way to reuse field widgets for normal form fields. The code of field widgets heavily depend on an underlying entity field.

I think the best solution is to create a mock custom entity. As you obviously don't need to store the result, otherwise you would already use an entity, you can set

"storage" = "Drupal\Core\Entity\ContentEntityNullStorage",

in the entity. Example for this is the core Contact Form, which needs very little code to implement fully customizable forms by reusing the form API for entity forms.

| improve this answer | |

Simply configure your field to unlimited value with image type, and you'll get exactly what you said: upload multiple images, provide there title and alt attributes, and sort them.

You can change this in the field parameter (number of authorized values).

| improve this answer | |

Your Answer

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