New answers tagged

0

You can use something like the following to convert all characters you want to convert into their corresponding HTML entity version. I have added a check on converting only non alpha-numeric characters into HTML entities. You can add a different logic to convert only those characters you want to convert (in the if condition with ctype_alum) The following is ...


0

Webforms now has a "prepopulate" option for most fields. Use the URL query string to populate a field that has been enabled for prepopulation


1

Just added a video link to show you : imgur.com/EmVha6e You just need to add a conditional to check if it's not ajax $request = \Drupal::request(); $is_ajax = $request->isXmlHttpRequest(); if (!is_ajax) { // code that sets the filter initial value } Credit: How can I detect AJAX request inside Drupal?


0

I think it's possible to add this attribute to all input fields using a bit of JS, something like this should work: (function($, Drupal) { Drupal.behaviors.autocompleteFieldBehavior = { attach: function (context) { $(context).find('input').each(function () { var name = $(this).attr('name'); if ($(this).attr('autocomplete').length ...


0

Alternative to Form Hook, you can use the webform-form-{form-id}.tpl.php template file to accommodate your changes. For Example, $form['submitted']['name']['#prefix'] = '<div class="form-group">'; $form['submitted']['name']['#suffix'] = '</div>'; $form['submitted']['name']['#attributes']['class'][] = 'form-control snow_form_control'; Like ...


0

You can use module conditional fields if you want to do this node form


0

Drupal 8 has a very well structured system to show hide fields based on values of other fields. It is called the Form API #states system. You can see drupal.org documentation on #states. While defining the form you can map the visible and invisible states of the form element based on the value of another form element. This is an example from the ...


0

This code uploads one file with Ajax, attaching it to an existing node's file field. The content type is file_test, and the field is field_da_files. (I'm not a professional programmer, so there are no doubt better ways to do this.) Here's some HTML/JS that talks to a Drupal controller. It sends the node id, and the file to be stored. In uptest.html.twig: ...


0

You can use the Markup class: Markup::create('<strong>test 1</strong>') Full example with rendering a table can be found here: https://stefvanlooveren.me/blog/how-render-table-drupal-8


0

I liked @mpp's answer on how to create a linkit field if you have Linkit module enabled. His example was not code formatted, so this is just a repost using formatted code for better readability and to make it easier to copy paste this to use in your own projects. Create a linkit field with Drupal's form api: $form['block_link'] = [ '#type' => 'linkit', ...


0

The following worked for me: function MY_MODULE_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id){ if($form_id == 'node_CONTENT_TYPE_form'){ $form['meta']['#access'] = FALSE; } }


0

The code you are showing is the same code Drupal core uses, for example in BanDelete::submitForm(). public function submitForm(array &$form, FormStateInterface $form_state) { $this->ipManager->unbanIp($this->banIp); $this->logger('user')->notice('Deleted %ip', [ '%ip' => $this->banIp, ]); drupal_set_message($this->t('...


6

Drupal core doesn't use the dot in the form IDs because, as the documentation for FormInterface::getFormId() says, the form ID should be a unique string that can be a valid PHP function name, since it's used in hook implementation names such as hook_form_FORM_ID_alter(). The form IDs Drupal core uses follow the <module name>_<form name> schema, ...


1

Check out the example on Batch operations. And remove batch_process() from your code. Since you are starting the batch in a form submit handler batch_process() is interrupting that. Just batch_set() and Form API takes care of the rest. // Only needed if not inside a form _submit handler. // Setting redirect in batch_process. batch_process('node/1');


1

There is two problems: You form method is GET so form submit action will be the actual path with the params like node/10?search_location=kathmandu&op=Search&form_build_id=form-s4JrAE91au_BWakeBLD7RUsktRTBXFCpJQrnHGiOjg8&form_token=ES2W0RDpLOnWZUsXOnP4f9gBmSXcYLvqhO9uy1ee4Vk&form_id=d7_exp_form The second one you set your action to '/buy/{...


0

In your case, you don't need to specify custom submit handler because if your form ID is mysimple_form, Drupal should use mysimple_form_submit as default form submission function. For more info see the https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7.x#submit_property


0

There is also module (Media Library Form API Element) that supports this kind of implementation: $form['image'] = [ '#type' => 'media_library', '#allowed_bundles' => ['image'], '#title' => t('Upload your image'), '#default_value' => NULL|1, '#description' => t('Upload or select your profile image.'), ];


1

If you use media core module to manage files, you have already uploaded your file, and you want to attached it to filed eg field_file $node = Node::load(NID); $node->set('field_file' , ['target_id' => FID]); $node->save(); Note: FID is your file id.


1

In your custom form use code like this: $form['imagefile'] = [ '#type' => 'managed_file', '#title' => $this->t('Imagefile'), '#default_value' => $this->configuration['imagefile'], '#weight' => '0', '#upload_location' => 'public://images/redaktion/', ]; And here's a piece of code how it works low level: ...


0

Do not forget at the end of your hook_form_alter() or hook_form_FORM_ID_alter(): $form = system_settings_form($form); If you don't want to add the "Save configuration" button, you have to add your custom callback submit with $form['#submit'][] = '_my_callback_form_submit'; and : function _my_callback_form_submit($form, &$form_state) { variable_set('...


0

The correct way to set a redirection after a form is submitted, in Drupal 8, is following these steps. Implement hook_form_alter() or hook_form_FORM_ID_alter() to add a form submission handler to the form On the form submission handler, use FormState::setRedirect(), which require a route name, or FormState::setRedirectUrl(), which requires a \Drupal\Core\...


0

/* * hook_form_views_exposed_form_alter */ function THEMENAME_form_views_exposed_form_alter(&$form, &$form_state, $form_id) { if($form['#id'] == 'views-exposed-form-global-search-default'){ $form['#attributes']['class'][] = 'row popup-form'; //add form class $form['combine']['#attributes']['class'][] = 'search_input'; //add class to ...


0

In Drupal 8 to have the file download rather than redirect to it you can use: $uri = $file->getFileUri(); $headers = array( 'Content-Type' => $file->getMimeType(), 'Content-Disposition' => 'attachment;filename="'.$file->getFilename().'"' ); $form_state->setResponse(new \Symfony\Component\HttpFoundation\BinaryFileResponse($...


4

Drupal Form API sets a form token to prevent you from modifying forms in this way for security reasons. Consider this issue queue on Drupal.org: https://www.drupal.org/project/finder/issues/1383918 Drupal adds a #token thing (which is reflected in a hidden field) for registered users to prevent people tricking others into submitting a form for them ...


-1

$form_arg = Drupal::service('class_resolver') ->getInstanceFromDefinition('\Drupal\dh_clean_up\Form\CleanUpSubForm'); $form_arg->setOriginTermId($term_parameters['origin_tid']); Drupal::formBuilder()->getForm($form_arg) public function getFormId() { return 'dh_clean_up_facility_sub_form' . $this->originTermId; } public function ...


1

function mymodule_form_my_image_node_form_alter(&$form, &$form_state) { // If the node is being created, redirect the users to the page where // they can choose the content type for a new node; otherwise, redirect // them to the page showing the node. $destination = (!isset($node->nid) || isset($node->is_new)) ? 'node/add' : "node/{$...


2

Ok, So thanks to 4k4 I now understand what i was doing wrong, and for the favour of everyone that will meet this issue again: The form_alter is invoked as well when ajax callback is invoked. by the time the execution got to my ajax callback (getAjaxArgumentsFields) the form_alter has already altered my form, so all i had to do was return the fields without ...


0

I need to create a form for all nodes of a type. This form route has to be like this, the base /booking + the node alias. The node alias could be: /accommodation-test /rooms/accommodation-test /rooms/address-test/accommodation-test Final form route: /booking/accommodation-test /booking/rooms/accommodation-test /booking/rooms/address-test/accommodation-...


0

For drupal 8: $form['audio-file'] = [ '#type' => 'managed_file', '#title' => 'select file:', '#upload_location' => 'private://', '#upload_validators' => [ 'file_validate_extensions' => array('mp3 m4a wav'), ], '#accept' => '.wav,.mp3,.m4a', ]; It's all...


1

Not within the building of the form as far as I know. You'd need to strip out the values you don't want in the submit handler as you mentioned. This is probably the easiest way to remove the default form values: $values = $form_state->cleanValues()->getValues(); That will remove: form_id, form_token, form_build_id, op


1

I have a custom module to import CSV. This works for me. $form['#attributes'] = [ 'enctype' => 'multipart/form-data', 'class' => ['csv-import-form', 'mb-50'], ]; $form['csv_file'] = [ '#type' => 'file', '#title' => t('CSV File'), '#description' => $this->t('Upload file here.'), '#element_validate' => ['::...


2

All what '#type' => 'file' form elements do is to provide a bare <input type="file"> element. You get a prompt to select a file from your machine and on form submit the browser sends a request to your server, server forwards it to PHP, PHP extracts the file from the request, PHP stores it to the server's temp dir and when the script ends it deletes ...


1

Use more placeholders in your route, like path: 'booking/{url_alias}/{anyother}' Then add a default for the last one, like defaults: anyother: "" Now your Path applies for two and three uri components. Check this page for default parameters in form - routes: https://www.drupal.org/docs/8/api/routing-system/parameters-in-routes/using-parameters-in-...


1

Is this possible? path: 'booking/{url_alias}' or path: '{url_alias}/booking' path: '{url_alias}/booking' paths can never start with a slug/placeholder. You'll have to use path: 'booking/{url_alias}' In your form: /** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state, $url_alias = NULL) { // Some DB ...


2

Instead of unsetting the #value property (which works, but I find it personally counter-intuitive), you could try setting it by using the form_type_image_button_value() function. As an example: function my_custom_module_form_views_form_commerce_cart_form_default_alter(&$form, &$form_state, $form_id) { if (!empty($form['edit_delete'])) { ...


0

I found it. Silly me, it was the module Menu link (field), it actually says in the project page The "Menu settings" tab is however removed from the node form and replaced by an field widget. Argh, so much time looking for the reason, I didn't see that one when I uninstalled the ones that were interfering.


1

Are you sure this is a coding error? Are you loading any large quantities of content in the form by any chance? Loading a lot of nodes in a select field, for instance, can generate memory overflows.


0

Ended up resolving this issue with the following code: (function ($, Drupal) { /** * Check/Uncheck all checkboxes. */ Drupal.behaviors.selectAll = { attach: function (context, settings) { $(".form-checkboxes").prepend($('<input type="checkbox" class="form-checkbox shield-select-all"/><label class="option shield-select-all-...


4

You need to unset the #value on your image_buttons: $item['#type']='image_button'; $item['#src']='sites/all/themes/mytheme/images/trash.svg'; $item['#alt']='Remove'; unset($item['#value']); // this line here The line item that is deleted is determined by the #triggering_element in your $form_data. This element is determined by a function ...


1

As suggested in the comment the SQl query were made on the hook_form and the hook_form_submit contains only the $form_state['rebuild'] = TRUE;. Detailed code is as follows: function form_example_form($form, &$form_state) { //your form fields or items $form['submit_button'] = array( '#type' => 'submit', '#prefix' => '<div class="button-...


1

In the Drupal 8 forms api, any form element attributes not directly supported by the API get stuffed into the '#attributes' FormElement property. This property supports the entire HTML spec for form element tag html attributes, as far as I know. It's the catch-all for anything the Drupal development folks don't feel the need to directly define and model. $...


0

3 $triggering_element = $form_state->getTriggeringElement(); $button_name = $triggering_element['#name']; if ($button_name === 'button1') { // ... } Works both for validateForm() and submitForm(). Ensure you have #name for all your buttons. E.g.: $form['button1'] = [ '#type' => 'submit', '#name' => 'button1', '#value' => $this->t('...


0

So, what i wanted ... for ($i = 0; $i < count($arr_git); $i++) { $form[] = [ $item['repo_name'] = [ '#type' => 'submit', '#title' => 'name'.$i, '#prefix' => '<div class="form__item">', '#attributes' => ['class' => ['item_name']], ], $item['repo_del'] = [ '#type' => 'submit', '#name'...


Top 50 recent answers are included