Views filter depending on the number of node references

I don't have enough points to leave a simple comment. I haven't tested this yet. However, I think that you need to select in the 'Relationships' section the node reference. This will join the two tables and give the view access to all the fields in both. Then add an argument and when configuring the argument use the relationship you choose. I'm not sure which argument is best to choose but I think that node title is a good one for the summary and then select the Summery, ascending or desc. This actually creates a list of all the possible titles of A with the number of node B attached to each with a number next to is. When the title of node A is clicked in the block or page view it opens the page with node A's title as the big page title and all of fields of B as long as you selected the relationship under each fields setting.

I wish I had time right now to test it. It's only a theory but I'm sure it's the general direction of solving this.


Access denied to custom REST API endpoint for anonymous user

So it looks like there is a core issue that doesn't permit leaving out some type of REST authentication. The easiest solution appears to be the Feeds HTTPFetcher AA (Advanced Authentication) module, as it allows you to enter your authentication credentials in the custom parser settings. The downside is that I have to create a user (and possibly a role) in D8 for this, but at least it's workable.


Your thing you came up with is certainly one way of doing it, though you're adding a step. If you can guarantee that your entity reference field will always be on the order, then you could just join your query to the entity reference table and check it against the current user's UID.

Something to the effect of:

INNER JOIN `field_order_user_reference` ON `commerce_order`.order_id = `field_order_user_reference`.entity_id
...
WHERE
`field_order_user_reference`.user_id = ***CURRENT_USER***

Or something to that effect.

The way you have it implemented now, you will start to see performance degradation since you're adding a lot of overhead. Using pure SQL will help tremendously and you shouldn't see any slowdown.

Alternatively, since your order has an entity/user reference field attached to it, you should be able to just add it as a filter and set the filter user as the current one. Maybe not, but if you haven't tried it, it'd be worth a shot.


It sounds to me like you are running more than one PHP version on the server.

Did you remove the current (old) PHP version before adding the new one? Did you restart apache/the server after installing?

You may need to tell Apache manually to use the new php56.

check your httpd.conf for the LoadModule definition that defines it and make sure it's referencing the correct PHP installation.

Centos 7 http.conf location: /etc/httpd/conf/httpd.conf

Note that any changes you make here require that you restart apache. Also note that changing here has a risk of bringing down apache, so modify with caution.


How to implement review ratings with Fivestar?

Yes, you can do it, you can combine the Views module with the Views Aggregator Plus or with the Views Calc module.

Views Calc:

  Adds simple calculations to a views table. You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug
  in theme makes the view look more spreadsheet-like (right justifies
  numeric fields, shades calculated columns and rows, and underlines
  calculated rows).

Views Aggregator Plus:

  In addition to what Views and Views Calc do, this module:

  enumerates group members
  produces tallies, i.e. textual histograms
  aggregates on Views PHP code-snippet evalutations
  can filter out result rows on regexp patterns
  gives you sorting on Views' Math expressions
  can process Webform submissions
  lets you add your own custom aggregation functions

  ... and it puts summary statistics at the bottom of your aggregated
  table as well!


Field prints twice, or not at all when added to template file

Your template file will only print fields that are not hidden in the Manage Display window, so you definitely need to make it 'default'.

It's probably printing twice because you have the default print render($content); somewhere in your template file.

If you want to print the field separately and not have it print when the main content is printed you need to hide the field in the template file not in Manage Display:

<?php hide($content['field_description']) ?>

Make sure you do this early in the file, before print render($content);.


How to add classes to BODY tag dynamically based on page path/depth?

To expound on Nikhil Mohan's answer, you can implement template_preprocess_html() inside your theme's template.php file. Read the documentation on Overriding Themable Output to understand the basics of what is going on here.

Within this function, you have access to the variable $vars['classes_array'], which holds a list of classes that will be applied to the HTML <body> tag on the page.

Unfortunately, information about the current page's location in the menu is not immediately available. You could use menu_get_item() and then menu_get_ancestors() to get this information, but that is a lot of processing power for something that we can probably get to with a simpiler approach.

Assuming you are using the pathauto module to automatically create semantic paths for your content pages based on the menu path (i.e., your Melbourne Theme Parks page would have the path 'melbourne/theme_parks') you can use the page's path to create the classes you are looking for:

function THEMENAME_preprocess_html(&$vars) {
  $path = drupal_get_path_alias();
  $aliases = explode('/', $path);

  foreach($aliases as $alias) {
    $vars['classes_array'][] = drupal_clean_css_identifier($alias);
  }
}

That's it. Drupal will now look at the path alias of the current page and add a class to the <body> tag for each chunk of the path alias.


adding rel attribute to image link in a node

I need to add a rel attribute to my image link. How can I do
  this?

You can add a data attribute to your link in l() function:

// your image
$image = array(
    'style_name' => 'the name of the image style',
    'path' => 'relative path to your image',
    'alt' => '',
    'title' => '',
    'attributes' => array('class' => array('some_class'))
);

// link elements
$text = theme('image_style', $image); // in your case it's an image
$path = 'link_url';
$options = array(
    'attributes' => array(
        'class' => array('some_link_class'),
        'rel' => 'some_relation'
    ),
    'html' => true
);

$link =  l($text, $path, $options);

result:


Multisite cannot find module in sites/default

So this was the issue,

When I created the sub-domain i used cpanel, even though I specified

/home/<username>/<subdomain-name>

as the home directory path,

it would override it in the vhost entry to:

/home/<username>/public_html/<subdomain-name>

so,  even though I created the symlink at the right place, it never hit it,
so when I went to the subdomain url is was picked up by the drupal htaccess as a url to the live site

lots of confusion and lots of annoying behaviours

As soon as I edited the vhost entry to the corect path, everything worked correctly

thanks for all the reads though

Jim


Warning to user for including cursing words in private message

Finally found a format that works.

Contrary to what the Drupal documentation says, the format:

word1|word2|word3

does not work.

The proper syntax is:

^.*(word1|word2|word3).*$

i.e.: caret then dot then star then open parenthesis then the words to search separated with a vertical bar then closed parenthesis then dot then star then dollar sign.

Many words may be added between the parenthesis. No need to add the plurals as regex will match the singular inside the plural.

Reminder: Regex stands for REGular EXpression so this value must be selected at the bottom of the condition page.


The correct directory structure is src/Plugin, not src/Plugins.

The files in config/schema/ and config/install/ look correct to me. I struggled with those mightily. And I'll emphasize that actions only seem to be registered when the module is installed.


How should I alter forms shown in a block?

There are two ways to display only some fields:

Get the original form, and remove unneeded fields. This can be done 2 ways, in hook_form_alter() or by calling drupal_get_form() and working on outputted array. This way is risky - save handler might be unable to save if some fields it expects are missing.
Create your own form, with your own inputs, validators and save handlers. Copy strings from form you are copying to keep using any translations already available. This is safer, but requires a bit more work.

In theory you can handle form in a block with php filter. I would not recommend it. It's way more manageable to keep code in files. And if you have APC, it's also way faster. Thus, modules are the way to go.


what are the css files with question marks - like modules/system/system.theme.css?pywps6u?

I assume this is resulting from the caching

You are correct. It is for caching; especially to prevent browsers from thinking they have already downloaded a certain file.

If the file was named system.theme.css, and your browser already downloaded that file several days ago, it won't download it again. This results in an outdated site. The suffix changes every time the CSS files change and forces your browser to download the file again.

You can safely edit the 'regular' CSS files on the filesystem. Take care though that is discouraged to edit system and module files, as they will be overridden during updates. Instead create a custom module or theme to implement the changes you need.


entityFieldQuery not returning term references - not in field_data but are in field_revision

So, I figured out what was going on -- I was using the 'moderation' plugin and so all the changes I was making were secretly getting marked as 'draft' despite me making the changes as an admin. Doh.


I need to add on condition to profile form submit handler profile2_form_submit_handler

A theme can not simply override a form handler. What you need is a form alter function (hook_form_FROM_ID_alter()) to alter the profile2 form, remove its original submit handler and replace it with your own.

THEMENAME_form_profile2_form_alter(&$form, &$form_state) {
  array_splice($form['#submit'], array_search('profile2_form_submit_handler', $form['#submit']), 1, 'THEMENAME_form_submit_handler');
}

Because your are changing the behavior of your site, this should be implemented in a custom module rather than in the theme. Themes are about presentation.

Also, instead of altering profiles on form submit, you could also implement hook_profile2_presave() to alter the profiles before they are saved to the database, regardless on how they are created (ie. your code will also work for profile created programmatically).


You can use Profile Switcher

  Used to switch between install profiles found in /profile directory.
  This module is useful for moving an existing site to distribution.

I had the same problem last year you can check it out at - Changing from a Profile to Standard profile after the installation


Multisite setup on local development environment

Not sure what exactly you want to do.

Multi-site is usually used to create separate drupal installation from the same drupal folder. To create one, you need to copy default/default.settings.php to yoursite.com/settings.php, make it writable and then visit the site, which should present you with the installer.

You only need to something with sites.php if you want to override the default domain mapping and e.g. also server siteB.com from sites/siteA.com. Also, Drupal doesn't search for a settings.php in 'all' but 'default'.

Your naming scheme sounds more like you want a mobile version of your site, which usually just implies that a different theme is used and some other mobile specific things. There are modules which can automatically changing the theme when the site is requested by a mobile browser.


Loading module-related files only on certain pages

You should use hook_js_alter() within template.php

function yourthemename_js_alter(&$javascript) {
  if ('this is true') {
    unset($javascript['sites/all/modules/chosen/chosen.js']);
  }
}

I'm wondering if either solution will result in caching issues though.  If I may: I would first try to figure out why my JavaScript collides with the module and fix it there.

You can also use the hook within a custom module if you already have one that relates to what you're trying to accomplish here.


How to use taxonomy terms(with depth) on a views exposed filter?

http://drupal.org/sandbox/ser_house/1832320 is not done but i am using it on my site and works fine even with other exposed filters.

Only problem not really related to this module is that my vocabulary is 5000+ terms and its Drupal taxnonomy core issue on how to handle large amount of terms.


Controlling the display format of a rss feed


running drush core-requirementsfrom your drupal site's directory more info and tail /var/logs/[httpd | apache2]/foobar_error.log will be your friends here.


How to create paragraphs item programmatically?

Yes, That was for adding the value in existing paragraph item. If you want to create new paragraph item with new value try this code.

$node = node_load(...);

$paragraph = new ParagraphsItemEntity(array('field_name' => 'name_of_field_in_node', 'bundle' => 'name_of_paragraph_bundle'));
$paragraph->is_new = TRUE;
$paragraph->setHostEntity('node', $node);
$paragraph->field1_name_in_paragraph_bundle[LANGUAGE_NONE][0]['value'] = 'Test Data';
$paragraph->field2_name_in_paragraph_bundle[LANGUAGE_NONE][0]['value'] = 'Test Data';
$paragraph->save();


The trick is to simply set $form['#action'] to whatever URL you want to POST to.

Like this:

//....
$form = array(
  //..build the FAPI array
);
$form['#action'] = "shop/checkout";
return $form

In the place where you build the form. And the POST is sent to "shop/checkout".


How to print drupal module version with drush 6.5.0

You can use the following command to check all the info about a module. For this command is :

drush pmi module_name

This command provide info like this :

Extension        :  module_name
 Project          :  module_name
 Type             :  module
 Title            :  module_name
 Description      :  Improves Drupal's login system.
 Version          :  7.x-1.5
 Date             :  2015-05-01
 Package          :  Other
 Core             :  7.x
 PHP              :  5.2.4
 Status           :  enabled
 Path             :  sites/all/modules/module_name
 Schema version   :  7000
 Files            :  none
 Requires         :  none
 Required by      :  module_name
 Permissions      :  none
 Configure        :  admin/config/system/module_name


Can't access admin after moving localhost to live server

Install drush
Go to your drupal-core/sites/mysite folder in command line
type sudo drush uli
The console will print a link, use that to access your site as user 1


Views templates: How to print file fields

Using  this seems to do exactly what I want

<?php print $view->style_plugin->rendered_fields[$row_count]['field_programme']; ?>

which is extremely useful since it can be used even for fields that have been excluded from the display of the view.


View menu routes missing until first page load

Problem background

I actually found an answer to this problem. Drupal has a rather aggressive way of deleting menu items that has the router_path field set to NULL (or empty) in table menu_links. If Drupal finds such a record it will delete the record upon the next run of menu_rebuild(); (see docs) or documentation block below.

/**
 * Populates the database tables used by various menu functions.
 *
 * This function will clear and populate the {menu_router} table, add entries
 * to {menu_links} for new router items, and then remove stale items from
 * {menu_links}. If called from update.php or install.php, it will also
 * schedule a call to itself on the first real page load from
 * menu_execute_active_handler(), because the maintenance page environment
 * is different and leaves stale data in the menu tables.
 *
 * @return
 *   TRUE if the menu was rebuilt, FALSE if another thread was rebuilding
 *   in parallel and the current thread just waited for completion.
 */

Solution

Each menu item created this way must contain the property customized and have its value set to to 1. This forces Drupal to update the record in table menu_links with the matching router_path instead of deleting it. See function _menu_navigation_links_rebuild($menu) around line 2929 in menu.inc. _menu_navigation_links_rebuild($menu) is called from menu_rebuild().

Example

This will create a new link on the top level in a menu named 'your-menu-name'.

$ls = array(
  'menu_name' => 'your-menu-name',
  'link_title' => 'Your Link Title,
  'link_path' => 'your/link/path',
  'plid' => 0,
  'weight' => 0,
  'customized' => 1, // "The magic property"
);

$newpid = menu_link_save($ls);


after updating 7.12 to 7.14 can't update modules

This is probably a problem with folder/file permissions. You can try changing the permissions of the sites/all/modules folder, and of the problematic modules' folders. You can read more about changing permissions here (follow the links there to see what's recommended; basically 755 should do). Possibly these modules cannot be removed by Drupal because of the ownership settings of the files/folders in question.

You can also do a manual update, as explained in the answers to this question.


Can you use FAPI with transactions: Yes.

But you can't or rather shouldn't use it the way you describe. Transactions only take effect when you commit them, so there really is no point in starting the transaction in the validation. Also what happens if you have a validation error, you won't commit the transaction. I believe that starting a transaction will effect other incoming queries as well.

Transactions are only good if you want to do multiple queries at once, and do all or nothing. Like insert data in main table and revision table and then update the revision number in main table.

What are you trying to do that makes you think that you should make transaction in such a way?


They're in the aptly named url_alias table, but you shouldn't query it directly. The path alias manager service is preferable:

$alias = \Drupal::service('path.alias_manager')
    ->getAliasByPath("/node/$nid");

As always, inject the service if you can.


I'm unable to access variables in template from preprocess function

You need to apply EntityViewBuilderInterface::viewMultiple before you can render the nodes in a twig template:

$variables['products'] = \Drupal::entityTypeManager()
  ->getViewBuilder('node')
  ->viewMultiple($nodes);

Twig:

{{ products }}

You can add a view mode to viewMultiple() as second argument, for example teaser.


Is there a way to integrate revisioning with Panels + CTools content types?

Unfortunately, I can't think of any simple way to do what you want.

I would probably have solved it by having the content type pull it's content from the entity they are displayed on instead.

It's possible that fieldable panel panes could be useful to you.

In the end, if you really need revisioning on the the content type settings form, you're gonna have to implement it yourself. Since the form is a standard Drupal form, I would try doing it with a node type as backend, instead of doing the whole thing from scratch. You should be able to just load up the edit form for a node, and re-use most of the functionality.


Suppose you want to get the ip in the page.html.twig file.

in your

  YOURTHEME.theme

you can try

use Symfony\Component\HttpFoundation;

function YOURTHEME_preprocess_page(&$variables) {
  $variables['page']['ip'] = \Drupal::request()->getClientIp();

}

in your template

  page.html.twig

you can try:

{{ page.ip }}


Call a custom module's function from template file

a function doesn't have a url unless you set up a callback url for it first with hook_menu. Then you can point your link to it and process the data. So in your case it'd look something roughly like that:

In your custom module:

function mymodule_menu() {
  $items['some_url/%'] = array(
    'page callback' => 'mymodule_myfunction',
    'page arguments' => array(
      1,
    ),
  );
  return $items;
}

function mymodule_myfunction($id) {
 // update database
}

Then in your template use l() as Kevin mentioned (you should adjust to fit your variables etc):

print l('Action', 'abc/20');

This is very simplified. You'd want to probably enable some access limitations on that new url (abc/%) etc and you can read more about that in the hook_menu docs I linked to above.


I had the same problem. You're almost done, but missed some settings ;). You just need to do some Format settings for Views Accordion in your View.

Here are the steps to make your grouping field as the "header" or "trigger" of the accordion action.

Go to  Format: Views Accordion Settings and select Grouping field.
Check "Use the group header as the Accordion header"

Save View. That's it. Now your Grouping field will act as Views Accordion Header and avoids duplicate headers too.

Hope this helps.


How to make relation between user term and nodes terms?

You can do it by using view :

add field in views
add relationship of user
add expose filter against term id or term name
if you want show on user profile page add contextual filter against user id


How to implement multiple approvals with emails?

Instead of using the Webform module for this, I would use a custom content type for this, with the fields similar to what your webform is using. And instead of submitting a webform, a node of this custom content type is to be created.

This content type should have these fields:

A field to reflect the "state" (Pending or Approved, maybe also a state like "Escalated"?), say you name this field like field_approval_status.
An "entity reference" field to select the Supervisor.

With the above setup, you could use the Rules module to notify the Supervisor, using a rule that is similar to the rule included in my answer to "How to send an email via a Rules action using a field key?", and which looks like so:

{ "rules_notify_reviewer_about_outstanding_approval" : {
    "LABEL" : "Notify reviewer about outstanding approval",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--blog" : { "bundle" : "blog" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_blog_reviewer" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "[node:field-blog-reviewer]",
          "subject" : "Blog Post waiting your approval",
          "message" : "[node:author] has submitted a new Blog post waiting your approval.\r\n\r\nYou can review it at: [node:edit-url].",
          "language" : [ "" ]
        }
      }
    ]
  }
}

If the supervisor then wants to forward it to another supervisor, all that's needed is to edit the node and change the selected supervisor to another one.

You may want to add some extra logic and/or permissions related to such field_approval_status field, i.e. to ensure that when such node is created, the author cannot set it to "Approved" right away (only to "Pending"?). That's something you could do using the Rules module (to validate/enforce that), or you might want to use the Field Permissions module for that.

Note:

To avoid that creating nodes is too intimidating for most users, you want to look at the Simplify module also, which helps to de-clutter forms. Here is a quote from its project page:

  Simplify allows particular fields to be hidden from the user interface. This helps to de-clutter forms and present a more user-friendly experience to content editors.


Its at the bottom of the 'Appearance' page (admin/appearance), in the section labeled 'Administration Theme'.


I use Menu Block for this purpose.  You can specify which levels of which menu you want to show, and the blocks display conditionally depending on the current active trail.


How to set up the database for load-balanced Drupal 7

db2 should never be written to if it is a slave of db1, because any write to db2 will never be propagated to db1, and they will quickly get out of sync.  The database must be shared and consistent.

There are 3 ways of getting a shared and consistent database experience: (1) Only have one database for all reads and writes.  This is the easiest, but provides a single point of failure, and unless the db is on a separate machine, it can result in unequal response times for the different servers.  (2) Use a Master-Slave setup and split your read and write requests between the master and slave.  Ideally, a master and slave databases are on different machines than the application servers.  (3) Use a multi-master so that writes to one are propagated to the other databases automatically, and vice-versa.  Again, usually the database machines are separate from the application servers.

The question is on how big does your system need to be?  If you are big enough to need more than one database server, then you should be looking at a cluster solution (MariaDB with Multi-Master Galera cluster, for example), but for that you need an odd number (minimum of 3) machines, which should be separate from your application servers.  Furthermore, in order to minimize bandwidth and cache rebuilding, you should also use a shared memcached server for cache tables.

As a point of reference, I implemented our system with a MariaDB Galera Cluster setup as a Multi-Master, but I treat it as a Master-Slave (which minimizes the chance of write conflicts).  I use AutoSlave to separate read and write requests, and send the read and write requests to different ports using HAProxy.  HAProxy then sends them to either a read or write server.  The "read" and "write" servers are really just part of the same Multi-Master cluster, but if my write master goes down, I have configured HAProxy to failover to the "read" servers until the "write" server comes back up.  The same thing happens for the "read" requests: Read requests are load balanced between the available read servers, but should they ever go down, HAProxy is configured to redirect all reads to the write server.  The end result is that Drupal thinks it is splitting up reads and writes, the cluster thinks that it is a multi-master, and it performs like a Master-Slave, with the advantage that it does not fail if either the master or the slaves go down.


I deleted my .htaccess. easy way to fix this?

Here you go the . htaccess for drupal 5.x

http://drupalcode.org/project/drupal.git/blob/refs/heads/5.x:/.htaccess


How to get and display menu items except the parent item?

You can do this by configuring the Menu levels on your Menu Block and placing that Block in a region of your theme. Additionally configure the Visibility of the block so it only appears on pages where you want it.

You can learn more about the Menu levels configuration here: Drupal 8 Navigation Menu Blocks configuration.

In your case you want the Initial visibility level and Number of levels to display to be either:

1 and 3

OR

2 and 3

AND

you'll want the Expand all menu items to be checked, unless you have all the items Expanded under Menu settins.


Restricted access on certain files in Open Atrium

Maybe you could create 2 files sections. The first one, accessible to everyone. Then another one, in a subspace, that would be private (check settings upon creation).

Maybe you could display then the whole structure using only one "files and folder" widget if this is what you need


What is difference between field tables?

First used for field in Drupal 6.x versions.

Second used for fields in Drupal 7.x version.


How to call a function in a form from another form?

I created amap.services.yml

services:
  listenrolments:
    class: Drupal\amap\ListEnrolments
    arguments: []

and ListEnrolments.php

<?php
namespace Drupal\amap;
class ListEnrolments {
  public function __construct() {
  }
  public function list() {
    some code...
    return $rows;
    }
}

and in my two forms, inserted

$rows = \Drupal::service('listenrolments')->list();

at the right place.
And it works!


How do I add fields and hide them from client?

Field permissions module would probably be the way. https://drupal.org/project/field_permissions

"The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity."

Check the issue queue though, for example:
https://drupal.org/node/2069281, "Profile2 field is empty after profile is saved"


Creating user alert node on User Alert module

The module defines a "User Alert" content type; when you go to http://example.com/node/add/user_alert (replace example.com with the domain name of your site), you are going to create a node of that content type, if you have the permission to create nodes of that content type.

/**
 * Implements hook_node_info().
 */
function user_alert_node_info() {
  return array(
    'user_alert' => array(
      'name' => t('User Alert'),
      'base' => 'user_alert',
      'description' => t('A User Alert is a short Twitter like message displayed at the top of the site, alerting users to critical information like an online sale, new blog post, or breaking news. After viewing it, they can click and close the message.'),
      'has_title' => TRUE,
      'title_label' => t('Title'),
      'disabled' => FALSE,
    )
  );
}

Check on admin/people/permissions you have at least the "User Alert: Create new content" permission; that is the permission to create nodes of that type. Then, you need the "User Alert: Edit own content" permission to edit the nodes you created.


If I use Panels and Views, do I need to use Blocks at all?

Well, it depends on what your needs are.  Panels and Views is a very powerful combination that can handle almost anything.  That said, there may still be times when you need or want a block.  For example, the Heartbeat and Revisioning modules both supply useful blocks that I use on my (mostly Panels and Views) site.  Yes, these two modules have Views integration, but their built-in blocks are already configured and easier to use than customizing views to meet my needs.

If you need a custom block and are trying to keep things in Panels, you can add a custom content pane.  As a bonus, such panes can be exported with the Features module if you have a complicated deployment.


Does db_affected_rows() works well with PostgreSQL?

To summarize for Drupal 6:

db_affected_rows() gives you number of rows returned by a select if the database is MySQL but not if it's PostgreSQL.
In Drupal 6 if you are using PostgreSQL you can run pg_num_rows() on the query to get the number of rows.

It is indeed database specific.

[Reference: this comment in the Drupal documentation]


How to get a count of groups that user has joined?

To get Count of all groups....

$groups = og_get_all_group($group_type = 'node');
$count = count($groups);

To get User Groups Count

$user_groups = og_get_groups_by_user();
$user_count = count($user_groups);


Add menu itens in Commerce Kickstart administrative toolbar

You're able to modify the Commerce Kickstart 2 admin menu from this path: /admin/structure/menu/manage/management

It's a normal menu created during installation called "Management".


Theming property non-object when transversing the $node object

menu_get_object('node') should be: menu_get_object()

No need for node as its implied when you call that function.

Also you need to put it in a conditional:

if($node = menu_get_object()) {       }


This form was missing from the server cache on Drupal 8

I fixed that prevent that drupal cached the page, this way, because the forms can't be cached:

// Deny any page caching on the current request.
\Drupal::service('page_cache_kill_switch')->trigger();

EDIT:

Recently was commited Add #cache[max-age] to disable caching and bubble the max-age

When $build['#cache']['max-age'] is not set, permanent cacheability (Cache::PERMANENT) is assumed.

To indicate that a render array is not cacheable at all, set $build['#cache']['max-age'] = 0 (i.e. zero seconds).

And to indicate that a render array is cacheable only for a limited amount of time, e.g. 5 minutes, set $build['#cache']['max-age'] = 300; // 5 * 60 = 300.


How can I debug/test my custom migrate module?

The place you want to step through is the while loop in MigrateExecutable::import() - this is where each source row is received after prepareRow(), run through the processing pipeline ($this->processRow), and saved to the destination plugin ($destination->import()).


How to create slideshow with views using images from node's field

You might have more luck with galleryformatter it's easy to use and works.

The module allows you to select a gallery formatter for an image field.


There are different ways to query (output? render?) paragraph field values.
If the idea is to print the value in a template, you may find some clues in this page: https://www.drupal.org/node/2532824

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

But that will also depend on the theme you are using and how do you use it


Access callback infinite loop in specific case

I think if you add the access login in the form_alter, the user should be redirected properly. IOW something like this:

function yourmodule_form_alter(&$form, $form_state, $form_id) {  if($form_id == 'CONTENT-TYPE_node_form') {  global $user;
  if(user_access("create slide content")) {
    $allowed_limit = variable_get('allowed_limit', 1);
    $slides = db_query("SELECT nid, count(*) ct FROM {node} WHERE type = :type AND uid = :uid", array(':type' => 'slide' ,':uid' => $user->uid))->fetchAssoc();
    if ($slides['ct'] < $allowed_limit || in_array('administrator', $user->roles)) {
      return TRUE;
    }
    else {
      drupal_set_message('You cannot post more than one photography. But you can edit the one you posted below if yo wish to.');
      drupal_goto(drupal_get_path_alias('node/'.$slides['nid']));
    }
  }
}


Make feeds importer to replace instead rename file path

The problem was on the server. It was not supporting image GD extension that prevented for generating images with a new path.


extract a field and the link to content from all nodes

If you want get node of page content type ,you can try another content types

$type = "page"; // machine name for Basic Page
$nodes = node_load_multiple(array(), array('type' => $type));
$arr=array();
foreach($nodes as $node){
     arr[$node->nid]['email']= $node->field_email['und'][0]['value'];
     arr[$node->nid]['url_alias']= drupal_get_path_alias('node/'. $node->nid);
    }


Default value to 'datetime' field in form loaded from the database

The response is in this thread : on stackoverflow

$form['valid_dt'] = array(
    '#type' => 'datetime',
    '#default_value' => DrupalDateTime::createFromTimestamp($data->valid_dt),
    '#title' => $this->t('Valid'),
);


Search for path inbound and outbound processing, that's what the alias and language prefix systems use for example. Both are tagged services, see PathProcessorAlias and the corresponding service definition path_processor_alis.

In Inbound, you cut off the part you want and store it somewhere in a service or so, where you can access it again where you need it. And in outbound, you add it again. As you seem to require both language and country, you will need to make sure the priorities are correct in relation to the language prefix handling.

Keep in mind that this will not give you any possibility to have different interface or content translations as there isn't really a way to store it. If you need that, you more likely need to use a language per language/country and figure out how to do fallbacks correctly.

There is also a module available that helps with this: https://www.drupal.org/project/purl. It apparently has an 8.x dev version, but I have no idea about the state of it.


Views Slideshow Output different in IE vs Firefox/Chrome/Safari

When browsers create different markup, the problem is most likely an error in the HTML, where IE is particulary bad at making broken HTML work.

Try comparing the actual source code for the page to see if it is the same.

If even the source is different it's most likely an issue with a reverse proxy or similar. Some are known to cause problems with IE with certain configurations.


Try Administration Views module. It comes with views based listing. Which can be easily modified based on our requirements.


Change display order of View block in Content area of page

Try out the Field as Block:

  Field as Block provides an easy way to display one or more fields of the current node in a block.


Adding different classes to menu item list

Your function signature is off, it should be like this:

function newtheme_item_list($variables) {
  $items = $variables['items'];
  $title = $variables['title'];
  $type = $variables['type'];
  $attributes = $variables['attributes'];
  ..
}

You should check the docs, when creating theme functions.


I can't give the complete solution, Yet I will try to relate things what you have asked to things what we have in Drupal,

Form type 1 =>  Any Node type (say Article)
Form type 2 =>  Any Node type (say blog)
Student => Drupal User (has a profile of student, use profiles2 module )
Teacher => Drupal User (has a profile of Teacher, use profiles2 module )

User Permissions for Node creation, Node edit by its own author. Views to display the forms and user redirection module to get something you want.


In Drush what is the difference between ard and arb?

They're actually aliases of one another, so you can use either.

If you type drush help arb you'll see at the bottom:

Aliases: ard, archive-backup, arb

And for posterity, drush help ard:

Aliases: ard, archive-backup, arb


Is there any way to capture only the updates from "drush cex"?

Take a look at Config partial export module

It is able to export to a tarball only modified configuration files.

For available commands in drush:
drush cpex --help


Can a coupon be programmatically added to an order using the add to cart subscriber?

Got an answer via Slack.  You only need to update the OrderInteface and set the coupons property, then resave the order.  PromotionOrderProcessor handles applying the coupon to the order.

Something like this should work within your event subscriber:

  /** @var \Drupal\commerce_promotion\Entity\Coupon $to_apply */
  $to_apply = $coupon
  /** @var OrderInterface $cart */
  $cart = $event->getCart();
  $cart->set('coupons', $to_apply);
  $cart->save();


How to load paragraph entity on node object?

$paragraph = $node->field_paragraph->getValue();
// Loop through the result set.
foreach ( $paragraph as $element ) {
  $p = \Drupal\paragraphs\Entity\Paragraph::load( $element['target_id'] );
  $text = $p->field_name->getValue();
}


How to adapt the name of a custom Drush command?

You would have to change a couple of things:

/**
 * Implements hook_drush_command().
 */
function drush_content_types_drush_command() {
  $items['mijn-contenttypes-lijst'] = array(
    'description' => dt("Show a list of available content types."),
    'aliases' => array('mcl'),
  );
  return $items;
}

The array key under $items and the "aliases" value under that need changed. The array key is used to identify the callback to invoke when using the drush command or alias. The callback, for whatever reason, doesn't start with the command file prefix but rather starts with "drush" and then the command file prefix and then the array key listed above replacing the dashes with underscores. So the second (callback) function would look like...

/**
 * Callback for the content-type-list command.
 */
function drush_drush_content_types_mijn_contenttypes_lijst() {
  $content_types = array_keys(node_type_get_types());
  sort($content_types);

  drush_print(dt("Machine name"));
  drush_print(implode("\r\n", $content_types));
}

Making those changes should give you what you want. More information about creating your own drush commands can be found here: Command Authoring


How can i import plain password that are not encrypted during a user migration?

You can use Ivan Jaros' code in two ways:

As you said, preprocess your passwords to convert them to hashes.  This can be done via a Drush script that can be run from the command line.  Drush scripts are just snippets of PhP code that run in the Drupal context.  Run by  the command:

drush @site-alias scr [path to php snippet]

The alternative is to override you CVS Source class and use the preparerow method to hash the password.

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $password = $row->getSourceProperty('password');
    $hash = \Drupal::service('password')->hash($password);
    $row->setSourceProperty('password', $hash);
  }

As pointed out in the comments, you can also use a process plug-in to do this.  The callback plugin only uses static classes and AFIAK the hash method requires access to the context information that is not available via static methods.

Here's some quick untested code to create your own process plug-in to hash a plain text password.

<?php

namespace Drupal\my_mode\Plugin\migrate\process;

use Drupal\migrate\MigrateExecutableInterface;
use Drupal\migrate\ProcessPluginBase;
use Drupal\migrate\Row;

/**
 * Converts a plain password to an hash.
 *
 * Example:
 *
 * @code
 * process:
 *   password:
 *     plugin: my_module_hash_password
 *     source: field_password
 * @endcode
 *
 * @see \Drupal\migrate\Plugin\MigrateProcessInterface
 *
 * @MigrateProcessPlugin(
 *   id = "my_module_hash_password"
 * )
 */
class HashPassword extends ProcessPluginBase {

  /**
   * {@inheritdoc}
   */
  public function transform($value, MigrateExecutableInterface $migrate_executable, Row $row, $destination_property) {
    $hash = \Drupal::service('password')->hash($value);
    return $hash;
  }

}


How to find "next day date" (xx/xx/xx 00:00:00) from a given date & time value in Rules?

Let's see my example.

First: I created content type with two date fields: date1 and date2

Second: I created rule

Create Action 'Add variable' to store first date field value in your
variable
Create Action 'Set data value' and choose your second date field as
Data and your variable name as Value
Create Action 'Set data value' and choose your second date field as
Data and don't "Switch to data selector", simply set "+1 day
midnight" as Value

What's the point: when you r creating 'Set data value' action and choosing Date type you can see next description under Value field in form:

  The date in GMT. You may enter a fixed time (like 2015-08-16 14:05:10)
  or any other values in GMT known by the PHP strtotime() function (like
  "+1 day"). Relative dates like "+1 day" or "now" relate to the
  evaluation time.

If you google strtotime() php function you can simply understand what goes on.

"+1 day midinight":

"+" means add
"day" means what to add
"midnight" means "The time is set to 00:00:00"


I believe you can utilize theme_pager to accomplish your goals.  Look for examples on how theme_pager is implemented.  But theme_pager is definitely what you want.


How to display the recent user revision in a views block with contextual filters?

I ended up using PHP Code in the contextual filter:

$cpath = explode('/',current_path());
$path_uid = $cpath[1];
if (array_key_exists(3, $cpath)) {
  $path_vid  =  $cpath[3];
  return $path_vid;
}
else {
  $result = db_query("SELECT vid FROM {user_revision} u WHERE uid = (:uids) ORDER BY vid DESC LIMIT 0,1", array(':uids' => $path_uid))->fetchField();
  return $result;
}

Would be nice to put this in a custom module so if have to make changes and do not have to touch every display of the view.


Drupal commons running very slow, what are the key modules to disable?

This is normal for a Drupal site with a lot of modules. There are many SQL queries and huge use of memory to provide these admin pages, but if you look the site as a normal visitor, will see that this isn`t the same.

Commons, specifically, i had many issues related to very slow admin pages, when developing a large social network, with the many modules from Commons itself and many others specific from the project.

To improve this, you can:
 * tune your MySQL (the first thing to do is set your tables as INNODB, that you help a lot)
 * use memcached
 * use PHP APC
 * Look around http://web.archive.org/web/20110516021804/http://www.morningtime.com/Drupal-6x-Performance-Guide/513 (the MorningTime site removed the link, so you`ll only be able to see in the webarchive)


Set the value of a hidden field in form block

OK, I have found a working solution. I added $form['field_goal_id']['und']['0']['value']['#value'] = $node->nid; to hook_form_alter in template.php, and the value is populating the field and the form is submitting successfully. Sweet!


Fivestar multiple axis reviews and views

Fivestar Widget

I believe the Fivestar widget stores values as a percent average rather than as a vote average. In otherwords the Fivestar widget is storing a value between 0-100 rather than 0-5.

When you have a Fivestar widget collecting 0 to 5 stars, each star is worth 20.  This is why when you have an average of '2 stars', your seeing a value of 40. (2*20=40)

To extend this:

A node with 1, 2 star vote will be stored as 40
A node with 2, 2 star votes will be stored as 40
A node with 1, 2 star vote and 1, 3 star vote will be stored as 50

This can easily be fixed by dividing the displayed output by 20.

From there, I believe your view may already be setup properly.

I'll rework my answer if this isn't relevant here.


Can't use Google Analytics Statistics Module - Impossible to login

Turns out this module is no longer supported and it appears many others also have problems authenticating with it. I recommend NOT using it. I also tried Google Analytics Statistics Counter module, and while I was able to get it setup it wasn't as intuitive as I'd hoped so I just used the 'Statistics' core module, even if it's not the 'preferred' choice performance-wise. For now it will do.


How do I create a block only for the user "owning" the profile page?

So I found out :

Either you can directly go in view and add a "FILTER CRITERIA" > "(author) User: Current" and it will hide the content for user that are not the current logged in user
Or you can go in the block settings, select "Pages on which this PHP code returns TRUE (experts only)" and add in the box <?php global $user;
return $user->uid == arg(1); ?> and the block disappear totally if you are not the current user.


Restrict content to a user role in a template file

To check in twig if the user is authenticated you can use the default variable logged_in:

{% if logged_in %}

The user is authenticated".

{% endif %}

This works because the user module provides the variable in preprocess for all templates:

/**
 * Implements hook_template_preprocess_default_variables_alter().
 *
 * @see user_user_login()
 * @see user_user_logout()
 */
function user_template_preprocess_default_variables_alter(&$variables) {
  $user = \Drupal::currentUser();

  $variables['user'] = clone $user;
  // Remove password and session IDs, since themes should not need nor see them.
  unset($variables['user']->pass, $variables['user']->sid, $variables['user']->ssid);

  $variables['is_admin'] = $user->hasPermission('access administration pages');
  $variables['logged_in'] = $user->isAuthenticated();
}

Generic roles

If you want to check a generic role, you can't use hasRole(), because this method is not available for accounts. You would have to use getRoles() and check if the role is in the returned array:

{% if 'example_role' in user.getroles  %}

The user has the role "example_role".

{% endif %}


Module to allow multiple paths for a single node?

You can already do this using core's Path module in Drupal 6. If memory serves, it should be in admin/build/path/add. Simply create two aliases that both point to node/153.

I should caution, however, that this may raise red flags with search engines. They typically frown on duplicate content, and your SERP rankings will likely suffer as a result.


Call-time pass-by-reference has been deprecated in phptemplate_init() with specific theme

The indications to solve this issue are available at: http://drupal.org/node/1423518


Delete all nodes from database except from user1 and admin

Yes, you could do that with

views_bulk_operations

It will delete the nodes and users progressively using the Batch API.

Create a content / node based View
Add the bulk operations field
Configure bulk operations field to add "Delete item'
Add filters to View to exclude content from user1 / admin
Run the View, check to select all rows, and bulk delete the relevant nodes.

Repeat using a user-based View to delete users.

Note, prior to deleting users, check the account cancellation settings at Admin > Configuration > Account settings > Registration and cancellation


How to hide the grid lines from Yaxis and draw only one line from specific Yaxis points?

Refer to HowTos about vertical axis, located within the Community documentation of the Charts module. Here is the relevant part of it:

Refer to #2356053-2: Automatically adjusted value range for vertical axis, which explains how to automatically adjust the minimum and maximum of the Y-axis to fit the available data. Specifying a "Max" and "Min" value is optional. Specifying a minimum of 0 is recommended in the event that numbers will always be positive, while for the maximum value the recommendation is (usually) to just leave it empty.
To experiment with this in your own site, use the column chart with the number of nodes for each content type (located in charts/examples/views ):

If you do not specify a maximum there, you get a close to perfect chart, no?
If however you only have a few nodes (like a dozen or so) but use a huge maximum (like 240 ...), the chart looks not so nice, right?


If "tag" is "event" - how to do condition with php

This is where you will find it in node.tpl.php

$content['field_tags']['#items'][0]['taxonomy_term']->name

Be sure to test it for empty() or run it through isset() before you use it.


This is a Drupal no, no.  Leave root user alone. Just leave it.  If you are worry about security, change the username admin, to something else (admin is the most commonly use name hacker try to use).   Then just use uid 2 to administrate the site.


How can I upload bulk images as separate nodes in drupal 8?

DropZoneJS can auto-create media entities for every uploaded image.

Remember that you need to set up an entity browser using the DropZoneJS-Widget for the bulk-upload feature.

Your image gallery is an entity reference field to media entities (unlimited cardinality).

If you are looking for a general tutorial on how to set up media entities, I found this tutorial quite helpful.


The short solution to my original question can be coded like this:

function betapp_testajax_callback($form, &$form_state) {
  return $form['mybtn'];
}

function betapp_testajax_form($form, &$form_state) {
  dd('');
  dd('betapp_testajax_form');
  $form['mybtn'] = array(
    '#type' => 'button',
    '#id' => 'mybtn',
    '#default_value' => 'Ignored default value',
    '#prefix' => '',
    '#suffix' => '',
    '#ajax' => array(
      'callback' => 'betapp_testajax_callback',
      'wrapper' => 'testajaxwrapper',
      'method' => 'replace',
      'effect' => 'fade'
    )
  );
  $prevval = '(blank)';
  if (isset($form_state['values']['mybtn'])) {
    $prevval = $form_state['values']['mybtn'];
    dd('prevval : ' . $prevval);
  }

  $form['mybtn']['#value'] = 'Newval ' . rand(0, 100);

  dd('newval  : ' . $form['mybtn']['#value']);
  return $form;
}

which lead to output like:

betapp_testajax_form
newval  : Newval 48

betapp_testajax_form
prevval : Newval 48
newval  : Newval 62

betapp_testajax_form
prevval : Newval 62
newval  : Newval 0

betapp_testajax_form
prevval : Newval 0
newval  : Newval 59

My usage requires a little bit more; whenever a button is changed, there are other elements that should be updated as well. But I think I managed to pull it together (looks correct for now anway), and in the spirit of sharing, here's what I managed to glue together:

function betapp_testajax_callback2($form, &$form_state) {
  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace('#mybtn', drupal_render($form['mybtn'])),
      ajax_command_replace('#inp', drupal_render($form['inp']))
    )
  );
}

function betapp_testajax_form2($form, &$form_state) {
  dd('');
  dd('betapp_testajax_form');
  $form['mybtn'] = array(
    '#type' => 'button',
    '#id' => 'mybtn',
    '#default_value' => 'Ignored default value',
    '#prefix' => '',
    '#suffix' => '',
    '#ajax' => array(
      'callback' => 'betapp_testajax_callback',
      'wrapper' => 'testajaxwrapper',
      'method' => 'replace',
      'effect' => 'fade'
    )
  );
  $prevval = '(blank)';
  if (isset($form_state['values']['mybtn'])) {
    $prevval = $form_state['values']['mybtn'];
    dd('prevval : ' . $prevval);
  }

  $form['mybtn']['#value'] = 'Newval ' . rand(0, 100);

  $form['inp'] = array(
    '#type' => 'textfield',
    '#value' => $prevval,
    '#id' => 'inp'
  );
  dd('newval  : ' . $form['mybtn']['#value']);
  return $form;
}

This code updates the original button, and sets the input field to the previous value of the button. My case requires modifying other buttons, but hopefully that will work. If not, I'll bug you on this thread again.

Thank you.


Rule to store user's last post date and scheduled rule based 30 day reminder

Use the Rules module together with Rules Scheduler (a sub-module of it), as explained in the 3 steps below. These steps are based on these assumptions:

content type = article.
interval 30 days.

In this case, a date field is added to the user profile, so that for each user you can indicate an appropriate date for the "next article".

Step 1: Create a field to store the "next article" date

Add a field to the "user" entity with machine name (say) field_next_article. Allow only 1 date (to store when the "next" article is allowed).

Step 2: Create a Rules "Component"

Here is the Rules Component to be created (in Rules export format, just import it in your own environment via copy-paste):

{ "rules_send_email_notification" : {
    "LABEL" : "Send eMail notification",
    "PLUGIN" : "action set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "user_to_notify" : { "label" : "User to be notified", "type" : "user" } },
    "ACTION SET" : [
      { "mail" : {
          "to" : [ "user-to-notify:mail" ],
          "subject" : "Friendly reminder about your next article",
          "message" : "This is a reminder about your next article on [user-to-notify:field_next_article] ...",
          "from" : "[site:mail]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

Obviously, the Subject and Content of the eMail may need review / tuning, while you might also want to use some other From eMail ID.

Step 3: Create a "Rule" using the Rules Component

Here is the Rule to be created, in Rules export format (just import it in your own environment via copy-paste):

{ "rules_user_reminder_after_30_days" : {
"LABEL" : "User Reminder After 30 Days",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "rules_scheduler" ],
"ON" : { "user_login" : [], "node_insert--article" : { "bundle" : "article" } },
"IF" : [
  { "entity_has_field" : { "entity" : [ "account" ], "field" : "field_next_article" } }
],
"DO" : [
  { "schedule_delete" : {
      "component" : "rules_send_email_notification",
      "task" : "[account:name]"
    }
  },
  { "data_set" : { "data" : [ "account:field-next-article" ], "value" : "+30 day" } },
  { "schedule" : {
      "component" : "rules_send_email_notification",
      "date" : {
        "select" : "account:field-next-article",
        "date_offset" : { "value" : 2592000 }
      },
      "identifier" : "[account:name]",
      "param_user_to_notify" : [ "account" ]
    }
  }
]

}
}

Note that the above rule refers to the Rules Component from the previous step.

The schedule_delete that is part of this rule is to ensure that previously "scheduled" reminders will get removed when updating the data field (so that it only triggers 1 reminder, and with the most recent date).


How to show all subterm nodes of a parent term with the simple_hierarchical_select module?

I found this issue solution after 2 weeks searching and experiments.
in views filter add "Simple hierarchical select - taonomy with dept" and in dept field of settings of this filter select 1 .
Now , when select a parent term , secound term with dept 1 has been showing too.


It seems you're looking for the Content Complete module

  Content Complete is a CCK extension module that allows to tag CCK fields needed for completion (CCK Complete). The module checks the tagged fields against the content provided for those content types, and computes a complete percentage that can be shown to the user.

Image from the project page

Similar module is Field Complete

  In some situations you want to mark an entity field to indicate it should be completed but not enforce its completion at that time. This module extends the choice between Required and Not required to "desirable" completion.


Drupal admin area and login, Securing them with HTTPS

It's not the question you asked, but the simplest answer is you should just change your policy.

"Hacking" core (patching it) and running unstable releases is reality of running a website.

The two patches needed for securepages frequently need re-rolls, reviews, or improvements. Get involved in that cycle and help get them stable.


From the looks of the error, it looks like vbo operation or the action is trying to insert a blank value into the field_data_field_workflow_states table.

Without actually seeing any code it's a little harder to determine what's going on in the vbo or the action, but check either list_of_node_for_expire or action::workflow_vbo_given_state_action and make sure you're working with the correct data before it makes the database request.


How to check if an entity is referenced before deleting?

(Entity)Reference Field Synchronization module should be able to help:

Having 2 Entity reference fields pointing back at eachothers entities, they can be set to be updated so that if an entity A with field 1 references to an entity B with field 2, entity B automatically points to entity A.
This is very helpful when you need to be able to reference from any entity, and not just be able to perform back reference queries (as provided by Entity reference).

Just add an synchronized reference field to a parent, and on delete test if it has values or not.
Also, see this feature request in Entity reference issue queue.


Conditional Fields Changed Answer Problem

Adding another dependency with field 3 - emptied when question 2 is no should most likely fix your problem


Problems w/ themes and multi-site installation

I have also experienced this issue as well. It seems that drupal doesn't want to recognise themes and modules on a multisite subdomain basis (i.e. sites/yoursite.com/themes is ignored!!!). I don't know if this is intended behaviour but the only solution I have found thus far is to put all modules and themes into the sites/all folder and then to check they are enabled in the admin interface.
Drupal will correctly respond to the subdomain request (and rewrite paths where appropriate) so long as you have the sites/yoursite.com folder.


How can I implement Schema.org on my Drupal 6 site?

Anyone coming across this looking for this in Drupal 7 (I know the question is for D6), see the Schema.org module. Using this module sites administrators can specify what schema.org terms they want to associate with their content types (e.g. Art Gallery, House, Event, Person, etc.) and their fields (description, participants, etc).

Although this project is syntax agnostic, the schema.org types and properties selected by the site administrator will be used as part of the native Drupal 7 RDFa markup.

You can also use the Microdata module. Microdata is a module which takes care of embedding schema.org terms in HTML per the microdata spec. Core does it via the RDFa 1.0 spec. There is a UI for schema.org in microdata so that it does not have to depend on other modules for the UI (Drupal core does not include such UI).


How to avoid no-wrapper tags on regions?

From the code it looks like Zen adds that template suggestion in zen_preprocess_region(), but only to the content region:

elseif ($variables['region'] == 'content') {
  // Allow a region-specific template to override Zen's region--no-wrapper.
  array_unshift($variables['theme_hook_suggestions'], 'region__no_wrapper');
}

If you're editing the Zen theme directly (which you shouldn't be :P) just remove those 4 lines; if you're creating a sub-theme, implement your own region preprocess function, copy the code from Zen's, and leave those lines out:

function MYTHEME_preprocess_region(&$variables, $hook) {
  // Sidebar regions get some extra classes and a common template suggestion.
  if (strpos($variables['region'], 'sidebar_') === 0) {
    $variables['classes_array'][] = 'column';
    $variables['classes_array'][] = 'sidebar';
    // Allow a region-specific template to override Zen's region--sidebar.
    array_unshift($variables['theme_hook_suggestions'], 'region__sidebar');
  }
}


Does  Drupal have an AJAX solution for search results, preferably with Apachesolr integration?

Depending on your needs, there are a couple of solutions.  Probably the closest thing to Apple's Live Search feature is the Finder module.  It does not integrate with Apache Solr at this time, however.

I would also keep your eye on the Inline Ajax Search module as Solr integration is on the roadmap.  It might need some contributions to push integration through.

A third solution to try is the Apache Solr AJAX module.  It might not fit exactly what you are trying to do, however it allows for inline refreshing of the page when queries are entered and filters are enabled.


Find the path to php 5.5’s binary.
Find the path to drush.

Execute

/path/to/php_55/bin/php /path/to/drush status


You can use Views PHP module.
This module allows the admin account (user 1) to add fields, filters and sorts to views which use PHP code. It also supports additional accounts when the core PHP Filter module is enabled.
Enable this module and add a filter PHP filter which you can select from views filter Global Category once you install above module.
Add php code for filter condition as per your requirement.


db_delete works fine, but the problem is that I was trying to delete the cache of the current form from within the code of that form e.g. submit form. Logically this is ok for me because I was trying to delete the cache at the end of my multistep form where the user cannot do anything else but navigate away.
There must be a check somewhere either in db_delete not to allow to delete the cache of the current form.
I tried and I managed to delete from cache_form other entries from the exact same place in the code, just not targeting the current_form cache.
I was aware that I'm deleting the cache of the current form, but I just wanted to test that the db_delete works, and then move on with a more complicated logic where I would not delete the current cache but the previous form from the cache.


Call Remove Button (File Upload) Programmatically using JavaScript

Easiest way to do is what @Molo mentioned in his comment.

$('#element_id').trigger("click"); OR $('.element_class').trigger("click");
$('#element_id').trigger("mousedown"); OR $('.element_class').trigger("mousedown");

Or you could, reset the .html() of the upload element

$('#'+id).html($('#'+id).html()); OR  $('.'+class).html($('.'+class).html());

JavaScript into Drupal can be done in various ways, you could reference your javaScript file in your theme's info file or you override the drupal_add_js function in template.php and add your JavaScript.

For more Information on how to put JavaScript into Drupal see this or this and these (module or module) could also be handy. This article explains how to programmatically submit a form in Drupal.

Here is a good tutorial, how to add your JavaScript to Drupal https://www.drupal.org/node/756722


How to install drush on a shared hosting without SSH and without composer?

Rather than using drush, consider writing a custom script you can call instead.

In Drupal 7 you can bootstrap Drupal from the command line like this:

<?php
chdir('/var/www/YOUR SITE ROOT');

// no time limit!
set_time_limit(0);

// set some server variables so Drupal doesn't freak out
$_SERVER['SCRIPT_NAME'] = '/importer.php';
$_SERVER['SCRIPT_FILENAME'] = '/importer.php';
$_SERVER['HTTP_HOST'] = 'somewhere.com';
$_SERVER['REMOTE_ADDR'] = '127.0.0.1';
$_SERVER['REQUEST_METHOD'] = 'POST';

// change to the Drupal directory
define('DRUPAL_ROOT', getcwd());

 // Drupal bootstrap throws some errors when run via command line
 //  so we tone down error reporting temporarily
error_reporting(E_ERROR | E_PARSE);

// run the initial Drupal bootstrap process
require_once('includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

// act as the first user
global $user;
$user = user_load(1);
// add your custom code here

You will need to tweak this to your specific needs. Place it outside your site root for security reasons.


Can I just have a color coded HTML editor in Drupal 6 that keeps line indentations?

Well I got myself halfway there and without the need to download an additional module, library, or plugin. By checking Apply source formatting and Preformatted, the Disabled Rich Text rendition shows code indented with some of the white spacing preserved.

You can find these settings in D6 via admin/settings/wysiwyg


How to add Properties to an Entity in code?

I've been researching and playing around with the ECK module all day and have managed to answer my own question. Hopefully someone else will find this helpful.

To the example code listed just add these lines before the save() function is called:

$entity_type->addProperty('title', 'Title', 'text', 'title');
$entity_type->addProperty('uid', 'Author', 'integer', 'author');
$entity_type->addProperty('created', 'Created', 'integer', 'created');
$entity_type->addProperty('changed', 'Changed', 'integer', 'changed');


How to change a field type from free-form text to a taxonomy term and keep its existing data?

Changing the field type as you asked is not possible.

However a possible alternative to achieve a similar result is like so (in the order specified):

Create a new taxonomy term field, so that "from now on" any future node updates (or new nodes being created) will use that new field.
Use the Rules module to create a rule like so:

Rules event: before saving content.
Rules conditions:

entity has field, with field = the old field.
AND NOT (entity has field, with field = the new field).

Rules Action: set Drupal message, which contains some instructions that the old field must be blanked out, and the new field should contain the appropriate value(s.

Obviously, this approach will take "some" time if this has to be done manually, 1 node at a time. But using Views (to build a list of similar nodes to be updated) and VBO (to mass update such lists) you might (should!) be able to speed up this process quite a bit. Refer to my answer to "How to bulk update select list fields?" for an example with way more details about that.


How to get a field value and multiply it to get price in a PriceResolver

I was able to get this to work by checking that field_discount_percentage is not empty, rather than just checking if the entity has field_discount_percentage. The error must have been from all the other entities that were returning empty fields as a non-numerical value of ""
public function resolve(PurchasableEntityInterface $entity, $quantity, Context $context) {
  if ($entity instanceof ProductVariationInterface && !$entity->get('field_discount_percentage')->isEmpty()) {
     $discount = $entity->get('field_discount_percentage')->getValue()[0]['value'];
     return $entity->getPrice()->multiply($discount);
  }
}


Default theme css wrongly included in another theme

The issue was happening on form pages that had CKEditor-enabled fields. The CKEditor module has a configuration option to specify additional CSS to load. By default, it loads the default theme's CSS. After changing this option, everything works as expected.


Override entire user login / register page

In template.php, you could add an alter form to add classes, a wrapper, and I think also be able to add/edit fields in the form. Would that be of any help?

Example:

function THEME_NAME_form_user_login_alter(&$form, &$form_state) {
    $form['#attributes']['class'][] = 'custom-class';
}

in template.php would add the class custom-class around the login form, which you can then use to style the form.

As for using templates, I think they might have to be added in the correct location as well, e.g. I have recently built a site using custom templates with the user pages templates in /sites/all/theme-name/templates/user/. This also allows you to use custom markup. For example:

<div class="custom-class--wrapper">
    <?php print drupal_render_children($form) ?>
</div>

which is used in the file user-register-form.tpl.php.

Also, have you considered using panelizer to customise pages, that would be a lot easier than using template.php or custom templates. And if a change doesn't seem to take effect, you should try and clear the drupal cache.


How do display a secondary menu within a drupal node without the node displaying as a actual menu item

I found a great module that seems to work great!  It's called menu position found here: http://drupal.org/project/menu_position and it's super easy to use.


How to resolve message ' Requires: Commerce_checkout (missing)'?

You need to install the Commerce module.

Commerce Checkout is a submodule thereof.


How to create audit trails/order revisions?

I'm assuming you're using Drupal 7 here but one of the most effective ways to do is to handle it the same way that Commerce Kickstart does: with the Message stack.

There is a Commerce Message module exposes some of the common events, you'll just need to create a view and tie it into your order page or figure out some other way of handling things.


Drupal Search API Placeholder && Front Page?

Check for drupal_is_front_page()

  Return value

  Boolean value: TRUE if the current page is the front page; FALSE if
  otherwise.

function THEME_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['search_api_views_fulltext']) && drupal_is_front_page()) {
    $form['search_api_views_fulltext']['#attributes']['placeholder'] = t('Search Text here...');
  }
}


How to set image style for particular image in node creation or edit?

If you are asking "How can I theme the first image in a multi-value field differently from the remaining images in that field?" you can use a custom field template.

First, copy content-field.tpl.php from the CCK module (found in modules/cck/theme/content-field.tpl.php) to your theme's directory.

Then copy it to content-field-field_NAME_OF_FIELD.tpl.php eg something along the lines of content-field-field_pictures.tpl.php.

NOTE:  You must have both content-field.tpl.php and content-field-field_whatever.tpl.php in the same directory in your theme or it won't work.

Inside, it looks basically like this:

<?php if (!$field_empty) : ?>
<div class="field field-type-<?php print $field_type_css ?> field-<?php print $field_name_css ?>">
  <?php if ($label_display == 'above') : ?>

<?php print t($label) ?>:&nbsp;

  <?php endif;?>

    <?php $count = 1;
    foreach ($items as $delta => $item) :
      if (!$item['empty']) : ?>
        <div class="field-item <?php print ($count % 2 ? 'odd' : 'even') ?>">
          <?php if ($label_display == 'inline') { ?>
            <div class="field-label-inline<?php print($delta ? '' : '-first')?>">
              <?php print t($label) ?>:&nbsp;

          <?php } ?>
          <?php print $item['view'] ?>

      <?php $count++;
      endif;
    endforeach;?>

<?php endif; ?>

and you will be wanting to change the <?php print $item['view'] ?> line in the middle.

Dull ax approach, this would do it:

<?php if (!$field_empty) : ?>
<div class="field field-type-<?php print $field_type_css ?> field-<?php print $field_name_css ?>">
  <?php if ($label_display == 'above') : ?>

<?php print t($label) ?>:&nbsp;

  <?php endif;?>

    <?php $count = 1;
    foreach ($items as $delta => $item) :
      if (!$item['empty']) : ?>
        <div class="field-item <?php print ($count % 2 ? 'odd' : 'even') ?>">
          <?php if ($label_display == 'inline') { ?>
            <div class="field-label-inline<?php print($delta ? '' : '-first')?>">
              <?php print t($label) ?>:&nbsp;

          <?php } ?>
          <?php
            if ($count==1) {
              $first=str_replace('100x100','228x228', $item['view']);
              print $first;
            } else {
              print $item['view'];
            }
          ?>

      <?php $count++;
      endif;
    endforeach;?>

<?php endif; ?>

where, if in your CCK configuration you have 100x100 as the imagecache style for this field as the default, it is changed to 228x228 for the first image.

Obviously, if 100x100 appears anywhere else this fails so I am sure something more eloquent could be created.  But in either case, clear caches/theme registry and you should be on your way.

Also, I've left out any logic based upon toggling this on another field's value, but all the information is available in that template to do so.


The uploaded file likely exceeded the maximum file size (32 MB) that this server supports on remove image

For sure this is due to some problem with your sever setting, contact your webhosting company and talk with them regarding the issue.

It could be due to ModSecurity which is an  is an open sourceweb application firewall Apache module. which help in providing an external security layer that increases security, and help in preventing attacks.

The other reason could be the size your allow to upload that can be change in your server setting. It is also important to check apache max_execution_time.

If you have control over your server then you can try to change your php file

post_max_size = 128 MB
upload_max_filesize = 32MB


It's invoked in several places. It happens in _field_info_collate_types(), which is called from

field_info_cache_clear()
field_info_field_types()
field_info_formatter_types()
field_info_storage_types()
field_info_widget_types()

So there's a fairly large surface area for invocation.

hook_field_info() is for providing metadata about fields, though, so using it to programatically hide a field is doomed to failure. You simply don't have that option in the info hook.

Depending on what you mean by "hide" you'll either want to implement a form alter hook (to remove a field from a form), or a preprocess/view hook to hide it from being rendered, or maybe both. Obviously YMMV if you mean something other than those options.


How to print edit link on a node page if the current logged-in user has access to node edit

First of all you need to make sure to get access to your administrators as well as the author, also note that you need to load nid along with the uid

<?php
global $user;
$node = node_load(arg(1));
if(user_access('edit any "" content') || ($user->uid == $node->uid)){
    echo l(t('Edit this node'), 'node/' . $node->nid . '/edit');
}
?>


Is there a way in D7 that allows for multiple links in an image in a slider?

Views Slideshow

Views Slideshow can be used to create a slideshow of any content (not
just images) that can appear in a View. Powered by jQuery, it is
heavily customizable: you may choose slideshow settings for each View
you create

Then add a custom field to your view and put the links there.


How can I offer an option for users to switch between Unformatted and Table the Basic Styles section of Views.

I would most likely go for Views Display Tabs or Quick Tabs (and I would lean towards Quick Tabs because it has a d7 version and is more active).


How to save a field value according to another field value and with a user presave hook

To change a field according to another field:
function mymodule_user_presave($account) {

 $data = $account->field_a->value;
 $account->field_b->value = strtoupper($data);

 drupal_set_message($account->original->field_a->value . ' > ' . $account->field_a->value);
 drupal_set_message($account->original->field_b->value . ' > ' . $account->field_b->value);

}

To get the original values you would have to use $account->original. Otherwise you get the new values. To prove that it's working this is the output in messages from the code above after I entered abcdef in field_a:

abc > abcdef
ABC > ABCDEF
The changes have been saved.


TemporaryStreamWrapper error during installation

Where can I change the path for "tmp" file through file system.

You can set the tmp path by appending the following line in the site settings.php

$conf['file_temporary_path'] = '/tmp';

In Addition, all item stored in variable table in Drupal site's database can be set with $conf array in the same way.


How does Drupal know which Entity View Mode to use?

With a tiny bit of glue code you can use specific node template files for different view modes, so they can become pretty useful:

function MYMODULE_preprocess_node(&$vars) {
  if($vars['view_mode'] == 'some_type') {
    $vars['theme_hook_suggestions'][] = 'node__' . $vars['node']->type . '__some_type';
  }
}

That will allow you to use template files with names like node--article--some-type.tpl.php specifically targeted to that view mode.

Other than that MPD's answer has all of the other common cases covered.


I can answer the first part of your question...

Drupal uses render arrays for the different outputs. Since you only specify two single dimension arrays with #markup they are rendered as 2 strings.

There are multiple ways to achieve what you want, I will highlight 2;

Use #prefix and #suffix:

$output['element1']=array (
  "#type"=>"markup",
  "#markup"=>"Hello World!"
  "#prefix"=>'

',
  "#suffix"=>'

',
);

Use nested elements:

$output['element1']=array (
  'row' => array(
    '#prefix' => '
',
    '#suffix' => '
',
    'cols' => array( // This has no #, so is the next level of elements
      '#markup' => t('Hello World!'),
      '#prefix' => '
',
      '#suffix' => '
',
    ),
  ),
);

See this related issue: How to nest elements in a render array.

However, there might be cases where it is not possible to alter the output of modules. Instead you want to do this in the theme. Your suggestion was not that bad. It is just that in twig arrays are noted with a dot symbol. {{ content['element1'] }} should be {{ content.element1 }}

        {{ content.element1 }}

        {{ content.element2 }}


Show relationship summary using Entity Reference

First off, you only need an entity reference field on the content type Books that points to Author in your example. It would be a pain in the long run to manually maintain the two relationships and all data needed to describe your relationship is given in the Book->Author field.

Now let's create a View that lists books.

(I've removed the second column in the screenshot from Views as no settings were done there)

Add the entity reference relationship under Relationships.
Add Content: title and use your relationship.
Under Format and Settings, set group by to the Content: Title field you created in the step before.

Now all books are listed and grouped by their author.

In my example I also sort by the authors name. If you rather show the Nid of the content, just switch from Content: Title to Content: Nid.


How do I display the user login in a popup?

There is a module for that: Modal Forms. Enable and configure it, you're just a checkbox away from modal login :)


Views exposed Filter by date: month OR year

You should be able to add the same filter twice and set one to a Month granularity and the other to a Year granularity. Then you can rearrange the filters and setup an OR grouping and place the year in that one


Filter a view by a value being absent from a multiple value field

You could use hook_views_query_alter() to modify SQL query.

/**
 * Implements hook_views_query_alter().
 */
function example_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == 'discussions') {
    // Exclude discussions the current logged user has participated in.
    $uid = Drupal::currentUser()->id();
    $nids = Drupal::entityQuery('node')
      ->condition('type', 'discussion')
      ->condition('field_participants', $uid)
      ->execute();
    $query->addWhere(0, 'nid', $nids, 'NOT IN');
  }
}

In the example above we are getting ID's of excluded nodes using entity field query and then them to NOT IN condtion.

The resulting SQL query will be as follows:

SELECT node_field_data.created AS node_field_data_created, node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
WHERE (nid NOT IN ('1', '2', '3')) AND (node_field_data.type IN ('discussion'))
ORDER BY node_field_data_created DESC

Alternative way would be using JOIN with extra conditions:

/**
 * Implements hook_views_query_alter().
 */
function example_views_query_alter(ViewExecutable $view, QueryPluginBase $query) {
  if ($view->id() == 'discussions') {
    // Exclude discussions the current logged user has participated in.
    $uid = Drupal::currentUser()->id();
    $definition = [
      'table' => 'node__field_participants',
      'field' => 'entity_id',
      'left_table' => 'node_field_data',
      'left_field' => 'nid',
      'extra' => [
        0 => [
          'field' => 'field_participants_target_id',
          'value' => $uid,
        ],
      ],
    ];
    $join = Drupal::service('plugin.manager.views.join')->createInstance('standard', $definition);
    $query->addRelationship('participants', $join, 'node');
    $query->addWhere(0, 'field_participants_target_id', NULL, 'IS NULL');
  }
}

The generated SQL query:

SELECT node_field_data.created AS node_field_data_created, node_field_data.nid AS nid
FROM
{node_field_data} node_field_data
LEFT JOIN {node__field_participants} participants ON node_field_data.nid = participants.entity_id AND participants.field_participants_target_id = '1'
WHERE (field_participants_target_id IS NULL) AND (node_field_data.type IN ('discussion'))
ORDER BY node_field_data_created DESC

The view itself becomes quite simple. No need of contextual argument and aggregation.


I guess you want the url alias to be /sous-specialites for the english node. If so, I think you can use Global redirect module.

  From the documentation,

  What?

  GlobalRedirect is a simple module which…

  Checks the current URL for an alias and does a 301 redirect to it if it is not being used.
  Checks the current URL for a trailing slash, removes it if present and repeats check 1 with the new request.
  Checks if the current URL is the same as the site_frontpage and redirects to the frontpage if there is a match.
  Checks if the Clean URLs feature is enabled and then checks the current URL is being accessed using the clean method rather than the
  'unclean' method.
  Checks access to the URL. If the user does not have access to the path, then no redirects are done. This helps avoid exposing private
  aliased node's.
  Make sure the case of the URL being accessed is the same as the one set by the author/administrator. For example, if you set the alias
  "articles/cake-making" to node/123, then the user can access the alias
  with any combination of case.
  Most of the above options are configurable in the settings page. In Drupal 5 you can access this after enabling the globalredirect_admin
  module. In Drupal 6, the settings page is bundled into the module.


Remove the title from the node.tpl.php and create a new block with the following PHP code:

<?php
$node = node_load(arg(1));
print $node->title;
?>

Enable visibility only on view node pages.

CCK Blocks is a very handy module for these things, but unfortunately the node title isn't listed as an element in display mode.

[EDIT]

If you are on D7 and you are using Omega theme, Delta module should work for you. Check specifically Delta Blocks module from that package.


Adding a block to the page but not declaring it in hook_block_info()

The block may be positioned using the Context module, or via custom code in about a million places. What you can do is temporarily modify the template_preprocess_block() function in block.module, identify the block you're looking for by looking at the data in $variables['block'], and then looking at the output of debug_backtrace() to see the callstack and find the place the block is coming from.


How can I filter which entities are available in the admin form for an Entity Reference Field?

1.) You can create the limited list of Articles with Views, then use that Views in the Entity reference Field settings as the source.

2.) This should have probably gone into a separate question. Try researching into modules related to autocomplete, like: Search Autocomplete, Autocomplete Search Suggestions.


Manipulate a render array in hook_node_view

Suggestions

Get the node from the $build (it should be in there somewhere) and build custom content for your field like $build['custom_field'] = [...].
Override the twig template for the field - this will let you alter the presentation of a particular field. Ex: implement node--field-custom-field.html.twig based on field.html.twig and alter the output of the field there.
Override the twig template for the entire node. Ex: implement node--article.html.twig based on node.html.twig and alter the output of the node there.

Let me know if any of these helps. More details on exactly what or why you want to alter stuff will be helpful.


Restrict Location per Domain in OpenLayers

I think you can do this with:

GeoIP API
Context
Context GeoIP
Domain Context


How can I access block metadata from custom plugin instance?

Generate unique form ID based on context contains the answer you're looking for.

Short answer is, you have to make this unique id yourself. See the mentioned simplenews project and how I solved it there.

Keep in mind that block plugins are not only usable by core block entities, they can also be used by Page Manager/Panels, where you have many blocks in a single variant and even by projects like block_field, which allow to use block plugins on content entities. You must not rely on anything but your own configuration array.

I think I once opened a core issue about this, to introduce a method so that a unique ID can bet set on a block plugin, but I can't find it anymore, only another core issue (https://www.drupal.org/node/2405879) where I mentioned that I can't find that issue anymore :)


Ckeditor toolbar not entirely showing up

Updated answer:

Go to "Home › Administer › Site configuration › CKEditor".

Then select an individual profile in the upper section (not the Global settings).

You'll be on the "Edit CKEditor profile" page, where there is an "Editor appearance" section. The 6th item down (just below the color picker) is the toolbar selector.

There are 5 options, if none of the selections meet your needs, you can easily create a custom toolbar with exactly the buttons that you want to have available.

The module author included a note below the toolbar selector, you can open the "ckeditor.config.js" located in "sites/all/modules/ckeditor" and create your custom toolbar there. It will appear in the selector after you create it.

I've included all of the buttons available for the normal CKEditor, but the module author has added some that are specific to Drupal. You can take a look at them in the config.js file.

Here are the standard plugin buttons, you can pick and choose which ones you want:

[ 'Source','Cut','Copy','Paste','PasteText','PasteFromWord','-','Undo','Redo' ]
[ 'Link','Unlink' ]
[ 'Image','Table','HorizontalRule','SpecialChar','-','SpellChecker' ]
[ 'Source','About','InsertSnippet','BGColor','SimpleLink', 'Select', 'SelectToText', 'SelectorUpdateSelector','SimpleLink' ]
[ 'About','BGColor' ]
[ 'Format','Font','FontSize' ]
[ 'TextColor' ]
[ 'Bold','Italic','Underline','Strike','Subscript','Superscript','-','RemoveFormat' ]
[ 'NumberedList','BulletedList','-','Outdent','Indent','-','Blockquote','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock' ]

Be Well,
Joe


How do I auto generate products via attribute?

Assuming you are using Drupal 7, you've got a couple of options:

Commerce Migrate will let you create products as part of a migration. It's a bit more time consuming but it's repeatable and is very powerful.
You can use Commerce Bulk Product Creation to create products based off of fields in the UI. This gives the ability to create those products once and isn't repeatable.


Query condition that needs to return true no longer working

I found out here that since Drupal 8.7.0 (at least) the field part of the condition can not be an expression.
Since you can't use "where" you must figure out another way to force the condition to always be true. Maybe you could mess around with the operator like this:

Instead of overriding the entire condition, use the "LIKE" operator:
$conditions[$key]['value'] = '%';
$conditions[$key]['operator'] = 'like';

Or if that doesn't work, the "NOT IN" operator:
$conditions[$key]['value'] = array('w00t');
$conditions[$key]['operator'] = 'NOT IN';

Hope this helps you!


Show a maintenance page while moving the site

First put your site into the maintenance mode than ("Administer > Site configuration > Site maintenance"), and than do the following:

Create the template file for maintenance page as maintenance-page.tpl.php.

Tutorial for creating a template file for maintenance page: https://drupal.org/node/195435


getting URL from Route: breaks in localhost subdirectory

Drupal 8 is very smart to detect in which environment it is running. If you have this path

/mySite/dir1/dir2/dir3/myAlias

then Drupal is installed in /mySite, but the root of the webserver is still in /.

If you want to get rid of /mySite you have to point your webserver at this directory. Usually you define a vhost with this path and choose a local sub domain, which is configured in the nameserver or your local host file.

With a correct configured vhost there shouldn't be any problems.

See https://httpd.apache.org/docs/current/vhosts/


To change the timeformat I had to change TimeFormat             from            .replace(':m', ':mm') to  .replace('h', 'HH') in fullcalendar.js


How can I disable a region at with the context module at all pages but the  (home page)

Set ~<front> in path. This will exclude only the front page.

I just tried it and it works properly.


Have you already tried this module?
http://drupal.org/project/ldap_integration

We use this on our (drupal) user control panel to let user authenticate from our LDAP database. Personally I haven't installed it myself, I'm using the drupal 7 version, which works great to!
http://drupal.org/project/ldap


After using hook_views_data() to declare your custom tables/fields, use a custom Views handler to override or reformat the output.


You have to implement hook_cron to run you task periodically on drupal cron.

function hook_cron() {
  // Your code here
}


create text box search for multi select field in view

You are looking for Finder module, it will display the autocomplete dropdown list to the users.

  Finder allows Drupal site administrators to create flexible faceted
  search forms to find entities such as nodes or users based on the
  values of fields and database attributes.


How to print custom date format in Twig?

Try to use this -

{{ item.content.field_publication_date|date("M") }}

But, I think you will get your solution in

{{ item.content|date("M") }}

Where item.content contains the date string inside field--node--field-publication-date.html.twig.


Upgraded to 7.31 but getting "no pending updates" message

Go to '[your-website]/admin/reports/status' and if there you see that Drupal version is 7.31 (which you probably will see), if there is no some other errors and everything works fine on website you successfully did update.

It is not necessary to always have database update if you are updating some module or Drupal itself.


Alter entity reference autocomplete field

This should be done by writing a custom CTools EntityReference selection plugin.  Your new class would just extend EntityReference_SelectionHandler_Generic_node and I think it would only need to override the getLabel() method to make things "just work".


How can I add multiple conditions for the same field taxonomy term in views query?

you try this code:

$and = $query->andConditionGroup();
foreach($ch_id as $key => $val_array){
   $and->condition('node__field_characs.field_characs_target_id', $val_array, 'IN');
}

$query->condition($and);


How to programmatically disable Global Theme Settings?

See here for a related question.

The theme settings are not individually saved as variables. They are all in a single variable, whose name depends on your theme. For example, if your theme name is mytheme, the variable name will be theme_mytheme_settings.

You can disable the logo and name like this:

$my_settings = variable_get('theme_mytheme_settings', array());
$my_settings['toggle_logo'] = 0;
$my_settings['toggle_name'] = 0;
variable_set('theme_mytheme_settings', $my_settings);

You can also disable settings by means of the features key in the .info file for your theme. The defaults are:

features[] = logo
features[] = name
features[] = slogan
features[] = node_user_picture
features[] = comment_user_picture
features[] = comment_user_verification
features[] = favicon
features[] = main_menu
features[] = secondary_menu

If you don't specify any of these, all are enabled. If you specify some, only the ones you specify are enabled. So if you wanted to hide logo and site name, you would put this in your .info file:

; features[] = logo
; features[] = name
features[] = slogan
features[] = node_user_picture
features[] = comment_user_picture
features[] = comment_user_verification
features[] = favicon
features[] = main_menu
features[] = secondary_menu

See the theme settings documentation for more info. You need to be careful with this depending on what theme you are using. If you're overriding a base theme, these are the keys, but a contributed or custom theme might have different keys.


Follow this checklist and it will work:

Make sure your module is called sanabel_calculator. If it isn't, change sanabel_calculator_menu() to MODULE_NAME_menu(). It's wise to use your module name to prefix all functions that it defines, as a rudimentary namespacing system. You might want to change iban_generator() to sanabel_calculator_generator() as part of that, to avoid confustion in the future.
Return something meaningful from your function. drupal_set_message() can return NULL, and other than that will only ever return a plain array. This is not acceptable as a page callback result, which needs to be a render array (or, less ideally, a string).
Make sure the module is enabled
Clear Drupal's caches

As an aside, consider defining a proper access callback or at least arguments for your page. It may not matter, but it's a good practice to get into.

If it still doesn't work after that, follow the steps again through again. If it still doesn't work, you've got something wrong with your installation. Try to install the module on a fresh copy of Drupal to confirm that.


How do I save session data for the anonymous users?

It because drupal save session with key, this mean you should do something like

  $_SESSION['yourkey']['xxx'] = serialize($data);

You can try this.

function lists_session($key, $value = NULL) {
  global $user;

  static $storage;

  // If the user is anonymous, force a session start.
  if(!user->uid) {
    drupal_session_start();
  }

  if ($value) {
    $storage[$key] = $value;
    $_SESSION['lists'][$key] = $value;   // I use 'lists' in case some other module uses 'type' in $_SESSION
  }
  else if (empty($storage[$key]) && isset($_SESSION['lists'][$key])) {
    $storage[$key] = $_SESSION['lists'][$key];
  }
  return $storage[$key];
}

So, to save a variable in Session:

lists_session("xxx", serialize($data));

And to retrieve the value, just use:

$myVar = lists_session("xxx");

and aslo as MOLOT mentions sometimes session not stareted for anonymous users then you should drupal_session_start() manually.


How do I make a twitter scheduler on drupal 7?

Create a node type ‘Tweet’
Create a Feed Importer
Add JSON mappings
Add the Import URL
Use some custom code or perhaps Rules in combination with Tweet module api to schedule and send tweets

Modules:

Feeds
Tweet
JSONPath Parser
Rules

Credits: http://www.bariswanschers.com/blog/easily-import-tweets-drupal-using-json-and-feeds


Log in on your drupal.org account (or create one)
Go to My Account > Edit > My Newsletters (https://www.drupal.org/user/[uid]/edit/newsletter where [uid] is your user ID)
Check "Security announcements" and click "Save"


How to display custom table without using views?

Instated of "echo"

  echo $output;

You have to write

  return $output;


Link a Drupal 7 site with a Facebook account

You might want to check out Drupal for Facebook.

A quote from the project page: If you already have content in Drupal, you can expose it on Facebook.

Documentation can be found on http://drupal.org/node/195035


How can I use webform to upload assets and create a project that can be assigned to different users

if you want client submissions to become content I recommend EntityForm Then you could use for example the Workbench module to assure the content is moderated by a manager into approval.

You likely want your content type to show limited items to the client and then more options to the manager. I would try to do this with the Field Permissions module.

Lastly you could automate sending emails and stuff on some events if you want using Rules.


How can I "merge" two fields when a form is submitted?

I would suggest you hook_node_presave() for this. Write this function somewhere in your custom module, just print the $node array. You would found all the fields value there that you can alter accordingly. Your code should be something like this.

function mymodule_node_presave($node) {
  if ($node->type == 'content type name') {
   // Append last name field value with first name field.
  }
}

This hook function get executed before node_save() that will save your changes in db.