How to apply a style to a specific page?

I guess you want to apply that class to the body tag. If that's true then you just need to append body_classes array and put your class in the end.

set body_classes = [
  logged_in ? 'user-logged-in',
  not root_path ? 'path-frontpage' : 'path-' ~ root_path|clean_class,
  node_type ? 'page-node-type-' ~ node_type|clean_class,
  db_offline ? 'db-offline',
  theme.settings.navbar_position ? 'navbar-is-' ~ theme.settings.navbar_position,
  theme.has_glyphicons ? 'has-glyphicons',
  'path-product-add',
]

And then clear cache of your website.


Admin role with this module you can add more super users.

  This module is a little helper to maintain an administrator role which
  has all available permissions. By default, Drupal only has one super
  user and this module helps improve this drastically.


how to display sub menu under the respective main menu

You have to use the module menu block. This module allows you to display child items of a certain parent item of a menu.


How to translate the Automated Logout module administration?

There IS a Polish translation of the autologout module available. Though it is currently only translated for 42%.

The way I understand (translate???) your question is something like so: How can I show the admin interface for the Automated Logout module in the Polish language?

To answer that question, just swich to the Polish version of your site, and then use the admin link. As an alternative, enable the "language switcher block" so that it is shown within the theme you're using for Administration. Then navigate to anywhere within admin (whatever language), and use the language switcher block to show the admin interface in Polish (for about 42%). If you also want the remaining 58% to be shown translated, then it's up to you to actually add your custom translations of the various missing translations.


you can copy views-view-row-rss.tpl.php to your theme folder
and then

<description><?php print $description; ?></description>

replace with

<description><?php print preg_replace("/<style\\b[^>]*>(.*?)<\\/style>/s", "", $description); ?></description>

it will remove css

if you also have inline styles then you need this

<?php $description = preg_replace('/(<[^>]+) style=".*?"/i', '$1',$description); ?>
<description><?php print preg_replace("/<style\\b[^>]*>(.*?)<\\/style>/s", "", $description); ?></description>


Preventing a block's custom template file from being cached

Probably not the best way to do this, but I was able to overcome this by rebuilding the theme cache when this block was run using:

<?php
drupal_theme_rebuild();

I'd love if someone could help with a better answer though!


How to keep in sync git repository and related htdocs directory?

use the "post-update" hook in the /hooks directory provided in your .git directory to push a copy (sans -gitignore- the files not needed) each time you make git commits to your dev files


Better to use PDO for DB related operations in Drupal like db_select(),
db_insert(), db_update() and db_delete().

Here you no need to worry about place holder and other injections.

Ex:
   $result = db_select('node', 'n')
    ->fields('n')
    ->condition('nid', $node->nid,'=')
    ->condition('status', 0,'>')
    ->condition('uid', array(1,5,7),'IN')
    ->execute()
    ->fetchAssoc();

Note from db_query() API page : Use this function for SELECT queries if it is just a simple query string. If the caller or other modules need to change the query, use db_select() instead.

Do not use this function for INSERT, UPDATE, or DELETE queries. Those should be handled via db_insert(), db_update() and db_delete() respectively.


How to display previous and next arrows in views

There can only be a previous button if there are content before the current page. So logically there is no content before page 1. So obviously there will not be any previous page to go to.


Does changing the order of questions reflected in past quiz results too?

Here is a copy/past from the answer to issue # 2862591

It depends on your revisioning configuration.
Out of the box, Quiz will version changes so that your old results are not affected.
If you were to change the Quiz/Questions in any way, you may see issues with reporting since the quiz and question version IDs have changed, so new users will be taking a different version of the Quiz. But, this means that all data is preserved.
If you turned revisioning off, reordering the questions or selecting "random order" should not affect old results or reporting as the question IDs remain the same. But you have to be more careful since changing something like removing an answer or question will definitely affect old results.
I'd suggest trying on a test copy of your DB just to make sure.

I'm posting this as a wiki answer, hoping for it to marked as accepted, so that this question is no longer considered as unanswered also.


Field variable customization in node.tpl.php

If you want to hide the label, go to Admin > Structure > Content types > Coupon > Manage display.


I found a solution to this issue by performing a query on 'field_data_field_vehicle_reference' table.

For my case, the solution can be something like this:

function engines_of_vehicle($vehicle) {
  $nid = $vehicle->nid;

  // get all engine nids referenced to this vehicle
  $engine_nids = db_query('SELECT ref.entity_id FROM {field_data_field_vehicle_reference} ref WHERE ref.field_vehicle_reference_nid  =:nid AND ref.bundle =:bundle', array(':nid' => $nid, ':bundle' => 'engine'))->fetchCol();

  //load all engines referenced to this nid
  $engines = node_load_multiple($engine_nids);

  return $engines;
}


How to effectively manage a site with Drush make?

"Make files", in the Drush and Drupal context, define a set of modules, themes and libraries that make up a site. While one could stick the entire sites/all/modules directory into git, the make file is a lot faster to handle, both for git and the developers. Below is a make file from an actual project of mine. I've cut out a lot as the whole file is hundreds of lines, but I've retained enough to show all of the functionality I've used.

; API
api = 2

; Core
core = 7.x
projects[drupal][version] = 7.14

; Contrib modules
projects[date][version] = 2.0-alpha4
projects[email][version] = 1.0

; Media and file_entity go hand in hand - please make sure they work together.
projects[media][version] = 2.0-unstable5
projects[file_entity][version] = 2.0-unstable5

; Cron modules
projects[ultimate_cron][version] = 1.6
projects[background_process][version] = 1.12

; Performance modules
projects[expire][version] = 1.0-alpha2
projects[cache_actions][version] = 2.0-alpha3

; Unstable modules
projects[menu_node_views][type] = module
projects[menu_node_views][download][type] = git
projects[menu_node_views][download][url] = http://git.drupal.org/project/menu_node_views.git
projects[menu_node_views][download][revision] = f46dd41eb8c4e693a6642a6c461afa57d99a6f1b

projects[filefield_sources_plupload][type] = module
projects[filefield_sources_plupload][download][type] = git
projects[filefield_sources_plupload][download][url] = http://git.drupal.org/project/filefield_sources_plupload.git
projects[filefield_sources_plupload][download][revision] = da374770b80fcbc0dab17158d38c8436ef29caca

projects[menu_token][type] = module
projects[menu_token][download][type] = git
projects[menu_token][download][url] = http://git.drupal.org/project/menu_token.git
projects[menu_token][download][revision] = 8c18fbb

; Libraries
libraries[mediaelement][download][type] = "file"
libraries[mediaelement][download][url] = "https://github.com/johndyer/mediaelement/zipball/2.7.0"

; Patches

; #1491150: node_load in menu_node_menu_link_insert is not safe - http://drupal.org/node/1491150
projects[menu_node][patch][] = http://drupal.org/files/menu_node-node_load-in-menu_node_menu_link_insert-1491150-1.patch

; Fix rendering of relation endpoints
projects[relation][patch][] = http://drupal.org/files/relation_table_endpoints_break.patch
projects[relation][patch][] = http://drupal.org/files/relation_bundle_permissions.patch

libraries[jquery-json-min][download][type] = "file"
libraries[jquery-json-min][download][url] = "http://jquery-json.googlecode.com/files/jquery.json-2.3.min.js"
libraries[jquery-json-min][download][sha1] = "2a4615b93c65dd50f92117c570121035a0327fee"
libraries[jquery-json-min][destination] = "libraries/jquery-json"

The api line defines which Drush make API to use for the rest of the file. One important thing to notice about the file, is that all modules either have a specific version, or point to a specific git commmit. We never have -dev versions in our files. When we show up at a client meeting, or hand over the make file to the Jenkins server, there must never be any surprises. The exact version included in the file should be tested and expected to pass all types of tests. This is important to be able to delivery something of high quality.

In my company, the general agreement is that every team provides a shell-script called "build", in the root of the repository, which is responsible for setting up the site, so that automated tests can be run by the same cross-team CI setup.

Module updates can be done quickly directly on sites for testing, but officially by updating the make file, and rebuilding the site.

My team currently uses this set of build-scripts. I'm working towards moving much of the functionality into a drush extension that will heavily use provision though. A CLI version of Aegir if you will.


Passing a node field as a contextual filter to a view pane

I found a straightforward solution for this in a comment in the issue queues:

  Basically there is a Display Mode on each content type for Tokens that can be used to control exactly what is rendered by tokens that are used.

  To enable it per content type, do the following:

  In the actual Content Type itself, got to the "Manage Display" tab.
  Scroll down to the end of the field listing and click the "Custom Display Settings" link.
  Enable (Check) and Save the Token option to enable the Token Display mode.
  Go to that display mode (Grey display mode tabs near the top) and any field settings you do here effect what the tokens render (which is the same ones Panels uses).


Restricting fields using field permissions would probably be the easiest way to do it; I've had to do something similar with Profile2 in the past and it involves overriding the access callback for profile pages, and checking that the user has a certain role.

Here's some sample code if you want to try it that way:

function MYMODULE_menu_alter(&$items) {
  // Ensure that category profiles are only visible if the user has the correct role
  $items['user/%user_category/edit/parent']['access callback'] = 'zylo_user_category_access';
  $items['user/%user_category/edit/tutor']['access callback'] = 'zylo_user_category_access';
  $items['user/%user_category/edit/school_staff']['access callback'] = 'zylo_user_category_access';
}

function MYMODULE_category_access($account, $type_name) {
  // First make sure the user has normal access to the page
  if (profile2_category_access($account, $type_name)) {
    // Check that the user has the correct role
    return in_array(str_replace('_', ' ', $type_name), $account->roles);
  }

  return FALSE;
}

It isn't the prettiest but it does get the job done


How do I allow only username for password reset form?

Using the following module solves the issue as it has an option to make the reset form 'username only'.
https://www.drupal.org/project/sharedemail_pass_reset/


Form AJAX - Update button value via Ajax

From the FAPI Reference:

#ajax['wrapper']
This property defines the HTML id attribute of an element on the page which will be replaced by the html returned by the #ajax['path'] or #ajax['callback'] function. Usually, a div element is used as the wrapper, as it provides the most flexibility for placement of elements before, after, or inside of its HTML tags. This property is required for using AJAX requests in on a form element.  Note that the entire element with this ID is replaced, not just the contents of the element.

So this:
'#prefix' => "
",

Should be:
'#prefix' => "
",

Also buttons don't have a #default_value, so replace:
'#default_value' => t($is_marked),

with:
'#value' => t('@value', array('@value' => $is_marked)),

And you should be on track (the change to t() is just for sanitisation, see Translating Variables).


How to link Question node to current page?

Make sure your Question-content type as a field called "node_reference_field" with the EntityReference module.

Once that's done, you just need to make sure the nid of the current node is stored in this field. Since you're using a custom block with a generated form, it won't be that hard.
I suggest you try something like:

$node = node_load ($form_state['nid']);
$form['node_reference_field']['value'] = $node->nid;

I'm not sure about the coding, but with the EntityReference module, you aren't far from a solution.


Did you check the 'Allow multiple values' checkbox in the 'More' section of the contextual filter setup?  The 'More' section is collapsed by default, so it's easy to miss...

You have to check that box:


Solution for the URL Alias and question marks issue with Webform

By default, webform will redirect you to an internal URL with the submission parameter sid. The only way to prevent this parameter to being displayed is to redirect the user to an external URL.

What you can do is set up a bit.ly short URL that targets your thankyou page, therefore webform will think it's an external URL, won't add the submission parameter and the user will land on your http://www.somesite.com/thankyou page.


Does a user role change remove their Profile2 fields?

If you are using Profile2 in combination with Profile2 Reg Path (which you probably do or in this case - might as well use it), then you'll find two sections when you are editing Profile2 (at admin/structure/profiles/manage/profile_name_here) :

Roles - that's where you assign which roles will have the fields from Profile2;
Assign Roles During Registration - that's where you set the roles to assign to a newly registered user if user creates a profile following the path you've set.

So, in your application you'd check "PendingArtist" and "ApprovedArtist" in "Roles" section, so that your fields show up for both of those roles. Then, in "Assign Roles During Registration" section you would check only "PendingArtist", so that only PendingArtist role gets assigned to a newly created user. In the end, when the role of PendingArtist is changed to ApprovedArtist - the data entered in profile2 fields remains as entered originally.


Installing require-dev dependencies from core/composer.json

By default, Composer will install also the development requirements, if you don't use the --no-dev option.
I ran  composer create-project drupal/drupal test 8.3.*@dev, and in the output of the command I could see the following:

  Installing drupal/drupal (8.3.x-dev
  8a84ec5556f354861f1ddc5d7a80081b91ca42df)
    - Installing drupal/drupal (8.3.x-dev 8a84ec5)
  Cloning 8a84ec5556 from cache
  Created project in test
  Loading composer repositories with package information
  Installing dependencies (including require-dev) from lock file
  Package operations: 76 installs, 0 updates, 0 removals

  [Omissis]

  Installing drupal/coder (8.2.11) Downloading: 100%
  Installing phpunit/phpunit (4.8.28) Downloading: 100%

If you downloaded the archived release for example from https://www.drupal.org/project/drupal/releases/8.2.7, which doesn't include the development requirements, you need to run composer update from the directory containing core and composer.json.
I tested composer update --dev after removing the vendor directory from the test directory created from the previous command, and I got this output:

  You are using the deprecated option "dev". Dev packages are installed by default now.
  Loading composer repositories with package information
  Updating dependencies (including require-dev)
  Package operations: 76 installs, 0 updates, 0 removals


Here's a workaround that worked for me.

Prerequisites: Pathauto and Transliteration modules.

Add a new text field to your taxonomy called "cleaned_name", or whatever you like. In a later step we will populate this field at view execution with the term name after passing it through pathauto_cleanstring.
Add the "Taxonomy term: Name", and "Taxonomy term: cleaned_name" to your view. The "cleaned_name" field must be below the "Name" field.
In the view settings for the "Name" field, mark the "exclude from display" checkbox.
In the view settings for the "cleaned_name" field, click on "Rewrite results" to open the rewrite settings, then mark the "Rewrite the output of this field" checkbox.
This will cause a textbox to appear, where you can build your link html. For example:

[name]

Next implement hook_views_pre_render. The idea is to take the the name, run it through pathauto_cleanstring, and store it in the cleaned_name field.  I used the following code:

function YOUR_MODULE_NAME_views_pre_render(&$view) {
    if ($view->name == "MACHINE_NAME_OF_YOUR_VIEW") {
       //dpm($view->result); INSTALL DEVEL MODULE AND UNCOMMENT THIS IF YOU NEED TO SEE WHAT FIELD NAMES TO USE
   module_load_include('inc','pathauto');
   foreach($view->result as $key => &$result) {
      $cleaned_name = pathauto_cleanstring($result->taxonomy_term_data_name);
  $result->field_field_cleaned_name[0]['rendered']['#markup'] =  $cleaned_name;
   } // End of FOREACH statement
   unset($result);
     }
}

Adding a field to your taxonomy just to have a place to return a transliterated version of your field is a little ugly. Another alternative I tried was to add the name field to the view twice, with the idea of running only one of them through pathauto_cleanstring, and thus having both a clean and uncleaned version available as tokens to build the link. This did not work however, because although you can add the term name field twice to a view, and views will create two tokens ([name], [name_1]), in the backend both tokens point to the same field. If we modify this field, both tokens will output the modified value.

Another alternative I tried was to build the link html inside the hook_views_pre_render function, and use that to overwrite the value in $result->taxonomy_term_data_name. That avoids the need to add a field to the taxonomy. However, the problem here is that views will escape the html when it displays it. I wasn't able to find a way around this.


Assuming I've parsed this all out correctly, you should be able to achieve what you're looking for using Rules. You'll need to install core's PHP Formatter for its integration with Rules to call variable_set() as an action, though beyond that it's pretty straightforward:

Event: When cron maintenance tasks are performed
Condition: Data comparison (Parameter: Data to compare: [site:url], Data value: http://example.foo.edu/)
Action: Execute custom PHP code (Code: variable_set('cas_server', 'auth.example.edu');)

Mind the trailing slash in the condition URLs - it's the path to the home page, not the domain name, so the slash is required.

Of course, you could bind it to whatever event you feel is most appropriate, and duplicate the same rule for your dev and test instances with the appropriate CAS servers (going this route would also mean you could export this with Features). I've tested the above reaction rule, and it seems to work on my own D7 instance (with the URL condition set accordingly):

# After cron
[dmw@seraph aqueduct]$ drush vget cas
cas_server: "auth.example.edu"

It's been a while since I've used the old Rules, though I don't see why something similar can't work for D6.


Twig invalid render array keys from a valid array

Build the array with renderable children:

  $vars['highlight'][$key] = [
    'title' => [
      '#markup' => 'Title here',
    ],
    'desc' => [
      '#markup' => 'Description here',
    ],
  ];

Now the loop to render each value separately should work or have the same result by rendering the complete render array:

{{ highlight }}


Allow user to choose role immediately after registration

I solved this by using the Rules module and 2 basic pages. Not a very scalable solution, but works in this limited application.

User registers using Facebook Connect or the core Drupal registration process.
The new user with the "basic" role is redirected (via Rules) to a "select your role" page with links to a "Welcome new driver" page and a "Welcome new owner" page.
Upon viewing the node, "Welcome new driver/owner", with the role "basic" a rule is triggered which sets the desired new role, removes the "basic" role and triggers role-specific welcome email.


Problem with image width in views/ block

You can try hook_preprocess_image in template.php

function <THEMENAME>_preprocess_image(&$variables) {
    // If this image is of the type 'thumbnail' then assign additional classes to it:
    if ($variables['style_name'] == 'thumbnail') {
        $variables['attributes']['class'][] = 'myclass';
        $variables['attributes']['class'][] = 'yourclass';
        $variables['attributes']['width'] = 'yourclass';
    }
}

OR

function <THEMENAME>_image_style($variables) {
  $style_name = $variables['style_name'];
  //print_r($variables);
  $path = $variables['path'];
  $style_path = image_style_path($style_name, $path);
  if (!file_exists($style_path)) {
    $style_path = image_style_url($style_name, $path);
  }
  $variables['path'] = $style_path;
  if (is_file($style_path)) {
    if (list($width, $height, $type, $attributes) = @getimagesize($style_path)) {
      $variables['attributes'] = array('class' => 'fullwidth');
      $variables['width'] = '400px';
      $variables['height'] = '400px';
    }
  }
  return theme('image', $variables);
}


Installed Bluez theme as a sub-theme but can't change Appearance Settings

In one of your comments you wrote you created your my_bluez folder within the "sites/all/templates folder".

If that's really the name of the folder where you created the my_bluez subfolder (i.e. that it is not a typo in your comment here), then I wonder what result you would get if you would rename that folder to "sites/all/themes". Because that would make it comply with the Community documentation about Installing themes (bullet 3 in that list there). It would make it even  harder to realize for Drupal that my_bluez theme is actually like a clone of the Bluez theme, no?. Just to be sure, after renaming that foled I'd then also clear the Drupal cache.

If that still doesn't work, then I wond if it could be related to some (missing) file permissions of that newly created folder.

Does this help somehow?

PS: Creating a "clone" seems to me like a better term of what you're trying to achieve. Creating a sub-theme is really something related to base themes in Drupal-eze.


Entity Field Query - Most efficient way to get authors of nodes

You are doing a lot of potentially unnecessary loads. Unless you need those nodes at some point on the page request, you will be doing a lot of unnecessary database reads.

I would EFQ to get the node list, and then do another query to just get the $uids. This example will retrieve the node list you're looking for:

$efq = new EntityFieldQuery();
$efq->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'application')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_one', 'value', $value1)
  ->fieldCondition('field_two', 'tid', $value2)
  ->fieldCondition('field_three', 'tid', NULL, 'IS NOT NULL');
$result = $efq->execute();

if (isset($result['node'])) {
  $query = db_query('SELECT DISTINCT uid FROM {node} WHERE nid IN :nids',
    array(':nids', array_keys($result['node'])));

  $uids = $query->execute->fetchCol();
  $users = user_load_multiple($uids);
}


You can use the Embedded Google Docs Viewer module:

  The Embedded Google Docs Viewer module adds a new formatter to the File field using the Field API. This formatter displays PDFs, Microsft Word documents, Powerpoint presentations, or Excel spreadsheets directly within a Drupal node.

There's a tutorial that details how to use it on the module page.


Can I use the Migrate module to sync a site database with a Filemaker Pro database?

Yes, it's possible.

You can use the Migrate module from Drupal 8. This module allows you to import data from an SQL source. You have to create a custom module to configure the migration. In that module, you should create a migrate source plugin class extending the abstract SqlBase class provided by the core Migrate module.

The SQL source plugin must implement three methods:

query(): Returns the query that selects the data from the source
database.
fields(): Returns available fields on the source.
getIds(): Defines the source fields uniquely identifying a source
row.

Plus, you'll have to declare the connection to the source database in the settings.php or settings.local.php file. So, you'll have the Drupal 8 connection configuration and your migrate source database:

$databases['migrate']['default'] = array (
  'database'  => 'source-database-name',
  'username'  => 'source-database-username',
  'password'  => 'source-database-password',
  'host'      => 'source-database-server',
  'port'      => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver'    => 'mysql',
);

Finally, you need you define the migration that uses your created plugin and the database:

id: filemakerpro
label: 'Filemaker Pro'
source:
  plugin: filemakerpro
  key: migrate
process:
  title: title
  field_datetime: datetime
  field_place: place
destination:
  plugin: 'entity:node'
  default_bundle: yourbundle

Once you have done this, you need to execute the migration. You can execute it periodically and migrate will add the content.

You can have more information in the Migrating data from a SQL source (the info I posted here is a briefing from that link).


How to have multiple users in a user reference field

Yes, you can do that.
You need to select "Autocomplete (Tags style)" as the widget you use in the Form display.

After you have done that, you can use commas to add multiple users in the same widget (provided you have set cardinality to > 1).


How to validate input data that are previously saved?

oh..

drupal submit  form hook does the magic


I've always used the Porter Stemmer module to handle that, it works a treat.

This module implements the Porter stemming algorithm to improve English-language searching with the Drupal built-in Search module.
The process of stemming reduces each word in the search index to its basic root or stem (e.g. 'blogging' to 'blog') so that variations on a word ('blogs', 'blogger', 'blogging', 'blog') are considered equivalent when searching. This generally results in more relevant search results.


Views filter (contextual?) by Taxonomy id

Add Term ID as contextual filter.

When filter value is not available, select Provide Default value

For Type, select Term ID from URL

This is automatically pickup the term from your node, your view preview will go blank, because the actual view edit page does not have a term. It will show up when you look at the node.


How to display a Paragraph field with a condition

Depending on how complex your logic is, you can either write it inside the paragraph preprocess function, as in:

function THEME-NAME_preprocess_paragraph_PARAGRAPH-TYPE($variables, $paragraph) {
  if(some_condition) {
    $variables['field_name'] = $paragraph->get('field_name')->value;
  }
  // ...
  return $variables;
}

or write the same logic inside twig template if its simpler, as in:

{# paragraph--PARAGRAPH-TYPE.html.twig #}

{% if condition %}
  {{ content.custom_var }}
{% endif %}

I can elaborate and edit this answer if you are more specific.


Unable to render posted date in node--article.tpl.php

I was able to render the date by performing

print format_date($node->created, 'article');


Need to print all the function calls Drupal makes

I would recommend using Xdebug as opposed to any other methods.

Xdebug can easily be installed and then all you have to do is enable profiling and navigate around your site.

Not only does it list all function calls but it counts how many times each is called during a request and also times the function call, so you know exactly where to look to resolve bottlenecks.

The results can be viewed using Webgrind (browser-based) or KCacheGrind (KDE/linux), amongst others.

This is more efficient because you are not tampering with the code and littering it with debug statements.


D7: How do you get the name of a module?

You can use the system_rebuild_module_data() function to get a list of all module data in the system:

$module_list = system_rebuild_module_data();

Each entry in the array returned from that function contains all the details about the module, e.g.:

It's the same function used by the system modules admin page so I think it's safe to assume this is the best way to get this particular data.


How does #value_callback really work (nested elements, ...)?

One thing i want to add before replying to your questions. Drupal core FAPI doesn't allow multiple #value_callback. It allow only one #value_callback per element type. Even You don't have to add #value_callback key in your hook_element_info() if your value callback follow the format form_type_' . $element['#type'] . '_value'.
// See code in include/form.inc from function _form_builder_handle_input_element line 2034

$value_callback = !empty($element['#value_callback']) ? $element['#value_callback'] : 'form_type_' . $element['#type'] . '_value';

1) How does #value_callback work, what should you return in it, etc. ?

value_callback provides a way to process values before they are returned to the form submit function. You need to provide a #value_callback if you want to do fancy processing on the input. If you just want #value set to #default_value, you don't need this hook at all, since that will happen anyway. This function is mainly useful if you need to do something non-standard with the value, like transpose an array into an option list.
Value callbacks should consider three conditions:

Input is being provided directly. This happens when a form is submitted.
No input is provided, but the field definition has a default value.
No input is provided and there is no default value.

1.1) what exactly are you supposed to return in #value_callback and why do the individual callbacks work in the way they do (or don't do in case of the first one).
So value callback is supposed to check the $input !== FALSE and then modify the $input value as per your logic. If its false that means $input value is not provided in this case you can return the $element['#defalut_value']. So in your first value callback TST_value_callback_1 if you want to make that work you have to return the value with the same array key something like.
function TST_value_callback_1($element, $input = FALSE, &$form_state) {
  //example of input retrieving magic
  $input['testing_test'] = $input['testing_test'] . '_valc_';
  return $input;
}

In your second value callback TST_value_callback_2  it was adding value to $form_state['values']['inp'][0] because you was returning an array with index 0 having the value ABC_valc_ like array(0 => 'ABC_valc_');
// code from include/form.inc from function _form_builder_handle_input_element line 2109

// Set the element's value in $form_state['values'], but only, if its key
// does not exist yet (a #value_callback may have already populated it).
if (!drupal_array_nested_key_exists($form_state['values'], $element['#parents'])) {
  form_set_value($element, $element['#value'], $form_state);
}

1.2 is there any way how to make the #value_callback store the data in 'element root' ($form_state['values']['inp']), i.e. in the same place as if I used form_set_value in #element_validate?
Setting the #tree to false in your form element should do the trick.
$ar['inp'] = array(
  '#type' => 'TST',
  '#tree' => FALSE,
  );

you will be able to get the value in $form_state['values']['inp'] but in this case #value_callback will not do any affect, and $input in #value_callback is set to NULL  i don't know why. So you better use the ($form_state['values']['inp']['testing_test'])
2.1) Is there any way to enable 2.2 behavior without setting #value_callback in ?
2.2) Why are individual #value_callback functions run (and their outputs are saved to $form_state) only when parent (A) #value_callback is run (even if it doesn't reference or call the individual functions in any way)?
Hopefully my above explanation help you to understand the role of #value_callback. Even though custom element that is made of a nested set of other elements, are also elements so individual value callback will be called for each subelement. There is too much too explain Please take a look at _form_builder_handle_input_element
3) Do I understand this flowchart correctly that #value_callback is called before #element_validate?
yes #value_callback is called before the #element_validate callback. For more explanation See Creating Custom Elements
For practical example see examples module.
See also:
https://api.drupal.org/api/examples/form_example%21form_example_elements.inc/function/form_type_form_example_checkbox_value/7
https://api.drupal.org/api/examples/form_example%21form_example_elements.inc/function/form_example_phonenumber_combined_value/7


Categorizing and Sorting Webform Submissions

Webform Report module allows users to create simple, dynamic reports based on data collected by the webform module. It adds a new node type that contains the report criteria, and the data displayed is updated automatically as webforms are submitted. The data can be sorted according to the viewer's preference without altering the report criteria.


Formatting my Link field with multiple values

The two best ways to do this are the one you suggest by creating a tpl.php like you mention and doing your work in there directly.  Another (and preferred by many, but a bit more complex) is to use template_preprocess_field.

A very good explanation of how to go down the second route is http://www.digett.com/blog/01/18/2012/change-output-single-field-drupal-7-node

That way you don't end up with a whole bunch of field.tpls and you can isolate your changes in that function.


PHP contextual filter code in drupal 7 'no query was run'

I would suspect that no query is run because your code snippet isn't returning anything. The thing that jumps out to me is that you are trying to use $result as the first row returned by the query, however it is actually the entire result set.  For example, retrieving data from a DB usually look similar to the code below:

$result = db_query($sql);

// Iterate over the collection ($result).
foreach ($result as $record) {
  $agency_id = $record->agencyid;
}

In the example you posted above, you could use the following code snippet to pull a single field from the first row in the result set:

// This would return the agency ID.
return db_query($sql)->fetchField();

Take a look at the documentation of fetchField() for more information on how it is used.


Use drupal_add_js() for this.

Please also check these resources; they could help you out.

For using other versions of jQuery, there is the jQuery Update module.


Do following steps:

Instead of Set data value use Add an item to a list in action. In List field select node:field-previous-tenant, in Item to add field select node-unchanged:field-tenant. At last add an action Save entity and select node in Entity field.


Menu items are nested using the item path. Take look to the paragraphs module:

/**
 * Implements hook_menu().
 */
function paragraphs_menu() {
  $items = array();
  $items['admin/structure/paragraphs'] = array(
    'title' => 'Paragraph Bundles',
    'description' => 'Manage Paragraph bundles',
    'page callback' => 'paragraphs_admin_bundle_overview',
    'access arguments' => array('administer paragraphs bundles'),
    'file' => 'paragraphs.admin.inc',
  );

  $items['admin/structure/paragraphs/list'] = array(
    'title' => 'List',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => -10,
  );

  $items['admin/structure/paragraphs/add'] = array(
    'title' => 'Add Paragraph Bundle',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('paragraphs_admin_bundle_form'),
    'access arguments' => array('administer paragraphs bundles'),
    'type' => MENU_LOCAL_ACTION,
    'file' => 'paragraphs.admin.inc',
  );

  $items['admin/structure/paragraphs/%paragraphs_bundle'] = array(
    'title' => 'Edit paragraph bundle',
    'title callback' => 'paragraphs_bundle_title_callback',
    'title arguments' => array(3),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('paragraphs_admin_bundle_form', 3),
    'access arguments' => array('administer paragraphs bundles'),
    'file' => 'paragraphs.admin.inc',
  );

  ...

  return $items;
}

Also if you want to add your menu item to an existing menu other than administration use the menu key.

$items['menu-item'] = array(
  'title' => 'Foo bar',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('foo_bar'),
  'menu' => 'user_menu'
);

Check the hook documentation for more information.


How to integrate an Android database in Drupal?

Consider using the Feeds module for such kinds of imports. Here is an excerpt from its project page:

Import or aggregate data as nodes, users, taxonomy terms or simple database records.

One-off imports and periodic aggregation of content
Import or aggregate RSS/Atom feeds
Import or aggregate CSV files
Import or aggregate OPML files
PubSubHubbub support
Create nodes, users, taxonomy terms or simple database records from import
Extensible to import any other kind of content
Granular mapping of input elements to Drupal content elements
Exportable configurations
Batched import for large files

Especially the first bullet seems to be what you're looking for.
Consider refining your question to provide some more details of the database format of your Android app. E.g. is it a PDO-compliant DBMS? If so, and in case you'd want to consider it, it might be possible to use a co-existance setup also (= use Drupal to only 'display' your data residing in your Android app).


theme_preprocess_views_view_fields() function in drupal7 does not accept static variable as index

Static vars aren't special beyond persisting inside the scope of the function they were created, for the duration of a single page build. You categorically can use a static var as an array index.

Take the following code:

function some_test(&$variables) {
  static $i = 0;
  print $variables[$i];
  $i++;
}

$variables = array(
  0 => 'test1',
  1 => 'test2',
);

some_test($variables);
some_test($variables);

Which outputs the following:

test1
test2

Proving that $variables[$i] is accessed as expected.

The problem with you code must be somewhere else, as it's not being caused by a language issue as you suggest.

At a wild guess, $variables['view']->result isn't keyed in the same way you expect it to be (possibly keyed by the result's base table ID instead of a zero-based list). Dumping out $variables['view']->result should tell you pretty quickly what's happening.


Cannot add a file with Search API Attachments

there are some steps to follow in the module README.txt file :

https://cgit.drupalcode.org/search_api_attachments/tree/README.txt?h=8.x-1.x#n81


taxonomy_get_parents_all will do what you're looking for, but I don't believe it's possible in views.
http://api.drupal.org/api/drupal/modules--taxonomy--taxonomy.module/function/taxonomy_get_parents_all/6

That being said, there's a module that might help you with that. It's called Taxonomy Views Integrator http://drupal.org/project/tvi


How do I programmatically update the rendering language?

Yes, this is not a handler setting. This is configured directly in a display.
To update a View programmatically use the storage property of the View object (which is by the way a reference to the config object discussed in the comments) and get a reference of a display (the master display is default):
$view = \Drupal\views\Views::getView('myview');
$storage = $view->storage;
$display = &$storage->getDisplay('page_2');
$display['display_options']['rendering_language'] = '***LANGUAGE_language_content***';
$storage->save();


Display certain content based on whether a date is in the past or future

Please follow below instructions to add new custom code field.

Go to admin/structure/types/manage/your_content_type/display
Click on Add Custom Fields Vertical Tab @ Bottom of Screen.
Click on Add a Code Field.
Use $entity object to get Release Date based on that display the message.
Enable the Code Field in right place.

Post comments if you have any Questions.


I was able to resolve the issue. You just have to prefix your test with test_. Seriously! No kidding!

My test looks like the following:

<?php
/**
 * @file
 * Contains Drupal\Tests\phpunit_d8\Unit\MathTest
 */

namespace Drupal\Tests\phpunit_d8\Unit;

use Drupal\Tests\UnitTestCase;
use Drupal\phpunit_d8\Math;

/**
 * Class MathTest
 * @package Drupal\Tests\phpunit_d8\Unit
 *
 * @group math
 */
class MathTest extends UnitTestCase {
  /**
   * Very simple test to MathTest::addNum().
   */
  public function testAddNum() {
    $math = new Math();
    $this->assertEquals($math->addNum(1,2,3), 6);
  }
}

Also, pushed at https://github.com/ajitdev/phpunit_d8


Use this if you just want the URL:

<?php print url('user/login'); ?>

If you want to print a link:

<?php print l(t('Login'), 'user/login'); ?>

And in your case it would be:

<?php print l('<span>' . t('Login') . '</span>', 'user/login', array('html' => TRUE)); ?>


I'd say you need the views module.

I haven't used it with entity reference before, but I think you will need to set up a new view that displays events and use the relationship settings to link them to your city nodes.

If you don't actually need the cities to be nodes, you could make them a taxonomy instead which is much simpler to create a view for because you can make a field on your event that directly references the taxonomy.

Finally, to 'allow the user to choose' anything you need exposed filters in your view.


Drupal 7 - Retain checkbox values across pages

Store the selected checked box in a database. Load each check box as the pagination goes and check the #default_value

example if I had 3 checkbox in a table select for my pagination:

$values = array();

$values[1] = TRUE;
$values[2] = FALSE;
$values[3] = TRUE;

$form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#default_value' => $values,
    '#empty' => t('No campground to claim'),
  );

Obviously there is more to this, like pagination, but it should get you on the right track.


how to comment individual image in popup form drupal 7?

First, in your content type edit page, make the "Preview Before Submit" option disabled or optional. Once you do that you will see the Submit button.

Even you make the Submit button appear, the same will happen and user will be redirected to the actual page with no modal display. From the pattern of your modal window, I guess you are using colorbox plugin. If yes then you need to open this colorbox as an iframe option.

<script>
    $(function () {
        $(".example6").colorbox({iframe:true, innerWidth:425, innerHeight:344});
    })
</script>

So even you submit the page, the page will not be redirected outside of modal.

EDIT #1
Then I think you may have to alter the form you are using and check for form elements with a debug() function. Then I guess in your form_alter you can do the following,

<?php
  function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if (isset($form['type']) && $form_id == 'mymodule_node_form') {
      // Hide the preview/submit button.
      $form['actions']['preview']['#access'] = FALSE;
  }
}
?>

Have a check on the variable that sets the preview, by

variable_get('comment_preview_' . $node_type);

If it's set then can be disabled via,

variable_set('comment_preview_' . $node_type, DRUPAL_DISABLED);

I hope this will be helpful to your cause.


How to inject custom dependence in custom entity?

You cannot; per the Services and dependency injection documentation:

  Note: It's not possible to inject services to entity object. See this issue for more details.

You'll have to get the service from \Drupal directly.


Add custom class to link outputted by views

You can do this on the server side with a Views field tpl.php file, or on the client side with jQuery.

For the server side method, go to your view edit -> Advaced -> Theme:Information -> chose your field you need to create a one template file (in your theme/templates folder):

For example: if your field name is title you will see something similar to this:

Field Content: Title (ID: title): - click on it and cope the code

views-view-field--YOURVIEWNAME--page--title.tpl.php -paste it here

Now you have 3 variables to play with

 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.

Easy way - do it with str_replace function :D

<?php $output = str_replace('<a', '<a class="someclass"', $output); ?>
<?php  print $output; ?>

Also you can play around with($row) and create your own output. To easy development install devel module so you can dpm($row) and see what it contains. or you can print_r($row). have fun <3

Fastest way to do this with jQuery you can simple add class to your fields anchor tag.

$(document).ready(function() {
    $('.your-views-class-name .your-view-field a').addClass('someclass');
}

open firebug(int firefox) and find your view class name and field class name which contains anchor tag and add class to it. You can do this in YOURTHEME - scripts.js or any other js file you want.


Why direction nav transition not working on Flexslider module?

I see the same issue sometimes.
When I look at my local direction anchors, they are display:none by default, but the WooThemes example they are display:block.
Also, obviously, the opacity and left/right css3 transitions don't work.

In Chrome you can test the :hover selector on the .flexslider element.

I have seen this work properly in some sites.

It looks like there's a responsive breakpoint at 860px that you need to consider, so I placed these styles at min-width:861px.
If you make these styles the default, the arrows will always be visible under 860px. This is why I put the styles at 861 and above.

Anyway, my approach to 'fixing' this was to simply reinforce the display, opacity, left/right, and transition settings in my theme CSS.
Not sure if all of this is necessary, but it does work :)

/** Media Queries: min 861 only Flexslider
------------------------------*/
@media (min-width: 861px) {
    .flex-direction-nav .flex-prev {
        -webkit-transition-property:left, opacity;
        -moz-transition-property:left, opacity;
        -o-transition-property:left, opacity;
        transition-property:left, opacity;
        -webkit-transition-duration:0.3s;
        -moz-transition-duration:0.3s;
        -o-transition-duration:0.3s;
        transition-duration:0.3s
    }
    .flex-direction-nav .flex-next {
        -webkit-transition-property:right, opacity;
        -moz-transition-property:right, opacity;
        -o-transition-property:right, opacity;
        transition-property:right, opacity;
        -webkit-transition-duration:0.3s;
        -moz-transition-duration:0.3s;
        -o-transition-duration:0.3s;
        transition-duration:0.3s
    }
    div.flexslider .flex-direction-nav a {
        display:block
    }
}


In misc/states.js, it looks for the closest form-item, form-submit, or form-wrapper. Here's the line:

$(e.target).closest('.form-item, .form-submit, .form-wrapper').toggle(e.value);

This does not play well with the way radios are themed, and states.js does not find anything to toggle. Wrapping the itinerary_name radios in a container and applying #states to the container item is what I would call the quickest workaround.

$form['itinerary_radios'] = array(
  '#type' => 'container',
  '#attributes' => array(),
  'radios' => array(
    '#type' => 'radios',
    '#options' => array(
      'new' => t('Create a new itinerary'),
      'existing' => t('Use an existing itinerary'),
    ),
  ),
  '#states' => $trip_states
);


How to verify a token in the url of a drupal 7 site against an external web service and skip the login form all together?

So, I don't have a working solution for this (yet!) but I'm working on a similar use case. From what I've read, you can't really have an authenticated user do anything on a Drupal site without passing them through the user module, creating a user, and storing info about them in the database.

I believe you need to write a module that passes a user object based of the email in your json response to user_external_login_register passing in some sort of programmatically populated dummy text for the extra fields you need, and then programmatically create the user and log them in in the background. In theory, all you need to do is pass the user object based off of your 200 response, and proceed to create and log the user in.


How can I get bundle of an entity from type and id?

Use entity_load to load the entity as mentioned by @Nikhil.

Then use entity_extract_ids, to extract the bundle. Example:

$entity = entity_load('node', array('7'));

list(, , $bundle) = entity_extract_ids('node', $entity);

echo "Bundle name is : " . $bundle;

The function entity_extract_ids returns a numerically indexed array (not a hash table) containing the elements:

0: Primary ID of the entity.
1: Revision ID of the entity, or NULL if $entity_type is not
versioned.
2: Bundle name of the entity, or NULL if $entity_type has no bundles.

where, 0, 1, and 2 are array indices. However, the approach used by core and contrib modules is to use the list() function.


how to check whether an error occurs due to a specific field in drupal?

This is what you are looking for:

https://api.drupal.org/comment/28464#comment-28464

Edit: Code excerpt from link:

/**
 * Custom Form Validation.
 * Removes all form validation errors caused by a 'foo][bar' form element.
 */
function my_module_form_validate($form, &$form_state) {
  $errors = form_get_errors();
  if ($errors) {
    // Clear errors.
    form_clear_error();
    // Clear error messages.
    $error_messages = drupal_get_messages('error');
    // Initialize an array where removed error messages are stored.
    $removed_messages = array();

// Remove all errors originated by the 'foo][bar' element.
    foreach ($errors as $name => $error_message) {
      if ($name == 'foo][bar') {
        $removed_messages[] = $error_message;
        unset($errors[$name]);
      }
    }

// Reinstate remaining errors.
    foreach ($errors as $name => $error) {
      form_set_error($name, $error);
      // form_set_error() calls drupal_set_message(), so we have to filter out
      // these from the error messages as well.
      $removed_messages[] = $error;
    }

// Reinstate remaining error messages (which, at this point, are messages that
    // were originated outside of the validation process).
    foreach (array_diff($error_messages['error'], $removed_messages) as $message) {
      drupal_set_message($message, 'error');
    }
  }
}


Create a kind of coupon with a entity references or node reference and no autocomplete

This is the way to avoid the autocomplete in a node reference
    unset($form['MYFIELD']['#autocomplete_path']);


Is there a way to alter only the printable invoice for Ubercart 3.8?

I see 2 possible solutions:

Create separate template called "when_client_prints" and link to this    template from Views Orders.
Edit current invoice template within your custom module with the logic like if user hasn't id * then show the logo. (* stands for the UID of client account)


There are two things you can do here in order to try and make you site more portable.

In your templates:

Always use l() for all links (even JavaScript links)
If you need to reference an image in the theme use:

<img src="<?php echo $base_path . drupal_get_path('theme', 'themename'); ?>/logo.png" />

In your content:

You do not really have a way in order to preserve uploaded content URL's unless using some form of file manager which do not create absolute links, but much rather links that get sent to drupal that redirect to the file
If the above is not going to work for you then a modification of the rewrite rules for the drupal site sitting under the subdir is required to basically rewrite all URLs requested that start with sites/default/files/(.*) rewritten to subdir/sites/default/files/$1

And the apache mod_rewrite rule may look like the following.

# Redirect all files requests to a subdir
RewriteRule ^/?sites/default/files/(.*) /subdir/sites/default/files/$1 [R=301,L]


There is an ongoing discussion in Drupal.org forums:

https://www.drupal.org/node/2533498

According to the latest answer on that thread: to be expected in 8.4

Best regards,

Oleg


Content type creation with table of fields

Use field collection to make a group of fields, then set that group to unlimited entries, simple.


The namespace on your AdminSettingsForm class is incorrect.
It should be Drupal\company_info\Form;


Can I remove unused core modules from Drupal?

Modules that have never been enabled are not a performance issue.

The issue report you linked is referring to what Drupal does when it doesn't find an enabled module; in such case, Drupal rescan the directories where the modules are placed, causing performance issues. To avoid it, modules should be uninstalled from the module page, and then deleted from the server directories; if you do this, you will never have any performance issue.

If you are thinking of removing the database rows found in the "system" table referring to those core modules that you don't use, then it is useless, as Drupal adds those rows back every time you visit the module page.
If Drupal were not doing that, you would not be able to install new modules. When you visit the modules page (admin/modules in Drupal 7), Drupal rescans the directories where modules are placed, to list the new modules you could have copied on the server. If it finds a module that   doesn't have a row in the "system" table, it adds it; it cannot know if you removed that row from the table, or it is a module that you copied on the server, and you want to install.

If you are thinking of removing the module files for those core modules you don't use, you should keep doing it every time you update Drupal; as there isn't any gain, it's useless doing it.


Hook for a JS library in a custom module not working drupal 8

Just wrong indentation. Dependencies need two spaces indentation:

ajax_form:
  version: 1
  js:
    js/ajax_form.js: {}
  dependencies:
    - core/jquery


How to set a custom URL for a node without pathauto?

This seems to be a duplicate of this issue

Try using hook_node_insert($node) for new content and/or hook_node_update($node) for existing content:

function mymodule_node_insert($node) {
  if ($node->type == 'mytype') {
    $node->path['alias'] = _some_awesome_pattern_maker($node);
  }
}

function mymodule_node_update($node) {
  if ($node->type == 'mytype') {
    $node->path['alias'] = _some_awesome_pattern_maker($node);
  }
}

_some_awesome_pattern_maker($node) {
  // massage node and return string
}


There are several things you can do to make your site work with Drupal a little better.

First,  it is a bit unclear how you are using your user reference field.  When I add the labels Admin and normal it sounds a bit like you are duplicating The users functionality already built-in.  Go to admin/people and look at the definition of roles and permissions.  It will allow you to define categories of users and assign them access to specific categories of content and activities on the site.

Next.  Define your view to achieve what you want, ignoring the panel.  'Taming the Beast' at nodeone.se demonstrates doing exactly what you are looking to do.  I recommend watching the entire series to understand exactly how Views works.
Note that applying contextual filters can be a little tricky.  I recommend you do not use path aliases when using them.

Only after you have your view displaying should you add the additional complexity of placing it in a panel.  Once again, nodeone has an excellent series for understanding how panels works.  Panels works closely with Page Manager and the videos show them working together.


Cannot get articles or custom content types to load on front page

By default, in a fresh Drupal 8 installation, your homepage is populated by the frontpage view. Make sure that your homepage URL under admin/config/system/site-information is /node. That is the default URI of the frontpage  view.

You can find the definition of that view under admin/structure/views/view/frontpage.

If you need a guide about the Views module, you can find it on Chapter 9. Creating Listings with Views.


This might work

if (($route = $collection->get('entity.example.canonical'))) { // base_route
      $current_route = \Drupal::routeMatch()->getRouteObject(); // get current route
      $current_route->setRequirement('_role', 'administrator');
}


Add ctools processing for content loaded via ajax

You need to call Drupal.attachBehaviors() after inserting the new content into the page.

Change this:

$parent.append( data );

To this:

$parent.append( data );
Drupal.attachBehaviors($parent);


How can I create a link, within a form, for a user to download a file?

Okay, so I found a solution that works pretty well, though I'm sure there are better ways to do this.

I resolved on the submit button approach, as it seems all buttons in Drupal 8 turn into submit buttons anyway. Here's the code for the button itself.

$form['taxonomy_download'] = [
      '#type' => 'submit',
      '#value' => t('Download Default Taxonomy Terms'),
      '#limit_validation_errors' => array(),  //don't run form validation when this button is pressed
      '#submit' => array('::downloadFile'),  //call this function when the button is pressed
];

Then, for the downloadFile function:

public function downloadFile(array &$form, FormStateInterface $form_state) {

    // Creates a string of the file location. SERVER_NAME returns the
    // name of the host site, e.g. 'www.example.com' or '50.0.0.1'
    $buildUrl = 'http://' . $_SERVER['SERVER_NAME'] . '/sites/default/files/Example.xlsx';

    //drupal_set_message($buildUrl);    //uncomment this line to see what is getting passed

    $url = Url::fromUri($buildUrl);     //Creates a url from the file location

    $form_state->setRedirectUrl($url);  //Redirects the user to the file location
}

You will need to place the file that you're trying to download into the public files folder, found in your Drupal installation's sites/default/files/ folder. You can test that you have the file in the correct location by typing the full path (e.g. http://www.yoursite.com/drupal/sites/default/files/ExampleFile.ext) into your browser's address bar. The file should download when you go to that address.

Finally, you will need to include use Drupal\Core\Url; at the top of your code to make the fromUri() and setRedirectUrl() functions work.


Create folders in custom installation profile fails when usind drush site-install

I found a solution that works.

Drupal sets it's own constants, such as DRUPAL_ROOT which can be used instead of $_SERVER['DOCUMENT_ROOT'].

So, all I had to do was to change $site_root = $_SERVER['DOCUMENT_ROOT']; to $site_root = DRUPAL_ROOT;, for it to work correctly when installed via Drush.


Show content that referenced to a user to him

If you have a content type with a user reference field and you want to display a list of these content types that reference the currently logged in user, you could create a view, Filter it on published nodes of that type, and then add in an Argument, which would be the field in question, and then supply as the default argument the uid of the currently logged in user.  Then just set up whatever Fields you want displayed and you should be on your way.


Limiting input on node title and plain text area fields

There's the beta version of the Maxlength module which can be applied to built-in fields as well custom text fields.  The Maxlength module allows you to set maximum length of any field; one option includes showing a javascript character countdown on the edit forms next to the applicable fields.

You could also take the js library this module is based off of and apply with the hook_form_alter approach.


How to send a confirmation reservation email using the Reservations module?

The Reservations: Email module is what allows you to send eMails. Some more details about it (from its project page):

  This module extends Reservations to send emails at different stages in the reservation process. Token based templates are included so the emails can be customized with any information from the Reservation node or User objects. Also included is a pseudo-token for a confirmation link that allows users to confirm reservations without the need to grant them the permission to confirm reservations.

However, looking at the module source, using tokens in the eMail body requires that the token module is enabled. So if you haven't enabled that module yet, it may explain why you "could not find a token to use to refer to the user in the email body" (as in your question).

Update:

About your extra comment like "... I had to add a new field to the reservation type to save the name of the user requesting the resource. I later used that field in the email.": that seems like a variation of what's written in the issue about "Sending emails to anonymous users". That issue contains a patch that you may want to look at also.


Get entity id in hook_form_BASE_FORM_ID_alter()

That CR is outdated, probably there's a later CR updating it: now you should use $form_state->getFormObject()->getEntity().


Here you declare

'allofus_four_grids_block' => [
      'variables' => [
        'block' => array('key' => array()),
      ],
      'path' => drupal_get_path('theme', 'basis') . '/templates/custom-blocks',
    ],

So you need to use the variable block :

$build = [
      '#theme' => 'allofus_four_grids_block',
      '#test_var' => $this->t('Test Value'),
      '#block' => array('key' => $block),
    ];

Not #doubles


I was having a lot of problems with the connection and authentication with the server until I change the bind dn format.

Maybe try something like this:

binddn = webwasher88@hnbwyo.com


How do I remap folder to different folder in URL?

Yes you can do this with remapping in .htaccess

Find this code:

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on

And add this line after it:

RewriteRule ^product-details/my-demo/(.*) my-demo/$1

So the complete version will be:

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on
  RewriteRule ^product-details/my-demo/(.*) my-demo/$1

See documentation for more examples.


I will again answer my own question here:

The change is made in the page.tpl.php template found the the template directory of your theme.

In this case, all I had to do is move the following:

<?php if ($breadcrumb): ?>

<?php print $breadcrumb; ?>

<?php endif; ?>

from it's present location under the main-wrapper to its new location under the content heading. Then I cleared the theme registry cache.

Make sure that if you move an "if" statement, that you always move its corresponding "endif" statement too.

:)


How to check if a field has more than one value

Use the length filter, which also works on arrays:

{% if items|length > 1 %}
  field contains more than 1 item
{% endif %}


ICalendar and Outlook opeing as node For Add to Cal Module Even After Clearing Caches

I'm a maintainer of the Add To Cal module. It turns out that this is in fact a bug, which we're patching right now.

Until the patch is released, you can fix the issue by downloading and enabling the Entity module on your site. The patch will add this as a dependency to Add To Cal.

Here's the issue on drupal.org: https://www.drupal.org/node/1744684#comment-9056553

EDIT: The 1.x-dev version now includes this bug fix, and it will be included in the beta4 release.


Neither #ahah nor path are used in Drupal 8. Instead of the first, Drupal 8 uses #ajax; instead of the second, it uses url which must be a \Drupal\Core\Url to which to submit the Ajax request.

Finally, callback is a PHP callback, which generally is a full qualified (using a PSR-4 namespace) method name.

Reference

Ajax API
PSR-4 namespaces and autoloading in Drupal 8


Reply to my self:

I have created a custom Controller that get the user from db based on the domain, i get the subdomain using this:

$subdomain = substr_count($_SERVER['HTTP_HOST'], '.') > 1 ? substr($_SERVER['HTTP_HOST'], 0, strpos($_SERVER['HTTP_HOST'], '.')) : '';

Not sure if its the best.

Then i compare to the user on db:

$result = \Drupal::database()->select('user_data', 'n')
            ->fields('n', array('id', 'user_domain', 'user_email'))
            ->condition('n.user_domain', $subdomain)
            ->execute()->fetchAllAssoc('id');

First you need to create a install schema with the domain created so you can fetch this.

Then loading by user email:

$user = user_load_by_mail($userEmail);

and pass the variable to the Twig.
Not sure if its the best way.


How to detect mobile viewport with in twig?

There is a Browser Object in twig which using that you can get some data about user's browser but it does not provide properties like screen width.

its recommended to use css or javascript in these situations but if you want to hide your block in server side so user might access only using a mobile phone then I recommend this steps:

first of all you should provide a value to check if user is using mobile or not, for this you should use a preprocess function (hook_preprocess_page I guess as will fire for any pages loaded) , there use a code like this to detect mobile, then add a boolean value to page which should be TRUE if user is using mobile.
after that in twig you will have that value, check if it is true and display your block


how to make images clickable in a listing (numerous thumbnails)

Click on the field for the image and you should see "link image to" and you can select "content". Set the filter criteria so that the system knows what content to link to. Also, the image should be coming from the content, such as as a thumbnail.


How can I find user role based on user id?

Use user_load() or global $user.

global $user;
$account = $user;
$role = $account->roles;// returns user role.

or

$user = user_load(uid);
$role = $user->roles;//return user role


How to call different fields from different content in same view?

To get the values of "cage rent per day" from B to A's view, you must add a relation in content A view with the "Fee category" field.

Then normally you should select in the "cage rent per day" field settings in view A, the relation you've just added.

However, the idea is to have some reference to content B in view A to access B's fields values. And this is possible with relations .


As a backup solution, I'll do it this way:

$form['#suffix'] = '<script type="text/javascript">some_function_to_do_what_i_need();</script>';
return $form;

this should work.


Images show up once, then have to clear styles folder to see again?

The fact that derived images can be fetched when they are absent from the filesystem but not when they are present indicates this is a webserver configuration issue.

The webserver rules are normally be set up so that any non-existent paths are routed to Drupal. When image thumbnails are generated they get served by Drupal, but once on disk they should be served directly from the filesystem. Check your .htaccess files (if using Apache) and somewhere there is likely to be an rule denying access to that area of the filesystem.


It depends on your settings.php $cookie_domain value.

/**
 * Drupal automatically generates a unique session cookie name for each site
 * based on on its full domain name. If you have multiple domains pointing at
 * the same Drupal site, you can either redirect them all to a single domain
 * (see comment in .htaccess), or uncomment the line below and specify their
 * shared base domain. Doing so assures that users remain logged in as they
 * cross between your various domains.
 */
# $cookie_domain = 'example.com';

For the session cookie, a value of:

$cookie_domain = '.example.com'; // Note the leading wildcard dot "."

will work across subdomains

Whereas a value of:

$cookie_domain = 'true.example.com';

will only work on true.example.com

If that session id is valid for that site database session table then the user will be logged in.


Localhost configuration and problem with file permissions

The web server must have a properly configured file structure to operate. The files should be placed under /var/www or /usr/local, not under /home. The /etc directory is for system and configuration files, not web data files.

There should be no reason for you to format the root partition when maintaining a system, but if you insist on doing so, put /var /usr and /home on a separate drive, and mount them under the root during boot. That way you will not lose any data.

If you are so desperate to ease the editing, work as root and learn to be careful. But make sure the files are under the correct group and owner for the web server to operate.


I found a way:

# cd to Drupal root folder
drush dl chosen
drush make sites/all/modules/chosen/chosen.make.example --no-core
drush en chosen -y

Update 04/29/2014: Chosen now provides Drush command chosenplugin.

This answer is still useful for other projects with *.make.example files but without custom Drush installation commands.


You need to specify the class (including the full namespace) to run that method on. E.g: 'callback' => \Drupal\my_module\Plugin\Field\FieldWidget\MyWidget::changeCountry


Swap columns inside every other row with Views and Bootstrap

Use Views Bootstrap and implement it using the grid.

  Views Boostrap module enables you to create components following the theme structure of the Bootstrap framework all within the configuration settings of the powerful Views module.


Grouping content by Years (For eg Archive 2014-2015 or Archive 2014-16)

The key challenge you'll face here is that neither Views nor Date modules provide aggregation options for date-based fields.

This can be solved by using the Views Date Format SQL module. It adds a nice little check-box that allows you to group dates by a custom formatted string, as shown in this example also:

In the above example, the custom date format is set to "M Y" (which translates to Oct 2015 for example), and the box for "Use SQL to format Date" was checked. This is the only configuration needed.


Get a dropdown for Views: Filter: Taxonomy Term Name

If your views is based in content type, you should use the term reference field in the filter. Example:

I have a content type of services composed of title, body, service category(term reference).
In my services views, I will add service category as filter. In my Better Exposed Filter, I can configure that service category if I want a drop down filter or autocomplete.

Using taxonomy term name shows autocomplete filter.

I hope it helps


call_user_func_array() expects parameter 1 to be a valid callback, function 'access_denied_node_form' not found

We have had this problem before in Drupal 6. It can happen if a content type is deleted, but, for whatever reason, nodes of that type still exist.

In this case, it would suggest that you have (or had) a content type called "access_denied" and this is no longer there.

First, note down the node ID of the node you're trying to edit. Then, find the node ID in the {node} table in the database, and find what node type it is.

Then, look in {node_type} in the database to see if your node type is listed there.

If you're missing a node type, you will need to restore the node type before you can edit that node. For example, if you uninstalled a contrib module that provided a particular content type, and that module didn't uninstall cleanly, you might have this issue, so you'd need to reinstall that module to fix things up.

There isn't any way that I know of to find the base module associated with a particular node type, unless it's obvious (the book module provides a node type of book, or similar), but if you are really stuck, you can always delete the node by visiting /node/123/delete - after all, if the base module is no longer present, the node itself probably isn't very useful to you.


List of nodes that have no taxonomy terms

Try this:
1. create a node view
2. in 'Fields', add 'Node: nid'
3. in 'Relationships', add 'Taxonomy: Node'
4. in 'Filters', add 'Taxonomy: Vocabulary', in next step, choose 'Is empty (NULL)' as the operator.
5. test some of the nids given in the preview to see if they are the ones you are looking for, you might need to tweak a little the usage of relationship.
Step #3 is here to give you extra operators to choose from.

update

Okay the above assumes the content type only has one term field, so nevermind...
Now that I understand the issue better, I think you will probably need views_or module. Also we don't need 'relationship' anymore.

On my test Views, I use filter 'taxonomy:term(term id)' for each vocabulary, chain them together via Views_or. Set them to dropdown with hierarchy. Then highlight all terms in the vocab and check 'is none of' for the operator on the left. It's a very ugly query but that's the only way I got it to work...You'd better cache it for a better performance. I attached some screenshots hope to clarify the config part.


Is there a way to show the Google Analytics panel inside a drupal site?

Google analytics reports Provide you a default report page. You can use the Query hooks to make your own query and show it as a block or panel.

They provide common queries like visits, Top pages viewed etc.


Let Composer place a Git repo into a custom path

"require": {
    "composer/installers": "dev-master",
    "miteshmap/axelerant_custom": "*"
},
"extra": {
    "installer-paths": {
        "web/core": ["type:drupal-core"],
        "web/modules/contrib/{$name}": ["type:drupal-module"],
        "web/modules/custom/{$name}": ["type:drupal-custom-module"]
        "web/profiles/contrib/{$name}": ["type:drupal-profile"],
        "web/themes/contrib/{$name}": ["type:drupal-theme"],
        "web/themes/custom/{$name}": ["type:drupal-custom-theme"]
        "drush/contrib/{$name}": ["type:drupal-drush"],
    }
}

We can do that when composer/installers have defined the type and for that a request was merged with master here - https://github.com/composer/installers/pull/269

And to add the new merge of composer/installers into your json. you can update the composer.json as per the The solution proposed here - https://github.com/drupal-composer/drupal-project/pull/118. The same is explained in above code.


Drush 8 raises an error while running 'drush runserver'

I solved installing the last version of Drush via composer:

$ # Remove previous drush installation file
$ sudo rm /usr/local/bin/drush

$ # Install drush globally via composer
$ composer global require drush/drush
$ ln -s ~/.composer/vendor/bin/drush ~/bin/drush

Now it works.


How to print a message when a Pane is empty?

Create a new pane with that text and set a visibility rule on it - there should be an existing rule that you can use. If not a ctools rule plugin is pretty simple to write and you can have that rule plugin check to see if comment count is 0.


Can I create an aggregate view that only shows totals without details?

You can individually set any field to not display in a View.


Driver not specified for this database connection

You've already provided the target DB name with the second param to addConnectionInfo(), so you just need to remove the 'default' element from the array, and shift the connection params up:

$old_database = array (
  'database' => 'grantexpert_registration',
  'username' => 'grantexpert_usr',
  'password' => 'xxxxxx',
  'host' => '62.168.127.59',
  'port' => '5432',
  'driver' => 'pgsql',
  'prefix' => '',
);

Database::addConnectionInfo('olddatabase', 'default', $old_database);
db_set_active('olddatabase');


How to style nested paragraph fields without duplication, in Views (and nested fields appear)

Seems I found an answer. I suddenly remembered there was something called the Views field View module. I installed it, played around with it until I found a "views" field. I was able to create a second view for the nested paragraph, add it to the first paragraph' view, through the and use a conditional field based off 'parent ID' and got exactly what I was looking for.

For reference, this video shows most everything you'd need to know, for using it:

[YouTube] View-ception: Using Views within Views.


Redirect to view display after form submission

Routes are not only defined in yaml files, but also dynamically in route subscribers.

Drupal\views\EventSubscriber\RouteSubscriber collects routes from all views displays which implement DisplayRouterInterface::collectRoutes, like the Page display:

PathPluginBase::collectRoutes:

  public function collectRoutes(RouteCollection $collection) {
    $view_id = $this->view->storage->id();
    $display_id = $this->display['id'];

    $route = $this->getRoute($view_id, $display_id);

    if (!($route_name = $this->getOption('route_name'))) {
      $route_name = "view.$view_id.$display_id";
    }
    $collection->add($route_name, $route);
    return ["$view_id.$display_id" => $route_name];
  }

This produces route names like view.my_view.page_1 and you can redirect in a form submit:

$form_state->setRedirect('view.my_view.page_1');


How to make Rules ignore case sensitivity when comparing strings

Make a custom module called 'email_lowercase' and place this code inside it, before runnin this new action, do on both emails 'convert a data type' to 'text', then run the new action this custom module provides with Example@example.com TEXT-token-value you have just converted. After running custom action it will return a TEXT in lowercase, then comapre your email1-text-converted with the TEXT returned from custom module.

Note: you will nedd rules conditional module to compare (add conditional, add an IF) your variables AFTER this custom action is triggered.
Done.

<?php
/**
* Implement hook_rules_action_info()
* Declare any meta data about actions for Rules
*/

function email_lowercase_rules_action_info() {
 $actions = array(
  'email_lowercase_action' => array(
    'label' => t('Convert to lowercase a TEXT email'),
    'group' => t('custom'),

    'parameter' => array(

        'email' => array(
                'type' => 'text',
                'label' => t('$text-variable-token-Email to be lowercase'),
                ),
    ),

    'provides' => array(
      'email_lower_case' => array(
        'type' => 'text',
        'label' => t('email in lower case'),
      ),
    ),
  ),
);
  return $actions;
}

// rules function numero a texto
function email_lowercase_action($email) {
  $email_lower_case = array();
  $email_lower_case = strtolower($email);

  return array (
  'email_lower_case' => $email_lower_case,
 );
}

NOTE: there are no EMAIL data types for rules, thats way i suggested to firts convert an email field to text. It may work if you don't, i did not tryed that.


Cloning a live/production site to a test/development version

For most of our D6 and D7 sites we use drush to clone and sync staging and development environment from the production server.

Basic setup of the test/staging environment should be done using drush make or cloned from your version control.
Then you can sync the data using drush sql-sync [paramenters] [source] [destination] and user generated content using drush rsync [source] [destination].
Depending on your setup it might be advisable to run a script that truncates your user table or similar.

Both drush and drush make is easily installed using Homebrew or similar.

From now on you can easily resync your database using sql-sync as often as needed.


In Drupal 7 how do I add an anchor tag to a path alias menu link

You can add the full url with the anchor tag. Not the best for deployment but a work around.


Limit the number of discount per product to 1, Commerce Discount

You could use the Flag module to get this to work, by configuring an appropriate (non-global) flag, which you should then use to (automagically) flag each product by the customer, after such discount was applied (for the first time). To actually flag such products by the customer, you should use the Rules module, which integrates extremely well with the Flag module. All that's left is to find the appropriate Rules Event for such rule to be triggered (somewhere along the lines of "checkout completed" I would assume).

Any time a customer buys a product, you can verify if it is the very first time, or yet another time. For this verification, all you'd have to do is use a Rules Condition to check "has this user yes or no flagged this product already (by the flag you created for this purpose)".

If you're not familiar with the Flag module, checkout either of these:

The set of 8 video tutorials about the Flag module.
Flag's Community documentation.


How about following these steps?

Save the original import file
Update the original file
Delete the last import
Import again


Enable users to edit user profile and nodes in same page

Try these modules
https://www.drupal.org/project/quickedit
https://www.drupal.org/project/jeditable

And for views, use editableviews


How do I add administrator approval on webform submitted data?

Use the Rules module to create a rule that sets a node to unpublished when it is saved. You might also want to have a look at the Content Approval module.

  a module that enable the approval of a content (node) by an
  administrator prior its publication (like the existing feature for
  comments).


Does the 'field table' always hold the current value? Or is it only in newest revision?

You are totally correct, the newest value is in the field_data table, you can rely on that.

field_revision just has a copy of the same data so that it knows about the revision immediately. I think it's just more hassle free to keep field_revision completely up to date rather than being one step behind field_data.


I managed to target the individual content nodes using the following code. Hope this helps someone.


CKEditor for Drupal 7 does not show the page contents

I solved my problem. In my numerous attempts, I had checked the wysiwyg filter in the configuration page of CKEditor. I unchecked it, and everything is OK now.


Is drupal bootstrap phases will be called for each page request or its only once on site load?

Since Drupal is a PHP application, there isn't a persistent process running on the server for it (unlike some other language frameworks).  This means that Drupal will bootstrap for each request it handles.  This can be a page load, a request to make an image derivative, an AJAX handler, a 404 page, and other things that aren't thought of as normal pages.  It also means that concurrent requests will result in concurrent PHP execution.

However, with the way it is designed, there are various levels of bootstrap, and different requests don't require the full bootstrap.  For example, a page request from a cold cache will require the full bootstrap.  When the page cache is enabled, and there is a hit, it will stop at DRUPAL_BOOTSTRAP_PAGE_CACHE.


Modules Page: Keep Package Sections collapsed

This is a different approach, but installing the Module Filter module will allow you to quickly filter the list of modules by simply typing a few letters of the module's name.  Alternately, you can quickly show only the modules from the categories that you would like to see by using the vertical tabs it places on the left-hand side of the page.


Execute a view in code and pass multiple arguments to an exposed filter?

It looks like you're you doing an exposed filter and contextual filter for the type. As setArguments is for contextual filters and setExposedInput for exposed filters. If you've only got the exposed filter for type you should be able to remove setArguments and the 2nd argument on buildRenderable (which you dont need if you're doing setArguments)

I've got something very similar with an exposed type filter and just pass it an array to setExposedInput  and it seems to works

$view->setExposedInput(['type' => ['news','page']]);


Menu subitems only displaying on a single page

So it turns out that the particular theme we're using relies on the Show as Expanded option on the top-level menu items to determine that it should display as a fly-out.


I made good experience with Mollom. But you need a free registration at their site.

Update: Unfortunately Mollom has announced the end-of-life for their service by April 2018.

Update 2020: I really like the antibot module. It's lightweight and pretty effective.


How to allow users to add images to an existing node?

In D8 you can use a form mode for this to assign a reduced node edit page to a specific user role.

See https://www.drupal.org/project/form_mode_control


What you want is a contextual filter on your user reference field. It should be label like Content: Instructor (or whatever you named your instructor or coordinator field). For the When the filter value is not in the URL option, select Provide the default value and use the User ID from logged in user option.


print.module error - Warning: file_put_contents

Take a look at the INSTALL.txt file.  You need to give the webserver write access to the dompdf/lib/fonts directory.

In my case, I chowned it to apache:apache.  Make it mirror how you have your sites/default/files directory set up.


How to define jQuery in libraries for avoiding conflict with theme with library?

Every library needs to have all it's dependency listed !
As libraries can be loaded independently.

  drupal will make sure to include every file only once.

So this is correct. yes.


Do you have a template for views-view-rss.html.twig in your theme folder?
Try enabling the Twig debug feature if you are not sure.

The default one in core/modules/views/templates works properly (same core version).


Drupal 7 - Error on Checkout, e-Commerce

If you're new to Drupal commerce, try installing Commerce Kickstart.  There are detailed installation instructions available.

Drupal Commerce is fairly complex and there are lots of different types of errors that can result.  Commerce Kickstart is a package (known in Drupal as an installation profile) that sets up most of the commerce stuff for you.  If you're not experienced in working with Drupal, this is an easy way to get started without having to troubleshoot error messages.

If you do try Commerce Kickstart, do so from a new site.  If you try to install over Drupal Commerce it could get messy.


What's the easiest method for migrating content from Drupal 7 to another Drupal 7?

You should use the Features module to export the configuration for your content types (and any related things - taxonomies and the like).

To move content between the sites, I'd recommend looking into the Deploy module, which will allow you to "push" content from one site to another. It requires some configuration to get it all set up, but it works really well, particularly with nodes that have dependencies on other entities (via entity reference or taxonomy term reference or things like that).

If you want to use Migrate (which is probably not a bad idea, depending on your data). You could also look into the migrate_d2d module, which has a UI that let's you just point at another Drupal site, and then press "Go" and it'll pull in all your content.

tl;dr: There's lot of ways to do it, but the "best" way depends on the data in your sites.


Ability to flag each uploaded image separately after doing multiupload

It's easily possible to create a node per uploaded picture using a custom module. Alternatively, you could use https://www.drupal.org/project/node_gallery to let users upload every picture to its node from the very beginning.


Add rel="nofollow" to menu displayed by menu_block module

If you use different menus then:

There's a module for that(tm) Menu Attributes

If it's the same menu then things get farm more complicated as you'll have to implement some hook. Take a look at hook_menu_block_tree_alter in menu_block.api.php.


Best practices for protecting from injection on form fields

If you use the Drupal core database API functions, the content will be automatically escaped, preventing SQL injection.

You can run the content through filter_xss prior to insert, otherwise you'll need to do that on display.

Drupal core stores the content unsanitized and sanitizes it on output.

User input should be validated on input and filtered on output.

More info on sanitization functions here: http://api.drupal.org/api/drupal/includes!common.inc/group/sanitization/7

See also http://drupal.org/writing-secure-code for information on writing secure code.


If Statment in Custom node template based in feild content existance

That's weird, the first code works in my end. Are you sure the node--specials.tpl.php is being called in the first place? I am suspecting that maybe you're still using node.tpl.php though I'm not sure.

Try to print some text in your tpl file to check if it is being used by your content type.


Adding a 'post to everyone' option in Drupal Commons

Ok, I think I have enough information to help. Just because something is listed as a Group Post (i.e. something that can be posted into a group) doesn't mean it needs to be. In other words, by nature of not selecting any groups you are effectively leaving the piece of content out of the group context.

Then, I might consider simply modifying the view which powers the user feed (this is a view that ships with Commons) and including non-group posts with a specific flag/tag. So to recap:

Create a tag (using taxonomy) or a flag (using this module) that effectively denotes a piece of content being non-group specific. e.g. public
Instruct your users by way of a bit of help text on the node type that they should use that tag and not post into a group.
Modify the view powering a user's feed (I think this is called Activity Stream IIRC) to include your newly tagged or flagged content.
Fancy bonus: Use a bit of JavaScript to disable the group field if either of the above flag/tag conditions are true. (Pseudo-Code: if node has tag public then disable list box)

That should get you there. Hope this helps.


Add placeholder/help text to Views exposed filter?

You can do this with preprocess functions.  Here's a tutorial on doing this for the default search box; you can do views exposed filters in a similar way.

You may also be able to use the Compact Forms module to do this, though I don't know if it is compatible with Views exposed filters.

Also, there's a module for showing helper text below a field: Better Exposed Filters

To set it up, simply enable the module and then navigate to your view edit page.  Under Exposed Form, click Basic next to Exposed form style and change it to Better Exposed Filters.  Then adjust as necessary.

However, this module will not automatically hide the text upon input.


How does Drupal determine the context in which to display the admin theme?

There is now a hook for this: hook_admin_paths(). As usual, the default configuration is in system_admin_paths() but there are many other implementations in core, search for _admin_paths.


I don't know the Smart_IP module's mechanism, but I think you should simply solve your problem outside of Drupal: adding an Apache redirection like Redirect "landberg.at" "landberg.at/en". Somewhat brutal but should work...


You can do something like below:

write below code in any module

function modulename_theme() {
  $themes = array (
      'search_input' => array(
      'render element' => 'element',
    ),
  );
  return $themes;
}

/**
 * Implementation of hook_element_info()
 */
function modulename_element_info(){
  $types['search_input'] = array
  (
    '#input' => TRUE,
    '#theme' => 'search_input',
    '#theme_wrappers' => array('form_element'),
  );

  return $types;
}

write below code in template.php:

function themename_search_input($variables){ //echo "<pre>";print_r($variables);exit;
  $element = $variables['element'];
  $element['#attributes']['type'] = 'search';
  element_set_attributes($element, array('id', 'name', 'value', 'size', 'maxlength'));
  _form_set_class($element, array('form-number'));

  $extra = '';
  if ($element['#autocomplete_path'] && !empty($element['#autocomplete_input']))
  {
    drupal_add_library('system', 'drupal.autocomplete');
    $element['#attributes']['class'][] = 'form-autocomplete';

    $attributes = array();
    $attributes['type'] = 'hidden';
    $attributes['id'] = $element['#autocomplete_input']['#id'];
    $attributes['value'] = $element['#autocomplete_input']['#url_value'];
    $attributes['disabled'] = 'disabled';
    $attributes['class'][] = 'autocomplete';
    $extra = '<input' . drupal_attributes($attributes) . ' />';
  }

  $output = '<input' . drupal_attributes($element['#attributes']) . ' />';

  return $output . $extra;
}

In cs file:

input[type=search]::-webkit-search-cancel-button {
    -webkit-appearance: searchfield-cancel-button;
}

and use #type = search_input. It may help you


Taxonomy View - show only terms with children

I would do quite as Arthur did, but I don't think double relationship is necessary  :

Set a relationship "parent term"
Make it mandatory
Display "term" with the relationship

You then will have only parent terms with children displaying.

Of course, you'll then have to aggregate or group to avoid duplications of parents with multiple children.


Possible to have 2 contextual filters with "or" rather than "and"?

OR is built in Views 3 (see this issue) with a rather pleasant interface.

But for what you need, you can do this with a single filter: "Content: User posted or commented - Display nodes only if a user posted the node or commented on the node."

Views 3 AND/OR filter interface:


Is there a central document store in Drupal 6 or a module that does?

Sounds like the FileField Sources module is exactly what you're looking for.

  FileField Sources is an extension to the FileField module. The
  FileField module lets you upload files from your computer through a
  CCK field. The FileField Sources module expands on this ability by
  allowing you to select new or existing files through additional means,
  including:

  Re-use files by an auto-complete textfield Attach server-side files
  uploaded via FTP Transfer files from a remote server (cURL required)
  Paste a file directly from the clipboard (Drupal 7 only) Select
  existing files through the IMCE file browser


With enabling modsecurity_crs_41_sql_injection_attacks all submit form return forbidden 403

I found the solution by consulting the log:

[Wed Nov 15 16:53:03.313249 2017] [:error] [pid 27752] [client 54.208.242.36] ModSecurity: Access denied with code 403 (phase 2). Pattern match "(^[\\"'`\\xc2\\xb4\\xe2\\x80\\x99\\xe2\\x80\\x98;]+|[\\"'`\\xc2\\xb4\\xe2\\x80\\x99\\xe2\\x80\\x98;]+$)" at ARGS:field_cl_ref_no[508752]. [file "/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"] [line "64"] [id "981318"] [rev "2"] [msg "SQL Injection Attack: Common Injection Testing Detected"] [data "Matched Data: '\\x22 found within ARGS:field_cl_ref_no[508752]: '\\x22()"] [severity "CRITICAL"] [ver "OWASP_CRS/2.2.9"] [maturity "9"] [accuracy "8"] [tag "OWASP_CRS/WEB_ATTACK/SQL_INJECTION"] [tag "WASCTC/WASC-19"] [tag "OWASP_TOP_10/A1"] [tag "OWASP_AppSensor/CIE1"] [tag "PCI/6.5.2"] [hostname "www.d8.dev.xxxx"] [uri "/node/add/occlient/19784"] [unique_id "Wgxw738AAQEAAGxoJOMAAAAH"]

[Wed Nov 15 17:19:51.286111 2017] [:error] [pid 28380] [client] ModSecurity: Access denied with code 403 (phase 2). Pattern match "(?i:(?:\\\\A|[^\\\\d])0x[a-f\\\\d]{3,}[a-f\\\\d]*)+" at ARGS:form_token. [file "/usr/share/modsecurity-crs/activated_rules/modsecurity_crs_41_sql_injection_attacks.conf"] [line "55"] [id "981260"] [rev "2"] [msg "SQL Hex Encoding Identified"] [data "Matched Data: E0X10B found within ARGS:form_token: xCyRB87OqEoGB47ngDdQJ0gVaIa5fy4JtgE0X10BVW0"] [severity "CRITICAL"] [ver "OWASP_CRS/2.2.9"] [maturity "8"] [accuracy "8"] [tag "OWASP_CRS/WEB_ATTACK/SQL_INJECTION"] [tag "WASCTC/WASC-19"] [tag "OWASP_TOP_10/A1"] [tag "OWASP_AppSensor/CIE1"] [tag "PCI/6.5.2"] [hostname "d8.dev.xxxx"] [uri "/node/1369392/edit"] [unique_id "Wgx3N38AAQEAAG7cNtYAAAAK"]

I disabled the rules id 981173 and 981260 in vhost and then it turns

<Directory /var/www/html>
                Order allow,deny
                Allow from all
                Options +FollowSymLinks +ExecCGI
                RewriteEngine On
                AllowOverride All

            <IfModule security2_module>
                    SecRuleRemoveById 981245
                    SecRuleRemoveById 981248
                    SecRuleRemoveById 981173
                    SecRuleRemoveById 981231
                    SecRuleRemoveById 950901
                    SecRuleRemoveById 981260
            </IfModule>

    </Directory>


How to display the user registration or profile field on the search page?

Copy the template file YOUR_SITE/modules/search/search-result.tpl.php to your theme and modify the code inside with this:

<?php
//obtaining the username
$username = explode('(', $title);
$username = trim($username[0]);
//getting the user object
$user = user_load_by_name($username);
?>
<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>
  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url; ?>"><?php print $title; ?>

  <?php
  /*
   * The following lines will print the info
   */
  print $user->field_date_of_birth[LANGUAGE_NONE][0]['value'] . "
";
  print $user->field_gender[LANGUAGE_NONE][0]['value'] . "
";
  print $user->field_your_industry[LANGUAGE_NONE][0]['value'] . "
";
  print $user->field_your_city[LANGUAGE_NONE][0]['value'] . "
";
  print $user->field_zip_code[LANGUAGE_NONE][0]['value'] . "
";
  print $user->field_countrynew[LANGUAGE_NONE][0]['value'] . "
";
  ?>

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

    <?php if ($snippet): ?>
      <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?>

    <?php endif; ?>
    <?php if ($info): ?>

<?php print $info; ?>

    <?php endif; ?>