File upload becomes empty after form submit for anonymous users

6 days 4 hours ago

I've build a form in Drupal 9 with Form API. When logged in as admin, all is working fine. Selecting a file as anonymous works, and the validations are checked. But when I submit the form, the managed_file becomes empty. Is this a permission issue? Which one?

/** * @param array $form * @param \Drupal\Core\Form\FormStateInterface $form_state * * @return array */ public function buildForm(array $form, FormStateInterface $form_state): array { $form['logo'] = [ '#type' => 'managed_file', '#title' => $this->t('Logo'), '#upload_validators' => [ 'file_validate_extensions' => ['png'], 'file_validate_size' => [2 * 1024 * 1024], 'custom_validate_image_resolution' => [1500], ], '#upload_location' => 'public://logos/', '#required' => TRUE, ]; $form['submit'] = [ '#type' => 'container', '#prefix' => '<div class="col-12">', '#suffix' => '</div>', ]; $form['submit']['submit'] = [ '#type' => 'submit', '#value' => $this->t('Submit'), ]; return $form; } /** * Custom validator for image dimensions where either width or height should * meet the minimum size. * * @param File $file * The file ID to validate. * @param int $minimum_dimension * The minimum dimension size. * * @return array * An array of error messages, empty if no errors. */ function custom_validate_image_resolution(File $file, int $minimum_dimension = 1500): array { $errors = []; $uri = $file->getFileUri(); // Load the file as an image. $image = \Drupal::service('image.factory')->get($uri); if ($image->isValid()) { $width = $image->getWidth(); $height = $image->getHeight(); // Check if either dimension is below the minimum size. if ($width < $minimum_dimension && $height < $minimum_dimension) { $errors[] = t('The image dimensions must have at least a width or height of %dimensions pixels.', ['%dimensions' => $minimum_dimension]); } } else { $errors[] = t('Unable to load the image file.'); } return $errors; } /** * @throws \Drupal\Core\Entity\EntityStorageException */ public function validateForm(array &$form, FormStateInterface $form_state) { // on choose file, $fids is populated, on submit it becomes empty :/ $fids = $form_state->getValue('logo'); if (!empty($fids) && !empty($fids[0])) { $fid = reset($fids); // Get the first element (file ID) $file = \Drupal\file\Entity\File::load($fid); if ($file) { $errors = $this->custom_validate_image_resolution($file, 1500); if (!empty($errors)) { // Log errors and set form errors foreach ($errors as $error) { $form_state->setErrorByName('logo', $error); } // Delete the file if it's temporary if ($file->isTemporary()) { $file->delete(); } } } else { \Drupal::logger('my_module') ->error('Failed to load file with ID: ' . $fid); } } else { $form_state->setErrorByName('logo', t('No valid file uploaded.')); } } /** * @throws \Drupal\Core\Entity\EntityStorageException */ public function submitForm(array &$form, FormStateInterface $form_state) { $node = Node::create([ 'title' => $form_state->getValue(['title' => 'textfield']), 'type' => 'my-node', 'status' => 0, 'field_logo' => [ 'target_id' => reset($form_state->getValue('logo')), 'alt' => $form_state->getValue(['title' => 'textfield']), 'title' => $form_state->getValue(['title' => 'textfield']), ], ]); $node->save(); } }
user3086053

Showing local tasks in toolbar with hook_toolbar: caching problem

6 days 6 hours ago

I'm creating a module using the toolbar api showing all administrative functions in a more compact toolbar. I'm having "cache" troubles showing the local tasks in the toolbar... How can I keep these items outside the toolbar cache?

In my custom module I use hook_toolbar to add the local tasks

/** * Implements hook_toolbar(). */ function compact_toolbar_toolbar() { $items = []; ... $tasks = _compact_toolbar_local_tasks(); $items = array_merge($items,$tasks); return $items; }

And a function to generate the toolbar local tasks...

/** * Create local tasks toolbar items */ function _compact_toolbar_local_tasks() { $items = []; $route = \Drupal::routeMatch()->getRouteName(); $manager = \Drupal::service('plugin.manager.menu.local_task'); $primary = $manager->getLocalTasks($route, 0); foreach($primary['tabs'] as $key => $tab) { // add toolbar tab $items[$key] = [ '#type' => 'toolbar_item', '#cache' => [ // Can I overrule the toolbar cache here? 'max-age' => 0, ], 'tab' => [ '#type' => 'link', '#title' => $tab['#link']['title'], '#url' => $tab['#link']['url'], '#access' => $tab['#access'], '#attributes' => [ 'title' => $tab['#link']['title'], ], ], '#weight' => $tab['#weight'], ]; // check if task is active if($tab['#active']) { $items[$key]['tab']['#attributes']['class'][] = 'is-active'; } // get secondary tabs for each primary tab $route = $items[$key]['tab']['#url']->getRouteName(); $secondary = $manager->getLocalTasks($route, 1); // get secondary tabs as tray if (!empty($secondary['tabs'])) { $links = []; $items[$key]['tab']['#attributes']['class'][] = 'toolbar-parent'; // create renderable array of secondary links foreach ($secondary['tabs'] as $skey => $stab) { $sname = substr($skey, strrpos($key, '.') + 1); $links[$sname] = [ 'type' => 'link', 'title' => $stab['#link']['title'], 'url' => $stab['#link']['url'], ]; } // add tray with secondary tasks $items[$key]['tray'] = [ '#heading' => t('Secondary tasks'), 'toolbar_secondary_tasks' => [ '#theme' => 'links__toolbar', '#links' => $links, '#attributes' => ['class' => ['toolbar-menu']], ], ]; } } return $items; }

When I disable the cache in hook_page_top in core/modules/toolbar/toolbar.module everything works like a charm. Otherwise my custom items won't follow the current page...

/** * Implements hook_page_top(). * * Add admin toolbar to the top of the page automatically. */ function toolbar_page_top(array &$page_top) { $page_top['toolbar'] = array( '#type' => 'toolbar', '#access' => \Drupal::currentUser()->hasPermission('access toolbar'), /* '#cache' => [ 'keys' => ['toolbar'], 'contexts' => ['user.permissions'], ], */ ); }

Can I overrule the toolbar cache by using the #cache array in my custom toolbar items? Which tags/context should I use?

This is how the toolbar looks like with my compact_toolbar module enabled... (but toolbar cache disabled) I really like the result! - I also made the menu behave like a simple dropdown menu and added a "content menu" to quickly add new content...

user2606129

Proper way to get input field value with AJAX

6 days 6 hours ago

I want to do some calculations in node edit form vith ajax. Form fields is created via UI, so i need to drill into field array to get value(s). Maximum result what i have is replacing target field with result of #defaul_value of source fields. Nothing happens when i change source.

<? use Drupal\Core\Form\FormBase; use Drupal\Core\Form\FormStateInterface; use Drupal\Core\Ajax\AjaxResponse; use Drupal\Core\Ajax\ReplaceCommand; function module_form_alter(&$form, &$form_state, $form_id) { $form['field_source']['widget'][0]['value']['#ajax'] = array( 'callback' => 'myAjaxCallback', 'method' => 'replace', 'effect' => 'fade', 'event' => 'change', 'wrapper' => 'calc', ); $form['field_source2']['widget'][0]['value']['#ajax'] = array( 'callback' => 'myAjaxCallback', 'method' => 'replace', 'effect' => 'fade', 'event' => 'change', 'wrapper' => 'calc', ); $form['field_target']['#prefix'] = '<div id="calc">'; $form['field_target']['#suffix'] = '</div>'; $form['field_target']['#disabled'] = TRUE; /* some calculations */ $s1 = $form['field_souce']['widget'][0]['value']['#default_value']; /* HOW TO GET PROPER SOURCE VALUES "ON FLY" WHEN EDITOR CHANGES IT? */ $s2 = $form['field_souce2']['widget'][0]['value']['#default_value']; $result = $s1 * $s2; $form['field_target']['widget'][0]['value']['#default_value'] = $result; } function myAjaxCallback($form, FormStateInterface $form_state) { return $form['field_target']; }

Calculations gives result, but only with values which already submitted, so when i change source values AJAX firing & fading, but nothing happens whith target. What i try is get values with:

$s1 = $form_state->getValue('source'); <-- gives "0" $result $s1 = $form['field_souce']['widget'][0]['value'] <-- get error Unsupported operand types
Otto Matik

How to handle session for anonymous users for CSRF tokens?

6 days 6 hours ago

I need to provide a list of CSRF tokens in drupalSettings for every anonymous user to make safe requests to API endpoints. The CSRF service mentions the need for session to exist for the seed, but I do not know how to correctly create the session.

This is what I tried in a hook_page_attachments_alter() implementation.

/** * Implements hook_page_attachments_alter(). */ function foo_page_attachments_alter(array &$attachments) { // Needed for persistent, per-user, csrf tokens. $session = \Drupal::request()->getSession(); if ($session->isStarted() === FALSE) { $session->start(); } /** @var Drupal\Core\Access\CsrfTokenGenerator $csrf */ $csrf = \Drupal::service('csrf_token'); $attachments['#attached']['drupalSettings']['foo']['tokens'] = [ 'pathA' => $csrf->get('/pathA'), 'pathB' => $csrf->get('/pathB') ]; $session->save(); }

I have also tried the following way to verify the session has been started, but none of them worked.

if (session_status() === PHP_SESSION_NONE) { session_start(); } \Drupal::service('session_manager')->start(); \Drupal::service('session_manager')->save(); \Drupal::service('session_manager')->regenerate(); \Drupal::service('session')->start(); \Drupal::service('session')->migrate();

The complete code I am using is the following one.

user21641

How can I add a template suggestion for a field formatter based on the current view mode?

6 days 6 hours ago

In my Drupal 10 theme how I can get Entity View Mode? I use this to rewrite suggestions

/** * Implements hook_theme_suggestions_HOOK_alter(). */ function MYTHEME_theme_suggestions_image_formatter_alter(array &$suggestions, array $variables) { $entity = $variables['item']->getEntity(); $field_name = $variables['item']->getParent()->getName(); $suggestions[] = 'image_formatter__' . $entity->getEntityTypeId() . '__' . $entity->bundle() . '__' . $field_name; }

But I need also View Mode (full, teaser). Something like this:

image-formatter--node--article--VIEW-MODE--field-image.html.twig

Aleksandr

How do I apply a discount for the second and successive items only if the quantity for those items is higher than 1?

6 days 7 hours ago

Using Commerce Discount and Commerce Discount Extra modules there is no problem to set discount rule conditions for product type and quantity. This way I can set up 20% off discount that is applied for a cart line item when this line item has specific product type and quantity more than one. 20% off discount is then calculated for this line item and multiplied by quantity.

However, my need is to apply such discount not to each item from line item quantity. I simply want to exclude applying discount for one (first one) on the basis: 0,2*(n-1)*X where n is qty and X is product base price.

The problem is that line item discount type in Commerce Discount module is calculating before quantity calculation (only for qty of 1) and proper price component is added to line item price.

The solution I've tried was to divide calculated discount (0.2*X/n) but the result calculated for quatity 3 or 6 or 9 is inaccurate (wrong, decimal number).

Is there a hook or other solution that can allow me to "return" the part of discount that should not be applied, or am I simply missing something and there is a more natural way to achieve what I described (for example, the order discount rule)?

dubwise

How to utilise isDefaultRevision() for forward revisioning?

6 days 8 hours ago

Since "Support revisions in different states" went into the core it is now theoretically possible to have forward revisions of nodes. For example publish revision 1 then create revision 2 but keep it unpublished. This is very useful when someone needs to create new version of a node that needs to be approved before publishing.

Sounds great so here's what I did:

  1. I've created a node with title "Published revision". The node ID is 1 and it's revision is 1.
  2. I've created a new revision of node 1 and changed it's title to "Unpublished revision". This node has revision 2 and it has immediately been set as default revision.
  3. At this moment /node/1 shows the node with title "Unpublished revision".
  4. I've used PHP to load node 1 with revision 1 and I've set it to default revision ($node->isDefaultRevision(true)).
  5. At this moment /node/1 shows the node with title "Published revision".

So far so good. However the problem is that I'd like to edit revision 2 but I can't:

  1. /node/1/edit shows edit form of revision 1.
  2. /node/1/revisions/2/edit is of course 404.
  3. And on top of that when I go to /node/1/revisions the revision 2 is listed as "Current" which of course is not true because default revision is 1. (Let's say I can live with that for now)

Questions:

  1. How to edit arbitrary node revision?
  2. How to control which node revision is saved as default revision?
SiliconMind

How to remove custom block parent div's?

6 days 9 hours ago

I have created custom block in my custom module. I have created block template file into module templates folder. Custom block content coming successfully as per given in block__MODULENAME__dummmy_xyz.tpl.php file. I have only added following code into my block tpl file:

<div class="wrapperDummy">Hello</div>

But it is coming with block parent div's, Block id and block-inner tag. I dont want to show those extra div's. Following is the hook_theme which I have in my module file:

/* * Implements hook_theme(). */ function MODULENAME_theme($existing, $type, $theme, $path) { $items = array(); $items['MODULENAME_dummmy_xyz_block_theme'] = array( 'type' => 'theme', 'path' => drupal_get_path('module', 'MODULENAME') . '/templates', 'template' => 'block__MODULENAME__dummmy_xyz', 'variables' => array() ); return $items; }

I am rendering block into tpl using,

$block = block_load('MODULENAME','dummmy_xyz'); print drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));

block.tpl.php code:

<?php print $outer_prefix . $inner_prefix; ?> <?php print render($title_prefix); ?> <?php if ($title): ?> <h2<?php print $title_attributes; ?>><?php print $title; ?></h2> <?php endif; ?> <?php print $content_processed; ?> <?php print render($title_suffix); ?> <?php print $inner_suffix . $outer_suffix; ?>

Kindly guide me.

Reshma

How to customize my front page with background image?

6 days 10 hours ago

I have site for which I need to design a custom front page using my sub-theme with page page--front.tpl.php.

I need to place a background image and on title at left alignment and little bottom thre image background buttons and in that bottom center need to place on caret with hyperlink which will take you to rest of the half page.

Any suggestion?

Dhwani Trivedi

How to remove markup from file field

6 days 11 hours ago

I have added a file field in views and when displaying it has some markup like this

<div id="file-218" class="file file-image file-image-jpeg contextual-links-region"> <a href="#"> </a> <h2 class="element-invisible"> <a href="#"></a> <a href="/mdm.dev/file/218">6783c11f-0b05-49e3-a494-ca68d2e6c23b-2060x1366.jpeg</a></h2> <div class="contextual-links-wrapper contextual-links-processed"> <a class="contextual-links-trigger contextual-links-trigger-active" href="#"> Configure</a> <ul class="contextual-links"> <li class="file-edit first"> <a href="/mdm.dev/file/218/edit?destination=gallery-page">Edit</a> </li> <li class="file-delete last"> <a href="/mdm.dev/file/218/delete? destination=gallery-page">Delete</a></li> </ul></div> <div class="content"> <img typeof="foaf:Image" src="http://10.200.1.10/mdm.dev/sites/default/files/ styles/w206xh154/public/6783c11f-0b05-49e3-a494-ca68d2e6c23b-2060x1366.jpeg?itok=bk_SdoJ3" alt=""> </div> </div>

While all I need is

<img typeof="foaf:Image" src="http://10.200.1.10/mdm.dev/sites/default/files/ styles/w206xh154/public/6783c11f-0b05-49e3-a494-ca68d2e6c23b-2060x1366.jpeg?itok=bk_SdoJ3" alt="">

How can I remove this markup. Can I use views-view-field-field_name.tpl.php. Only line this file contains is print $output. How can i use this file to remove markup. Or does any preprocess hook helps

Nabil

How do I remove the ellipsis button in the pager?

6 days 12 hours ago

I have a view with video and have replaced the links to different pages with a button. However, when there are many videos, an ellipsis (...) appears floating, and I want to remove it. I have the View with full pager but I don't see how to control this to hide it. Thanks!

Cesar

Views pager labels translation per context

6 days 13 hours ago

Now that I finally have managed to have Views pagers appear, I'm wondering how I could change the strings collection (prev, next, first, last...) per View. That's because in a View that displays items in chronological manner, I would rather see labels like older/newer rather than previous/next. Can this be done somewhere in views template or in template.php? (No jquery here, please :))

no more drupal

Alter label with token

6 days 14 hours ago

I am trying to build a questionnaire that simply replaces (alters) the label of a list field. I am doing so by replacing a token from views (embed) and implementing hook_form_alter() in a separate module.

How can I save that value and write it to the database? I am using an Entity form and a list-field.

This is the snippet I am struggling with, found on Store token replacement values in the database rather than tokens themselves.

function question_to_label_node_presave($node) { if ($node->type == 'page') { $replaced_text = token_replace($node->field_question['und'][0]['value']); $node->field_question['und'][0]['value'] = $replaced_text; } }

I am currently trying to run this in a custom module, but I cannot find the right content type for the Entity form. I am using the Devel module to find the right array value.

Stefan Carlsson

Get the breadcrumbs for a specific node other than the current

6 days 15 hours ago

I have a list of nodes created by a view. Those nodes tend to have titles that are mostly the same, but since they are in a rather logical hierarchy defined by the menu I'd like to output the breadcrumb to the nodes as well.

I couldn't find a core-function that does that. Anyone an idea how to work around/on that?

nocksock

Outputing the field as link doesn't properly show the field properties

6 days 16 hours ago

I want to output an image field as a link in a view. I've seen many tutorials but get stuck at one point.

I already added the link on top of the image field. By clicking on the image at rewrite results, I could check Output this field as a link, but checking it won't give me the fields properties where I could fill in the link field details, as shown in this screenshot.

Do you know what I'm missing?

These are the other view settings for that field.

Chris Klein

How can I add animation/fade to modal/dialogue boxes?

6 days 17 hours ago

The current state of a modal/dialog opening in Drupal 8 (and 7 for that matter) is pretty clunky from a user experience perspect. Leveraging some type of animation/fade would really enhance the elegance + cohesiveness of the modal. I notice bootstrap allows a "fade" class on the modal, which gives it a fade effect (I assume). Is there a way to add this type (or any type) of animation to a Drupal 8 modal without needing bootstrap? Am I missing something simple?

Edit: Thanks for quick replies and patience with a newbie. So I'm opening a node/add form into a modal with a link like so..

<a class="use-ajax" data-dialog-options="{&quot;width&quot;:800}" data-dialog-type="modal" href="/node/add/article">Add Article</a>

I'd like the modal to open/close with a fade effect (or slide in, etc). Is there a way to leverage JS, CSS or Drupal itself to create this animation?

Is there a better solution all together to displaying a node/add form in a popup/lightbox type element with ajax?

Thank you!

Sampsonite

hook_form_FORM_ID_alter being called twice (even before submit)

6 days 18 hours ago

I want to make some changes to the "Content" page. The ID of the form is views_form_content_page_1, so I made a quick test (after drush cr of course):

function my_module_form_views_form_content_page_1_alter(&$form, FormStateInterface $form_state) { kint($form); }

When I go to the page, the $form is being printed twice by the devel. I checked, all of the array items are the same. If I do kint('cat');, then it will print cat two times.

Why is this happening? Of course I could make it work, that my action will run only once (eventho drupal tries to run it twice) but I would like to rather solve this one, and understand if it's a bug, and why it is happening.

ssibal

Set the Contextual Filter: Author uid. to a default user?

6 days 19 hours ago

I have a view called Map Items showing a list of map markers in a chart.

Info: I have 3 Accounts in my drupal installation called person1, person2, and admin.

I've set the contextual filter to Author uid: User ID from Logged in user. and its working perfectly, but what I want some additional setting that when there is no logged in user I could set person1's map item to show. Right now when there is no logged in user the view shows the map item of admin user and not person1.

How am I going to accomplish this?

Richard
Checked
22 hours 21 minutes ago
most recent 30 from drupal.stackexchange.com
Subscribe to Drupal StackExchange feed