Make a public object property visible in other places I am using a class inside a Drupal module. I inserted the class inside the html.tpl.php like this:

require_once(drupal_get_path('module','shop')."/jcart/jcart.php");

Now I can use its properties in the pages but I need it to use one of them ($jcart->subtotal) inside a block module I created like this:

function MYMODULE_block_info(){
    $blocks = array();
    $blocks['total'] = array(
        'info' => t('Total amount of the cart'),
                //'cache' => DRUPAL_NO_CACHE,
    );
    return $blocks;
}

/**
 * Implements MYMODULE_block_view().
 */
function total_block_view($block_name = '') {
    $block['title'] = t('Total');

        $total = $jcart->subtotal;

    $block['content'] = $total;
    return $block;
}

notes:

I cannot add the class twice with require (because the $jcart) is being initialized inside the class and cannot be done twice
I need a block with so I think the variable is not visible in a Drupal block.

I would use a function to instantiate your class in a static fashion and then you have access to the same instance across your page load:

function MYMODULE_jcart_instance() {
  $jcart = &drupal_static(__FUNCTION__, NULL);

  if (!$jcart) {
    module_load_include('php', 'shop', 'jcart/jcart');
    $jcart = new jCart(); // Or whatever this might be
  }

  return $jcart;
}

From then every time you need access to the jcart class instance anywhere else on the site you just call:

$jcart = MYMODULE_jcart_instance();

Just a quick note, putting in an include into html.tpl.php is not a good way to do this. The theme layer is not invoked until all other processing has been done so your include should really be in a module file. I've shown this above using the module_load_include() function.

Hope that helps

EDIT

I've just seen your previous question relating to this and you mention that the class is instantiated in the include file already. If that's the case just change your static function to this:

function MYMODULE_jcart_instance() {
  $included = &drupal_static(__FUNCTION__, FALSE);

  if (!$included) {
    module_load_include('php', 'shop', 'jcart/jcart');
  }
}

and then add a call to this in hook_init() (this will be called before pretty much any of the rest of your code):

function MYMODULE_init() {
  MYMODULE_jcart_instance();
}

If $jcart is declared in global scope you'll need to add global $jcart to the functions that want to use it.


Replace main menu block with nice menus I am using Bootstrap theme, attempting to build a basic skeleton site that will use Nice Menus dropdown. Cannot get it to work: if putting in a block it displays alongside main menu, if disabling block and enabling Nice Menu 1 in Structure -> Blocks it does not behave correctly, no dropdown on hover

Nice menu works in same way as you required. Did you configured this module correctly?

First you need to look into configuration of this module(Nice menus).

After that you need to configure your nice module correctly in block list as in attached image. If still error persists then look for JS error.


Fields from different content types in a single page Using field permissions i have set 10 fields from various content types (articles, page, etc) to private.

While the rest of the fields is filled by the user, the publisher needs verify and fill those 10 fields to publish the content.

Is it possible to get all these fields in a single page so the publisher don't have to go to the individual content types to fill those fields.

My first thought would be to rethink your publishing workflow.

Having that said, I would try to create a view which takes content from all content types. Instead of showing the content, show the appropriate fields and create a filter so only unpublished content is shown...


How to add a book page: material types empty I run a Drupal 7 website since a year and have been always upgrading it - up to the version 7.10.

I have 2 Books and users' Blog at my web site. One of the Books is holding "Site Help" and "Imprint" stuff.

Now there have been a need to add to add 2 new pages "Terms of Service" and "Privacy Policy" to that book.

I go to /node/add but there is a message that no "material types" have been defined.

But I don't remember deleting them. And when I go to /admin/structure/types I see both "Machine name: blog" and "book" defined there:

Thank you

Node/add works for me, but try admin/content/add.  Also check that you are logged on as the administrator.


I cannot log into after migration I've searched what feels like hundreds of solutions and implemented them all. I've also searched this website in order to find the same question, but I was unable to locate it.

I have a development site and a production site. To migrate between the two I use github push and pulls. This hasn't been an issue in the past, however, I have run into this problem multiple times. After a file migration Drupal no longer allows me to login. I attempt my login credentials and immediately receive an Access Denied page.

My site cookies are reading and writing no problem. I've located the cookie ID and found it's entry in the database. So the cookies seem to be working fine and the database entries are working somewhat fine.

The problem that I can see is that the database session records are not saving any user ids. When I manually change the user id in the db record to 1, for my IP, and then refresh the website, I'm logged in. Any ideas?

https://stackoverflow.com/questions/2846935/cannot-login-to-drupal-in-chrome-or-firefox-but-safari-works suggests that I update $cookie_domain in the settings.php file. I've tried every configuration and it has not helped.
http://www.go2linux.org/cannot-login-into-drupal-table-corrupted also suggest that I repair the sessions table. I've done that, cleared the sessions from the db and cleared my cookies. It did not work.
http://www.madebymorgan.com/blog/2010/07/15/cant-login-after-drupal-617-upgrade suggests that I update the values in my settings.php file: $cookie_domain and $base_url. I've tried every combination and was unsuccessful.
I've read the install.txt which says to run the following commands for proper permission and ownership levels: chmod o+w sites/default/settings.php, chmod o+w sites/default, chmod o+w sites/default/files, chmod a-w sites/default/settings.php, chmod a-w sites/default.  It didn't work.
The patch in http://drupal.org/node/56357#comment-236726 adds some code to your sessions file. I've done this and it didn't work.
On http://drupal.org/node/56357#comment-391535, markus_petrux had a good suggestion by defining the PHPSESSID with a new name as well as setting the cookie domain and path manually. It didn't work.
http://old.nabble.com/Re%3A-Can%27t-login-p22258960.html suggests adding register_shutdown_function('session_write_close'); at the end of settings.php works, which also didn't work for me.
http://drupal.org/node/6696#comment-204863 tells us to add some ini settings into settings.php, clear the cache, clear cookies, clear privacy, restart Firefox, and add to settings.php the following lines:

ini_set('session.cookie_domain', 'exampleorg');
ini_set('session.cookie_domain','www.example.org');
ini_set('session.auto_start', 0);

I also had the same problem, and it was related to mod_rewrite. I have enabled the mod_rewrite with the following command and the problem was fixed.

sudo a2enmod rewrite


How to show breadcrumbs for taxonomy terms in Drupal 7 I've just now started working on D7 but I can't figure out how to display the terms in the breadcrumbs as we do in D6( I guess using Taxonomy breadcrumb). Taxonomy breadcrumb module for D7 is in dev release.

Use Taxonomy Menu Trails module. its better than 'Taxonomy breadcrumb'.


Customizing system response emails outside of the admin panel Can registration emails be customized through code rather than through the admin panel? I have message content that's reliant on values entered by user. Thanks.

You can use tokens (provided by the Token module) in administrative e-mails.  If you need a token for a value not provided by the Token module, you can programatically create a token.


Products are stored without title and product variations. Can't display them Such a weird thing has happened in my commerce kickstart 2 store. Somehow some products are in database but have not product variations and have not Title, so I can't display them in backend to remove them.

Is there a way to display those products in backoffice or I will have to delete directly in database? If so, is safe to remove them only in products table?

UPDATE:

I went inside database. I figured out that products that are not displayed in back-end search have not product variations anymore. Most of these products had Title Field and I could delete them by searching in front-end, clicking in Title link - this took me to node page's product. But now there are a few ones that have not Title. In front-end searching display them, but there is not a link to view node's product. So I think what I have are nodes without product variations. And the question What I do to deleted them remains.

I'm not working on Kickstart as I prefer to have a custom install of Drupal Commerce.

Commerce concept is that each product you create is a variation and you can use those variations in a display (content type)

If you can't see and delete products in the products list, you can create a view (page) displaying commerce products in admin mode (page url : admin/my-view).
Then add fields like : product id, sku, title and commerce product delete link.

But it's really strange to have products without title in yourdatabase... because you can't create product without title.


Why in node.tpl.php $content is different from $node? I'm creating a custom template file for a specific content type.
I'm printing most of values with

<?php print render($content['field_blabla']); ?>

As some of them didn't show up and they are not empty I tried

dpm($content);

Indeed they aren't in the array printed, but if try

$node = node_load($node->nid, NULL, TRUE);
dpm($node->field_blabla['und'][0]['value']);

I can see the value!

What's the problem? Why are they missing?

Thanks

Sounds like their field display settings are hidden, which is one reason it would not be in the $content renderable array.

Check the display settings for the applicable view mode for this content type on the "Manage Display" tab.


Facebook Connect module I'm using Drupal 6 and FB Connect module, but I can't change Facebook login button design.

What it looks like, now.

What I want it to be.

A quick look at the code shows that this is being created via:

function theme_fbconnect_login_button($text, $attr) {
  return '<fb:login-button ' . drupal_attributes($attr) . '>' . $text . '</fb:login-button>';
}

which shows that Facebook is creating the button, and thus suggesting you are stuck with what you got.  Now, there may be some hidden attribute incantation to change the button, but given how brand conscious Facebook is, I doubt they will allow you to change it up using their SDK.


How to render-print content type fields in an article? I am building a Drupal website and came across with an issue.

I have created a content type called "comments" with 4 fields :

    -comment1 with machine name: **field_comment_1**

    - comment2 with machine name: **field_comment_2**

    - image1 with machine name: **field_image_1**

    - image2 with machine name: **field_image_2**

I have created an article and put the code below:

    <?php print render($content['field_comment_1']);?>
    <?php print render($content['field_comment_2']);?>

    <?php print render($content['field_image_1']);?>
    <?php print render($content['field_image_2']);?>

Unfortunately nothing shows... Any idea what I am doing wrong?

Many thanks for your help!

ok, here is what I would do:

Create a subtheme as per this video, let's call it mytheme
Go to sites/all/themes/mytheme and create a file there called

node--comments.tpl.php

Go to modules/node/node.tpl.php, open it and copy eveything inside
Paste that inside the node--comments.tpl.php that was created in second bullet
Inside the node--comments.tpl.php, substitute print render($content); with your code

  <?php print render($content['field_comment_1']);?>
  <?php print render($content['field_comment_2']);?>

  <?php print render($content['field_image_1']);?>
  <?php print render($content['field_image_2']);?>

The reason we subsitute print render($content); with your code is that your content-type has 4 fields and through your code you render all 4 of them one by one, so nothing is left for print render($content); to do.
Go to appearance, enable and set default mytheme
Lastly, clear cache to be sure all the changes are picked up (configuration -> development -> performance)

In this way, I would achieve to have my styling changes in a subtheme. So anytime I want to change something I can do it there and it will override what would be shown by the base theme, without changing core. This is following Drupal's best practices and keep my styling seperate from core, which makes the site more robust and easily maintained (& upgraded)

note: by creating the file node--comments.tpl.php and following these directions, you will just change the output of the custom content type called: comments, while leaving the rest of the nodes to be handled by the node.tpl.php, without interference.

P.S. you can do without step 1 and go straight to themes/bartik/templates (if bartik is your default theme), create there the node--comments.tpl.php and continue from there, and although this is faster, I think it is bad practice for the reasons explained above :)


Is there a implementaion of the foundation framework for panels? I recently heard about the foundation framework and I wondered if there is an implementation for panels.

There is ongoing work in the Zurb Foundation Theme to implement Panels support.

It look's like there has been some progress, I'd check that discussion out first and foremost; then have a look at the search for Panels in that module. There might be more...


Redirect logged in (authenticated) users to a different frontpage using rules or php code I need to always redirect authenticated users to a different page (to serve as their own frontpage) whenever they try to access the default (anonymous) frontpage. I want to achieve this using rules or through some custom php code in my template.php or settings.php file, NOT by enabling a new module. Thanks.

Added: i created the frontpage using Page Manager (packaged with ctools)

If you are using a particular node as your front page:

Create a new rule, event: content is viewed
Condition: data comparison -> node:nid equals to the nid of your front page node.
Add your conditions for user roles here.
Action: page redirect -> enter the path where you want to redirect the users

If you have PHP code module enabled already:

Create a new rule, event: content is viewed
Condition: execute custom PHP code -> return drupal_is_front_page();
Add your conditions for user roles here.
Action: page redirect -> enter the path where you want to redirect the users


How to make custom jquery method accessible from Drupal.behaviors, across multiple javascript files? I have a custom views plugin.  When the view is displayed, the javascript below gets loaded.  Note the custom method, do_stuff, which gets called from within Drupal.behaviors.

(function ($) {
  $.fn.do_stuff(indx){
    alert (indx);
  }
  Drupal.behaviors.mymodule = {
    attach: function (context, settings) {
      if (settings.hasOwnProperty('mymodule')) {
        $('.my-item').each(function(indx, item) {
          // do stuff to each item
          $(this).do_stuff(indx);
        });
      }
    }
  }
}(jQuery));

I would now like to create a second plugin, which loads a second javascript file.  This second javascript file needs access to the custom method, do_stuff.  Is there a way I could access the do_stuff code defined in the first javascript file, from within the second javascript file?  For example, is there a way to move the custom method inside Drupal.behaviors, so that it could then be accessed from within any other javascript file?

I use a slightly different JS pattern with Drupal, which is based on the Javascript Module Pattern.

var FOO = (function(me, $, Drupal, undefined) {
  me.name = "FOO";

  function do_something_awesome () {
  }

  me.do_stuff = function do_stuff () {
  }

  function init (context, settings) {
    me.do_stuff();
    do_something_awesome();
  };

  Drupal.behaviors[me.name] = {
    attach: init
  };

  return me;
}(FOO || {}, jQuery, Drupal));

Anything directly attached to me will be public on the FOO.  The rest is private.  Typically, I will pass in FOO into the closure in dependent libraries.


Don't Associate Orders With Drupal Users - Guest Checkout Only Drupal 8, Drupal Commerce

We desire a "guest only" checkout experience. We don't want to associate orders or customer profiles with Drupal user accounts.

An unauthenticated user can checkout as a guest and achieve this.

However, if a user is authenticated before they checkout their order and customer profile will be associated with their Drupal user. This is what I am trying to avoid.

Does anyone have pointers for how this might be accomplished?

It sounds like you're trying to work against some basic assumptions of Drupal Commerce, namely that users who are logged in should be associated to their data. This is true of Drupal itself - for example, an authenticated user cannot create an anonymous comment.

The simplest thing to do would be to instruct these users to log out. You can likely find a way to alter how Drupal Commerce creates new shopping cart orders such that authenticated users get anonymous orders associated to their sessions similarly to anonymous users, but I can't guarantee that the module throughout won't be checking to see if the user is currently logged in and making assumptions based on this elsewhere.


How to capture all clicks from user I need to track all clicks by a user (even with no JavaScript enabled.  What is the best hook_ function to use to track these requests so I may log them?

You can use Google Analytics Event Tracking module to track mouse click and other events. This module provides a hook where you can track click events.
From module page:

Event Tracking is a way to track user interaction with out registering a page view.
This module allows an interface for Google Analytics event tracking capabilities. It provides a hook for other modules or "glue code" and also has some handy drush commands.


how can have this url car1?category=blue car?category=red car2?category=blue for drupal 6.x
I have a vocabulary with terms
car1
car2

and a vocabulary with terms
red
blue
yellow

how can to do this
2 menu
1) car1 | car2     (this really how a select)

2) Allcolor |  red  |  blue  |  yellow

3) here the results

when I click on car1 I have a page with all the car1's color nodes (and the Allcolor menu active)
url think so must to be:
/car1

if I click on red I have the result of car1 red nodes
/car1?category=red
if select blue
/car1?category=blue

when am on red under car1 and click on car2 I have the red car2 results
/car2?category=red

not sure if the url is so, but which is solution for to do this
functionality?

I know that is simple with only one vocabulary type this
car1
  red
  blue
  yellow
car2
  red
  blue
  yellow

but I must to do with distinct vocabulary; the terms really are more

for every views is necessary to have one exposed;
but isn't possible manage the

1) car1 | car2                        menu1
2) Allcolor | red | blue | yellow     menu2

menu2 how a submenu of menu1, also if isn't a unique vocabulary?


Strange behaviour with hook_entity_field_access I've implemented hook_entity_field_access like this:

function opencase_entity_field_access($operation, \Drupal\Core\Field\FieldDefinitionInterface $field_definition, $account, $items = NULL) {
  if ($field_definition->getName() == 'field_linked_opencase_actor' && $operation == 'edit') {
    error_log($account->hasPermission('administer users'));
    return AccessResult::allowedIfHasPermission($account, 'administer users');
  }
  return AccessResult::neutral();
}

When I log is as a user without the "administer users" permission and I go to the edit page containing that field, I get a 'PHP message: \n', in the error log showing that the if-block has been reached and that the user does not have the permission. But the field still appears! If I return an AccessResult::forbidden, however, it works as expected. Any ideas why allowedIfHasPermission doesn't?

AccessResult::allowedIfHasPermission:

  Creates an allowed access result if the permission is present, neutral
  otherwise.

If access is allowed somewhere else, a failed check for the permission doesn't prevent access, because it creates a neutral result.

As you found out you probably need to build a forbidden access result.


Remove every Javascript except own theme scripts In my current Drupal 6 installation, a lot of Javascript scripts are being loaded (core scripts, jQuery, modules, etc).

I only have one script in my theme that I need, so I want to only include that file and get rid of everything else.

What's the best way to accomplish this?

In your template.php you can override the generation of $vars['scripts'] to be just your file.

However, I suspect that this is a really bad idea and may have a lot of consequences.


What is EntityStorage? I'm attempting to understand the concept of entity storage. For example in this tutorial

https://www.sitepoint.com/drupal-8-version-entityfieldquery/

it's using code to load the nodes from nids in a similar way to this

$ids = \Drupal::entityQuery('node')
    ->condition('status', 1)
    ->execute();

$node_storage = \Drupal::entityManager()->getStorage('node');

// Load multiple nodes
$node_storage->loadMultiple($ids);

But I'm not sure exactly what this is doing

$node_storage = \Drupal::entityManager()->getStorage('node');

My best guess is that it's loading the format of how the node is stored in the database so it knows how to load everything based on that format, but that's just a guess.

Also side note: the path I normally take is doing a foreach loop on the query results and loading the node based on the nid inside that. Like so. But I'm not sure what's best practice.

        foreach ($ids as $nid) {
            $node  = Node::load($nid);
        }

What exactly is entityStorage, and what function is it providing?

Entity storage is a storage controller for the entity that handles the actual CRUD operations of entity data in the storage. That means it is responsible for inserting and deleting the entity data in the actual storage/repository.

The storage can be a .yaml file (for config entities) or a SQL database (for content entities). There are some specific use cases for null storage (like e-mail message) which basically means no data is stored anywhere and entity with such storage is just virtual: It exists only per single request as you define it.

You can additionally write your own storage controller and use remote storage, a file, a stream or whatever the requirements are.


How can I update the name of a taxonomy term using hook_update_N? I have taxonomy terms of color and I made a typo in one of the color name. It should be 'Crystal Black Pearl' instead of 'Crsytal Black Pearl'. How do I change it using hook_update_N ? Thank you in advance.
function honda_model_install() {
  $term = \Drupal\taxonomy\Entity\Term::create([
    'vid' => 'honda-color',
    'name' => 'Crsytal Black Pearl',
  ]);
  $term->save();
}

honda_model.install
/**
* Fix typo of term name.
*/
function honda_model_update_8101() {
  $terms = \Drupal::entityTypeManager()
    ->getStorage('taxonomy_term')
    ->loadByProperties([
        'name' => 'Crsytal Black Pearl',
        'vid' => 'honda-color'
      ]); // load using typo
  if (!empty($terms)) {
    $term = reset($terms);
    $term->setName('Crystal Black Pearl'); // make correction
    $term->save();
  }
}

Make sure you include the block comment, as that's what gets displayed to the user when they go to /update.php
Flush all caches so hook gets pickedup.
PS: once update.php runs it gets recorded in the DB that it ran and it will not run this again. So if you later on need todo another update, you need to add a new hook and increase the number, EX: honda_model_update_8102.


Automate installation with Composer It was easy to get Drupal installed with a single drush command before:

            drush si $profile -y \
            --db-url=mysql://$MYSQL_USER:$PASS@localhost/$DB \
            --site-name=$DOM \
            --site-mail=$EMAIL \
            --account-mail=$EMAIL \
            --account-name=$USER \
            --account-pass=$PASS >> /dev/null 2>&1

and it would completely finish Drupal installation without expecting user to do anything on UI.

Now with Drupal switching to Composer package manager, I am using the following command

composer --quiet create-project drupal-composer/drupal-project:8.x-dev $HOME --stability dev --no-interaction

however, unfortunately this method expects user to finish Drupal 8 installation on UI entering database, username and password manually. I wonder is there any way to make Composer do installation till the very end without any human interaction?

So since nobody provided acceptable answer, based on the above comments I tried the following bash-script and it worked flawlessly:

sudo -u $USER /usr/local/bin/composer --quiet create-project drupal-composer/drupal-project:8.x-dev $HOME/public_html --stability dev --no-interaction
cd $HOME/public_html/web
drush si -y \
  --db-url=mysql://$MYSQL_USER:$PASS@localhost/$DB \
  --site-name=$DOM \
  --site-mail=$EMAIL \
  --account-mail=$EMAIL \
  --account-name=$USER \
  --account-pass=$PASS >> /dev/null 2>&1


How is the height defined for a region in a Drupal theme? I can see that regions are defined in the .info file for a theme but I can't see how these regions relate to CSS that would be used to style them.

For example, in the acq_minimal / Minimal theme, the Header region has a fixed height but I have examined defaults.css and other css files and the .php template files but I can't see how its height is defined.

The Header region height is fixed rather than flexible to the content within it, because if I put text in it with a really large font, this spills over other regions - i.e. the Header region does not stretch to fit.

But preferably I simply want to know how to change the height of the Header region (and other headers). Knowing how to change the width and set the position would also be useful.

Please advise.

Nothing magical is going on here; just look in the .info file for the stylesheets and then look at them. The CSS in there combined with the html in page.tpl.php and other template files build the pages drupal creates. Well, sometimes some javascript comes into play, but that covers the majority of page markup.

ADDITION:

I don't have the theme you are referencing in specific on my machine, and if you are using Drupal 7 it will be slightly different, but to use garland under Drupal 6 as an example, and to expound upon the above and comments below, if we open up its .info file, we will find a:

regions[header] = Header

This tells the theme engine that it has a region called header. So, if we look in its page.tpl.php file, we will find:

<?php print $header; ?>

So, when the user puts blocks in the Header region via the Block Administration page, drupal puts all of the html etc into the $header variable for those blocks, which is then output here when it paints the page.

As you can see, $header is wrapped in a CSS id and class, so you can then look back at the .info file to find your CSS files:

stylesheets[all][] = style.css

Opening up style.css reveals:

#header-region {
  min-height: 1em;
  background: #d2e6f3 url(images/bg-navigation.png) repeat-x 50% 100%;
}

which gives the first of many cascading styles to apply to the theme's Header Region.  Don't fret over the clear-block class, it's just a wizardly way of making sure nothing floats next to the header (and vice versa), and you aren't ready for that yet lol.

So if you do this with your theme, you should be able to discover how its header is styled.


page--front.tpl.php not working I have omega 4 installed as my sub-theme, in which i have a custom layout. Now i am trying to make my home page custom, for which i have defined page--front.tpl.php in my templates/system folder, but its not working. I did explored the drupal questions/answers but nothing worked for me. I also tried to add

$variables['theme_hook_suggestions'] = array('page__front');

But it doesn't seems to be working either. How do i make it work, please help??

You don't have to specify a suggestion for the front page, it is already one.

The only thing you have to do is create page--front.tpl.php and clear your cache.

See the list of template suggestions.

Then if it doesn't work then something else in your setup is interfering somehow but we don't know much about your site so it's hard to debug from there.


Redirect to a new domain? I'm currently running my drupal site on a subdomain (a.example.com). I would like to temporarily redirect any requests to example.com and www. example.com to a.example.com.

Mark Trapp already offered a great solution using .htaccess files. In this case I would prefer to add a little module code. I was thing about checking $GLOBALS['base_url'] and then redirecting with drupal_goto(). Are those the right functions and which hook would I use?

Maybe you're looking for the Domain 301 Redirect module. Here is a quote about it (from the module's project page):

  ... allows sites to 301 redirect to a domain that is marked as the main domain. This means you can have all subdomains and other domains pointing to the site 301 redirect to a domain that you choose as the main domain. This provides great SEO benefit.


WYSIWYG filter - Anchors get wiped out I'm trying to allow anchors in my ckeditor but they always get wiped out by the WYSIWYG filter module.

For hyperlinks, my allowed attributes in WYSIWYG filter are "a[!href|target<_blank|title|id|name]". Then in the Rules for Element IDs section, I put "anchor*".

So in my content, when I add an anchor named "anchor1", it adds

 to the markup, which get replaced by
&nbsp;
 once I save the content.

What am I missing to get this to work ?

Thanks !

According to the WYSIWYG Filter module page it follows TinyMCE valid elements syntax. From that page:

  ! Makes attributes required. If none of the required attributes are
  set, the element will be removed. For example, "!href".

It looks like your attribute string uses the exclamation mark to make the 'href' attribute required but the <a> tag you're putting in your content does not have that attribute so the element is being removed.


Force no cache for unregistered users Is there a way to force a fresh page to be served to unregistered users every time instead of the local cached version?

You can turn off caching by going to Configuration > Performance, and uncheck "Cache pages for anonymous users."  That will turn off page caching for the whole site.

If you only want to keep specific pages from being cached you can use Cache Exclude.

You can also (but it is not recommended; see the comments) enter this PHP snippet into the page's template, for example node--123.tpl.php.

// Keep the page from being cached
$GLOBALS['conf']['cache'] = FALSE;


Pages by taxonomy in Drupal 7 I'm creating a dummy website to learn Drupal 7.
The idea is to build a car garage.

I added "Cars" as a vocabulary in Taxonomy.
Under Cars I made a list of terms (and sub-terms):

Cars

BMW

1 serie

1.18D
1.20D

3 serie

3.30D
3.35D

5 serie

Mercedes

A-Class
C-Class

Audi

...

I used Taxonomy Menu module to display my Vocabulary as a menu item in my main navigation. But now I want my children (terms) to be shown on this page... And when I click on a specific term, I would like it to show this page's child-terms...

I also installed Views module, made a view that would filter like this: Taxonomy vocabulary: Machine name (= Cars), but it's showing everything within my vocabulary...

I searched a lot, maybe not using the right keywords... (new to Drupal).
I hope somebody can help me on my way...

When creating a view, choose for Show: Taxonomy Terms instead of the default selected Content.
Than you can define the Type of you terms and using a contextual filter (it is for Drupal 6, but the idea is the same) only show the terms that are a child of term page your on.


How do I override a function from a module? Firstly, sorry if this answer is covered elsewhere. I've done a lot of searching and can only find info on overring theme functions and hooks.

I am using a module that builds a price table for Drupal Commerce items. There is a function that formats the table headers:

/**
 * Helper function that takes care of the quantity displayed in the headers of
 * the price table.
 */
function commerce_price_table_display_quantity_headers($item) {
  // Set the quantity text to unlimited if it's -1.
  $max_qty = $item['max_qty'] == -1 ? t('Unlimited') : $item['max_qty'];
  // If max and min qtys are the same, only show one.
  if ($item['min_qty'] == $max_qty) {
    $quantity_text = $item['min_qty'];
  }
  else {
    $quantity_text = $item['min_qty'] . ' - ' . $max_qty;
  }
  return $quantity_text;
}

As you can see, this is not a theme function where I can override it in template.php but I can to tweak some of the output.

Obviously I don't want to edit the module itself in case it gets updated in the future, so, how can I redefine this function so I can chop and change a few things?

My work so far...

So far, I have tried to create it as a seperate module with a few subtle changes to show if it's working or not, but it's not overriding any of the output.

Info file

; $id$
name = Price Table: Tweaked Display
description = A different layout for the price table as shown on the product display nodes
package = Commerce (contrib)
core = 7.x

dependencies[] = commerce_product
dependencies[] = commerce_price
dependencies[] = commerce_price_table

Module File

 /**
 * Override of the helper function that takes care of the quantity displayed in the headers of
 * the price table.
 */
function commerce_table_tweak_display_quantity_headers($item) {
  // Set the quantity text to unlimited if it's -1.
  $max_qty = $item['max_qty'] == -1 ? t('Unlimited gnhh') : $item['max_qty'];
  // If max and min qtys are the same, only show one.
  if ($item['min_qty'] == $max_qty) {
    $quantity_text = $item['min_qty'];
  }
  else {
    $quantity_text = $item['min_qty'] . ' - this is working - ' . $max_qty;
  }
  return $quantity_text;
}

It's Drupal...there's always a way, but the amount of time it will take to do might make you think twice :)

If you look a bit further up the food chain so-to-speak you'll see that this function is exclusively used by commerce_price_table_field_formatter_view(), which declares a field formatter that is used for the commerce_price_table field type.

With that in mind, you can quite easily implement your own field formatter, assign it to the commerce_price_table field type, and use as much custom code as you want, all the time keeping in line with best practices.

Basically you need to implement hook_field_formatter_info():

function MYMODULE_field_formatter_info() {
  return array(
    'MYMODULE_commerce_multiprice_default' => array(
      'label' => t('MyModule Price chart'),
      'field types' => array('commerce_price_table'),
      'settings' => array(
        'calculation' => FALSE,
        'price_label' => t('Price'),
        'quantity_label' => t('Quantity'),
        'table_orientation' => t('Orientation'),
      ),
    ),
  );
}

And then implement hook_field_formatter_view(), field_formatter_settings_form() and (optionally) hook_field_formatter_summary().

For each of these functions just take the code from the same function in the contrib module, and make the changes where you need to.


How to configure a server with 4g of memory to run drupal 7 I'm installing Drupal 7 on a new server with 4 GB of memory. I'd like to get some hints on how to configure it properly, how much memory to give to MySQL, and how much memory to give to PHP. One thing I found out is that running Drupal 7 on Zend server is three times faster than running it on a normal Apache server. (I think it has to do with opcode caching. I noticed with devel module it uses one-third of the memory.

Can you share your configurations with me?

If you already have Drupal7 Data, you should load it into a staging environment and perform some buffer sizing based on the amount of data you have.

Step 1) You must first compute the buffer sizes for your dataset.

Step 2) If the recommended sizes exceed 75% of your installed RAM (in you case 3GB) then cap the needed buffers at 3GB.

Step 3) If you have InnoDB data and you did not enable innodb_file_per_table, you need to cleanup InnoDB by segmenting each table into its own physical tablespace (this only needs to be done once).

Once you have done this, you should plan to perform this configuration audit (Steps 1 and 2) every 6 months to make sure you have the proper MySQL caching in place.

Interestingly, I addressed a question similar to this and answered it on April 15th, 2011.


building a query with the database api and groupby multiple fields in drupal 7 first of all I simplified my query so it might be more useable to other users on this site.

I'm looking for a solution to use group by on multiple fields.

This query selects the values of the pop_links module where only unique values can remain.
resulting in 1 value per day, node and hostname. ( to display only one click per hostname a day )

Here's my plain sql query:

SELECT cid, nid, from_unixtime(timestamp) FROM pop_links_stats p
GROUP BY date(from_unixtime(timestamp)), hostname, nid ORDER BY timestamp

Here is a simplified version of the drupal 7 query I'm currently using:

$query = db_select('pop_links_stats','p');
$query->fields('p', array('cid','nid','timestamp'));
$results = $query->execute()->fetchAll();

I'm also already using the join method of the db api but I don't know how to add the above conditions.

Adding this below will group the fields by every day but I want to groupby on 3 fields.

$query->groupBy('DATE(FROM_UNIXTIME(p.timestamp))');

Turns out you you can 'stack' the groupby methods like so:

$query->groupBy('DATE(FROM_UNIXTIME(p.timestamp))')->groupBy('nid')->groupBy('hostname');

Which generates the following query string under the hood:

GROUP BY DATE(FROM_UNIXTIME(p.timestamp)), nid, hostname

resulting in the following drupal query for this question:

$query = db_select('pop_links_stats','p');
$query->fields('p', array('cid','nid','timestamp'));
$query->groupBy('DATE(FROM_UNIXTIME(p.timestamp))')->groupBy('nid')->groupBy('hostname');
$results = $query->execute()->fetchAll();


How to insert data into node and other tables at the same time? I create a Drupal module which install database tables during module installation, table is created using Drupal way. The tables are created perfectly and now i have to insert data into those tables.

Example table structure where i want data to be inserted in sequence :

Node (insert product name)
myproduct_category (take the inserted node id and save the product category and nid at the same time in this table)
myproduct_price (take the inserted node id and save the product price and nid at the same time in this table)

Once data are inserted into database, the site admin will retrieve those saved data and show it in front-end.

here's my current code to insert data into node, i just can't get the last inserted id and continue insert data into other tables :

            $node   = new stdClass();
            $node->title    = $val['ADDRESS_1'];
            $node->type     = 'basil_veco';
            node_object_prepare($node);
            $node->language = LANGUAGE_NONE;
            $node->uid      = $user->uid;
            $node->status   = 1;
            $node->promote  = 0;
            $node->comment  = 0;
            $node->created  = timestamp;

            $node = node_submit($node); // Prepare node for saving
            node_save($node);

Please tell me the way to go about if my approach is not the right way.

Thank you.

Why you are using custom code to store the records in the node table. Are you calling any API service or you creating form yourself?

If you have created content type, then just go with drupal way and call custom submit function to store products and price values in a separate table by using db_write_record() or db_insert() function to insert the record in the database.

Just go through the below link

https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_write_record/7
https://www.drupal.org/node/310079


Authenticated users missing from users_roles table I have created several authenticated users in my site through the admin/people/create interface. However, these users are not showing up in the users_roles table. Is this a known issue or am I doing something wrong.

When creating these users I used fake emails, so authentication emails where not received. However, I've turned off the "require email authentication option." Also, when using dpm() on a variable the contains all the users created from a user_load_multiple I can see that they have a 2 in the user role. So why is it not in the database?

It is not an "issue" - but the authenticated user role is not registered in the users_role table.  For this type of user, the status is determined by the field statusin the users table.

AFAIK, every user registered in the users table is considered having the "authenticated user" role, so there is no need to explicitly register this role in the  users_role table. Instead, users having this should have their status set to "blocked" when you want to "strip" them of any grants.


How do I get Drupal to preference one of a module's .tpls over another? I have modified a Global module so that it has a 2nd .tpl file. The original .tpl file is for sites using Zurb Foundation 5, the newer one I created is for sites using Zurb Foundation 6. Because this is a global module, these files exist in the same directory.

I've named the newer .tpl inline with what Theme Debug suggests (image_resp_item--f6.tpl.php).

Now, I've just got to tell the site that when it's using Foundation 6 to preference the .tpl named image_resp_item--f6.tpl.php.

However, I'm completely lost at where to start with this. Is this something I set up on the module's .module file? Or something I set up on each sites template.php file? Is there a hook I can use?

Sorry its kinda vague - been dumped in the deep end here - any advice is appreciated.

Update the modules weight in the DB.

This code is for a custom module, when enabled:

/**
 * Implements hook_enable()
 */
function YOUR_MODULE_enable() {
    db_update('system')
    ->fields(array('weight' => 1))
    ->condition('type', 'module')
    ->condition('name', 'YOUR_MODULE')
    ->execute();
}


How do you force Drupal to re-render images? I have an image style. It's defined as requiring images which are 60x60, however all of the images it's created are 500x500.

This is a screenshot of the image style definition:
https://monosnap.com/file/GEIcrx6kRjeHg1b9VoDnRSAFNLgXmJ

I would think that this image would be a tad smaller (pixelation is intentional):
https://monosnap.com/file/E6oUIF3rxZ3qtLRTcbgJPGwZUg0j1e

I was able to disable and re-enable the responsive images in borealis on one of the environments, and that re-generated the same image, but that did not work on this environment.

You can try to flush your image style cache, eg. with this module: https://www.drupal.org/project/imagestyleflush

See also this answer: Rebuild images from image style


Display values of custom fields created on media entity in a template file I'm trying to display the values from the custom fields that have created on my Media Entity to my page--media.html.twig file. The fields that I'm trying to output are Location and Photographer

I tried using this code below, to make it work.

{{ node.field_photographer.entity.value  }}

Also tried an alternative

{{ content.field_photographer.entity.value  }}

Your question is more about how to handle Drupal templates and passed variables. I suggest you to use Devel and Devel Kint modules to be able to debug variables just in your template like this:

{{ kint() }} - print all available variables

{{ kint(your_var_name) }} - print particular variable

And don't forget to enable twig debug mode - it will show you templates structure.

Once you have everything visible it becomes much easier to understand.


db_query to drupal variable I have a the following query:

function background_audio_file_query($path) {
  $result = db_query("SELECT uri
    FROM `file_managed`
    WHERE `filemime` = 'audio/mpeg'
    LIMIT 1 , 30",
    array(':uri'=>$path))->fetch();

return $result;
}

How can I pass this to a Drupal variable?  I am assuming variable_set() but I am having trouble with the syntax.  Could anyone lend a hand?

If you want to set a variable with the URI returned from the query, you just execute code similar to the following one:

variable_set('variable name', $result->uri);

Replace "variable name" with the name you want to give to the Drupal variable, which is the same one you pass to variable_get().


When a user goes from one page to another, how can I see where they came from and where they are going? I need to hook into whenever a user moves from one page to another. I need to know where they are coming from and where they are going. My scenario is that anytime that a user heads to a certain section of the site (search) it modifies the path to add a variable. But I only want to to do so when they are coming from outside that section of the site.

I have been looking at hook_url_inbound_alter() which gets me in when a user is about to move to another page, and gives me where they are going, but not where they came from. Any suggestions?

Drupal does not track this information, so you need to do it yourself, using sessions (*).

If your pages are not being cached, then the best place to track user progress would probably be in hook_init. This is called very early on in the process - so in effect you have the information of knowing where the user wanted to go before anything is displayed (you could redirect the page at that stage for instance).

If your pages are being cached, in particular using a cache mechanism that bypasses Drupal such as Boost or an external cache proxy, then you will need a Javascript based solution that sends the information back to your site. How to implement this is beyond the scope of this answer.

(*) Note however that Drupal implements it's own session handling, so you need to do some extra work to use session variables (the session variables you set are only available through $_SESSION on the next page load - in the mean time you need to keep track of them yourself. Some people have written example implementations, or you may want to try the session api module).


How to make a raw SQL query to get the node/node_votes pairs? I'm not familiar with drupal. Using raw SQL, I'd like to extract votes given to each node, but I wonder how vote_rating is related to node?

I see that the votes are stored in field_vote_rating of this table:

mysql> DESCRIBE `field_data_field_vote`;
+-------------------+------------------+------+-----+---------+-------+
| Field             | Type             | Null | Key | Default | Extra |
+-------------------+------------------+------+-----+---------+-------+
| entity_type       | varchar(128)     | NO   | PRI |         |       |
| bundle            | varchar(128)     | NO   | MUL |         |       |
| deleted           | tinyint(4)       | NO   | PRI | 0       |       |
| entity_id         | int(10) unsigned | NO   | PRI | NULL    |       |
| revision_id       | int(10) unsigned | YES  | MUL | NULL    |       |
| language          | varchar(32)      | NO   | PRI |         |       |
| delta             | int(10) unsigned | NO   | PRI | NULL    |       |
| field_vote_rating | int(10) unsigned | YES  |     | NULL    |       |
| field_vote_target | int(10) unsigned | YES  |     | NULL    |       |
+-------------------+------------------+------+-----+---------+-------+

I'm aware of Drupal's database structure schema, which looks like so:

But I cannot figure out how to make a query to connect them.

My question: How to make a raw SQL query to get the node/node_votes pairs?

Any suggestions?

Try this query:

SELECT field_vote_rating from field_data_field_vote
WHERE entity_type = 'node' AND entity_id = $nid;

You can use the database api to create SQL Queries


How to add 'font color' option to Buedit I have used other text editors but BUEdit is my text editor of choice: lightweight and robust.

However, what I lack in its buttons is a function to enable users to colorize (and hence beautify) their texts. I'd be grateful to know how to do so.

You can enrich Bueditor by adding buttons to it. You can find some very well written documentation about how to add buttons to the editor in the official bueditor page.

After you have learned how to create buttons, you can use one of the already implemented buttons for text color. You can find a demo and the actual button code here.

The steps that I followed in a clean Drupal 7 installation:

Installed Bueditor
Navigated to Configuration - Content Authoring - Bueditor
Selected a random editor (e.g. Default) and hit "Edit"
Copied the 2 files from the second link in the library folder inside
modules/bueditor
Added the following lines in "Editor specific library files":

%BUEDITOR/library/bue.style.js

%BUEDITOR/library/bue.colorbox.css
I went to the bottom of the page, above the "Save Configuration" button and in the blank button I added a title (i.e. Color), in the "Content" field I added the code from the second link (the code that is marked as: "Button code" (simple copy and paste)
In the place of the icon I just wrote: Color
Now just hit: "Save configuration" and go to the bottom of the page and check in the demo editor how it works.


Is there any way to export user account information and content profile together? I need to export all the information of a few user accounts and relevant content profile nodes together per user.
It doesn't matter what format it should be but I'll eventually import back to the same site.

It seems that View Bulk Operation does the job but in the Views I must include all the profile fields,CCK fields and all the rest of the information the account and the node has.
So it's just not realistic in my case.

Is there any way I can export all the data that belongs to one user ?

I would still go with Views, unless you want to do it in your own custom module as suggested in the other answer.

There is Profile CSV, but this is limited to user accounts and core profile fields. There was a feature request for Content profile, but that issue wasn't finished, and in fact a Views-based approach was also suggested in that thread.

You can build a view of user account fields and related CCK views using Views relations, and export to CSV using the Views data export plugin. (And you can later import CSV via User import).

I believe any solution other than Views requires coding.


How to show download count of a product I am using drupal commerce for an e-commerce site. I have a view for listing the product. I want to show download count oof each product in product listing page as mentioned in the screenshot. How can I achieve this?

You can do it by setting up a view of product line items, adding both the product and order relationships, filtering by order state, turning on aggregation, grouping by Product ID and summing on the line item's quantity field.

Else try the https://www.drupal.org/project/commerce_reports commerce reports module.


Template suggestions for file_entity.tpl.php Short version

My aim is to theme a file field in a view of node fields. In the view configuration, the field formatter is set to Rendered file and a view mode is selected. How do I suggest a template file?

Long version

What I see is, theming of a file entity is done through file_entity.tpl.php in file_entity module. I copied this file to my theme folder and tried following names:

file_entity--my-view-mode.tpl.php
file-entity--my-view-mode.tpl.php
file_entity--views--my-view-mode.tpl.php
file-entity--views--my-view-mode.tpl.php

None worked. So I tried to hook in some suggestions like below as view_mode_templates.module also does.

<?php
MYTHEME_preprocess(&$vars){
  $vars['theme_hook_suggestions'][] = 'file_entity__views__my_view_mode';
}
?>

This ends up loading that file-entity--views--my-view-mode.tpl.php but funnily I get an error like this:

  Fatal error: Only variables can be passed by reference in
  blah/blah/file-entity--views--my-view-mode.tpl.php on line 71

Which is actually this line:

hide($content['links']);

Funnier thing is if I comment that line out, I get a fatality masterkill WSOD with no error message.

If I try to do it like below, again as view_mode_templates.module does, it doesn't see the suggestion.

<?php
function MYTHEME_preprocess(&$vars) {
  if (array_key_exists('file_entity', entity_get_info())) {
    $vars['theme_hook_suggestions'][] = 'file_entity__views__my_view_mode';
  }
}
?>

So, does it maybe not suggest the theme suggestion in the correct place? Do I need to suggest this in something like template_preprocess_file_entity(&$variables) or template_preprocess_entity(&$variables)? Which don't have the appropriate $vars['theme_hook_suggestions'] array as far as I couldn't see.

Any comment is hardcore appreciated, thanks.

There's a documentation about template suggestions at Displaying Media under the heading Further Theming.

  The theme suggestions provided by the File Entity module are:

file__{file type}
file__{file type}__{view mode}
file__{mime type}
file__{mime type}__{view mode}
file__{file id}
file__{file id}__{view mode}


How to add field update your password in drupal webform? I want to add three fields in webform:

Current password
New password
New Password Again

Current password should be existing password and  last two fields(New password ,New Password Again)should update only if  current password is correct(validated). In short I only wants to add "update your password functionality" in my website using webform .

Any Idea how to do this ?

Webform Password Field

  This module allows you to add a password component to a webform. It
  doesn't validate the password in any way.


Customize user login block I've been playing around with Drupal 8 since about a week. A couple days ago I tried to design the user login page to my needs but I couldn't quite do it. My problem is the following:

I want to customize the user login form (/user/login). I can edit the user login page (page--user--login.html.twig) but I can't find out what the name is of the user login form? How can I restructure the elements of the user login form? Or am I looking in the wrong place?

I appreciate any help you can give!

One thing that helps immensely is to enable Twig debugging in your services.yml (not recommended for production environment).

parameters:
  twig.config:
    debug: true
    auto_reload: true
    cache: false

The auto_reload and cache settings can also be set to their development settings so you do not need to rebuild cache (remove compiled twig templates manually).

This will enable HTML comments that show what template is being used for various components in markup. Bartik and Classy, by default, displays this as block.html.twig. The template suggestions for a block is block--PLUGINID.html.twig where the PLUGINID is the the block's plugin id with underscores replaced by dashes.

Example debug output from my local development environment using a sub-theme of Classy:

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'block' -->
<!-- FILE NAME SUGGESTIONS:
   * block--userlogin.html.twig
   x block--user-login-block.html.twig
   * block--user.html.twig
   * block.html.twig
-->
<!-- BEGIN OUTPUT from 'themes/custom/blah8/templates/block--user-login-block.html.twig' -->
<div id="block-userlogin" class="contextual-region block block-user block-user-login-block" role="form">

templates/block--user-login-block.html.twig


Error importing csv with batch API I'm using this code in my batch job:

<?php

function my_module_csv_import() {

  $folder = "csv";
  $files = scandir($folder);

  // define batch array structure
  // NOTE: minimal parameters defined to simplify code
  $batch = array(
    'title' => t('Reading File'),
    'operations' => array(
      array(
        '_my_module_batch_read', array($files_array),
        ),
        ),
        'finished' => '_my_module_batch_finished',
        );

        // set batch
        batch_set($batch);

        // process batch
        batch_process('');

        return '';

}

function _my_module_batch_read($files, &$context) {

  variable_set('site_offline', '1');

  // define batch limit
  $batch_limit = 500000;

  // assume the batch process has not completed
  $context['finished'] = 0;

  foreach($files as $csv_file_path) {

    // open the file for reading
    $file_handle = fopen($csv_file_path, 'r');

    if ($file_handle){
      // check if file pointer position exists in the sandbox, and jump to location in file
      if ($context['sandbox']['file_pointer_position']) {
        fseek($file_handle, $context['sandbox']['file_pointer_position']);
      }

      // loop through the file and stop at batch limit
      for ($i = 0; $i < $batch_limit; $i++) {

        // get file line as csv
        $csv_line = fgetcsv($file_handle);

        // NOTE: at this point, do what ever you'd like with the CSV array data!
        if (is_array($csv_line) && isset($csv_line[0]) && isset($csv_line[1])) {
          // DO STUFF
        } else {
          dpm("PROBLEM READING LINES");
        }

        // retain current file pointer position
        $context['sandbox']['file_pointer_position'] = ftell($file_handle);

        // check for EOF
        if (feof($file_handle)) {
          // complete the batch process
          $context['finished'] = 1;

          // end loop
          break;
        }
      }
    }
  }

  $context['finished'] = 1;

}
?>

it works fine, but sometimes it breaks.
The $csv_line results to have PROBLEM READING LINES and I get
 warning: htmlspecialchars() [function.htmlspecialchars]: Invalid multibyte sequence in argument.
I can't figure out how this could be possible, since the csv is correct.
Can anyone point me in some solution?

Found the error: the problem is that I'm not resetting $context['sandbox']['file_pointer_position'].
This causes batch pointer start reading the CSV file in the wrong position.
To correct this, it's enough to add

$context['sandbox']['file_pointer_position'] = 0;

to the check for EOF

if (feof($file_handle)) {
    // complete the batch process
    $context['sandbox']['file_pointer_position'] = 0;
    $context['finished'] = 1;
    // end loop
    break;
}


drupal_add_js causes blocks to be executed twice I added this code to template.php (in Zen subtheme):

function mytheme_preprocess_page(&$vars) {
  if ($vars['is_front']) {
    drupal_add_js (libraries_get_path('jquery.cycle') . '/jquery.cycle.all.js', 'file');
  }
}

Just after adding it, each block (e.g. drupal search block, my custom blocks etc) and also this preprocess function are executed twice. I checked it using a debugger. The output on pages is OK, but executing blocks twice has performance implications.

By the way, the same happens if the JavaScript file is added in mytheme_preprocess_html() instead of mytheme_preprocess_page.

Is hook_preprocess_page() the right place to add JavaScript code? (I guess not.) Is there another way of adding JavaScript to a specific page other than the above? (I know I can add in mytheme.info, but it will add to each page, whereas it's needed only on front page.)

I finally discovered two circumstances when blocks are executed twice:

First is adding a missing javascript file, either in theme.info file or in theme_preprocess_page() function using drupal_add_js.

Second is by adding a broken url(..) image reference in a css file which is actually used on the page.

Here are the steps to recreate the problem with css, for javascript it's analogously:

install Drupal (it has Bartik theme as default) and log in, to see
the search box
in a debugger, set a breakpoint inside function search_block_view()
refresh the page and check that the breakpoint is reached once
go to /themes/bartik/css/styles.css line 1467 and change the line containing:

background: url(../images/search-button.png)

into something that does not exist:

background: url(../images/search-button1.png)

refresh the page with shift and check that the breakpoint is reached
twice

Maybe such behavior is obvious for someone more advanced and has rational explanation, but for me it is not obvious and took me a while to discover. Anyway the conclusion is just to make sure that all loaded css and javascript resources are available and nothing is missing, otherwise blocks will be silently executed twice and depending what they contain, the page may load longer.


How can i display a environment indicator notice on my dev and staging when browsing the site? I know there is a environment_indicator module that displays a bar on the bottom of the website showing if your on staging or dev. http://drupal.org/project/environment_indicator

I want to know if there is a way to do this without having to install a module, by doing it via the settings.php file where I can make it output some html to indicate im on staging or dev.

You can't output HTML (or text) directly from settings.php without throwing an error, since settings.php is interpreted during bootstrap.

Provided you have a clean install, on your staging site, have the following line in settings.php:

$conf['site_name'] = 'This is a staging site';

All assignments to the $conf array you do in settings.php will override whatever value you set the in the administrative GUI for the site.

An alternative solution, if you don't have a clean install and the site's name is no longer displayed by default, is to add your own conf variable to settings.php:

$conf['is_staging_p'] = TRUE;

and modify your theme to output some indicator if this predicate is TRUE;


Customizing main_menu so that it shows nested elements with styling in Drupal 7 I have the following menu structure which i like to implement in Drupal 7 :

Home

About

About Us

Team

So far i have the base elements displaying correctly using :

<?php
print theme('links__system_main_menu',
array('links' => $main_menu, 'attributes' => array('id' => 'dropdown-menu',
'class' => array('fixed'))));
?>

Problems :

It doesn't display nested elements
I can only control the styling of the first level but in my code i have to apply a subclass of 'sub-menu' according to my theme.

Can someone point me to a starting point ? Thanks

As far as I know, it's not possible to make theme('links__system_main_menu' [...]) display the nested elements. That suprised me, too...

One way to fix this: set up a region in the theme for the menu and put a menu block in there. This will display the nested elements, however styling the menu itself won't be much easier than before. theme_menu_tree() and theme_menu_link() hooks could be useful.

Also, check out the Menu block module.

p.s. I'm currently doing something similar that you do and it seems to be quite complicated for me, too, so I just summarized what I've already found.


contextual and downward filterable tagcloud I am not sure how I would properly and clearly explain this question. What I am looking for in general is a tagcloud that is sensitive to context. So it will only list the tags that are relevant to the content that you are looking.

Let's say you have a repository of links all of which can be tagged freely. On the highest level (the entry archive page) you will have a tagcloud that shows all the tags that exists. Once you will click on one of those tags, it will list all the links that are tagged with that specific keyword. However, the tagcloud will now not show ALL tags, but just an aggregation of all tags within the context of the tag on which you have already filtered. Quite an abstract explanation. Let me try to give an example. Let's say you have 5 links, which are tagged comma separated:

Link1: tag1, tag3
Link2: tag1
Link3: tag2, tag5
Link4: tag3, tag5
Link5: tag4, tag5

So, on the highest level, you will have a tagcloud that shows all tags: tag1, tag2 ... tag5. Let's say you click on tag3. On the archive page of tag3, you will only see tags that are relevant to that tag, in this case: tag1, tag3, tag5 (see Link1 and Link4, both are tagged with tag3, but have tag4 and 5 additionally)

I hope I could make it a bit clear. Any clues on how to accomplish this with Drupal?

What I think you are saying you want to do is this:

Grab all content that is tagged with a certain term, then
List in a block all taxonomy terms from that content

And if so, it's pretty straightforward to loop through a list of node and aggregate and each taxonomy term that is attached to each node, and then stylize a block of those terms, eg,

$nids= // execution results of a view or other sql that filters on a term;

$found=array();
foreach ($nids as $nid) {
   $node=node_load($nid);
   foreach ($node->taxonomy as $t) {
      found[$t->tid]=$t->name;
   }
}

which will (if my off the top of the cuff php code is accurate ;-) produce an array $found that is a list of terms that can be styled however you wanted in a variable or block, most simply like:

 foreach ($found as $tid => $name) {
    $content.=l($name,'taxonomy/term/' . $tid) . ' ';
 }
 return $content;

You can probably do all of this in a View itself with some funky templating, too, if you didn't want to create a module and/or theme preprocess function.


Disabling access to admin pages during maintenance I need to do some maintenance on a website that is updated by a number of contributors, what is the easiest way for me to disable access to the admin part of the website while I'm working on it?

Assuming that you are user 1, and that the contributing users all have a particular role; you should be able to just remove the administer site configuration permission from that user role whilst you're working.  This should disallow access whilst under maintenance mode.


Is form data cached? Is form date cached? I have an interesting bug on my site. There is a form for logged in users and it is used very frequently. Sometimes, after long time usage, some data doesn't change when it should (another node..). It looks like it is cached.

How can i disable this "form cache" or force form on creation to load new data, not cached (old)?

thanks

As far as I know, Drupal doesn't cache submitted form data. However, generated HTML Code is cached in many places.

I've come upon this problem when rendering a form in a block produced by a custom module. If block caching is active and the form is sometimes rendered with some fields pre-filled (The user's name, the previously used search term), that version of the form might be cached and displayed to other users.
This particular case is easily fixed by setting $block['my_block']['cache'] = DRUPAL_NO_CACHE; in your module's implementation of hook_block_info.


How to check config setting in custom service class with dependency injection? In a custom Service class, I need to check a config setting.
I'm able to do this using \Drupal::config(static::SETTINGS) as documented here: https://www.drupal.org/docs/drupal-apis/configuration-api/working-with-configuration-forms
but Coder complains:

WARNING | \Drupal calls should be avoided in classes, use dependency injection instead

What service should I inject here?
I only need to see the immutable config value, I don't think I need a ConfigFactory.
More info:
When I try to inject the ConfigFactoryInterface, using the pattern I have followed for many other services, I get this error:

Error: Call to undefined method Drupal\my_custom_module\Api\DataPartner::config() in Drupal\my_custom_module\Api\DataPartner->hasDebugPermission()

The code in the hasDebugPermission() method looks like this:
  /**
   * Private function to control whether displaying debug info is permitted.
   *
   * @return bool
   *   TRUE if debugging is permitted for current user in current environment.
   */
  private function hasDebugPermission() {
    $config = $this->config(static::SETTINGS);
    $result = DATA_PARTNER_FORMS_DEBUG
      && $config->get('display_debugging_info')
      && $this->account->hasPermission('debug forms');
    return $result;
  }

And I have declared static::SETTINGS like this:
  /**
   * Config settings.
   *
   * @var string
   */
  private const SETTINGS = 'my_custom_module.settings';

The call to $this->account->hasPermission() works fine after injecting \Drupal\Core\Session\AccountInterface, but the call to $this->config('my_custom_module.settings')->get('display_debugging_info') does not work after injecting \Drupal\Core\Config\ConfigFactoryInterface.

Make sure you inject config.factory and then you need to use:
$this->config
  ->get('my_custom_module.settings')
  ->get('display_debugging_info');

You can see that Drupal::config() is:
public static function config($name) {
  return static::getContainer()
    ->get('config.factory')
    ->get($name);
}

So after injecting your service, the equivalent of \Drupal::config('my_custom_module.settings') is:
$this->config->get('my_custom_module.settings');


Testing Services from outside site I have been a little frustrated with trying to get outside applications to consume services. The services browser is invaluable in testing the services themselves but fails in helping test the servers. For instance, if I do a views.get in the service, it returns an array (php) with node references. When I try the JSON server module, it does not return the node references. Are there any recommendations on how to test different service functions out through JSON? I though that a PHP file could be written to do this, but I wanted to see if anything out there exists alreay.

I found a module called Web Service Clients.  It is still unstable, but it works.

  Parallel to the Services module, the Clients module provides the ability to implement pluggable clients to external web services, including external Drupal sites running the Services module, the main use case being ingesting content from other Drupal installs via the Services module XMLRPC server.


Composer error with Ctools package I'm trying to update my site using composer.

I was previously using the Composer Manager module, but I've removed this as it's no longer supported, and composer support is built into core.

I'm now getting an error with the Ctools module (though I suspect the problem lies with composer rather than Ctools):

# composer require "drupal/ctools ~3.0"
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package drupal/ctools ~8.3.0-alpha21 is satisfiable by drupal/ctools[8.3.0-alpha27] but these conflict with your requirements or minimum-stability.

Installation failed, reverting ./composer.json to its original content.

Copying my composer.json file below in case it offers any insights:

{
    "name": "drupal/drupal",
    "description": "Drupal is an open source content management platform powering millions of websites and applications.",
    "type": "project",
    "license": "GPL-2.0+",
    "require": {
        "composer/installers": "^1.0.21",
        "wikimedia/composer-merge-plugin": "~1.3",
        "drupal/address": "~1.0",
        "symfony/intl": ">=1.0"
    },
    "replace": {
        "drupal/core": "~8.2",
        "drupal/entity": "8.*",
        "drupal/pathauto": "8.*",
        "drupal/simple-conreg": "8.*",
        "drupal/swiftmailer": "8.*"
    },
    "minimum-stability": "dev",
    "prefer-stable": true,
    "config": {
        "preferred-install": "dist",
        "autoloader-suffix": "Drupal8"
    },
    "extra": {
        "_readme": [
            "By default Drupal loads the autoloader from ./vendor/autoload.php.",
            "To change the autoloader you can edit ./autoload.php."
        ],
        "installer-paths": {
            "modules/contrib/{$name}": [
                "type:drupal-module"
            ],
            "modules/custom/{$name}": [
                "type:drupal-custom-module"
            ],
            "profiles/contrib/{$name}": [
                "type:drupal-profile"
            ],
            "themes/contrib/{$name}": [
                "type:drupal-theme"
            ],
            "themes/custom/{$name}": [
                "type:drupal-custom-theme"
            ],
            "libraries/{$name}": [
                "type:drupal-library"
            ],
            "drush/{$name}": [
                "type:drupal-drush"
            ]
        },
        "merge-plugin": {
            "include": [
                "core/composer.json",
                "sites/all/modules/entity/composer.json",
                "sites/all/modules/pathauto/composer.json",
                "sites/pasgonreg.lostcarpark.com/modules/simple_conreg/composer.json",
                "sites/all/modules/swiftmailer/composer.json"
            ],
            "recurse": false,
            "replace": false,
            "merge-extra": false
        }
    },
    "autoload": {
        "psr-4": {
            "Drupal\\Core\\Composer\\": "core/lib/Drupal/Core/Composer",
            "Drupal\\composer_manager\\Composer\\": "/var/www/drupal/sites8/all/modules/composer_manager/src/Composer"
        }
    },
    "scripts": {
        "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
        "post-autoload-dump": "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
        "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
        "drupal-rebuild": "Drupal\\composer_manager\\Composer\\Command::rebuild",
        "drupal-update": "Drupal\\composer_manager\\Composer\\Command::update"
    },
    "repositories": {
        "0": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        },
        "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    }
}

I'd really appreciate if anyone can offer any insights.

James

Try taking off the "8". "3.0-beta1" works for me.

They have started changing the format of the versions by removing the "8" for some reason.  Not all the projects have changed yet.


No data returned when SSL enabled for REST server via services module I am running a LAMP stack on CentOS with Drupal 6 and the latest Services module. Over HTTP the REST server I have running works fine and behaves as expected.

When I installed an SSL certificate I forced all port 80 traffic to 443 (SSL). This worked fine for Drupal but has caused the REST server to return no data. Naturally I have removed the force SSL and allowed both HTTP and HTTPS for the time being.

I am testing via Fiddler, which when used to access the endpoint over HTTP, returns the expected data. Testing over HTTPS I receive no data. Do I need to make a configuration change to the REST server?

OK so I had some help in where to look on StackOverflow but ultimately I discovered my problem myself.

The issue was that I was using a name based Virtual Host rather than an IP one.

So to be clear, I had:

<VirtualHost MyDomain:443>

and I needed

<VirtualHost *:443>


Using a different administration theme according to the role Is there a way to use different administration themes according to the roles assigned to users?
I have two roles (admin, editor), and I want that, when creating content, users with the admin role use the garland theme, while users with the editor role use another theme.

The ThemeKey module lets you set the theme using many different tests. While it doesn't specifically set admin theme in the usual way, it will certainly let you set a theme for a role and a path, achieving the same result. Some more details about this module (from its project page):

  ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties. It can also be easily extended to support additional properties exposed by other modules


Attaching a view with exposed filters block to user profile in D7 Here's a riddle:

I want to create a user profile page that will display some user info at the top (from Profile2) and a tabbed view of that user's nodes.  Pretty similar to Twitter's profile page, with the only exception being that on the right side I want to put an exposed filter block so as to filter the contents of this view.

Sounds simple?  It was simple in D6, but in D7 it's a mystery.  In D7 in order to attach a view to user profile you have to use the EVA module, which does not allow for "Filters Exposed in Block" option. If you create an exposed filters block from the Master, it returns the default "all" argument even though you are on user/# page and theoretically passing the correct argument to the Views.

By contrast, exposing the filters inside EVA and placing them above the View works and passes the correct arguments, but then the profile page looks ugly.

So how does one resolve this riddle?  How can I have a View on user-profile page and have a functioning Exposed Filters Block on the side?

Having exposed filters in a block is really only meant for page views.

There is a work around for creating a block view that will work with an exposed filters block at https://drupal.stackexchange.com/a/38994/10729 - Note also the comment below the answer, which talks about creating a custom module for the block, which is much better than using the PHP input filter if you don't mind making modules.

Then you can assign the block to show on the profile page.

A potential downside is that you cannot reorder the view via the profile fields display admin area like you can with EVA. This may or may not be an issue depending on wheere exactly you are positioning the view.

You could also instead print the block manually in your theme on that page exactly where you want it, or you could even put the views_embed_view() line directly in your theme and not worry about the block at all.


How can I access the CiviCRM contact record 'group' value(s) of the current user? The unique key is email address. Perhaps there is a CiviCRM API?

EDIT

There is a CiviCRM API. My code so far:

civicrm_initialize();
$content = civicrm_api('contact', 'getvalue', array(
  'email' => $GLOBALS['user']->mail,
  'version' => 3,
  'return' => 'first_name')
);

I need the user's group, not first name.

You can even use 'email' api to get the contact id(as you have the email address in $GLOBALS['user']->mail) and then use 'GroupContact' api as above to get the groups record.

$result = civicrm_api3('Email', 'get', array(
  'sequential' => 1,
  'return' => "contact_id",
  'email' => $GLOBALS['user']->mail,
));


2 user registration forms I need to show users 2 registration forms. 2 different forms with different fields. 1 form for free registration and 1 form with admin approval registration. how can i achieve that?

It seems there is not any module that provides this functionality directly. But certainly you can achieve it using other contributed modules.

Profile2
This module allows you to create user profile for the users. You can create profile for the two users like free_registered user and admin_approved users, and can add any number of fields on the user profiles.

Profile2 Registration Path
This module allows you to set the unique registration path for each profile2 user profile.
So after installation you will have two registration forms for each profile2 user profiles. You can access this form from the path specified in Profile2 Registration Path module configuration.

Let me know if any issue occurs. :)


Drush returns "sh: php: command not found, code: 127" Drush returns "sh: php: command not found, code: 127"

I just managed to get Drush working finally on my MacBook-Pro (2008).  For the longest time Drush would not interact with the Drupal installation.  Turns out the reason for this was the fact that Drush expects to use the default MacBook-PHP which is different from the MAMP-Stack-PHP which is what Drupal will be using.

This was sorted out and now appears to mostly work.  My environment is MacBook-Pro with Drupal-7.31 and Drush-5.9.  I am using the MAMP-PHP-5.5.14.

The conflicting PHP issue was resolved by renaming the MacBook-Default PHP file by adding an extension to its name. Then the .bash_profile file was modified to add a PATH to the MAMP-PHP and an alias was added for file-name of the PHP that Drush usually expects to substitute the newer MAMA-PHP.  If you need the details, those are explained in my other recent question: "Drush on Macbook Pro cannot read Drupal Correctly".

Now there is another issue coming up. When I run a "drush upc" or a "drush owiz" command, I get an error: "sh: php: command not found, code: 127". This seems to be telling me that Drush runs an sh-shell command which cannot locate my new MAMP-PHP file.

Any guidelines in fixing this, if this is in fact what this error means?

Exit code 127 means "command not found", just as the error message says. https://www.gnu.org/software/bash/manual/html_node/Exit-Status.html

If php is in your PATH, then this should not happen.  If you want to explicitly tell Drush which php to run, then set the DRUSH_PHP environment variable as explained in the Drush README.  This should help out in the case of Drush commands such as the ones you mention before, that run a Drush subcommand in a new process.

Update:

To make things work correctly, you need to understand how bash initializes itself.  For example, did you know that .bash_profile is sourced if you run ssh user@host, but it is not sourced if you run ssh user@host pwd?  Drush uses the later form to re-launch Drush subprocesses, so if you initialize your PATH in .bash_profile, then it will be fine when you test it in the shell, but it will be broken for Drush subprocesses.

To get around this problem, you should also export your PATH in your .bashrc file, as bash will source this file for non-login shells.  Be sure to set up your PATH at the TOP of the file, as there is a line near the top that reads: [ -z "$PS1" ] && return.  This causes the script to exit if ssh did not create a tty (run ssh -t to create a tty; Drush adds this flag for interactive commands only.)


How do I overwrite the variables in my theme? function rate_preprocess_test(&$variables) {
  extract($variables);
  $buttons = array();
  foreach ($links as $link) {
    $button = theme('rate', $link['text'], $link['href']);
    $button .= $link['votes'];
    $buttons[] = $button;
  }
  $variables['buttons'] = $buttons;
}

I want to overwrite the $link['votes'] variable to add a <span> tag around $link['votes'].

This is the code I added to template.php, but it doesn't contain the <span> tags that I  added.

function mytheme_preprocess_test(&$variables){
    $link['votes']='<span>'.$link['votes'].'</span>';
}

I want to add the span tags around $link['votes'].

If you are wondering why the <span> tags don't appear in the button output from rate_preprocess_test(), that is probably because mytheme_preprocess_test() is called after rate_preprocess_test().
I take rate_preprocess_test() is defined inside a module; in that case the preprocess function defined inside the module is invoked before the implementation of the preprocess function contained in the theme, as reported in the documentation for theme(), which lists the preprocess functions in the following order:

template_preprocess(&$variables)
template_preprocess_HOOK(&$variables)
MODULE_preprocess(&$variables)
ENGINE_engine_preprocess(&$variables)
ENGINE_engine_preprocess_HOOK(&$variables)
ENGINE_preprocess(&$variables)
ENGINE_preprocess_HOOK(&$variables)
THEME_preprocess(&$variables)
THEME_preprocess_HOOK(&$variables)


"Notice: unserialize() [function.unserialize]: Error at offset 10301 of 11637 bytes on views_db_object->load_row()" I use the E-Commerce Kickstart distribution. Almost always I get some error, every time I update and save any view.

Please could anybody tell me what is causing this error, or give me some suggestions?

I have encountered the same issue and thus far to resolve but I found this article.

http://www.zyxware.com/articles/3337/drupal-errors-drupal-views-notice-unserialize-function-unserialize-error-at-offset-1009-of-1036-bytes-in-views-db-

so...i researched some more and found this solution. I added this line to bootstrap.inc

$data = preg_replace('!s:(\d+):"(.*?)";!e', "'s:'.strlen('$2').':\"$2\";'", $variable->value);
$variables[$variable->name] = unserialize($data);

in the variable_init function


Several field templates or on node template? Try to figure out when field templates are the wrong approach...

I've been told and agree that you should ultimately avoid creating node templates and try to process things before they hit the theming layer. I believe this because you alway want to add more room for theming later, and data changes should stay with the proper entity... at least a field template if not template preprocess, nodeapi, etc.

So... if I have a node type that's requiring I end up with 3-5 field templates, to do some logic on the display of links vs. text, add standard suffix text, etc. When do I throw in the towel and just do it all in the node template because that's the right thing to do?

Maybe I just need contemplate?

Your thoughts?

I would never recommend Contemplate to someone who needs true control over the output.

Here is what I usually do:

I make php stuff and logic stuff on the node_preprocess, only sending to node.tpl variables ready to be echoed, or arrays to be foreach'ed and then printed, in the case of cck fields with multiple values.

And I never run functions of any type on node.tpl.php. If you need to run a function, run it on preprocess!

Using this approach my templates become faster, as they can take take a little more advantage of the internal template caching system, and also, my node.tpl.php gets REALLY easy for me and others to understand it.


Can I have separate playlist for each node? I have this problem:
I have a nodetype Audiobook.
In this page I set title, ahthor, description and other informations.
I want to insert episodes of this audiobook in a playlist that user can display on audiobook page.
When user clicks on an episode, it plays automatically.
I'm trying to use mediafront, but I must create a view for each list, it's tedious.
I tried to use nodehierarchy, by creating a content tuype "episode", but, when I click on one it opens a page and I can't switch to next easily.
Any idea? I searched the internet, but there's doesn't seem to be no module.

It sounds like you want a second content type called episodes. You can do this by adding a relationship between the audiobook and episodes with an entity reference field. When creating the field you can define how the relationship works. Episodes can then be ordered and you can setup a single view to display the episodes for a particular audiobook in which ever way you choose. The view would accept the audiobook node id as an argument selecting episodes by relationship for extra ease of development and simplicity.

You could also use the inline entity form module to add and edit related entities.


Views and Lightbox 2 I have created a view. The view contains a title. The title currently links to the node.

I have Lightbox 2 installed.

To get the node to load in the lightbox I have to add more information to the link see below:

click here to see node content

URL paramenters Format = simple makes only the content of the node load in the lightbox window.

My question is how do I add the additional information (?format=simple & rel="lightframe[|width:800px; height:600px; scrolling: auto;]") to the view title link

I am using Drupal 7

In your title field deselect "Link this field to the original piece of content"
select "Rewrite the output of this field"
add two fields "Content:path" *"Global:Custom text"* and hide them from display by selecting "Exclude from display "
In the Global:Custom text field select Rewrite the output of this field and enter lightframe[|width:800px; height:600px; scrolling: auto;]
Go inside your title field again. Look under "Replacement patterns" for [view_node] and build up your link. Make sure the two fields Content:path and Global:Custom text are arranged before your title field or else you wont be able to use them.

Your link should look something like:

[title]


How can I use conditional logic to not display a  in page.tpl.php based on node id? I'm using a theme that has regions not supported by Panels' "Disable Drupal blocks/regions" settings. I've tried to remove the  using an if statement in PHP, but either my PHP syntax is wrong or I'm not using the correct Drupal variables. Right now the section looks like this:

<?php
    if ($node->nid != 51) {
        echo '
';
            { if ($left) { print $left;}
        echo '
';
 ?>

I have a feeling I'm not nesting the second if statement correctly in PHP though.

If you're trying to hide the left sidebar when viewing node 51, this is not the right way to do it. Edit the block visibility settings for the blocks in the left sidebar so they are hidden when the path is 'node/51'. Then in your template you can do this:

<?php
  if ($left) {
    print '
' . $left . '
';
  }
?>

This will hide the entire div#left when there are no blocks in the left sidebar.


Add a term to a vocabulary I am using Drupal API as api_driver to run BEHAT scenarios. Please see below scarios for creating a term for the taxonomy "test_new". While running, this got success but when I take the application and look for the new term created it showing on the listing page. But when clicking on Edit of that term, name and description is not get updated, its showing empty but parent field is correctly mapped.
Why is this happening?
  Given "test_new" terms:
    | name              | parent         | description_field    |
    | Test term one     | Test parent    | term one description |
    And I wait for 20 seconds

It got worked by adding language and format for terms. Please see below code.
  Given "test_new" terms:
    | name           | parent      | description          | format     | language |
    | Test term one  | Test parent | term one description | plain_text | en       |


How to get pathInfo in twig? I want get the pathInof in my template twig :

How i can reach pathInfo please in my template ?

The screenshot is a render element of a link which gets printed in the template completely. What you find inside is for internal usage and is most times protected anyway.
To get this request parameter in your template build your own variable in preprocess:
$variables['path_info'] = \Drupal::request()->getPathInfo();

You might also need to add a cache context if your template depends on this information:
$variables['#cache']['contexts'][] = 'url.path';

Then print it in Twig:
{{ path_info }}

This is the general approach. In this specific case if you are interested in the current path (including the base path) then you could simply use a Twig function:
{{ path('<current>') }}


How to build a url path from raw path and arguments? In Drupal 7, from within a module,

My goal is having a menu path (e.g. "/path/to/page/%/%/view/%") and an array of arguments (e.g. array('foo1', 'foo2', 'foo3')), be able to build the resulting path (e.g. "/path/to/page/foo1/foo2/view/foo3").

After looking all over in the Drupal API, I cannot find a function that would do that.

Does such function exist?

EDIT:

The placeholders can be different as well. e.g. "/path/to/page/%user/%blah/view/%". The original raw path is dynamic and is only known during runtime.

I thought that format_string may work for %user and %blah, but what about the % in the end, does format_string work to replace that one too?

I don't think core has a function like that but it's easy enough to write a simple version:

$path = '/path/to/page/%foo/%bar/view/%';
$args = array('foo1', 'foo2', 'foo3');

$wildcards = array();
foreach (explode('/', $path) as $part) {
  if (strpos($part, '%') === 0) {
    $wildcards[] = $part;
  }
}

if (count($args) != count($wildcards)) {
  // Handle it
}

foreach ($args as $key => $arg) {
  $wildcard = $wildcards[$key];
  $pos = strpos($path, $wildcard);
  if ($pos === FALSE) {
    break;
  }

  $path = substr_replace($path, $arg, $pos, strlen($wildcard));
}
print $path;

Result is: /path/to/page/foo1/foo2/view/foo3


How do I display a link icon in custom modules? I would like to display an icon of correct answer but in my condition full URL is displaying (it's not displaying icon ) how I'll manage.
This icon will be on a table so the user can click that icon and check the answer. please guide me where I'm doing wrong. here I have put some linking portion of my code. I'm writing custom modules in drupal 8.
Thanks

$imgsrc = $base_url.'/scp/sites/default/files/images/corr_icon.gif';
$correct_link = Url::fromUserInput('/answer/'.base64_encode($data->ans_refno).'by'.base64_encode($data->q_id));
'isanswer' => \Drupal::l($imgsrc, $correct_link),

You can convert markup with image tags and convert it into URL with image like below:

use Drupal\Core\Render\Markup;

$imgsrc = Markup::create("<img src ='$base_url/scp/sites/default/files/images/corr_icon.gif'>");
$correct_link = Url::fromUserInput('/answer/'.base64_encode($data->ans_refno).'by'.base64_encode($data->q_id));
'isanswer' => \Drupal::l($imgsrc, $correct_link),


Should QA engineers directly update Drupal database tables via SQL? Is it generally accepted that it's ok in the Drupal community for QA testers to directly update and delete data in Drupal core tables via SQL? Or is it considered a bad practice? I'm talking about non-production environments--Production is definitely a no-no.

We are fortunate enough to have dedicated Quality Assurance engineers. I'm a developer and am very cautious about writing SQL update and delete statements on our Drupal tables (again, non-production). We usually script things in drush or use Drupal's API.

I think our QA engineers are great, but it seems like a very risky venture to directly update and delete data in core Drupal tables with SQL, even in non-Prod. I would think using tools such as Selenium or scripted solutions that use an API would be preferred, as long as they provide the same functionality.

Your input would be greatly appreciated. Any links with guidelines on this topic would be extremely helpful too.

If you directly update and delete data in Drupal tables via SQL, you don't allow Drupal core and third-party modules to detect such changes.

Instead, I suggest you have a look at some (common used) modules that may help updating/deleting such data, in "the Drupal way". Just to mention a few:

Flag - eg to "mark" nodes, users, etc for anything that's relevant for testing purposes.
Rules - eg to automagically make all sorts of things happen (eg after something like a node or user got flagged with the Flag module).
Views Bulk Operations (VBO) - to perform mass updates/deletes on a "list" (created with the Views module) of nodes, users, etc, whereas the actual operations to be performed can be "specified" with custom rules (created with Rules), or the other way around where you create such VBO-list and use it as input for creating lists and loops using Rules.

By using the "Drupal way", you also respect its permissions/roles architecture while performing testing (instead of getting around all that via direct updates/deletes). Wouldn't you rather want to discover security holes in testing areas?

Apart from that, there is also the Devel module to facilitate automatically generating nodes, comments, terms, users, and more (for testing purposes).


Question regarding SearchAPI and Index performance/scaling I have a site that will need to deal with thousands of nodes. it's an internal site, not public facing, with a daily concurrent user base of no less than 80 and no more than 100 users.

I am trying to figure out how to deal with search and indexing. The Big problem is I need facets and whatnot, but I also need instant data retrieval. So users can't wait for indexes to catch up. can one index via  SearchAPI near instantly?

On average, there might be 2-300 new nodes created per day, every day, by users, and an additional 5-600 nodes created per day+ through automated imports (Feeds).

I was thinking of just using straight views, and trying to do search filters, but it's not scalable and after a few months to a year it would be quickly unmanageable.

TL:DR: Many many nodes per day need indexed search with facets (SearchAPI and FacetAPI using ElasticSearch). Near instant retrieval required. If a user creates a node, they need to be able to see that node in the index within a few seconds or less.

Alternatively, thinking out loud, could I have it submit the new node to the index on every new node addition?

Regarding Search, I would suggest to go with external Search System, like ApacheSolr, Elastic Search, Algolia, etc. This will make sure that database will not be overloaded with content index.

I'm working on a project where we currently have almost 2 Lac nodes and around 30-500 nodes created every day. The number of concurrent users are 1-20 max. We're using ApacheSolr (Solr hosted on different server) with Search API and Search API Solr Module and results are retrieved in less than 1-2 Seconds (The Project is internal of Client's Company so can't share the link here).

  I was thinking of just using straight views, and trying to do search
  filters, but it's not scalable and after a few months to a year it
  would be quickly unmanageable.

Using view for rendering search results will not help much in terms of instant results. Preferred way will be writing custom code to query based on keyword and show results based on requirement.

  Alternatively, thinking out loud, could I have it submit the new node
  to the index on every new node addition?

Indexing of Node after Creation/Updates are managed by module. The search indexing is normally done when running Cron. So setting up your site Cron to run every minute will make sure that the nodes are indexed instantly.

Hope this helps.