The file names are not transliterated on upload I am using Drupal 7 and have transliteration module enabled.

I have a file field and I want to have the names of the uploaded files to be transliterated on upload.

The url alias for the nodes are well transliterated. But the file names are not.

I checked the settings for file system. The current settings are:

Transliterate file names during upload.(checked)
Lowercase transliterated file names. (checked)

If I "Transliterate existing file names" (admin/config/media/file-system/transliteration) then the names of the files I have already uploaded are transliterated. But still, when I upload new files, the file names are not transliterated.

Any ideas why the names are not translated on upload?

File names are not URL aliases. Pathauto has never had any sort of integration with files at all.


add text before block is being displayed in region content I have a block that I want to display in my Content region which works fine but the block is always fix aligned in the top left corner (float: left property). How can I set it so, that my content displays above the block in my region?

Assign this css code to one class of your block ( or the #id )

.your-block-class-name:before {
  content: "";
  display: table;
}


Odds Link Hover Behavouir Hello i dont seem to be able to change the colour of my links hover on my main content table. Ive tried everything but it seems to want to stay white. Can anyone identify the CSS i should be changing?

thanks

main left table here-
enter link description here

This does the job:

#main-content table tbody .views-field a:hover {
  color: orange;
}

It's a CSS specificity issue (also the reason that I never use ID's to style elements).  Check this page out from Stuff and Nonsense for a REALLY good explanation on CSS specificity (in relation to Star Wars).


How can I programmatically deactivate multiple user accounts? I have tried the following code, but something doesn't work, could you please help. I need to deactivate several accounts at once, if they satisfy the conditions:

$ids = \Drupal::entityQuery('user')
  ->condition('roles', 'student')
  ->condition('field_school_id', $node_id)
  ->execute();
$users = User::loadMultiple($ids);

$storage_handler = \Drupal::entityTypeManager()->getStorage("user");

foreach($users as $user){
  $entity = $storage_handler->load($user->id());
  $entity->set("status", 0);
  $storage_handler->save($entity); // THE PROBLEM IS IN THIS LINE
}

The problem is that you load the users two times. In the foreach loop you already have the loaded entity available in $user.

Change your foreach loop to look like this and it should work:

foreach ($users as $user) {
  $user->set("status", 0);
  $user->save();
}

You can also remove the $storageHandler since you don't use that any more.


Page view mode and node settings I have been creating new view modes with the entity view mode module as well as created template files for the new view modes.

At this point I would like to know how I tell a given page or url (ie. front page) which view mode of a particular content type to use

You can create a view and go to Format section and display it as content then select the view mode you want. After that go to  admin/config/system/site-information and change the Default front page to the view that you have created.


Tree view of node under taxonomy Hi I am facing a serious problem to list all nodes/subterms under each terms. Let's say I have several terms.

Games
   -> Cricket
   -> Football
   -> Badminton
   -> Tennis
     -> Long Tennis
     -> Table Tennis
   -> Hocky

Here you can see Games is the top most categories and Cricket, Football etc are sub categories. Must note: Tennis has 2 sub categories.

Each last term has some contents. That means Football, Cricket all are have several contents. But Tennis don't have any content. Long Tennis and Table Tennis has contents.

My aim is to show all the 1st level categories (That means Cricket, Football, Badminton, Tennis, Hocky) and then show all content under taxonomy term tree.

Like this below:

Categories:
   -> Cricket
   -> Football
   -> Badminton
   -> Tennis
   -> Hocky

Football:
   How to play Football?
   Football ground measurement.
   What is Football

Badminton:
   How to play Badminton?
   Badminton ground measurement.
   What is Badminton

Tennis:
  Long Tennis:
      How to play Tennis?
      Tennis ground measurement.
      What is Tennis
  Table Tennis:
      How to play Table Tennis?
      Table Tennis ground measurement.
      What is Tennis

Hocky:
   How to play Hocky?
   Hocky ground measurement.
   What is Hocky

I tried with Taxonomy View but no success. Tried to create the taxonomy-term.tpl.php file but I failed to give the display. I have modified the code many times so I can not paste the code here.

I am using Drupal 7 and views 3.

Is there any solution to solve this? Can you suggest me how can I achieve this? I think I am running on some wrong way. Please help me and give some advice to solve the things.

Lots of thanks in advance.

This can be done with Views Tree module. Install the module and read the readme.txt file to implement the same. Do get back in case of any doubts.


How do I count the number of products in cart programmatically? I have created the custom block, here I want to count the number of products which is presented in the cart and tried with commerce_cart_order_load function to get the user selected products.

Is there any other methods to count the number of product in cart ?

Please help me how to achieve this !

In Drupal 8, carts are special orders, related to a user (like regular orders). In a custom module, you can fetch the logged in user orders, filter them by a convenient boolean field called 'cart', sort them by creation date to get the last cart for this user. Then you can get the items count for this cart order :

in mymodule.module :

use Drupal\commerce_order\Entity\Order;

function mymodule_preprocess_[page|block|something_else](&$variables) {

  // get orders...
  $query = \Drupal::entityQuery('commerce_order')
    // ...for logged in user, could be anonymous (uid = 0)
    ->condition('uid',\Drupal::currentUser()->id())
    // ...which are carts
    ->condition('cart', 1)
    // ...last created first
    ->sort('created', 'DESC')
    // ...get only one
    ->range(0,1);

  // execute this : you get an array of a unique order ids (last cart)
  $cartsOrders = $query->execute();

  // I found one : this user has a cart
  if(count($cartsOrders) > 0) {

    // load the order which is the last cart for logged in user
    /* @var Order $lastCart */
    $lastCart = current(Order::loadMultiple($cartsOrders));
    // send this order items count to the template
    // ({{ cartItemsCount }} in your twig)
    $variables['cartItemsCount'] = count($lastCart->getItems());
  }
}

This may contains non optimal or ugly code, this is just a starting point (but quickly tested though, seems to work). Also this need to be tested in rare case scenarios or weird situations (involving anonymous users for example). My strategy (grab the last created cart order) may be wrong too...I would be happy to have a specialist feedback on this.

EDIT

I spent more time on this and had to debug a few things, here is some improvments (more Drupal Commerce 2 way) :

/* @var CurrentStoreInterface $cs */
$cs = \Drupal::service('commerce_store.current_store');
/* @var CartProviderInterface $cpi */
$cpi = \Drupal::service('commerce_cart.cart_provider');
$cart = $cpi->getCart('default', $cs->getStore());

$nbItemsInCart = $cart ? count($cart->getItems()) : 0;


Event Response not firing anonymous user I have a module in drupal8 which only job is on an event response is to redirect a URL. It works fine for everyone except anonymous users. How do I give the module privileges to fire on every user no matter if the are logged in or not.

This is the geographic_me_redirect.services.yml

services:
  me_redirect.process_me_request:
    class: Drupal\me_redirect\EventSubscriber\ResponseSubscriber
    arguments: []
    tags:
      - { name: event_subscriber }

This is the response

class ResponseSubscriber implements EventSubscriberInterface
{

    /**
     * Constructor.
     */
    public function __construct()
    {

    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {

        ///$events[KernelEvents::REQUEST][] = ['onRouteMatch', 27];
        //-- fires the event in the kernal early oo page load 20
        $events[KernelEvents::RESPONSE] = ['process_language_request',0];
        //-- For redirecting to another domain

        return $events;
    }

    public function process_language_request(FilterResponseEvent $event)
    {

    return my logic

    }
}

You can't do this when the redirect is already stored in the internal page cache. Because anonymous traffic is served from this cache before any event is fired.

You have to use this kill switch:

\Drupal::service('page_cache_kill_switch')->trigger();

If you put this in your event subscriber and clear the cache, then you prevent, that the response is cached in the internal page cache.


How to Disable "Upload" in IMCE to only keep "File browser"? I'm working on a website (Drupal 6) where filefield and IMCE are set to upload media into nodes.

The customer don't want the users to upload files in the default directory but in specific places, for this reason he asks me to remove the "upload" possibility and only keep the "file browser".

How can I say to the widget to use "file browser" by default?

Go to:

  Administration » Configuration » Media » IMCE

Select your profile.
Under Directories there are checkboxes: Browse,Upload,Thumbnails,Delete,Resize.

Uncheck: Upload


Unable to add Quantity in Stock in Drupal Commerce 8 using Commerce Stock Module I have enabled Commerce Stock Modules and its submodules
1. Commerce Stock API
2. Commerce Stock Field
3. Commerce Stock Local Storage
4. Commerce Stock UI

Created a Product Type ABC and added a field field_stock(field type Stock Level ) under fields section of Product Type ABC
Under Commerce >>  Configuration >> Stock
I have set the default configuration for STOCK SERVICES as - Use Default - and default value is set to Local Stock

and when I edit the products I see it as

What am I missing I have added a field but it does not show the text value where I can add quantity for a product ?

You need to configure the Stock Services found at /admin/commerce/config/stock/settings and choose Local Stock for your product variation.

Related topic can be found here.

EDIT: reading your question again and it seems that you added the field to the product itself, instead of adding it to the product variation. Stock field needs to be attached to the stock variation entity.


View that link to content in other languages I have a multilingual site where some content types are translated, and others will remain English only. I'd like to have lists of English content on other language sites. I've created a view that will list content from types that can not be translated, but the path variable is putting forward a translated link (e.g. /fr/node/123) even though it doesn't exist.

How do I get the link to the English version? If i have the node title "Link this field to the original piece of content " it links to the URL i am expecting, but I can't use that in rewriting...

You have to add NID field before the Title in Fields and make it Exclude From Display, I mean this

Then click on Title and in Show Rewrite results, check the Output this field as a link and use the following configuration

Now the Titles are linked to /en/node/[nid]


Commerce: What field to join line_item in order to get product price in custom query? I'm starting with line 'commerce_line_item' as a base table, and I want to get prices for each of the line item products attached to a Drupal Commerce Order, rather than just the order total. I need a listing of each product sold with prices, and neither views nor Entity Field Query offer enough options for me (I'm creating a master order statistics spreadsheet with phpexcel).

The only promising field I have in the 'commerce_line_item' table is an 'order_id', which I can't find a way to relate back to 'commerce_product' and a 'line_item_label', which does not join on the field 'commerce_product.sku'.

So what would I join on to get pricing information?

I asked a similar question here, but this has me slightly more baffled.

Here's my code below for the query.

  $query = db_select('commerce_line_item', 'i');
  $query->fields('i', array('line_item_label', 'line_item_id', 'quantity', 'data'));
  $query->condition('i.type', 'product', '=');
  $query->leftjoin('commerce_product', 'cp', 'cp.sku = i.line_item_label');
  $query->leftjoin('field_data_commerce_price', 'fcp', 'fcp.entity_id = cp.product_id');
  $query->fields('fcp', array('commerce_price_amount'));
  $query->leftjoin('commerce_order', 'o', 'o.order_id = i.order_id');

snip->

Thanks for your help!

As you can see in the graph from the question you're linking, there's a field that relates the line item with the products, that's not a database field but a Drupal field. This means that there will be a database table for the field data and revisions and you don't want to deal with that in a db_query, you should be using Entity Field Query instead that will know the database tables and fields to use in each case.

I'm guessing you want to get products from the line items you already have, or the order.

I'd get the line items with EntityFieldQuery:

$query = new EntityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'commerce_line_item')
  ->propertyCondition('order_id', <-your-order-id->)
  ->execute();

Now you've got the line items there, wrap them and get the product price:

if (!empty($result['commerce_line_item'])) {
  foreach ($result['commerce_line_item'] as $id => $value) {
    $line_item_wrapper = entity_metadata_wrapper('commerce_line_item', $id);
    $product_wrapper = $line_item_wrapper->commerce_product;
    $price = commerce_price_wrapper_value($product_wrapper, 'commerce_price', TRUE);
  }
}

Also, all this data is exposed to views, so you can create a view instead.


Why is this code causing an SQL error? I wrote code to select records from the database, but it is causing the following error:

  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error
      in your SQL syntax; check the manual that corresponds to your MySQL server version for the
      right syntax to use near 'FROM pricepackages pricepackages' at line 1: SELECT FROM
      {pricepackages} pricepackages; Array ( ) in view_packages() (line 25 of D:\xampp\htdocs
      \talyllyn\sites\all\modules\pricepackages\pricepackages.module).

What is wrong with the code I am using?

function view_packages() {
    $list = '
';
    $query = db_select('pricepackages')->execute();
    $i = 0;

    while ($record = $query->fetchAssoc()) {
        $list .= '
';
        $list .= $record['packageName']."	";
        $list .= ''.$record['packageDescp']."	";
        $list .= ''.$record['pPrice']."	";
        $list .= '
';
        $i++;
    }

    $list .= '
';
    return $list;
}

This is your current query as it's executed:

SELECT
FROM
{pricepackages} pricepackages

Which is obviously wrong; an SQL SELECT query needs one or more fields. To SELECT *:

$query = db_select('pricepackages')->fields('pricepackages')->execute();

Or specific fields:

$fields = array('foo', 'bar');
$query = db_select('pricepackages')->fields('pricepackages', $fields)->execute();


Content Type based template not working for Medical Zymphonies Theme I downloaded the Medical Zymphonies Theme and has been modifying that to create my own theme.

In the past, I have successfully used content type-specific template files with themes that I created. However, it is not working the current theme.
This is the template file for the theme.

I want a template specifically to basic page. So something like page--basic-page.tpl.php.

JamieR has provided a snippets in Drupal.org

function themeName_preprocess_page(&$vars, $hook) {
  if (isset($vars['node'])) {
    // If the node type is "blog_madness" the template suggestion will be "page--blog-madness.tpl.php".
    $vars['theme_hook_suggestions'][] = 'page__'. $vars['node']->type;
  }
}


How to add javascript to drupal 7? I found a responsive menu code here and I want to add it to my Drupal 7 site. I have no experience with JavaScript, but I thought that if i just copy the script into mytheme/js/menu.js, call it in mytheme.info, and add the HTML to a block, I will have the script up and running.

The HTML part works fine, but the JavaScript part isn't working.

Why doesn't my JavaScript code work?

Well adding JavaScript can be done through drupal_add_js().

You can add the JavaScript code in your template.php file.

Create a cool.js file where you copy the JavaScript code
Put the file in your themes/MYTHEME/js folder
In your template.php file, create a  page preprocess function

function MYTHEME_preprocess_page(&$vars) {
  drupal_add_js(drupal_get_path('theme', 'MYTHEME') . "/js/cool.js", array("preprocess" => True));
}

Clear the cache
Load your page and check the page source code to see if cool.js is being loaded; use ctrl+f to see if the file is present there
If the effect is still not coming, then verify the IDs in the HTML are correct


How can I remove "please wait..." from a form? I saw this Remove the "Please wait" text on Ajax Call but I can't find the form element. <?php dsm($form);?> and <?php dpm($form);?> return errors. This is what I found in $node:

I may have missed it. I tried using the ID path in the unset form function but it didn't work. This is what I'm putting in template.php:

function fivestar_form_fivestar_custom_widget_alter($form, &$form_state) {
  unset($form['field_funny']['#ajax']['progress']['message']);
}

I also tried theme_fivestar_form . . .

this can be done in css:

.fivestar-widget .ajax-progress
{
    display:none;
}


How do you save data that is in fields inserted via hook_form_alter? I created a module that just uses the hook_form_alter to add additional fields to an existing form. The problem now is when I enter in the information and submit none of the information inputed in the additional fields get saved when I go back to the form.

Other modules aren't generally programmed to be aware of your custom additions and don't know where/how you want to save the data. If you add fields via hook_form_alter() then you should also add your own submit and possibly validation handlers to the form similarly to this:

$form['#validate'][] = 'mymodule_someform_custom_validation';
$form['#submit'][] = 'mymodule_someform_custom_submission';

In the validation handler you can then validate your custom field data (if needed) and in the submit function you should save it. Small amounts of information can be stored in a variable, but if there's bigger amounts of data from different users you'll probably want to create a custom database table where to store all the information in.


How to add twitter tracking code to a Drupal site? Twitter now creates code to track visits to your site from twitter.  https://support.twitter.com/articles/20170807-conversion-tracking-for-websites#

Where would be the best place to put this code, into a template? is there a module for this like there is for google analytics?

The proper way is to use hook_page_alter() in your template.php or a custom module. But there's also a module out there to accomplish this task:

Take a look at the module Tracking Code. It allows you to inject arbitrary code inside <HEAD>, after <BODY> or before </BODY>.


Converting a timestamp to PHP date format for a field in a node template I have an imagefield, 'event_image' and printing all possible variables for the field tells me I have timestamp as a possible variable of the image to render. I use:

print '<pre>';
var_dump(get_defined_vars());
print '</pre>

// renders:
["timestamp"]=>
string(10) "1348629688"

... in node--mycustom.tpl.php to get the variables.

Now I can render the timestamp as such:

<?php print $node->field_event_image['und'][0]['timestamp'] ?>

... and it prints a UNIX formatted timestamp as:

1348629688

I'd like to convert this to a PHP date format. So I am guessing I would need to convert the UNIX timestamp somehow using the PHP gmdate function. Typically I would use something like this for raw php:

  $mytimestamp=1348629688;
  print gmdate("m-d-Y", $mytimestamp);

Which would take my timestamp and output:

09-26-2012

... but I just don't know how to do within the context of my drupal 7 field and the node template.

UPDATE:

Base on clive's comment below, it turns out a preprocess function is the way to go:
So in my theme's template.php file I now have:

function MYTHEME_preprocess_node(&$vars, $hook) {

$node = $vars['node'];
$field_items = field_get_items('node', $node, 'field_event_image');
$vars['upload_date'] = format_date($field_items[0]['timestamp'], 'mdy');

}

... and then in my custom node template, I have:

<?php print $upload_date; ?>

Note, 'mdy' is a custom format I set in the Drupal UI. That's better than using gmdate I suppose.

As already pointed out by  Mohammed Shameem:

<?php print gmdate("m-d-Y", $node->field_event_image['und'][0]['timestamp']) ?>

However, the Drupal way would be:

<?php print format_date($node->field_event_image['und'][0]['timestamp'], 'short'); ?>

The latter construct will render the date in the standard short date format set up for the site.  The former will use the format you pick.  The Drupal way ensures that the date format is standardized throughout the site.


Filter content type by media type I have a content type that has a media field that can contain audio, video or image, I created  a view and I want to filter the view depending on the media type is that possible using Drupal views or do I need to make custom code for this

You can add more info about the referenced Media in your content Views through a Relationship for that Media field.
Add the Relationship (under Advanced Views settings) called something like Media referenced from field_mixed_media under the Content Category.
You can Require it if you only want to see nodes that have that Field filled in (not empty).
Once you add that Relationship you will see more options when adding new Fields and Filters.
In your case you'll want to add the Filter Media type from the Media Category, it will use the Relationship by default, and Expose it.
The Exposed filter will show as a drop-down select list. If you want it display as checkboxes you can use the Better Exposed Filters module.


"Place block" ajax error when using nginx I'm having a lot of trouble configuring nginx properly for Drupal 8. Using the Drupal nginx recipe on the official site works well except for opening modal dialogs like the "Place block" dialog. This results in a 200OK response but an ajax error.

Here is a gist with the error.

I know this is an nginx configuration issue as I have a different conf file that doesn't cause this issue. This other configuration doesn't work with Drupal 8's active link javascript due to the way it adds the query parameters. Frustrating!

Sometimes writing it down helps to figure things out! The missing bit of configuration needed is fastcgi_param QUERY_STRING $query_string;

With the Drupal nginx recipe but with that line added in the location ~ '\.php$|^/update.php' { block its now working as expected, both the is-active class is added to the active menu link and the "Place block" ajax works properly.


Is there anywhere a good writeup on Drupal directory structure? I wonder if there is a good writeup on Drupal directory structure?

I haven't seen one, so let's start a list right here. In Drupal 5, 6 and 7 the structure looks like this:

includes - include files with php functions and classes that make up the Drupal API
misc - miscellaneous assets like javascript files and images
modules - Drupal core modules (not meant for contrib and custom modules)
profiles - installation profiles
scripts - shell scripts for developers and administrators
sites - all files that are added by a developer to create a site

sites/all/libraries - 3rd party libraries, eg. a wysiwyg editor
sites/all/modules - contributed and custom modules
sites/all/themes - contributed and custom (sub)themes
sites/default - contains the default settings.php
sites/default/files - the default directory for user-uploaded files
sites/example.com/modules - the site-specific modules directory in a multisite structure
sites/example.com/themes - the site-specific themes directory in a multisite structure
sites/example.com/files - the site-specific directory for user-uploaded files in a multisite structure

themes - Drupal core themes


How to disable status messages? I am creating/updating terms and nodes dynamically using code. It shows a lot of status message as usual. But I need to hide those message only for this task. That means if any user creates/updates terms or nodes it will show the status message.

How can I do that? Please note that the task will run by cron, so a lot of status massage will be stacked for display. Obviously nobody wants to be the poor person to see the huge list of status messages.

take a look to Disable Messages module http://drupal.org/project/disable_messages I think that could be useful for your needs.

  Features

* Filter out messages that match a full text string exactly.
* Filter out messages that match a regular expression.
* Permissions to specifically hide all messages of a given type from any role.
* Disable all filtering for specific users.
* Disable all filtering for specific paths.
* Apply filtering only for specific paths.
* Debug system to get messages in the HTML without showing it to the end users.


Adding more variables to menu for use in menu.html.twig I'm attempting to give menus more variables to work with besides the default menu_name,items, and attributes. This is because making a variable in the preprocess menu hook does not allow it to be accessible in the menu.html.twig template.

My ultimate goal is to be able to add menu items that contain the user id in the path.

I believe I need to add the var to menu by using hook_theme_registry_alter and follow the format of https://api.drupal.org/api/drupal/core%21includes%21theme.inc/function/drupal_common_theme/8.2.x

So I attempted to add a variable to menu in my .theme file like so

function mytheme_theme_registry_alter(&$theme_registry){
    $theme_registry['menu']['variables']['test_var'] = 'testing theme registry alter';
}

But when I do so nothing appears when I alter menu.html.twig like so

    {{ menus.menu_links(items, attributes, 0) }}
{#     {% macro menu_links(items, attributes, menu_level) %} #}
    {% macro menu_links(items, attributes, menu_level) %}
    {% import _self as menus %}
    {% if items %}
    {% if menu_level == 0 %}

        {% else %}

            {% endif %}
            {% for item in items %}
                {% if item.below %}

                {% else %}

                {% endif %}
                {{ link(item.title, item.url) }}
                {% if item.below %}
                    {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
                {% endif %}

            {% endfor %}

{{ test_var }}

        {% endif %}
        {% endmacro %}

How would I add more menu variables for use in menu.html.twig ?

UPDATE: I also tried {{menus.test_var}} but that just broke the page

UPDATE 2: Using {{ kint() }} the test_var did not appear anywhere

Here is an example from a real project I had done:
mytheme.theme:
/**
 * Implements hook_theme_registry_alter().
 * @param $theme_registry
 */
function mytheme_theme_registry_alter(&$theme_registry) {
  $theme_registry['menu']['variables']['top_parent'] = [];
}

/**
 * Implements hook_preprocess_block__menu_block().
 * @param $variables
 */
function mytheme_preprocess_block__menu_block(&$variables) {
  // set the top parent on the left nav
  if ($variables['elements']['#id'] == 'left_navigation' && !empty($variables['elements']['content']['#items'])) {
    // code removed

    $variables['content']['#top_parent'] = [
      'title' => $menu_content->getTitle(),
      'url' => $menu_content->getUrlObject(),
      'is_current' => ($current_path == $item_path)
    ];
  }

  // code removed
  }
}

In Twig:
  {% if menu_level == 0 %}
    <li class="left-nav__item active-trail is-active {% if top_parent.is_current %}is-current{% endif %}">
      {{ link(top_parent.title, top_parent.url) }}
    </li>
  {% endif %}

You are likely missing the part where you add test_var key to the content array:
$variables['content']['#test_var'] = "whatever";
With exception to flagging is-current, it looks like you're trying to do the same thing I did. You should strive to use the link function in Twig instead of a hard coded anchor unless there is no way around it.


Rendering field groups (not individual fields) I am using Field Group to group my fields. Purpose of this is to have better control when rendering them inside the node.tpl.php file. Specifically, I want to designate in the node.tpl.php where in the html document I want specific groups of fields rendered, while sorting fields and designating what fields belong to what group inside the UI.

Do you think Field Group is a good way of achieving this? If grouping fields using Field Group, how do you then render that group in the template file?

Edit: I am steering towards template solutions, avoiding the likes of Panels and DS.

I ended up using hide() on content elements I wanted place independently before print rendering the rest of content. As I have learned the way drupal renders/prints makes this very easy. Example:

<?php hide($content['product:title']); ?>

  <?php print render($content); ?>

  <?php print render($content['product:field_image']); ?>


jQuery.ajax() results in a 403 error I created a custom block and I was trying to use the ajax method of jQuery, but it seems that whenever I access the method of the controller, it returns a 403 error.

This is my contoller (custom_blocks/src/Controller/CustomBlocksController.php)

namespace Drupal\custom_blocks\Controller;
use Drupal\Core\Controller\ControllerBase;

class CustomBlocksController extends ControllerBase
{
  // $variable is the wildcard from the route
  public function ajaxCallback($variable)
  {
    return ucwords($variable);
  }
}

This is my routing file (custom_blocks/custom_blocks.routing.yml).

my.route:
  path: '/sample-page/{variable}'
  _defaults:
    _controller: 'Drupal\custom_blocks\Controller\CustomBlocksController::ajaxCallback'
    _permission: 'access content'
    _access: 'TRUE'

This is my custom JavaScript code (custom_blocks/js/command.js).

(function($, Drupal) {
     $('#custom-button').click(function(){
        var name = 'john doe';
        $.ajax({
             type : "POST",
             url: '/sample-page/' + name,
             success : function(response){
                  console.log(response);
             },
        }, 'html');
     });
})(jQuery, Drupal);

Hope someone can help me.

That's because by default Drupal only allows GET request on default controllers. In your case you should create a custom resource.

Using resources has multiple advantages:

No custom paths per request method
Access control
CSRF protection
Using the API that the REST module in Drupal 8 provides

It basically comes down to creating a class with an annotation:

             /**
              * @RestResource(
              *   id = "my_resource",
              *   label = @Translation("Resource label"),
              *   uri_paths = {
              *     "canonical" = "/sample-page"
              *   }
              * )
              */
             class CustomResource extends ResourceBase {
                public function post($data) {
                  // Do stuff with the posted data.
                }
             }

Some more elaborate examples:

Example one

Example two

You will have to alter your jQuery POST request to something like:

 $.ajax({
         type : "POST",
         url: '/sample-page/',
         data: {'uid':2},
         success : function(response){
              console.log(response);
         },
    });

The data you post in your jQuery request will be available in $data of your resource class.


using theme_menu_link() I am currently using theme_menu_link() but it themes every menu in Drupal. I only want to theme my main menu. How can I check for a specific menu?

function theme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

//if(id == main_menu){ theme it different }

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }
  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '<li' . drupal_attributes($element['#attributes']) . '>' . $output . $sub_menu . "</li>\n";

}

You can get the ID of a menu by looking at the URL when you edit it in the menu configuration admin interface and converting dashes to underscores.

For example, on admin/structure/menu if I hover 'User Menu' I see admin/structure/menu/manage/user-menu/edit which means that the menu machine name is 'user_menu'.

The $element contains the menu's id: $element['#original_link']['menu_name'].

So you can put that in your if() and get

if($element['#original_link']['menu_name'] == 'user_menu') {
  ...
}

where you replace 'user_menu' with the name of the menu you want.


How can I insert many field values under one term? I'm working on a module, of which one function is grab list names and stock codes from a custom table and create corresponding terms. Now, my current code creates a new term and corresponding stock code, however this is not very efficient. How can I create one term for each unique list name and create corresponding many field values? Below is my current code:

function liste() {
    $src = ['Ý', 'Þ', 'ý', 'þ', 'ð'];
    $tar = ['İ', 'Ş', 'ı', 'ş', 'ğ'];
    $query = \Drupal::database()->select("excel","m")->fields("m",["stokkodu","grupadi"])->condition("grupadi", "","!=")->execute()->fetchAll();
    foreach ($query as $q) {
        $term = Term::create([
            'vid' => 'liste_adi',
            'name' => str_replace($src, $tar, $q->grupadi),
            'field_stok_kodu' => $q->stokkodu,
        ]);
        $term->enforceIsNew();
        $term->save();
    }
}

I thought about selecting only grupadi and grouping by it and inserting to a temporary table and then inserting corresponding stock codes in another column delimited with comma or something; but if there is another more efficient way, please let me know. EDIT: I'm looking to do something like the following:

Current:

| Manyetik Matkaplar?n Yedek Par�alar?                                                | YMD2299001      |
| Manyetik Matkaplar?n Yedek Par�alar?                                                | YMD2299002      |
| Manyetik Matkaplar?n Yedek Par�alar?                                                | YMD2299003      |
| Manyetik Matkaplar?n Yedek Par�alar?                                                | YMD2299004      |
| Manyetik Matkaplar?n Yedek Par�alar?                                                | YMD2299005      |
| Manyetik Matkaplar?n Yedek Par�alar?                                                | YMD2303001      |
| Manyetik Matkaplar?n Yedek Par�alar?                                                | YMD2303002      |
| Manyetik Matkaplar?n Yedek Par�alar?                                                | YMD2303003      |
| Manyetik Matkaplar?n Yedek Par�alar?                                                | YMD2303004      |
| Manyetik Matkaplar?n Yedek Par�alar?                                                | YMD2303017      |
| Manyetik Matkaplar?n Yedek Par�alar?                                                | YMD2303022      |
| Manyetik Matkaplar?n Yedek Par�alar?                                                | YMD2303046      |
| Manyetik Matkaplar?n Yedek Par�alar?                                                | YMD2601044      |
| Manyetik Matkaplar?n Yedek Par�alar?                                                | YMD2608020      |
+-------------------------------------------------------------------------------------+-----------------+

Desired:

| Manyetik Matkaplar?n Yedek Par�alar?                                                | YMD2299001,YMD2299002,YMD2299003

I hope you get the idea.

You needn't have to do aggregation via temporary tables, it can be done in your query via a GROUP_CONCAT expression & GROUP clause:

$query = \Drupal::database()->select("excel","m")->fields("m",["stokkodu","grupadi"])->condition("grupadi", "","!=");
$query->addExpression('GROUP_CONCAT(m.stokkodu)', 'stokkodus');
$query->groupBy('m.grupadi');
$results = $query->execute()->fetchAll();
foreach ($results as $result) {
  $result->stokkodus contains a comma-delimited list of values that you can split with explode()
  $stokkodus = explode(',');
  // @TODO: add transform logic
}

In the example above, you can transform the exploded array then create an array of values for your multivalue field_stok_kodu field:

  // @TODO: add transform logic
  'field_stok_kodu' => [
    ['value' => $stokkodus[0]],
    ['value' => $stokkodus[1]]
  ];


How to add custom user fields to their comments? My users have the following fields: 'Avatar' (image) and 'Year' (number). When a user leaves a comment, I'd like to display these fields, the username and the user's current userpoints next to each other on top of the comment. The end result should look something like this:

The fields shouldn't be updated: when they change in the future, they should maintain the value they had at the moment the comment was posted.
How can I achieve this?

I haven't tried this out for sure, so this is kinda just spit balling, but the way I would do this would be to write a small little custom module. So, example:

You could have the date/avatar field stored as a field in the user table. Then in the comments, add both a date/avatar flied to the comment (under /admin/structure/types/manage/[node type]/comment/fields). So now you would have to two places to save the info.

To hook them up, I would write a custom module that uses hook_comment_presave to intercept the date and avatar field before the comment is saved, load the user info from the commenting user, and then replace the comment date/avatar from the user date/avatar. That way, the information that was with the user at the point of commenting will be forever with the comment.

You will of course need to theme it, and you will need to hid those comment fields from the user in the comment form. Your also gonna want to make sure the avatar is persistent, but I think this should be a workable solution. At least, that's where I would start.


'Could not find the alias' error after installing drush alias for Pantheon I'm attempting to get the drush alias to work with Pantheon, but when I try to run drush @pantheon.mysite.dev status I get Could not find the alias @pantheon.mysite.dev.

I've already installed the aliases by running terminus aliases, but it doesn't seem to be seeing the generated file. I did go in manually to confirm that the alias file was placed inside of the .drush directory.

When I run drush sa, I get the following:

@none
@self
default

I did recently installed drush 9 on my Drupal 8 sites, but I still have a number of Drupal 7 sites running an older version of drush. I understand that the directory structure for drush 9 is different. Do I need to install the aliases for it somewhere else?

Just so you're aware. I installed drush 9 via composer, and I'm using the drush launcher which lives in my bin directory.

If you already have terminus installed, you can use terminus drush instead of your local drush.

The advantage of terminus drush is that it already has everything you need to work with Pantheon.

The disadvantage is that you will have to do some work to set it up with your local dev environment; for that, I would just use your local drush.

So, the workflow looks like this:

Do I need to call a drush command on Pantheon? terminus drush
Do I need to call a drush command on my local dev server? drush


How do I install a 3rd party PHP library in sites/all/libraries - can I just plonk it in there? For example, according to the Drupal module s3fs, I can -- to quote their README.txt :-

  2b) If you don't have drush, go to to
  http://aws.amazon.com/sdk-for-php and click the orange "AWS SDK for
  PHP" button. On the page you're sent to, click the "aws.zip" link.
  Extract that zip file into your Drupal site's
  sites/all/libraries/awssdk2 folder such that the path to
  aws-autoloader.php is sites/all/libraries/awssdk2/aws-autoloader.php

So, yeah, that's effectively: downloading the library, and plonking it sites/all/libraries and that's it. But it doesn't work! I get:

  Unable to load the AWS SDK. Please ensure that the awssdk2 library is
  installed correctly.

I've tried everything else in the README.txt : drush installer, specific version of AWS SDK, permissions...

How do I install a 3rd party PHP library in sites/all/libraries - can
  I just plonk it in there?

Answer:
- It would appear you can, in some cases at least. With the example given the question, the problem was not whether or not a 3rd party php library could be just placed in the libraries folder, but rather some other unrelated issues that appear now to be resolved (the s3fs module make, coredumperror was very responsive today in helping me and they have updated their documentation). https://www.drupal.org/node/2596683#comment-10467823

Update

The "unrelated issues that appear now to be resolved" are that one of the setup procedures for the s3fs, as described in the README.txt, now work. By 'now work', I mean that I can install the module and do the described setup and use the S3fsStreamWrapper class provided with the module to read a file from an Amazon S3 bucket, more detail here https://www.drupal.org/node/2596683#comment-10467823 I had tried other approaches to reading S3 in Drupal, e.g. using examples elsewhere but was unsuccessful with those. But with this s3fs module I am now successful. With the s3fs module I had originally ran into issues whereby I got the aforementioned "Unable to load the AWS SDK. Please ensure that the awssdk2 library is installed correctly." error as stated in my question. But one of the maintainers of s3fs, coredumperror replied and updated the documentation as they discovered it had errors. So thanks very much to coredumperror on that, most appreciated. They have described what they changed in the above link. With this setup documentation updated and corrected, I was then able to use the s3fs module and read from a S3 file using the S3fsStreamWrapper provided with the module.


Where is the node created timestamp stored in the database? I need to create an SQL query that finds all nodes of a certain type created X days ago, so I can get their IDs. Due to the massive number of nodes in the database, I would prefer to use a direct SQL query, rather than entityQuery. I was warned entityQuery can be slow if working with large volumes of data.

Anyway, I need to find where is the node created timestamp stored in the database. In Drupal 7, it is stored directly in the node table, but not in Drupal 8.

The created date is stored in the node_field_data table as a UNIX timestamp in a cloumn called created.

Here's the code you would use to fetch the nodes that has been created X days ago, using a direct select query.

$day = 86400; // One day in seconds.
$days = 3; // The amount of days ago to fetch from.

$nids = \Drupal::database()->select('node_field_data', 'n')
  ->addField('n', 'nid')
  ->condition('n.created', \Drupal::time()->getCurrentTime() - $days * $day, '>')
  ->execute()
  ->fetchField();

$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);

Make sure to inject the database and the entity_type.manager services (if possible) when implementing the code yourself.


Creating muliple nodes from one page I want to create multiple nodes from one page where I input one or two values into each entity, where each of the entities has a reference.

Example:
If I had three kids, I would measure their height each week, entity types "kid" and "height". Height references to kid and instead of click add "height" three times and select which kid then input height, I would like to have a page with the names (or ID) of the kids, then one input field for each, so that when I save, three entities of height are created with the values specified.

There are a couple of modules to create entities (nodes etc) inline i.e in the parent form, when it's being created itself.

When you save the form, it creates the entity AND the entities that are referencing it, but it's up to you to create the entity structure and references to achieve what you want.

I can vouch for References Dialog

However, I think you are making it too complex and you only really want one node type (kids) with an unlimited field (height), if that is your real scenario.

For example you easily create a custom form with three (or loop for x) fields and when it saves it adds the result to existing nodes, eg :

// Get and render the form somewhere.
$form = drupal_get_form('kids_height_form');
print render($form);

/**
 * Form constructor.
 */
function kids_height_form() {
  $kids = array(2210, 2043, 2038);
  $entities = entity_load('node', $kids);
  // dpm($entities);
  foreach ($entities as $kid) {
    $id = $kid->nid;
    $form["height_$id"] = array(
      '#title' => 'Height this week for $id',
      '#type'  => 'textfield',
    );
  }
  $form['submit'] = array(
    '#type'  => 'submit',
    '#value' => 'Submit',
  );
  return $form;
}

/**
 * Form submit handler for kids_height_form().
 */
function kids_height_form_submit($form, &$form_state) {
  $kids = array(1, 2, 3);
  $entities = entity_load('node', $kids);
  foreach ($entities as $kid) {
    $id     = $kid->entity_id;
    $height = $form_state['values']["height_$id"];
    $count  = count($kid->field_height[LANGUAGE_NONE]);
    $kid->field_height[LANGUAGE_NONE][$count + 1] = array('value' => $height);
    entity_save('node', $kid);
  }
}

The top bit prints the form, the form constructor simply create as many text fields as there are node ids in the array and the submit handler does the same loop except also adds the result to a new delta for the height field and saves the entity.

You can also achieve this with EntityMetaWrappers and may be a bit neater but the process is very similar. (this is untested by the way and will need work to suit your needs);


How can I change the items order in a pulldown list of filter in views? Hello Drupal community.

I have a question about Views.
I have a “People” view with a role filter and the pulldown list for this filter look like this:

Administrator
Editor
Approver

I would like to know if it is possible to change the order of items in the pulldown list to make it look, for example, like this:

Administrator
Approver
Editor

Thank you.

I guess you could probably change the roles order in People>Permissions>Roles (simple drag and drop) and the Views filter will use it by default.


Custom form which on submit click inserts into the database I have created a custom form in my module so that when the user clicks submit, some changes are performed in the databases and other actions follow. The form is an empty form with only the submit button nothing else. When the user clicks the Submit button, a function is called to perform some tasks. However, I am getting some errors. Here's the code:

My module folder is formtest and is placed in sites/all/modules/

formtest.info

name = Test Form
description = Accept Challenge Form Submit
core = 7.x

formtest.module

function formtest_menu() {
$items['formtest'] = array(
'title' => 'Accept Challenge',
'page callback' => 'drupal_get_form',
'page arguments' => array('formtest_form'),
'access callback' => TRUE,
);
return $items;
}

function formtest_form($form,&$form_state) {
  $form['button'] = array(
  '#type' => 'submit',
  '#value' => 'Accept Challenge',
  '#submit' => array('formtest_action'),
   );
  return $form;
}

function formtest_action($form,&$form_state) {
  $query = db_insert('challenges')
    ->fields(array(
    'cid' => '$node->nid',
    'uid' => '$user->uid'
    ))
   ->execute();
}

/**
    * To display the form on a particular content type
    */

function formtest_node_view($node, $view_mode = 'full', $langcode = NULL) {
      if($view_mode == 'full') {
        if($node->type == 'challenge') {
          $node->content['my_form'] = array(
            '#markup' => drupal_get_form('formtest'),
            '#weight' => 1,
         );
     }
   }
  }

Well that's all. There's no form showing up..no error messages..nothing...I tried a var_dump() but nothing...That custom content page is displaying as it was but there seems to be no effect of this code. Would appreciate your help in any manner. Thanks

drupal_get_form doesn't return a markup as such. it returns an array of the form structure. to get the html out put you should run the drupal_render function.

something like drupal_render(drupal_get_form('formtest');


How to change or influence the block id and class of a view block I have a view with 2 blocks. One was cloned from the other.
I changed the machine readable name of both of the blocks (block_events_upcoming and block_events_upcoming_ical), but in the html i get as id and classes the beautys you see below.

<div id="block-views-d7410a6d5618e2d319a0eaab549b0ff2"
     class="block block--views
            contextual-links-region
            block--views-d7410a6d5618e2d319a0eaab549b0ff2">

Is there a way to change the ids and classes of the block. The css-class option in advanced settings only changes the css class in the block_content div not the top block-div.

The HTML ID is generated by concatenating block-view_name-block_name and
it seems there's a length limit of 32 characters. My block exceeded that limit.
So for me the solution was to shorten the block-machine-name.


Filter is Stripping URL with custom scheme There are times we are using custom schemes for URLs and storing them in Drupal 6.

The href attribute values are getting stored in the db properly.

So,

gets stored as it's written. However, when viewing the page the unknown scheme gets stripped so it outputs:

I've disabled all filters in the full HTML input format and have returned out of my hook_nodeapi function in my custom module, and disabled the WYSIWIG, and still the scheme gets stripped.

Any ideas where this might be happening?

I wouldn't recommend hacking the HTML filter in core. If you want you could copy/modify it into your own module and create your own filter, here is a link to a blog post that should help get your started.

Or you could try one of the contrib packages like Custom Filter.


Is it possible to run drush 8 smoothly on Win10 WSL (Windows Subystem for Linux)? As most here know, Microsoft and Canonical worked together to develop a Windows-included Linux-based, Ubuntu-oriented compatibility layer (WSL) and already gives the option to install it for all Windows users. One can now use BASH on his Win10 machine, via CMD or Powershell.

My question is, can it be used to run drush 8 (drush master) smoothly ? I ask since as most of you know, drush 8 / master doesn't run smooth on a Win-only environment.

Till now I ran drush 8 / master on an Ubuntu virtual machine but I wonder if it's possible to run it on Win10 using the new WSL release.

With my very basic OS knowledge, I can't strictly determine if having Bash and Ubuntu binaries in Windows is actually enough to run drush 8 / master smoothly on Win10, or, if something extra is needed and has not yet been released.
I don't know how to integrate the WSL with WAMP/Xampp as well as with the c:/drush folder (or even is these things are even possible), or maybe making some environment variable to anywhere would be enough.

By the way, there is now a new Facebook group for supporting new WSL users in general:

https://www.facebook.com/groups/987976957946948/

We haven't tried this yet. Please give it a spin, and report your results in the issue queue.

Note also that if you want the dev branch of Drush 8, you should use the 8.x branch.  The master branch is now Drush 9.


How to disable auto create customer profile after edit order? When I edit order (at url admin/commerce/orders/1/edit) and save order, a new custom profile will be created. I don't want that. How can I disable that?

This is happening because the inline customer profile form has the country selected, which is all that's required for a field value to be present. I believe we should add a fix to Drupal Commerce core to prevent this, but I don't know off the top of my head if there's already an issue in the queue for it. Feel free to search at https://www.drupal.org/project/issues/commerce and file an issue if you don't see it already. Thanks!


How to find a mails $mailkey I'm trying to theme a couple of different mails generated by notifications using the mimemail module. Is there a reliable method to find a mails mailkey for use in a template?

The easiest way to check the mailkey is if you look at the source code of the mail you received. The body-tag has a class with the mailkey. At least if you use the default template.


Make custom textfield autocomplete compatible with slashes? I have a form which uses a textfield with a custom autocomplete path and it works just as it should. However, I get some unexpected behavior when the title/search string contains a backslash (e.g. '10/07/2016 Meeting').

After some investigation I realized that Drupal seems to interpret those as 4 separate parameters with only the first (in this case 10) being passed to the autocomplete function.  I'm not sure how I can prevent this behaviour as the passing of the string to the form is handled internally by Drupal via the '#autocomplete_path' on the textfield itself.

I checked how entity reference handled this, but it is using an entirely custom field and not the '#autocomplete_path' on a regular textfield and wasn't of much use to me.

However it would seem odd to me that the textfield autocomplete shouldn't be able to support search strings with slashes - I just can't find out how to hook into the Drupal form to encode the string somehow.

How can I make my autocomplete field compatible with slashes?

Take a cue from the Drupal core's taxonomy autocomplete implementation and just recombine the arguments passed into callback function back into one string:

function taxonomy_autocomplete($field_name = '', $tags_typed = '') {

  // If the request has a '/' in the search text, then the menu system will have
  // split it into multiple arguments, recover the intended $tags_typed.
  $args = func_get_args();
  // Shift off the $field_name argument.
  array_shift($args);
  $tags_typed = implode('/', $args);


Media Gallery module field settings stored in database? I have installed the Media Gallery module for someone's site to upload fotoalbums with; it's need to add a file size restriction because quite a bit of pictures are coming in.
I can't tell what the exact error is in English; the site's language is Dutch. When I want to edit fields in my Media Gallery content type, I get a message that says the settings are stored in the database, locked and I can't change those settings anymore.

Update: There is a similar issue at Drupal.org; it looks like it isn't possible. Or is it?

You can make the 'dirty solution' from the link posted by @NikhilMohan into a more 'clean' one pretty easily:

function MYMODULE_form_media_gallery_node_form_alter(&$form, &$form_state) {
  if (arg(1) == 'add') {
    // Get the language code from the node object. Should be reliable.
    $langcode = $form['#node']->language;

    $form['settings_wrapper']['presentation']['media_gallery_allow_download'][$langcode]['#default_value'] = 0;
  }
}

If you're not comfortable writing a custom module you can easily drop this function into your theme's template.php file instead, but change the name of the function to MYTHEME_form_media_gallery_node_form_alter. Once you clear Drupal's caches the hook will start to be called.

Don't forget that Media Gallery is still in beta so you have to expect a few bugs/missing configuration options. Using hooks to alter the fields you need to is pretty much the only option you have here, without going directly into the database.


"This page was last modified on" code not displaying I added the following code to my node.topl.php but nothing is displaying on my site. What am I missing?

<?php
if ($submitted) {
  echo 'This page was last modified on ' . date( "F j, Y",$node->changed);
} ;
?>

Perhaps that content type has "submitted by" information hidden.

Try just:

print 'This page was last modified on ' . date('F j, Y', $node->changed);

And clear cache at Admin > Config > Performance


Embed video code from third party providers I want embed video to my node, module "Embedded Media Field" do this for some third party providers, but I want embed videos from Aparat which not supported by emfield. is there any other solution?

I looked at the embed code from aparat and it reminded me of Slideshare's code. I tested it by entering its embed code the same way I do with Slideshare (copying the embed code into a non-rich text editing window) and it worked.

As with Slideshare, sometimes the video doesn't appear even after loading. The fix if that happens  is to refresh. It will show the second time.


Assign a node to an organic group Programmatically assign a node to an organic group is following my previous question which I have found the solution for Drupal 7, but I am now looking for the same issue in Drupal 6.

How can I programmatically assign a node to an organic group?

I have tried the following and neither of them worked (assuming $target_group is the group ID that I want the $node to be assigned to).

$node->og_groups = array($target_group => $target_group);
node_save($node);

$group = node_load($target_group);
$node->og_groups[0] = $target_group;
$node->og_groups_names[0] = $group->title;

What is the proper way to do this?

You're on the right track.
You also have to add a row to the og_ancestry table. Someone posted sample code for Drupal 6 here.

/**
 * Implementation of hook_nodeapi().
 */
function mymodule_nodeapi(&$node, $op, $arg, $page) {
  switch ($op) {
    case 'insert':
      // let's autocreate a Wiki node for our Top wiki page when we create a Group
      if ($node->type == "group") {
        global $user;
        include_once (drupal_get_path('module', 'pathauto') .'/pathauto.inc');
        $path = pathauto_cleanstring($node->title);

        $wiki->type = "wiki";
        $wiki->status = 1;
        $wiki->uid = $user->uid;
        $wiki->name = $user->name;

        $wiki->title = $node->title . " Wiki";
        $wiki->body = t("This is the Wiki for your Community. Any member is allowed to edit this page. Be the first to edit this page by selecting the EDIT tab above and deleting this content and replacing it with your own.");
        $wiki->path = "wiki/" . $path;
        $wiki->og_initial_groups[0][$node->nid];
        $wiki->og_groups[0] = $node->nid;
        $wiki->og_public = 0;
        $wiki->og_groups_names[0] = $node->title;

        if ($wiki = node_submit($wiki)) {
          node_save($wiki);
          $sql = "INSERT INTO {og_ancestry} (nid, group_nid) VALUES (%d, %d)";
          db_query($sql, $wiki->nid, $node->nid);
        }
      }

      break;
  }
}


Remove attribute ID from site-logo (Panels Page Elements) I use a module panels everywhere with Omega 4. I try to put a site-logo in header and footer but Logo Page Element from Panels takes site-logo and render it with ID. So I have same ID twice in my page.

Header

Footer

How I can remove ID or render element with my markup?
How I can create own element for panels?

Thank you

This logo is created in ctools_page_logo_content_type_render function. Unfortunately we can't alter code of this function.
As a solution you may create your custom Ctools content type plugin, that will return logo without 'id' attribute. You can find more information about Ctools plugins here.


Why is my javascript not being executed? I have a Drupal 8 form and I'm applying some custom javascript to it. I've added a JS file, and a libraries file for my module containing a reference to it, but the code doesn't run.

in module_name/js/autocomplete.js

(function ($, Drupal, drupalSettings) {

  Drupal.behaviors.modulename_autocomplete = {
    attach: function (context, settings) {

      jQuery(function() {
        // Doesn't work
        console.log('foo');

        // Doesn't work
        alert('bar');

      });
    }
  };
})(jQuery, Drupal, drupalSettings);

and in module_name.libraries.yml

module_name.autocomplete:
  version: 1.0
  js:
    js/autocomplete.js: {}
  dependencies:
    - core/jquery
    - core/jquery.ui.autocomplete

As the comments suggest, I see no console messages and no alert, so it's clear the behavior is not being executed.

What do I need to change for this to work?

You don't attach your to your form:

$form['#attached']['library'][] = 'module_name/library_name';

Just a suggestion:

In your library yml it's unnecessary to append your module name to your library name.


How do you add a form to a content type? I have a view that had a list of equipment.  Each equipment node in the view needs a form so I can upload equipment drawings.  I would like the form to belong to the node because it makes it easier for submission to understand it's context.  Is there any way to do this?

I have webforms installed and I can create a webform for each node individually, but for some reason I can't find a way to add a webform for the content type.

Thanks!

If you are ok with custom code.

The form does not need to be inline to Content Type.
Consider this example
You have custom form. form builder of which takes an argument as nid.

function custom_form_builder($form, &$form_state, $nid) {
   $form['nid'] = array(
     '#type' => 'hidden',
     '#value' => $nid,
   );
  // form field goes here.
}
Now in your view add nid field along with other fields you need and an extra custom field.
In your views you can define custom template for custom field.
Implement template_preprocess_views_view() to call drupal_get_form('form_id',$nid) and make it available on the custom template.
Print the form on the template.
Now when the custom form gets submit you can get the nid to update in $form_state['values']['nid'].


how to change teaser display output via views I have a view that is displaying teasers of a content type. I would like to change order of one of the fields to come AFTER node links, any pointers?

Thanks.

Download and enable Display Suite module.

Then go to /admin/structure/types/manage/{content-type}/display/teaser and select layout of your choice.

Then add the links feature to the region of your choice


Add custom form to panels? How can I add a custom form to a Panels page in Drupal 7?

return drupal_get_form('my_custom_form');

I would prefer not to use the PHP input filter if possible.

Create a custom module that defines a block with that form as the content. You can then place that block anywhere on your site using the standard Drupal interfaces (blocks configuration, Panels, Context, etc.).

There are many readily available resources on creating custom modules that define blocks. The Drupal.org Module Developer's guide is a great place to start, as well as the Examples module, which includes a sample module for defining blocks that can be easily copied and customized.


Show specific submenu and mark specific item as active when front page or specific node type is opened My front page is basically a view that lists teasers of node type article. How can I show a specific submenu and mark one item in this submenu as active (+ its parent) when

1) the front page is opened or

2) any article is opened?

I know 2) can be done with the module "Context Active Trail" and "Context UI", but I want to do it without a module and I think the module can't do 1) anyway.

So finally I used the Menu Position Module, which works perfectly.


How to print correct path to file in .tpl.php? <img src="<?php print($base_path . drupal_get_path('theme', 'bartik')); ?>images/some-image.png">

The above code works only if you're in the homepage. If you go to any inner page, it looks for image inside the current URL, not just base URL.

So, it prints the image if you're under www.address.com but if you're under www.address.com/page, it doesn't print the image, because now it's looking for it inside e.g. www.address.com/page/sites/all/themes/bartik/images/some-image.png the problem is, it includes the /page/ part.

In source, the image URL doesn't include the full path (which is the problem I believe?), only the sites/all/themes/bartik/images/some-image.png part.

It appears $base_path is empty, which would suggest your code isn't in page.tpl.php (where that var is commonly available, having been added in template_preprocess_page()).

To make it available to your current template, implement a preprocess hook like the following, which is for a region.tpl.php template file:

function MYTHEME_preprocess_region(&$vars) {
  $vars['base_path'] = base_path();
}


How to call module function in template file? I have one custom function in .module file. Need to call that function .template file. Below is my code snnipet:

function non_login_preprocess_page(&$vars) {

  if(module_exists('test') && function_exists('test_get_rnd_data')){
    $vars['rnd_data'] = test_get_rnd_data();
    print_r("callled"); exit;
  }
}

the function exists does not return true. Is anything thing missing?

Please try bellow code and use module_load_include() function.

function non_login_preprocess_page(&$vars) {

  module_load_include('module', 'module', 'test');   // **add this line**

  if(module_exists('test') && function_exists('test_get_rnd_data')){
    $vars['rnd_data'] = test_get_rnd_data();
    print_r("callled"); exit;
  }
}


Linking to another website procedurally Hopefully this is a straightforward question.

I'm procedurally building nodes as I walk an XML feed, and am importing them into a production server.  I'm having issues importing node aliases, so I thought I could simply create links to the nodes as they will be on production (pathauto will take care of auto-aliasing them).

When I fill the href attribute of my link, instead of pointing to my website it points to my local server (it seems to be auto-changing my link).

I'm building my link like this:

$link = 'http://example.com/content/' . $current_node['name'];
$name = $current_node['name'];

and then assigning in my string

$output = "" . $name . "":

However, as I mentioned, it ends up pointing local instead of direct to my outside node.

If you're creating links, use l().

$url = 'http://example.com/content/' . $current_node['name'];
$output = l($current_node['name'], $url, array('external' => TRUE));


How can I save/load my Entity from a different database in Drupal 8? For a custom Drupal 8 module I am integrating data from a separate database (other than the default drupal database) by defining a new Drupal entity in my module.

How can I configure my Entity class (or an EntityStorage class?!) to get the data of this entity from a different database?
Can I change the injected (?) Database Connection object from which the entity is queried?

My question is similar to Drupal entity from different database dealing with Drupal 7. However, I think Drupal 8 has some different approaches.

Note: This other database is currently running on the same server.

At least if the "external" database is on the same server, there is an easy solution. The base_table of an entity can refer to a different database using . as a separator.

Just adapt the EntityType annotation in the comment above your Entity class. The following example uses the table myentity_table from the my_database database for this Entity's data:

@ContentEntityType(
 *   id = "myentity",
 *   base_table = "my_database.myentity_table",
 *   [...]
 * )


How to get menu title inside menu--main.html.twig file I created a suggestion for menu and using menu--main-sidebar.html to render menu.

I want to include menu title (title of block added to specific region from admin side) as first child of menu

I tried to use configuration (configuration.label shows menu title in block--menu-block--main.html.twig file) like below

{{ menus.menu_links(items, attributes, menu_level, menu_name, configuration) }}

That does not work.

So, how to get the menu title inside menu_links in menu--main.html.twig file?

You could try using the Simplify Menu module (which extends twig to support direct access to Drupal's menus for overriding markup).

See the example in this related thread: https://drupal.stackexchange.com/a/228982/79832


Autocomplete on "Unlimited" text field? I'm adding Drupal's built in Autocomplete functionality using hook_form_alter to set the #autocomplete_path like so:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  ...
  $form['field_company']['und'][0]['value']['#autocomplete_path'] = 'autocomplete/company';
  ...
}

This works perfectly for a text field where the number of values is 1, but doesn't work when the number of values is unlimited. I'm assuming this has something to do with the field be added via Javascript. Is there another hook I can tap in to in order to add the #autocomplete_path?

EDIT : Drupal 6.

You have to iterate your field's delta ; here, you only affect $form['field_company']['und']__[0]__, not  $form['field_company']['und']__[n]__

Stay in your hook_form_alter but iterate it each time your $form is rebuild :

    foreach($form['field_company']['und'] as $delta => $field) {
        if(is_array($field) && is_numeric($delta)) {
            $form['field_company']['und'][$delta]['value']['#autocomplete_path'] = 'autocomplete/company';
        }
    }


Can't save settings after copying site to new server I just recently copied a Drupal 7 site from one server to another, everything looks like it works fine except that I cannot save any settings.

Here are some other symptoms:

I can't disable or enable modules
Overlay doesn't work
Once I log out, I can't log back in
When trying to log back in with the wrong criteria, I don't get a message about the user/pass being wrong
admin_toolbar doesn't work (except immediately after clearing cache via drush)
Status report doesn't show anything being wrong

I've got varnish running on the server and I'm not quite sure if that would have anything to do with it.

I had to enable Mod Rewrite.
sudo a2enmod rewrite
If you're having this issue, also check that your .htaccess files copied over to the new server (I've wasted countless hours chasing this).


Is it possible to set block weight inside template? I display some blocks using context module and others using template. Is it possible to set block weight inside template?

Block weight is stored in the database. There are functions to change their weight, but templates aren't the place for manipulating database data, that's where you write the HTML out.

If you want to display context blocks in a different order from the blocks in the system UI, use the "Show row weights" link to set a value that's higher/lower than the value in block admin UI.


unsetting css is not working I am trying to unsetting the deafult CSS through a foreach loop, but seems its not working in hook_preprocess_html(&$variables)

here is my code, please have a look.

$arrCSS = drupal_add_css();
          foreach ($arrCSS as $key => $value) {
            unset($arrCSS[$key]['data']);
          }
          $all_css = drupal_add_css();
          print_r($all_css);

CSS should be manipulated using hook_css_alter(), not in an HTML preprocess (where it's too late).

function hook_css_alter(&$css) {
  // Remove defaults.css file.
  unset($css[drupal_get_path('module', 'system') . '/defaults.css']);
}


Cannot create hook_menu subitems with proper position in administrative menu I would like to add an hook_menu item and generate its expandable subitems under ubercart's 'admin/store/' path.

For now I have:

function activit_menu() {

  $items['admin/store/products-fabrics'] = array(
      'title' => 'Látky produktov',
      'access arguments' => array('access administration menu'),
      'type' => MENU_NORMAL_ITEM,
  );

      $items = array_merge($items, activit_generate_products_fabrics_menu_items());

    }

function activit_generate_products_fabrics_menu_items() {

  $products = activit_get_products_with_fabrics();

  $items = array();

  foreach($products as $product) {

    $items['admin/store/products-fabrics/'.$product['nid']] = array(
        'title' => $product['title'],
        'access arguments' => array('access administration menu'),
        'file' => 'd_forms.inc',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('activit_eshop_fabrics_of_products_form'),
        'type' => MENU_LOCAL_ACTION
    );

  }

  return $items;

}

But this code will create both 'products-fabrics' item and all its subitems at the same level in administration menu and 'admin/store/products-fabrics' item is not expendable. After clicking at 'products-fabrics' item you will see the same andimistration page as aftre clicking at 'admin/store' plus the subitems links at the top oft he page. I can hide this page with css an let only the subitems to be visible. But I need to create expandable 'admin/store/products-fabrics' item in order to be able to click directly at 'admin/store/products-fabrics/subitem'.

I was trying all the possible item types but no success. Is there something I am missing?

I think the MENU_LOCAL_ACTION type for your sub-menus is not the good choice.

The Menu item types documentation tell us :

  MENU_LOCAL_ACTION : Menu type -- An action specific to the parent,
  usually rendered as a link.

If you want to have a menu with sub-menus, you need to also define a page call back for it. You can use the system_admin_menu_block_page, witch display a bloc with all the sub-menus links.

// Main menu link
$items['admin/store/products-fabrics'] = array(
    'title' => 'Látky produktov',
    'page callback' => 'system_admin_menu_block_page',
    'access arguments' => array('access administration pages'),
    'file' => 'system.admin.inc',
    'file path' => drupal_get_path('module', 'system'),
    'type' => MENU_NORMAL_ITEM,
);

// Sub menu links
$items['admin/store/products-fabrics/'.$product['nid']] = array(
    'title' => $product['title'],
    'access arguments' => array('access administration menu'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('activit_eshop_fabrics_of_products_form'),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'd_forms.inc',
);


Print taxonomy information based on the link that is clicked Lets say I have a taxonomy called fruits. I have 3 links on my front page and the href-s are:

fruits/bananas
fruits/oranges
fruits/apples

I made a custom module to do this but I am not really sure what to do next...

function mymodyle_menu() {
    $items['fuits/%'] = array(
      'page callback' => 'mymodule_fruits',
      'access callback' => TRUE
    );
    return $items;
  }

  function mymodule_fruits() {
  //what to do?
}

I also have a template file for them. How to do this?

If you just want a custom pattern for the URL then you are better of with Pathauto module

Once you enable the module if you go to Admin -> URL Alias you will get a new TAB Pattern. In that you can define the pattern that you want to give to the taxonomy page. By default it would be [term:vocabulary]/[term:name]

So if your vocabulary name is fruits and your term name is apples then the url will automatically be turned into fruits/apples

After you enable the module you might have to do Bulk Update from URL aliases for the urls to take effect.

If the requirement is to add more information regarding the taxonomy terms or nodes with in the taxonomy term then you should use the views module

If you are simply trying to learn the how things work with in drupal then you should check the examples module it has got all sorts of modules to get you started with.


Hide Profile2 fields depending on it's value when viewing user profile I am relatively new to drupal and for days I'm stuck.

I need to hide fields from the user profile page when they have a specific value. Adding a CSS class would also do it. But I prefer deleting the array element.

I try to use the hook_profile2_view_alter() function in my template php. Sure I can access the field options but not it's value directly.

Perhaps I'm digging in the wrong hole and there is a smooth "Drupal way" to do it.

You'd be better off putting your code in a custom module, as you can implement hook_profile2_view() instead. That will give you far more control over the output.

Without more specifics it's hard to be accurate but generally speaking the code would look something like this:

function MYMODULE_profile2_view($profile, $view_mode, $langcode) {
  $field_items = field_get_items('profile2', $profile, 'field_name_of_field');
  if ($field_items) {
    $value = $field_items[0]['value'];

    if ($value == 'something') {
      $profile->content['field_name_of_field']['#access'] = FALSE;
    }
  }
}


Theme specific form field for custom content type I have created a custom content type and added some fields to it. I want to theme one of the fields which I added from the "Manage Fields" section.

I want to remove the div wrappers when the form field is rendered.

Is there any form field specific theme function which I can override in template.php and make my changes?

If you want to do it in template.php, you would use THEMENAME_field__fieldname__contenttypename() as theme function. If you like to use a special template file, you would name it field--fieldname--contenttypename.tpl.php and put it into yours themes template folder.

All needed information can be found in Drupal API documentation.


Modifying Commerce Cart Before Display We have a Drupal Commerce cart. The pricing can be altered based on discounts that come in from an external database via XML httprequests. It worked -fine- when the XML requests were made when the user hit the 'Add' button. But another developer removed that code and now wants the XML requests to be made on the cart form.

The problem I'm having is that it appears that the cart wants to display -before- my code will trigger and update the line items.

So... is there a way to hook onto a cart form/view so that my update code fires -before- the view is actually rendered? Below is a snippet. What happens is that the default pricing displays and -then- when the user hits the 'Update Cart' button, the code fires and updates the pricing with the discounts from the external database.

function formxml_form_alter($form, $form_state, $form_id){
global $user;
if(! $user)
  return;

if($form_id == 'views_form_commerce_cart_form_default')
      $order = commerce_cart_order_load($user->uid);

     // request pricing from external site and store in array
 $request_string = 'http://mysite/Start?CartID=' . $customer_number . '&Cust=' . $customer_number . '&Cntact=' . $contact_number;
    $result = drupal_http_request($request_string, $options);

$seq = 1;
foreach ($order_wrapper->commerce_line_items as $line_item_wrapper) {
    $line_item = $line_item_wrapper->value();
    $my_product_id =  $line_item->commerce_product[LANGUAGE_NONE][0]['product_id'];
    $product = commerce_product_load($my_product_id);
        $my_product_title = rtrim($product->title);
            // update each line item with prices from external db array
            ...
     }
    // now save order
$form_state['order'] = commerce_order_status_update($order, 'cart', TRUE);
commerce_order_save($form_state['order']);

The best and cleanest way to achieve what you want is with a product pricing rule and a custom action with what you have above. That way it goes through the normal Commerce hooks. You just create a rule reacting on "Calculate the sell price of a product."

If you only want the rule to fire on cart and checkout pages, you can also create a custom condition that checks your current path (or there might be a module that adds that condition for you.)

So instead of a hook_form_alter, you want to declare a hook_rules_action_info().


Content block doesn't show when query is added to the URL I have a Drupal 7 page where some of my content blocks don't show up, if there is a query added to the URL.

Say my block is main_content, and it is shown all all pages except the listed ones, where no page is listed; the block appears correctly on on www.mydomain.com, but not on www.mydomain.com?gclid=xxx.

This is an issue for me because Google AdWords banners are linking to my page with a query attribute, and then the page does not display correctly.

What could be the issue here?

I managed to fix this issue. I'm very new to Drupal and I'm administrating a site that someone else built. The problem was in template.php in a function called 'views_views_pre_execute'. Some code was checking for drupal path alias and some custom queries was built. I changed: '$path = substr(drupal_get_path_alias(request_uri()),1);' into 'drupal_get_path_alias($_GET['q']);' and now it works.


Drush make, git repository checkout specific subdirectory I've got a make file in which I want to pull in a remote Git repository and only fetch a subdirectory. I've tried as following:

projects[example_module][type] = "module"
projects[example_module][download][type] = "git"
projects[example_module][download][url] = "git@bitbucket.org:team/example_modules.git"
projects[example_module][download][subtree] = "example_module_subdir"

Though, this creates a example_module folder where I expect it to be, though it contains the entire repository. What am I overlooking? Is this impossible? (using Drush 7.0.0)

The [subtree] only works if the download is an archive.
See Project download options page for drush 7.x.


How can I change a content entity to a config entity? I created a project using Content Entity but now I need to change this entity to Config Entity. Do you know how I can do this?

ContentEntity and ConfigEntity are very different. My advice is to just start over.


Error after copying the updated files I want to update a site from Drupal 8.9 to 9.0. After copying all files and trying to execute update.php, I get the following error:

  The website encountered an unexpected error. Please try again later.
  Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException: You have requested a non-existent service "entity.manager". in Symfony\Component\DependencyInjection\ContainerBuilder->getDefinition() (line 1032 of vendor/symfony/dependency-injection/ContainerBuilder.php).

What can I do to update to Drupal 9.0?

My modules are up-to-date.

ctools
entity_reference_revisions
metatag
paragraphs
pathauto
redirect
svg_image
token
webform

Some modules still don't have a Drupal 9 compatible release. One option is to install the Upgrade Status module on your Drupal 8 site and resolve all compatibility issues before upgrading to Drupal 9 core.
After enabling the module, you can run the compatibility test from the Update Status UI (under Reports - admin/reports/upgrade-status). The test scans modules for the use of deprecated code, among other things. In the case of deprecated code, it'll tell you the file and line number of the problem so you know what needs to be fixed.
Here's a sample of the results when testing the Allowed Formats module, version 8.x-1.2:

As with any other modifications to contributed projects, make sure to use the project's issue queue and patches to modify the project's code.


Temporary disable ordering in Drupal Commerce I need to temporary disable ordering until some date. So, I need to unable users to have add to cart button and unable them to go to checkout or cart.

But still I need to enable everything after this date.

How I can do this in Drupal Commerce? I'm using v7.x-1.13.

The simplest thing to do would be to disable "Access checkout" permission for these non-privileged users. That may result in some usability issues where links appear that would be inaccessible, so you'll want to confirm that and adjust those interfaces appropriately.


Unable to change the background image in theme I am trying to change the background image provided in the theme. Below is the CSS snippet from style.css file:

.toplayer{
  background: url(../images/theme.png) right no-repeat;
  position: fixed;
  top: 0;
  right: 0;
  height: 100%;
  width: 100%;
  z-index: -1;
}

I put the new background image in the same directory and tried to change the background by overwriting the above CSS in following way:

background: url(../images/background.png)

After clearing the Drupal cache, I reload the page, but I don't see the new image. At the same, I tried to access the image from my browser, and got the following error:

Forbidden

You don't have permission to access /new/themes/drupal_theme/images/background.png on this server.
Additionally, a 403 Forbidden error was encountered while trying to use an ErrorDocument to handle the request.

Later on, I moved theme.png and rename the background.png as theme.png but I still see the old background image.

I think Your have 2 configuration problem.

File Permission (in Filesystem)
ErrorDocument Attribute (in Apache
Webserver)

First, You can solve permission error using 'chmod' command to the sites folder of drupal.

Try this:

  chmod -R 777 directory (777 means allow permission for all)

Second, ErrorDocument handle error can occured from invaild ErrorDocument attribute setting in .htacess or httpd.conf(or apache2.conf) file.

Try this:

check your .htacess file in 'install/' directory. If you can not
check this file, you can try 'ls -al' command in terminal. you have
to find 'ErrorDocument' attribute, and remove or correct it.
check your apache webserver configuration file (httpd.conf or
apache2.conf). If you can check 'ErrorDocument' attribute, you can
try remove this attribute in file. It is temporary, so you must
backup it before try suggested cases.
If you can not solve by case 1 and 2, you can try disable
'AllowOverride' attribute. Try find 'AllowOverride x' attribute and
replace to 'AllowOverride None'. Because, this problem can have
possiblity from .htacess file in parent directories. AllowOverride
attribute can control allow or deny additional configuration in
.htacess file.
You must restart apache service after try this cases. you can try
'service httpd restart' or 'service apache2 restart' command.

Hope this helps you...


Custom module integration with Views3 for D7? I have a custom module named ta_module which alters the user registration form.
But since I updated Views to version 7.x-3.0 - rc1, I have like a hundred errors barely the same as the following :

Warning: include_once(/{PRIVATE - DRUPAL ROOT FOLDER}/sites/all/modules/ta_module/views/theme/theme.inc) [function.include-once]: failed to open stream: No such file or directory in _theme_process_registry() (line 413 of /{PRIVATE - DRUPAL ROOT FOLDER}/includes/theme.inc).

Warning: include_once() [function.include]: Failed opening '/{PRIVATE - DRUPAL ROOT FOLDER}/sites/all/modules/ta_module/views/theme/theme.inc' for inclusion (include_path='.:/usr/local/lib/php') in _theme_process_registry() (line 413 of /{PRIVATE - DRUPAL ROOT FOLDER}/includes/theme.inc).

It seems like I need to create a /views/theme/theme.inc in my custom module folder. BUT TWO QUESTIONS REMAIN :

- Do I leave this file blank or am I supposed to put things in it ?

- Do I have to create other folders/files for Views not to interfere with my module ?

Thks for reading !  ;)

Have you tried clearing the cache?

The error is there because some module, expects that there is such a file and tries to include it. It could be a direct result of whatever views integration you are doing.

The error will go away if the file exists, an empty file with <?php is enough.


No Available release found On the module update area, my install of 7.56, can seem to find matches to core and a few modules.

How do I begin to fix this?

What I've tried so far:

Based on translating an answer in  Cannot update drupal8: “No available releases found” to v7, I attempted

drush vdel update_last_check -y
drush rf
drush cc all
drush cron

This failed to do anything meaningful.

Nothing helped in our case, but running the following command:

drush sql-query "truncate cache_update"


Share single CUSTOM function across multiple themes I have some repetitive code that I'd like to share across two separate themes. Is there a best practice for something like this?

I know I can simply create an include file in the sites directory and do it that way I just wasn't sure if there was another way to do it that would be cleaner?

Thanks in advance!!

Two options that I can think of:

Make the themes sub-themes of a parent theme and put the function in the parent theme's template.php file. (I like this solution because other assets (css, js, templates) can easily be shared as well. But unless the function has to do with presentation, it probably doesn't semantically belong in a theme at all.)
Create a simple module that contains the function.


Alias not working for a non default language When I create a node in a non default language, I set an alias.  After the node is saved, however, all internal links (e.g. menus) do not use the alias; they all use the node/[nid] link type, and when I navigate to the alias it returns the "page not found" error.

Aliases work fine for the nodes using the default language, and for language neutral nodes.

I enabled the Locale and the Content translation modules.

By default url alias created manually or by Pathauto works only for the language of the node.

But you could make it work for all languages ina few simple steps:

go to the page "admin/config/search/path",
find required url alias and click "edit"
select "All languages" in "Language" field and save

That's all, now this url alias will be active despite of what language has the user.

If manual change is not an option, you can:

try to use "neutral_paths" module (though it is in a sandbox mode)
create simple module that wil do the same

Module forces url aliases to be language neutral, it works both for pathtauto and manual path aliases:

<?php
/**
 * Implements hook_path_insert().
 */
function MYMODULE_path_insert($path) {
    _MYMODULE_path_language_fix($path['pid']);
}
/**
 * Implements hook_path_update().
 */
function MYMODULE_path_update($path) {
    _MYMODULE_path_language_fix($path['pid']);
}
/**
 * Fixing a given path id.
 */
function _MYMODULE_path_language_fix($pid) {
    db_update('url_alias')
        ->fields(array('language' => LANGUAGE_NONE))
        ->condition('pid', $pid)
        ->execute();
}
?>

If you already have lot of existing content with not correct languhae for aliases, then run this code

<?php
function _neutral_paths_set_all_to_neutral($type) {
    $num_updated = db_update('url_alias')
        ->fields(array('language' => LANGUAGE_NONE))
        ->condition('language', LANGUAGE_NONE, '!=')
        ->condition('source', $type . '/%', 'LIKE')
        ->execute();
    if ($num_updated > 0) {
        drupal_set_message(t('@num aliases were reset to language neutral', array('@num' => $num_updated)));
    }
    else {
        drupal_set_message(t('No aliases were updated.') . $type);
    }
}
_neutral_paths_set_all_to_neutral('node');
?>


The pager on a form doesn't update upon first submit of the form I have a form with filter checkboxes, submit button, results in tableselect and pager.

When I set some checkboxes and press the submit button, a query should be reexecuted, data should be placed into the tableselect and pager should be updated, because new data size can be different with old one.

When I do it the first time, query is executed successfully, tableselect also is updated without problems. But the pager doesn't want to be updated.
And to update the pager I have to press the submit button second time.
But it occurs only I pressed the submit button after the page with the form has been loaded.

Could you clarify me, how can I update the pager after first submission of the form ?

Here is a fragment of my code with the tableselect and the pager.

$q = \Drupal::entityQuery('node');
        $q = $q->condition('type', 'my_node_type')
            ->condition('status', 1);

        $pager_params = [];
        if ($event_types != []){
            $q->condition('field_art_der_veranstaltung', $event_types, 'IN');
        }

        $events = $q->sort('created', 'DESC')->pager(10)->execute();

        $nodes = Node::loadMultiple($events);

        $rows = [];

        foreach($nodes as $node){
            $rows[$node->id()] = [
                'nid' => $node->id(),
                'title' => $node->getTitle(),
            ];
        };

        $form['nodes_container']['nodes'] = [
            '#type' => 'tableselect',
            '#title' => $this->t('Events'),
            '#options' => $rows,
            '#header' => $header,
            '#empty' => $this->t('No events found'),
        ];

        $form['nodes_container']['pager'] = [
            '#type' => 'pager',
        ];

Seemingly, I have fould the solution.
Namely, to avoid it, I set the Element property for the pager explicitely.

Here are fragments of code.

$nodes = $q->sort('created', 'DESC')->pager(10, 0)->execute();

/// code here

$form['nodes_container']['pager'] = [
  '#type' => 'pager',
  '#element' => 0,
  '#parameters' => $pager_params,
];

Unfortunately, I didn't have a time to debug and find out why it didn't worked before but it works now. Newertheless, it works.


Need a Best Video Player For My Video Hosting Site I am creating a video sharing and hosting site on drupal but I am having difficulties in finding a good video player which can play almost all files. I have used media element but that is playing some mp4 files and some are not being played.

Secondly I want the video player to generate thumbnails by itself.

check that : jw_player.

For thumnbails you can use that : DailyMotion, Youtube.
its very simple to use it.


Can recurring initial payment period be changed after purchase is made? I've installed the drupal commerce framework and the Commerce recurring framework (it's awesome), and i've created a recurring product. That said, someone just made a purchase, and I realized that I accidentally set the initial period as 1 year (and it should be one month). I've since corrected it, but if someone has already purchased the recurring product, how can I change that period? Will it update for existing orders? If not, where can I go to change it for specific orders?

According to the official documentation

  Recurring process

  When an order containing a Recurring product is purchased for the
  first time for the current user, by default the module reacts on
  "Order is paid in full" event, a Recurring entity will be created
  associated with that product for the current order.

  On a cron event, the recurring entities with past due dates are
  retrieved and an order is created for each recurring entity associated
  with the recurring product and customer.

  Note: When this cron event runs it's the time to trigger the payments
  or use another technique to build a queue of payments.

  All this process is driven through Rules so most of it is modifiable

So from reading this, looks like all you gotta do is check the recurring entity that was created for that particular order and see if the due date is 1 month from now or if it's still 1 year from now. If the latter, then edit it and change the due date to 1 month from now.


How can I loop through all article content types and get the content of each I created a new article content and am overriding that by creating a template for it (ie: node--4.html.twig).

Then inside this template, I want to loop through all nodes that belong to article content type; and to achieve that, I created my .theme file and added the following code based on the answer for this question here:

<?php
  function capoeira_preprocess_page(&$variables) {
  $articles = \Drupal::entityQuery('node')->condition('type', 'article')->execute();
  $nodes = \Drupal\node\Entity\Node::loadMultiple($articles);
  $variables['articles'] = $nodes;
}

Inside the template I do have:

{{ kint(articles) }}

inside my template and I go refresh the page I show article as NULL.

How do I loop through the articles?

EDITED:

None of the below work:

function capoeira_preprocess_page(&$variables) {
  $articles = \Drupal::entityQuery('node')->condition('type', 'article')->execute();
  $nodes = \Drupal\node\Entity\Node::loadMultiple($articles);
  $variables['name'] = $nodes;
}

function capoeira_preprocess_node(&$variables){
  $variables['name'] = 'My name comes here';
}

function capoeira_preprocess_node_article(&$variables){
  $variables['name'] = 'My name comes here';
}

you can use

function YOURTHEME_preprocess_node_article(&$variables){
  $node = $variables['node'];
   $nid = $node->id();
   // similarly you can fetch other fields
}

then override article content type as node--article.html.twig
and pass data to twig file