New answers tagged

0

Blur Image Background is a image blur app used to blur part of your image very simple. You can also unblur the image, selecting camera, picture or feedback and give it a blurry effect, using this blur image editor.With Blur Image Background you can quickly transform your favorite images into fashionable eye-catchers.You can trace with your finger.It is very ...


0

You could add a fieldset for each person, something like this should work: for ($i = 0; $i < $num_names; $i++) { $form['names_fieldset']['person_' . $i] = [ '#type' => 'fieldset', '#title' => $this->t('Person ' . $i), ]; $form['names_fieldset']['person_' . $i]['name'] = [ '#type' => 'textfield', '#title' => $this->...


0

This simple code is working properly while migrating md5 password to drupal 8 $password_service = \Drupal::service('password'); $password = $row->getSourceProperty('user_password'); // 'user_password' is the old db column which is in md5 format $hashed_password = 'U' . $password_service->hash($password); // U will indicate that the password ...


1

I finally solved the problem by adding a template for the content type. This allowed me to simplify the preprocess function: function mytheme_preprocess_node__event(&$variables) { $startdate = $variables['content']['field_eventdate'][0]['#markup']; $enddate = $variables['content']['field_eventend'][0]['#markup']; if ($startdate === $enddate) { ...


0

On a unit test, you can use getConfigFactoryStub(): namespace Drupal\Tests\my_module\Unit; use Drupal\Core\DependencyInjection\ContainerBuilder; use Drupal\Tests\UnitTestCase; class MyModuleTest extends UnitTestCase { public function setUp() { parent::setUp(); $config_map = [ 'my_module.settings' => [ 'setting_1' => 'value_1'...


0

As mentioned by @Clive, breadcrumbs are not entities so I was not be able to get it done by adding a mytheme_theme_suggestions_breadcrumb_alter. Instead to solve the problem I had to do the following. On top of this, I ended up downloading and enabling Easy Breadcrumb to further modify the Breadcrumb Copy the breadcrumb.html.twig file from the Classy theme ...


0

This depends on whether the data needs to be manipulated by the site admins, the code, or is static. Variable to be manipulated by the code I would recommend using the State API. Fast and easy way to store variables in the database. Variable needs to be manipulated by the site admins I would recommend creating a Configuration Form. This takes a lot ...


2

Yes, use the following: composer update --prefer-source drupal/menu_block


0

Based on @berramou answer, I think this would be the right way (timezone and format wise): ->setDefaultValue(DrupalDateTime::createFromTimestamp(\Drupal::time()->getRequestTime(), DateTimeItemInterface::STORAGE_TIMEZONE)->format(DateTimeItemInterface::DATETIME_STORAGE_FORMAT))


0

I just had this after transferring an entire database (Drupal 8.8.1) from production back to dev. Same error on every single route I tried. Clearing the cache alone didn't fix it, but composer dump-autoload ("Generated autoload files containing 565 classes") followed by drush cr did.


1

Could be a redirect loop. You have to check whether the query string is already present and then stop redirecting again: public function redirectWithFilter(GetResponseEvent $event) { $request = $event->getRequest(); if ($request->query->has('city')) { return; } ... }


0

I managed to fix the problems with SolrClient install: https://stackoverflow.com/questions/41052999/php-warning-unable-to-load-dynamic-library-usr-lib64-php-modules-solr-so-und%C2%A0 This is how I can now query the solr server from php (right out of php SolrClient manual): $options = array ( 'hostname' => 'localhost', 'port' => '8983', ...


0

Another solution I happened upon since I first posted is $uri = $node->get('field_link')->uri; The difference between this and the accepted answer is that this approach gives the actual, raw value in the link field (with 'internal:' appended to the front) whatever it is, without URL alias translation. The accepted answer doesn't translate /node/123 ...


1

This is working for me, sending a XML file with \Drupal::httpClient() POST $endpoint = 'http://example.com/something'; $xml = '<>'; // You're XML here. // Make the request. $options = [ 'connect_timeout' => 30, 'debug' => true, 'headers' => array( 'Content-Type' => 'text/xml', ), 'body' => $xml, 'verify'=>true, ]; ...


2

The flag count in another table called flag_counts so you should do join with node table try the following: $database = \Drupal::database(); $query = $database->select('node', 'n'); $query->fields('n', []) ->condition('nfd.status', '1', '='); // Inner join to get the node status. $query->innerJoin('node_field_data', 'nfd', 'nfd.nid = n.nid'); /...


0

In a custom Drupal module do something like: function sfusd_scheduler_form_alter(&$form, $form_state, $form_id) { // Let's change sticky at top of lists to client preferred verbiage $form['sticky']['widget']['value']['#title'] = 'Pinned to top of announcement list'; }


1

For example, what was example.com/old-style-alias might now be example.com/a-very-different-alias. Redirect module is exactly what you need. This can automatically add a redirect when you change the node's alias or you can manually add them to the redirect list, which gets saved to the DB.


0

Had quite some time figuring out block caching in drupal 8, so I made this video tutorial explaining block caching (16 min.).


0

In your blockcache_examples.module file: use Drupal\Core\Cache\Cache; use Drupal\node\Entity\Node; /** * Invalidate the custom tag if entities of type "page" get updated */ function blockcache_examples_node_update(Node $entity) { if($entity->getType() === 'page') { Cache::invalidateTags(['blockcache_examples_page_updates']); } } /** * ...


0

More right, easy and universal way: $node = \Drupal::entityTypeManager()->getStorage('node')->load($id); $node_alias = $node->get('path')->alias; You can also do extra checks if you are not sure if an alias exists: if (!$node->get('path')->isEmpty()) { $node_alias = $node->get('path')->alias; }


0

There is no public method on the State object that returns the messages. The public methods on the object are: progress() setCompleted() setMessage() displayMessages() logMessages() The method displayMessages() is the closest method you can use to access the messages, the messages are then transferred to \Drupal\Core\Messenger\Messenger, which has a method ...


1

The problem as commented above is the type of the translatable properties on the schema. Needs to be changed from string to label also the translatable: false can be safely removed since is default behavior, and also no needed for label or text types. For more information about config translation check the cheatsheet.


0

Finally and because of the side effect of the solution proposed by Mike Nolan (see capture2 in my comment), I made it that way: function association_menu_local_tasks_alter(&$data, $route_name) { $oCurrentUser = \Drupal::currentUser(); switch ($route_name) { case 'view.association_members_and_persons.page_1': case 'view.association_members....


0

Just try: function hook_node_insert(\Drupal\node\Entity\NodeEntityInterface $node) { $id = $node->id(); }


0

Use Clear Specific Cache(https://www.drupal.org/project/ccos) module. The Clear Specific Cache module will help you to clear the cache of sole/specific entity type (i.e block, node, views block, view page, etc.) from contextual links, local task menu, and operations drop-button.


1

In my case, the '$result->_entity' was empty, so I had to get the value from the '$result->_object' : function YOUR_THEME_preprocess_views_view__YOUR_VIEW_ID(array &$variables): void { foreach ($variables['view']->result as $result) { $node = $result->_object->getEntity(); $title = $node->get('title')->getValue()[0]['value']; ...


2

The plugin was missing the proper annotation (added now in the question). Views plugins use Annotation Discovery. Adding something like the following solved the problem: /** * My custom serializer * * @ViewsStyle( * id = "hindi_custom_serializer", * title = @Translation("Hindi Custom Serializer"), * help = @Translation("Serializes views row ...


3

Since you don't know the password, only the hash, you can't migrate it directly. (MD5 is weak, but not that weak.) The whole purpose of hashing is that the password should be unknown to anyone except the user. There are 2 solutions to this. Reset all your users password and send a one-time-login password to them once they are migrated - as already suggested ...


5

Instead of rendering the URL object with toString() use the method Url::getInternalPath: $url = $link->getUrl(); if ($url->isRouted()) { $path = $url->getInternalPath(); }


3

UPDATE As discussed here, this issue was caused by some missconfiguration at view level and normally should not occur. Read the full post to get the full picture on how you can step on this error. ORIGINAL ANSWER I'm adding my findings as answer since comments have limitations both on styles and length, but by all means THIS IS NOT an actual answer to the ...


3

This has nothing to do with drupal. Need to edit the .htaccess file RewriteEngine On RewriteRule ^test/(.*)$ /new/$1 [R=301,L] This will redirect example.com/test/1 to example.com/new/1


0

It's easier to do // Split the name on spaces. $name = explode(' ', $node->title); // Get the last element. $last_name = end($name); If you're set on using regex, you should test it comprehensively using a regex tester. I believe, but don't know, that $match[0] will return the matching string, so the entire node title so that with two capture groups ...


8

The best practice is still to use Drupal's behaviors system even when not relying on jQuery. See Drupal 8 Drupal.behaviors without jquery for reference. That said, I think you're on the right path. I find jQuery just slows down the page load when vanilla JS will usually do the trick. That's just my opinion and there's a lot of debate out there.


0

I was able to resolve this from the info found here: https://skoop.dev/blog/2019/10/04/PHP-and-the-DigitalOcean-MySQL-cluster/ The problem stemmed from the default authentication method for MySQL v8 is caching_sha2_password, which the article above suggests is not supported by php yet. As the article suggests, we can switch back to the old authentication ...


1

You do not need internal:/ you just need to have some help text that says an internal path should begin with a slash. After that, when you create the links, you can do: use Drupal\Core\Link; use Drupal\Core\Url; use Drupal\Component\Utility\UrlHelper; .... .... .... function or method.... { $path = // get config value $label = // get config value ...


0

I recently needed this myself with the twist that I wanted to provide a default (svg) image when no image was uploaded. Twig Tweak makes this possible while still allowing me to control the output via Drupal's user interface. In my case, I'm styling a comment, so I want to render the user picture, and I'd like to use the "thumbnail" image style. This is ...


0

This error message is provided by \Drupal\Core\Entity\Element\EntityAutocomplete::matchEntityByTitle() called by \Drupal\Core\Entity\Element\EntityAutocomplete::validateEntityAutocomplete() method and is invoked at element validation (explained later) so it cannot be overriden using AJAX API. To do so, you can implement one of the following: Extend the ...


2

There is no dedicated delete button. Drupals default behavior (including paragraphs) is to automatically delete every empty field at the end of the list. The empty field you see is just a convinience for faster adding of a new item. Side node: To delete e.g. the first item of the list, remove the content and drag it to the bottom.


1

I don't think there is a node object in the node.add route, it doesn't exist there yet. But you can still get it from the node_type parameter. Untested, but following the code from NodeController.php you should be able to get the label with something like this: //get the machine name from route $machineName = \Drupal::routeMatch()->getParameter('...


2

You can create a views page that shows the most recent video. Structure > Views > Add new view Title: "Videos" Show content of type "Video" sorted by "Newest first" Check "Create a page" option Page title: "Video" Path: "videos" Display format: "Unformatted list" of "Full posts" Items to display: "1" Save & edit Save again Now go to the url: http://...


1

try to print it this way it gives you more control : <div id="candidature_spontanee" class="form-contact candidature_spontanee"> {# 1.use the attribute to set the form action and other attributes #} <form{{ attributes }}> {{ title_prefix }} {{ title_suffix }} {# 2.print the form elment using : {{ element.elements.key }} #} <div ...


0

the question is not clear but as I understand you want to pass the node type readable name to the template and this is the easiest way : function THEMENAME_preprocess_page(&$variables){ //Get the current page rendered node(s). $node = \Drupal::routeMatch()->getParameter('node'); if ($node instanceof \Drupal\node\NodeInterface) { // You can ...


0

if ($node = \Drupal::routeMatch()->getParameter('node')) { There's no node ID in the route at /node/add/foo, so there's no node available, and that condition will always be false. You need to create the node yourself, e.g. // Get the desired type from the route. if ($node_type = \Drupal::routeMatch()->getParameter('node_type')) { $node = \Drupal::...


1

Based on @Jaypan answer and @FLY comment I made a FieldWidget. This indeed removed the need for the hook_managed_file_process and hook_element_info_alter. This also made it possible to use the widget on a per field basis. First make your custom FieldWidget in [MODULE]/src/Plugin/Field/FieldWidget: namespace Drupal\[MODULE]\Plugin\Field\FieldWidget; use ...


0

In a custom module (mymodule), create a mymodule.links.task.yml file, and add the following: mymodule.admin_people: route_name: entity.user.collection base_route: route.of.your.custom.menu title: 'Tab text goes here' Here's what each part does: mymodule.admin_people Is the identifier of your menu tab item (the file being *.links.task.yml means its ...


2

I don't know how comfortable you are with code. I would suggest writing an update hook in a custom module. Something like: MYMODULE_update_8100(&$sandbox) { // On the initial run, set up the update. if (empty($sandbox)) { // Get all user ids. $sandbox['items'] = \Drupal::entityQuery('user') ->accessCheck(FALSE) ->execute(); ...


2

Enable "Layout builder" module first. On "Manage display" in entity config Default "Custom display" enable "Full content", then go there and enable "Use Layout builder" and "Allow each content item to have its layout customized." This will give you "Layout" tab in each node (of this type where you enable this in config) for ex. - how to arrange each field ...


0

Install the Block field module Create a paragraph type "Drupal block" In that paragraph type, create a new field using the field type from the new module Now you can place any block within the main content area just like an ordinary paragraph.


0

var notificationList = false; $('.show').click(function(){ if(notificationList) { notificationList = false; $('.field-something').hide(); } else { notificationList = true; $('.field-something').show(); } });


1

Ok, I solved it like this: function THEMENAME_preprocess_views_view_field(&$variables) { $view = $variables['view']; $field = $variables['field']; $rows = $variables['rows']; if ($view->id() == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME') { if ($field->field == 'FIELD_NAME') { foreach ($view->field as $fieldId => $field) ...


Top 50 recent answers are included