Show 404 on page for node path url instead of redirecting to it's alias

Make sure apache mod_alias is enabled and create a rule in .htaccess like:

Redirect 404 /node/.*$


Commerce: programmatically create new product with my ID

I don't see this as a bug, as we do want to prevent arbitrary IDs from being set in general. If you're doing it intentionally, though, I think your best bet would be to implement an override in a custom entity controller that extends the core functionality and changes the behavior of the is_new check like you've done.


Should QA engineers directly update Drupal database tables via SQL?

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

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

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

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

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


How to get Address Field to display correctly with Autocomplete?

Turns out that there is an incompatibility between Addressfield Autocomplete and/or the geocomplete.js library it uses, and the version of JQuery that gets bundled with Drupal 7.

The solution is to install the JQuery Update module, and set the JQuery version to 1.10


How to remove the RSS feed icon form the content listing pages?

If it's just the feed icon you need to kill, you could always just comment out or delete the line:

<?php print $feed_icons; ?>

from page.tpl.php?


You should report this in the module's issue queue.

Notice type errors are most of the time harmless and caused by sloppy programming or some edge case the developer didn't think of.


Views Infinite Scroll Set default page with position

I know this answer seems to be (might be) a bad solution but it works. Use the code window.history.back() for "Back to previous Page" link like follows

<input type="button" value="Back to previous Page" onclick="window.history.back()" />

                             OR

<a href="#" onclick="window.history.back()"> Back to previous Page </a>

As far as I know this is browsers default behavior. So it works.

I've tested it and working on latest version of all major browsers.

Hope it helps.


How to add a css class to the nodes in the front page according to taxonomy of each node in drupal 7?

Supposing that "field_tags" is the taxonomy field for which you want to use the taxonomy term values, you could use the following code.

function theme_preprocess_html(&$variables, $hook) {
  if ($variables['is_front']) {
    $terms = array();

    foreach ($variables['page']['content']['system_main']['nodes'] as $nid => $array) {
      $items = field_get_items('node', $array['#node'], 'field_tags');
      foreach ($items as $tid) {
        if (!isset($terms[$tid]) && ($term = taxonomy_term_load($tid))) {
          $terms[$tid] = drupal_html_class($term->name);
        }
      }
    }

    if (!empty($terms)) {
      foreach ($terms as $class_name) {
        $variables['classes_array'][] = $class_name;
      }
    }
  }
}


Bootstrapping Drupal from the command line

Don't even try this. Use drush, it is meant for this type of things precisely.

The drush php-script command will allow you to run any PHP script in the context of Drupal, but I would recommend writing those as a proper command inside a custom module.


How to fetch manual flate rate token on replacement pattern

You would need to two things to make this happen:

How to programmatically create a custom token. And you'll definitely want to read the API docs on the relevant hook function.
How to get at the line item given an order.

Let's assume your token has an $order object inside the $data variable. The next step would be to use entity metadata wrappers to pull in all the information, including line items.

<?php
$order_wrapper = entity_metadata_wrapper('commerce_order', $order);
foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
  $line_item = $line_item_wrapper->value();
}
?>

Your shipping line item is in there. dpm($line_item); to find it and then construct your token output.


Add static images to bottom of view page

In your view edit form, find 'FOOTER' (under Page Settins), click 'Add' and select 'Global: Text area'

In the content textarea, add your images markup (e.g. <img src="http://example.com/some_image.png" alt="This is my image!"/>), change text format to "Full HTML" and save.


Drupal module development - How to build admin items list?

I think you have at least two possibilities to proceed.

First, you can use "Views" module to display a list of whatever you want (you can easily configure it to display all contents of a certain content-type that the user currently seeing the page created, etc, etc). You can inspire yourselft with this article about creating an administration page with Views 2 (http://zugec.com/2010/08/create-administration-pages-views-2). It is not very different.

If you want to do it programmatically,  you can always create a "page" that displays whatever you want using hook_menu(). Just set the path under "admin/" and permissions the way you want. Use the page callback function to make the appropriate query (select the nodes you want, created by the current user, order them, sort them, etc...) and to display the results.

If you want more explanations about one of the two solutions provided up there, just ask and I'll develop deeper :-)


Send E-Mail When User Profile Fields Updated

Just Install Rules Module and set the conditions something like this:

Event: After updating an existing user account

Actions: Send a HTML Mail ($account variable is available to send updated values through mail)

Conditions: If needed


You'll find the .css files in your theme directory, usually sites/all/themes/THEME_NAME/css.

To see easily in which line of which css file is the rule you'd like to change, you can go to admin/config/development/performance and un-tick Aggregate and compress css files checkbox.

Then with Firebug or similar development tool you'll be able to explore the css.

Check also if there's a sass or less folder in the same directory. In that case, you would have to edit the relevant scss/less files instead of the css ones, and make sure your editor is well configured to compile them to css.

You can explore scss files with the help of FireCompass addd-on and less ones with FireLESS.

EDIT

As underlined by Beebee comment, if the css you'd like to override are into a module css file, such as webform's css, don't edit that file, but override it in your own theme's css file.


Trouble populating text field widget while executing node.create through Service using Rest server

Field values need to be surrounded by an array, which holds all the potentially multiple entries for the field, and yet another array which holds all of the potential translations for the field.

In PHP that looks something like this:

$node->field_text['und'][0]['value'] = 'Some Text';

I haven't tested it but I'd guess the JSON equivalent would be something like this:

"field_text":
{
  "und":
  [
    { "value": "Some Text" }
  ]
}

That may need a bit of tweaking.


problem in admin_path module with my custom content type paths

Check out overlay_paths module. Should solve your problem. Sounds like admin_paths() isn't accepting up your url aliases. http://drupal.org/project/issues/overlay_paths.


Corporate website, each page different style

You can create a new theme using one of the many starter themes, and then override templates to get as specific as you please.

For example, to override a particular content type's look, you'd edit node--contenttype.tpl.php where contenttype is your custome content type.

The template guide contains further info, including naming conventions to get your templates applied in the right place.


user_save adds values to the user, but they aren't "active"

It may be static cache, try:

$user_perm = user_load($uid, TRUE);


How to add an action button to item of content type page?

It appears to me that you should start with using the Flag module, with a so called "global" flag. And configure your flag so that it would show an appropriate "confirmation" whenever such node gets flagged.

Next you could use the Rules module and create a custom rule like so:

Rules Event: A node has been flagged, under "Some flag" (= the flag's label).
Rules Condition: Entity has field (related to your field_event_status field), to make it available for further processing in subsequent Rules Events and/or Rules Actions.
Rules Action: Set a data value (related to your field_event_status field).

With that you have the mechanics (logic) in place, and the only think left is theming the flag link(s) to have them shown as buttons. If you wonder how to make that happen also, then have a look at my answer to "How to add a custom icon or symbol to a flag link?" (i.e. the Option 2 part of it).

Tutorials

If you're not familiar with the Flag module, checkout the set of 8 video tutorials about the Flag module. Especially these tutorials from it:

Creating global flags and listing flagged content in Views.
Triggering Rules with Flag

More info

Refer to Flag's Community documentation for (way) more details.


HTML corrector doesn't close quotation marks in teaser

Doesn't look like it's a problem on your side. You can try the following:

drush php-eval '$text = "
<a href=\"http://goo"; print $text . "\n"; print _filter_htmlcorrector($text) . "\n";'

And for me the results are:

<a href="http://goo

<a href="http://goo

(The second line is the output of _filter_htmlcorrector().)

It would be worth seeing if there's an issue for this already, and if not creating one. I find the built-in HTML corrector too limiting anyway (it always strips styles for example IIRC), and use htmLawed. With that you get:

drush php-eval '$text = "
<a href=\"http://goo"; print $text . "\n"; print htmLawed_filter('process', 0, -1, $text) . "\n";'

Results:

<a href="http://goo

(Again, second line is the cleaned output - it's simply stripped the incomplete tag.)


How to get correct language code during installation?

Looks like getting it directly from config is working just fine:

\Drupal::config('system.site')->get('langcode')


Can I access node ID of the parent node of a field collection field in field-collection-item--FIELD_NAME.tpl.php

Load the field collection using entity_load by passing the entity id. It gives you object where you can get the Host entity of the loaded entity. example profile2 will have user entity as host entity, or commerce line item will have commerce order as host entity.

$entity = entity_load('field_collection_item', $your_file_collection_id);
$host_entity = $entity->hostEntity();
echo $host_entity->nid;


Linking in views with multiple fields displayed

Try this:

Format

Format: table
Show: fields

Fields

Content: Title

under "settings" check "exclude from display"

Content: Path

under "settings" check "exclude from display"

Content: Grant Amt
Content: Due date
Content: Body

under "settings" choose to rewrite output as follows:

[title]

[body]

... and then add filter and sort criteria as desired.


Finding variables available in preprocess node or node.tpl.php from cck fields

Yes, you can do something like this in a custom module:

function YOURMODULE_preprocess_node(&$vars) {
  drupal_set_message('
' . print_r($vars, true) . '
');
}

or this in your theme's template.php file:

function YOURTHEME_preprocess_node(&$vars) {
  drupal_set_message('
' . print_r($vars, true) . '
');
}

If that's too much information, you can get just the variable names with:

 foreach ($vars as $name => $value) {
   drupal_set_message($name);
 }

instead of print_r()ing the entire array.


The output of views field templates is flat markup. You can't change a render array like you can in field templates when rendering entities in view modes.

So if you want to change the output you have to start from scratch with the values that are in the database. In views field templates you can use the getValue() method from the field variable. As parameter you have to provide row:

{{ field.value(row) }}

The result is a single value or an array for multivalue fields.

Example

views-view-field--created.html.twig

The raw value from created is a unix timestamp

Timestamp: {{ field.value(row) }}

You can use the timestamp for example to reformat the date with the date filter from twig:

Date: {{ field.value(row)|date("m/d/Y") }}


hook_menu() is not the hook to alter the routes defined from other modules, but in this case not even hook_menu_alter() would help.

When users access a page using a path alias, Drupal gets the normal path (i.e. the path to which the path alias points) before rendering the page. So, for Drupal, users are always visiting /node/$nid, not /myarticle/my-article-name/. In fact, drupal_path_initialize() (called at bootstrap time) contains the following code.

  if (empty($_GET['q'])) {
    $_GET['q'] = variable_get('site_frontpage', 'node');
  }
  $_GET['q'] = drupal_get_normal_path($_GET['q']);

drupal_get_normal_path() is the function converting the path alias in the internal path.

In this case, a redirect from /node/$nid to /myarticle/my-article-name/ is, IMO, the solution. The Global Redirect module already does that, as the project page describes.

  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.

Also, notice the Why? section on that page.

  Once enabled, an alias provides a nice clean URL for a path on a site. However Drupal does not remove the old path (eg node/1234). The problem is that you now have two URLs representing the same content. This is dangerous territory for duplicate pages which can get you sandboxed by the search engines!


How can I overidde html.html.twig in a module?

Overriding templates in the modules is not suggested because Drupals architecture doesn't really support multiple modules overriding same template.

However if you are still willing to do this, you have to simply add hook_theme() like this in your module file:

/**
 * Implements hook_theme().
 */
function modulename_theme() {
  return [
    // Normally theme suggestion templates are only picked up when they are in
    // themes. We explicitly define theme suggestions here so that these
    // templates in this module are picked.
    'html' => array(
    'render element' => 'elements',
    'base hook' => 'html',
  ];
}

Note: This will cause error messages in case you don't have the html.html.twig template available in the templates folder.


Panels in-place editor shortcut won't appear from gear wheel

Tried to reproduce this with Drupal 7.34 and Panels 7.x-3.4. I created a page, selected In-Place editor for Renderer under General tab of the Panels edit page, added some blocks and added a Mini panel with blocks in it, went to the page and all the gear icons work. Maybe some JS issue is causing this?

Update

Based on checks, I think Contextual links displays the edit link for the "renderer" only. Ex. if Blocks is displaying the Mini-panel, the contextual link module displays the "Configure block" link. Same for Panels with mini-panels rendered inside it. So that's the explanation why the "Edit mini-panel" link isn't displayed under the "gear" icon.

NOTE: Please correct me if I'm wrong with this analogy though because this is just based on observation

Solution 1: Using the Custom Contextual Links. Though this uses Tokens it doesn't get the mini-panel's name so if you had 10 mini-panels you should create 10 CCLs also w/c would be quite tedious though but of course if it's needed, nothing is tedious I guess? :)

Solution 2: Creating a custom module that would check each rendered "block" in a page is a mini-panel and if it is, display both the "renderer's" link and add the mini-panels link.


How to render element array piece by piece

Succeeded it "my way". Template now looks like this:

<form class{{ attributes }}>

{{ element.output }}
{{ element.footer }}
{{ element.form_build_id }}
{{ element.form_token }}
{{ element.form_id }}
{{ element.actions }}

</form>

element.output prints the table
element.footer prints the prices
element.actions prints the buttons
and other fields are printing necessary hidden fields

I know that @4k4 is right and I even tried solution he proposed before, but for some reason it didn't work for me (probably my mistake) and I didn't have more time to spend on this and this solution works well.

Posted this, because it's answer to this question and IMHO this should be "legal" way to print form, achieved only from twig without forcing on creating theme function and other stuff.

Please be gentle with minuses.


I solved my problem.

Well i don't if what i did was the issue but it's working so ^^

I went in the parameters of the Search API Module. I went on the tab "Filters", in the "Precesseurs" part i just activated this 2 things : HTML filter Tokenizer I re-indexed everything and by magic it's working.


How to display referenced field data in view?

You want a backreference. For D8 this is an open feature request:

Implement Entity Reference Backreferences

You should consider to this is in a forward reference (what you call reverse). Because even if the feature Backreferences is available, you would also somehow need to manage that there is only one reference, which you want to get the title field from. You can control this in the forward direction by making the reference field single value, but not in the other direction.


How to create a view of nodes that are referenced by a node that references the current node?

Create a view of content type Physician and set relationship between
Patient --- Patient Medication & Patient Medication --- Physician keep both relationship required.
Now add all field related with Patient nodes.
Here only a block display with patient and  Patient Medication.


It's very simple...add a function to your module:

function MYMODULE_some_form($form, &$form_state) {
  // Build and return your form.
}

Call drupal_get_form() from whatever context makes sense to your use case, and render the result:

$form = drupal_get_form('MYMODULE_some_form');
$rendered_form = drupal_render($form);

Then you can use $rendered_form as the output wherever it makes sense to do so (usually a template file).


Can I give a role permission to configure one (and only one) block?

try the content access Module for drupal 7.x might be exactly what you need


Send message notification when license expired

To glue the bits you have together you need to relate your to-be-expiring-soon license with a uid which can feed into message_create. So something like this in your hook_cron call...

//...after assigning $license_ids

foreach($license_ids as $license_id) {

   //...@TODO: checks on previous alert messages

   $uid = db_select('commerce_license','cl')
     ->fields('cl', array('uid'))
     ->condition('license_id', $license_id)
     ->execute()->fetchField();

   //...@TODO: code for executing message_notify_send_message and sending message to $uid
}


To get started, add a composer.json file to your module.  The only thing you need here is the require section that includes your external library.

Composer manager is one way to combine all of your dependencies together, but there are other options to get Drupal to load your autoload.php file.  The technique I prefer is to create a project-level composer.json file in your Drupal root, and use the module composer_vendor to include your autoload.php file.

The easiest way to get started is to use the composer_generate Drush extension to build your project-level composer.json file.

$ drush dl composer_generate
 $ cd /path/to/drupalroot
 $ drush composer-generate > composer.json
 $ composer install

Composer-generate will add all of the projects currently used in your Drupal site, plus composer_vendor, so composer install should just work for you.  The main magic here is in the custom autoloaders added to the template; take a look at the output to see what was included.

Some caution needs to be used here, of course; the default template will put all of your modules in sites/all/modules/contrib.  You can edit the template prior to running composer install if this isn't what you want.

You'll also have to be careful if you have any modified modules; there are a number of ways to deal with any hacked content, but that's a bit beyond the scope of this one question.

Update

If you don't want to run Drush, you can also hand-type your own composer.json file using the project https://github.com/drupal-composer/drupal-project.  This is the template that composer-generate is based on.


Views Filters: show published items from the last week or minimum number of items

Since you're trying to create a Views filter using an "OR" relationship, you might want to consider module Views Contextual Filters OR (which only has a dev version today). Excerpt from its project page:

  ... provides a views plugin which modify query to support OR conditions for contextual filters.

Does this help?


Views Field View module does that. Create a new view and add both needed views as fields.

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.


Managed file: What is the proper way of setting #default_value?

Welcome to Drupal Answers. You just need to pass the fid integer value to the default value. To better understand what is fid see below description.

  fid is Unique File id that is stored in the database for each and
  every uploaded file using Drupal File System.

So, if you want to set default image then it should be uploaded via Drupal File System. Ideally, you need to store fid of the uploaded file in a variable using variable_set in submit handler and do variable_get in default value to set fid. That's it !!

Hope it answers :-)


Commerce Product Option is an unsupported module. You should not be using it. If you want similar functionality with core support (e.g. options on an Add to Cart form that aren't required to correspond to unique SKUs), use custom line item types with line item fields instead.


Why are Drupal hosting providers using Solr 3.x instead of 4.x or 5.x?

It probably comes down to LTS and backwards compatibility, though you'd have to ask each organisation for their specific motivation.

Solr 5 is not backwards compatible with 4, 4 is not BC with 3. So if there are users on legacy systems using older versions, upgrading would require all customers to upgrade their schema/integration too. Installing newer versions on new servers might mean customers can't migrate from one server to another, might break the generic model of system deployment, etc, etc.

Some companies will offer newer versions, but you'll probably find the older versions are always available too, otherwise the company is likely to have at least a few pretty irate customers when they switch it off.

Basically, if you tell someone that you're going to support a version of software for the foreseeable future, you have to do that. It's why so many shared hosting companies support obsolete versions of PHP - because the people hosting there have no intention of upgrading their code, but their sites still need to work.

There's no Drupal-specific reason (that I know of) to choose one version of Solr over another, as long as the contrib module you're using has support for that version.


Add element to the beginning of form, via hook_form_alter()

I was facing the same problem but found the answer thanks to this post: http://drupal.org/node/235354

Problem was that the field I was adding to my web form was not in a group when all the already existing fields were part of the group 'submitted' maybe because this is a webform. So setting the weight to -1000 didn't change anything.

function webform_boncommande_form_webform_client_form_6721_alter(&$form, $form_state, $form_id)  {

    $form['my_new_field_name'] = array (
      '#type' => 'checkbox',
      '#title' => t ('My new field is after the others'),
      '#weight' => -1000,
    );

}

To correctly make it work I just needed to create my new field inside the group 'submitted' like that :

$form['submitted']['my_new_field_name'] = array (...


Fix 404 error when adding conditional action to Rule?

Not sure (yet) what is causing your 404 error, but at this point I'm not convinced it is a bug ...

I imported your exported rule in my own site to experiment with it, this is what happened:

The import worked fine (of course), so I started from the very same Rule as your exported rule.
I then used the Rules UI to also add such "If", and then just show a Bingo-message on the site.
If I would want to add another "if", the URL that would be used for that would have relative path "/admin/config/workflow/rules/reaction/manage/rules_attempt_to_recreate_a_404_error/add/3/if".

Here is the proof of my experiment (an exported Rule, which includes some additional logic within that Conditional Rules Action, and for which I changed the label and machine name also, though only after I imported the rule):

{ "rules_attempt_to_recreate_a_404_error" : {
    "LABEL" : "Attempt to recreate a 404 error",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "node_delete--page" : { "bundle" : "page" } },
    "DO" : [
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "node:promote" ], "value" : "1" } },
            "DO" : [
              { "drupal_message" : { "message" : "Bingo, this one seems to work ... using \u0022Conditional Rules\u0022 ..." } }
            ]
          }
        ]
      }
    ]
  }
}

The scenario described above was completed in a Drupal 7.5x site, using these versions of related modules:

Rules: 7.x-2.9
Conditional Rules: 7.x-1.0-beta2

I suggest you try to import "my" rule here in your site, and see if you get any other messages while trying to perform that import.

To further pinpoint your issue, have a look at the typical Drupal logging information, you may find there some other indication about what's happening in your site around the time the 404 error occurs.

Notes:

I'm not sure if it could be an explanation for your issue (what it is that causes it), but I noticed that your scenario uses https://, while my scenario was performed using  http:// ... Debugging is the art of taking away all possible causes for an issue, so you may want to try in a site using http:// instead of https:// ... FYI: I tried a similar scenario using  https://, and did not encounter any problem or 404 error.
As an alternative to using the Conditional Rules module, you can also create corresponding Rules Components, with similar Rules Actions to be performed. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?".


Have you checked that the file has the right permissions when uploaded to the server? at least make sure the webserver user has read access to it.


Did you try Simple hierarchical select module. You can build your tree structure with Drupal taxonomy.

Unlike Hierarchical select this module provides a simple widget for taxonomy terms only. As an addition Simple hierachical select works as Views exposed filter.


Quick Uninstall/Reinstall of a Custom Module

Solution 1. Devel + Drush:

You can use devel drush command for module re-installation with all the module dependencies:

drush devel-reinstall modulename

There is also alias for this command

drush dre modulename

Solution 2. Drush:

This is something that I would typically use drush for

drush pm-disable mymodule
drush pm-uninstall mymodule
drush pm-enable mymodule

You could also use it to define your own custom commands to combine these into a single command.


How to re-activate the Drupal administrator account that got accidently blocked?

Open the users table and in the admin row, check the status column. 0 means blocked and 1 means active. Make sure it is set to 1.


give default value property to select element e.g select form element returns value if select has been checked

add this attribute

'#default_value'= 1;

to every select list and your data to select list must be an array with key and value

$element=array(
'#type'=>'select',
'#default_value'=>1,
'#options'=>array(
         0 => t('No'),
         1 => t('Yes'),
    )

);

maybe then you have to render this element array with theme_form_element to your data variable. sorry but i havent enough time to test this solution


Is it possible to have three levels of subdomains in Drupal 7?

The answer is "yes". A Drupal multisite can use whatever structure it likes, including the one you propose.

To do this for subdomain http://fr.subset1.example.com/ just create the following subdrectory sites/fr.subset1.example.com/. Make sure it contains the file default.setttings.php and a copy this to settings.php. Then create subdirectories files  (and optionally, modules and themes), and make sure they're all writable by the web-server user.

Then:

Set up DNS for this subdomain (fr.subset1.example.com) to point to the same IP as the default domain.
Create a serveralias (details below) (or vhost entry) for that directory that has the same web root as the default domain.
Point your browser to the base URL of your website (http://fr.subset1.example.com/) to complete the web based part of the installation of a Drupal site.

To create a multi-site instance, you also need to make sure the DNS for that instance points to the same web root as the default domain. If you've set up a sub-domain, the simplest way to do this is to add it as a ServerAlias. This means putting something like this in the Apache vhost configuration:

<VirtualHost *>
  ServerName example.com
  ServerAlias fr.example.com
  ServerAlias fr.subset1.example.com
  …
  DocumentRoot /var/www/example.com/htdocs/
  …
</VirtualHost *>

Alternatively, you may create a separate vhost for the multi-site. This requires a separate entry, but allow you to tailor the web server settings for this particular multi-site instance.

Repeat this procedure for any other subdomains you want.


How do I call a controller method from a twig template and passing arguments to it?

Passing arguments in route parameters

I think the missing part is the route that you have defined for the controller. You have to use this to generate the url:

$url = Url::fromRoute('entity.node.canonical', ['node' => 1]);

This example is for the node controller and passes the argument nid=1. The parameter names are defined in the route definition.

Passing arguments in query parameters

I've seen in one of your other posts that you want to use query parameters. This is an example for the user login:

$url = Url::fromRoute('user.login', [], ['query' => ['destination' => 'http://example.com']]);

For this to work you don't need to define a query parameter in the route. Simply inject the request as function argument (the request is always available to a controller, it's not necessary to define it in the route) and get the query parameter:

use Symfony\Component\HttpFoundation\Request;

  public function myController(Request $request) {

    $destination = $request->query->get('destination');

  }


Commerce 2.x confusion about multiple order types and order item types

As BojanZ (the maintainer of the module) has stated in his comment above, you have located a bug :) Congrats! Post it to the Commerce issue queue here:

https://www.drupal.org/project/issues/commerce?categories=All


In a Views template, how can I mimic the effect of "Link this field to its taxonomy term page"?

One easy-ish way to do that within the Views UI is with the option:

"Rewrite the output of this field"

Add term id field Check "Exclude from display"
Order the field so it's above the other fields
Edit the field you want to convert into a link
Check "Rewrite the output of this field"

e.g

[name]

to create a link.

You can also add a global "Custom text" to add arbitrary text using the replacement tokens there as well.

In that way, tokens from your view fields can be made available as replacement pattern options in your View.


How should I name  the node template files for my theme?

The following should work:

node--blog.tpl.php

Make sure that you also have a node.tpl.php in your theme folder and that you cleared the cache.

See also Page template suggestions are not working for more information.


Redirect to page in form submit and use the form data in new page

You can use server session to keep your form state something like below

function video_upload_subtitles_form_submit($form, &$form_state) {
    $_SESSION['my_form_data'] = $form_state;
    $form_state['redirect'] = 'player/video_subtitle/view';

}

// Then

function video_subtitle_view(){
    print_r($_SESSION['my_from_data']);
}


You should be able to access the JSON response objects by saying data[0] and data[1]. These will be the swatches. So instead of namespacing the objects (swatches) by name, as in "myjson.x.path" you will be able to access them by index, as in "myjson[#].path". Does it imply any limitation for your setup?

As per getting the key/value pairs, you should be able to use either jQuery.each function, or native js for (item in coll) traversal.


Show a Unique Header Image based on Path in Drupal 7

If you want to define your header image in appearance settings form:

theme-settings.php

**
 * Implements hook_form_system_theme_settings_alter().
 *
 * @param $form
 *   Nested array of form elements that comprise the form.
 * @param $form_state
 *   A keyed array containing the current state of the form.
 */
function YOURTHEME_form_system_theme_settings_alter(&$form, &$form_state, $form_id = NULL)  {
  // Work-around for a core bug affecting admin themes. See issue #943212.
  if (isset($form_id)) {
    return;
  }

  // We are editing the $form in place, so we don't need to return anything.
  $form['YOURTHEME_settings'] = array(
    '#type' => 'fieldset',
    '#title' => t('YOUR THEME Theme Settings'),
    '#collapsible' => TRUE,
    '#collapsed' => FALSE,
  );

  // display settings
  $form['YOURTHEME_settings']['display'] = array(
    '#type' => 'fieldset',
    '#title' => 'Display options'
  );

  $form['YOURTHEME_settings']['display']['header_type'] = array(
    '#type' => 'select',
    '#title' => t('Type of header'),
    '#default_value' => theme_get_setting('header_type'),
    '#options' => array(
      'default'   => t('Default header'),
      'christmas' => t('Christmas header'),
      'easter'    => t('Easter header'),
    ),
    '#description'   => t("Select type of header"),
  );
}

template.php

/**
 * Override or insert variables into the page templates.
 */
function YOURTHEME_preprocess_page(&$variables) {

  // header image
  switch (theme_get_setting('header_type')) {
    case 'christmas' : $variables['header_image'] = path_to_theme() . '/header-christmas.jpg';
      break;
    case 'easter' : $variables['header_image'] = path_to_theme() . '/header-easter.jpg';
      break;
    default: path_to_theme() . '/header-default.jpg';
  }
}

Alternatively
You can use css to define header image paths, so instead preprocessing page variables, use template_preprocess_html to provide appropriate body classes:

/**
 * Override or insert variables into the html templates.
 */
function YOURTHEME_preprocess_html(&$variables) {
  // add holiday classes to body
  switch (theme_get_setting('header_type')){
    case 'christmas' : $variables['classes_array'][] = 'header-christmas'; break;
    case 'easter' : $variables['classes_array'][] = 'header-easter'; break;
  }
}

css

/* HOLIDAY HEADERS */
.header-christmas #page_header { }
.header-easter #page_header { }


Panelizer: displaying node reference field

You'll have to create a custom formatter where you can control the output of the node reference. To create a custom formatter follow this tutorial: http://www.metaltoad.com/blog/drupal-7-tutorial-creating-custom-formatters

After that in panels when you add the node reference you can choose the custom formatter you've created:


How to access table tokens in views through handler

The answer ended up being very simple. All I needed to do was cast $values to an array, then access the id. Like this:

$array = json_decode(json_encode($values), true);
$value = $array['fieldid'];


CKEditor violates layout borders in Drupal 7

Install CKEditor module directly instead of use with wysiwyg module.


How do I create a container entity that contains variable number of fields

I'm not sure if I understand correctly what you want to achieve, but the following two modules come to my mind that could be helpful:

Field collection

  Field collection provides a field-collection field, to which any number of fields can be attached.

Field Group

  All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.

I suppose in your case Field Group would actually be the more interesting module to look at. You can wrap a group of fields and you can then set the number of the field group to unlimited.

You can also have groups inside of groups. But things can actually get a bit 'messy' when editing a node with grouped groups.


Callback on 'save' on 'new node form' doesn't fire

You would be better off using hook_node_submit which would fire when any node is submitted.

You can make it specific to your node by the following:

function MODULE_node_submit($node, $form, &$form_state)
{
    if ($node->type == "NODE-TYPE")
    {
        //do stuff
    }
}


I broke a view and i'm not sure how to fix it

Go to /admin/config/development/configuration/single/export and export the .yml file for that view, manually delete the flag_id filter section, and reimport the .yml file under "Single Item", that should fix it.


Adding a template file to an enabled theme is like adding a hook to an enabled module: In both the cases, Drupal will not notice there is a new template file, or a new hook, as Drupal keeps that information cached.
After you add a new template file, you need to clear the Drupal cache, or disable the theme for then re-enable it. In the latter case, you forces Drupal to clear the relevant caches.

As side note, exit should be never used in a template file, not even for debugging. Doing so, you would interrupt Drupal when it calls theme_render_template(), with the effect that the template file would not be rendered.

function theme_render_template($template_file, $variables) {
  extract($variables, EXTR_SKIP); // Extract the variables to a local namespace
  ob_start(); // Start output buffering
  include DRUPAL_ROOT . '/' . $template_file; // Include the template file
  // The code after this comment is never executed, if the template file executes exit().
  return ob_get_clean(); // End buffering and return its contents
}

For debugging purposes, it's enough to print a specific string that allows you to know if the template file is loaded.


Multiple Sticky Items within using 2 separate views

You have to add a filter, for the view highlighted nodes:

Content: Sticky at top of lists (= Yes)

and for the view other nodes:

Content: Sticky at top of lists (= No)


My approach to this would be to have a content type called Story that had 2 taxonomy term references. One tag field could just be called tags and then other could be called tag_types. These 2 fields would be 2 distinct Taxonomy Vocabularies in Drupal.

Drupal 7 actually installs with a tags vocabulary out-of-the-box which is assumed to be free-tagging terms as your legacy site appears to be already using. So you just need to make 1 vocabulary for the tag_types.

Anyways then in your migration class for Stories. Your source SQL statement would figure out the necessary terms for these 2 fields, probably using a sub-select, and the migrate module can set the terms for the content type as Stories are inserted into the system.

So, some psuedocode is:

<?php

class StoryMigration extends Migration
{
  public function __construct($arguments)
  {
    parent::__construct($arguments);
    $query = Database::getConnection('default', 'legacy')
      ->select('stories')
      ->fields('stories', array('pgid', 'page_title', 'page_body'));
    // Create subqueries to get the tags for the story we are on. We will call
    // a fake field in our SQL query as legacy_tags or legacy_tags_type to be
    // passed using Migrate field mappings.
    $query->addExpression('SELECT GROUP_CONCAT(term_name) FROM legacydb_terms WHERE page_id = pgid' ,'legacy_tags');
    $query->addExpression('SELECT GROUP_CONCAT(term_name) FROM legacydb_term_types WHERE page_id = pgid' ,'legacy_tags_type');
    $this->source = new MigrateSourceSQL($query);
    $this->destination = new MigrateDestinationNode('page');

    $this->map = new MigrateSQLMap($this->machineName,
      array(
        'pgid' => array('type' => 'int',
          'unsigned' => TRUE,
          'not null' => TRUE,
          'description' => t('Source ID'),
        )
      ),
      MigrateDestinationNode::getKeySchema()
    );

    $this->addFieldMapping('title', 'page_title');
    $this->addFieldMapping('body', 'page_body');

    // Import a story's tag(s). Make the term in the vocabulary if it's not
    // there already, ignore the CaSe of the term so sloppy legacy terms
    // come across as 1 term.
    // By specifying this could have a SEPERATOR VALUE this can create any N
    // terms provided by our SQL statement above.
    $this->addFieldMapping('field_tags', 'legacy_tags');
    $this->addFieldMapping('field_tags:create_term')
      ->defaultValue(TRUE);
    $this->addFieldMapping('field_tags:ignore_case')
      ->defaultValue(TRUE);

    // Similar steps as for the above term, but for the tags_type reference field.
    $this->addFieldMapping('field_tags_type', 'legacy_tags_type');
    $this->addFieldMapping('field_tags_type:create_term')
      ->defaultValue(TRUE);
    $this->addFieldMapping('field_tags_type:ignore_case')
      ->defaultValue(TRUE);
  }
}

Term Reference Fields and the Migrate module are described in the documentation. Adding SQL Expressions to an SQL query is covered in the sql documentation.

My above code is an example and not guarenteed to work. It's simply 1 method of doing this and is to be referenced as an outline. Your SQL schema and php may look different in the end.


403 error in files while hosting drupal site in hostgator

Read up on the basics of linux permissions. Figure out which user nginx is running under. Make sure that user has read access on files and read/execute access on directories.


Newbie question : where to put "advanced" page content?

IMHO it's easier to start with content, and add the design once the content structure is ready. Drupal tries to separate content and design as much as possible, so you can always change one and keep the other.

There are no mandatory modules, especially with Drupal 8 you can get very far without any additional modules.

Drupal stores the content of a page as "nodes". Nodes have a type, like "article" or "product". You can use the default node types that you get out-of-the-box, or define your own. Each node type has a number of fields, like a text fields, image fields, date fields, etc. You can enhance node types by adding additional fields. Drupal will take care of rendering those fields on a form, storing the content in the database, and displaying the content on the page. There is a lot more I could say about this, but I recommend that you read the documentation, especially the part about content structure.


I have done this in the past by adding a drop down that gives the user an option of selecting "embed" or "upload"  then use the Conditional fields module to show or hide the required field.


Actually, you will pass through your validateForm() method, whether you are using Ajax or not.

In the validateForm(), you have to set the appropriate errors on your fields which do not validate.
Then, as Charles Bamford stated, you need to handle the error management in your submit callback.

So basically, you would end up with some kind of the following structure:

public function buildForm(array $form, FormStateInterface $form_state) {
  $form['#prefix'] = '

  $form['my_field'] = [
    '#type' => 'textfield',
    '#title' => $this->t('My field title'),
  ];
  $form['submit'] = [
    '#type' => 'submit',
    '#value' => $this->t('Submit'),
    '#ajax' => [
      'callback' => '::myAjaxCallback',
      'wrapper' => 'my-ajax-target-element',
      'method' => 'replace',
    ],
 ];

 return $form;

}

public function validateForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValues();
  // I set error on my field here, but due to Ajax, the display
  // of error messages will be handled in the Ajax callback
  if($values['my_field'] != 'my expected value') {
    $form_state->setErrorByName('my_field', $this->t('This is my error message'));
  }
}

public function myAjaxCallback(array &$form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  // If $form_state contains errors, populate the ajaxResponse content with the error messages
  if($form_state->hasAnyErrors()) {
    $errors = $form_state->getErrors();
    $command_content = $errors['my_field'];
  }
  else {
    // Happily proceed to the submission of your form
  }

  $response->addCommand(new HtmlCommand('#my-ajax-target-element', $command_content));
  return $response;
}


Receiving Error message on every attempt to add or remove content. Is this normal?

Just add this code to your index.php file just after the php opening tag.

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

Then try to reproduce the scenario. You will see the exact error on web page and if you clear about error then definitely you can solve it.


Services module: what is the syntax of node.index parameters?

I usually call node.index this way

$nodes = xmlrpc($this->server_endpoint, Array('node.index' => Array(0,'nid,uuid,vid', array('type' => $contentType), PHP_INT_MAX)), $this->headers);

the parameters being:

Page number (usually I set it to zero and set the number of nodes per page to PHP_INT_MAX. This because I found page support buggy in a previous version, I haven't retested it recently)
Array with fields to retrieve (only that you find in the node DB table are available. Careful with it, less fields means better request speed)
Array with content type(s) to retrieve
Number of nodes in the index list per page

I dont'know how exacly goes in XML, but I think that it should be easy enough to adapt to that syntax, if necessary.


How can I embed a webform in an Ionic React app?

Here is specifically how to do this in Ionic + React.
First, Webform share uses the iframe-resizer library, which has an official react component.
So install the library into your app:
npm install iframe-resizer-react
Then add a component such as WebformContact.tsx (this example uses TypeScript):
import * as React from 'react';
import {
  IonContent, IonPage,
} from '@ionic/react';
import IframeResizer from 'iframe-resizer-react';

const styleWebformIframeEmbed: React.CSSProperties = {
  width: '1px',
  minWidth: '100%',
};

const WebformContact = () => (
  <IonPage>
    <IonContent>
      <IframeResizer
        src="https://example.com/webform/MY-WEBFORM-MACHINENAME/share/iframe-resizer/4.2.10"
        title="MY WEBFORM TITLE"
        frameBorder="0"
        allowFullScreen
        style={styleWebformIframeEmbed}
      />
    </IonContent>
  </IonPage>
);
export default WebformContact;

Note that you need to install the same version of iframe-resizer in both webform (drupal) + your ionic app.
Also note that if your site is https, you should be sure to specify that in the src tag; when React is hosted by Ionic, it will be run from http://localhost (Android) or http://capacitor (iOS), so if you do not specify https for the server, you will get a difficult to understand error:

iframeResizer.js:822 Failed to execute 'postMessage' on 'DOMWindow':
The target origin provided

But really what this means is that you are trying to access an https server in an iframe with http.  So specify https!


How to resolve the SMTP not connect to server drupal?

If you are using gmail account for SMTP then you need to enable "Allow less secure apps: ON" under "sign-in & security" of you google account settings.


Memory size exhausted when trying to run Cron manually

All you need to do is increase your PHP Memory Limit from 128M to 265M

In settings.php:

ini_set('memory_limit', '256M')

For more info/other ways to change it, see Changing PHP memory limits


How to iterate extra fields in a webform component

It's a serialised PHP string, so:

$unserialised = unserialize($input);

// Split $unserialised['options'] by the '|' char, then extract keys/values


View of date field showing time on all day events

Fixed this issue by creating a custom date format and date type.
/admin/config/regional/date-time


Entity reference field dependent on entity reference in referenced entity of another entity reference field

This isn't easily possible at the moment with the standard widget/autocomplete API as it has no context from where it is referenced.

To get something like that, you need a custom widget, one that supports to pass an argument to the views query based on your current node and then you need to connect it with your other field so that setting/changing a value there sends an ajax request to update your other widget, which then needs to get that value and pass it along to the views selection plugin.

Some related core issues:
* https://www.drupal.org/node/2776571
* https://www.drupal.org/node/2280479


A response built from the RedirectReponse class is not cached. So you should not need to set any cache metadata (*). The problem here is probably the page cache for anonymous requests, which caches all responses, even redirects and no matter if they are cachable or not.
You can disable this cache by using the kill switch before returning the response:
\Drupal::service('page_cache_kill_switch')->trigger();

This will only disable the Internal Page Cache. To control caches outside of drupal, like proxies or browser caches, go to /admin/config/development/performance and set a "Page cache maximum age".
(*)
On the basis of @Smartsheet eng's comment use LocalRedirectResponse directly to prevent that RedirectResponse might be converted to this response without cache metadata (which would be cacheable by default):
$response = new LocalRedirectResponse('/foo');
$response->getCacheableMetadata()->setCacheMaxAge(0);

You still need the kill switch because the Internal Page Cache doesn't process the cache max-age.


In the view configuration settings for the Image field, there is a "No Results Behavior" section that allows html text input:

You can add some html code like:

<img src="/sites/default/files/no-results.jpg" alt="Description">

to add an anchor image that only displays in the View if there are no Image files attached to the node field.


Panel pages context and View contextual filters - cannot get it working

1) Views -> Contextual filter: add a filter

2) Views -> Pane settings -> Argument input: choose "Input on pane config" (notice the label)

3) Panel page -> Content: add the View pane

4) Panel page -> Content: in the pane settings, set the argument (notice the same label)

5) For this scenario, the Panel page -> Context is not needed


Uploading changed Drupal content from production to server

GIT will not be helpfull in this case. To transfer a contenet type from one Drupal installation to an other one you can either export and import it or use the features module (with features GIT could be handy).

For the other configuration changes you might be succesfull with the strongarm module. But for small configuration changes it's often more convenient to take some notes and just redo them on production.


How to properly delegate form error to parent?

I did what I could but in the end I had to create new form element that provided me with the proper structure. The important thing about it though is mostly that it has input so the form element can be properly delegated whereas before I used fieldset which has no input therefore it would not display error properly.


Free Shipping for selected products in Drupal Commerce

I definitely think you should give Commerce Discount a try for this, it provides a Free Shipping offer type when commerce shipping is present and thanks to Inline Conditions, you can filter for the products you might want.


Display multiple node edit forms on one page with one submit button

This can be done with Views and Editable Fields. You then create a page view with the Editable fields for the nodes and your all set. Keep in mind load times and performance by narrowing down the number of WYSIWYG fields and reference fields.


How to append fields to published node in drupal?

guess its possible with a combination of hook_form_alter and hook_nodeapi

Do check out these methods... hope it helps...


Mailing content to a list/group of email addresses

You can use the new Newsletter module for D7.

Features

  Multiple newsletters lists configurable on terms, not vocabularies
      Plain text or HTML out of the box
      Multiple schedules Each newsletter can have more than one schedule, e.g. Daily, Monthly, Weekly, manually or even custom, eg
  after 10 new posts for this term.
      Centralized administration and configuration on single page.
      Users can customize the terms in the list they subscribe to
      Custom template per list
      Statistics (CTR and Open-Rate)
      Drupal 7 only


Merely disabling the Fast 404 module isn't enough if you are calling fast_404_ext_check(); in settings.php.  Be sure you've removed the Fast 404-related settings from settings.php.

Due to the way private files are implemented in Drupal, you will never be able to use private files with the extension-checking features of Fast 404.


One thing you can do is set up a "sticky" view which pulls out the node you're looking for and then store the nid of the node.  You could do this using hook_views_post_execute() in a custom module like so:

function MYMODULE_views_post_execute(&$view) {
  $nid = &drupal_static('MYMODULE_sticky_node_id');
  if(!empty($view->result)) {
    $nid = $view->result[0]->nid; // (or similar)
  }
}

(Replace all instances of "MYMODULE" with your module name)

Now if there is a result then it's nid should be stored in a static variable called 'MYMODULE_sticky_node_id'.

Next add a contextual filter of NID to the main view, leave "When the filter value is NOT in the URL" as "Display all results for the specified field", and under the "More" fieldset, tick "Exclude".

Next implement something like hook_views_pre_view():

function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'your_main_view_name') { // If need be add "&& $display_id == 'your_main_view_display_name'
    if ($nid = drupal_static('MYMODULE_sticky_node_id')) {
      $view->set_arguments(array($nid));
    }
  }
}

This will pull out the nid you saved while processing the sticky view and set it as the argument of the main view, therefore excluding it from that view.

You'll need to make sure that the sticky view is rendered before the main view for this to work.

Bear in mind that I haven't tested this exact code so it might need some tweaking to get it to work in context.


hook_schema() is not used differently from how it was used on Drupal 7, the only difference is that it is not used to create database tables for entities. (See, for example, node_schema().) In particular, you don't need to call drupal_install_schema()) in hook_install() to create custom database tables, which was instead necessary in Drupal 6.

.schema.yml files (for example, user.schema.yml) are used to define the schema for the configuration used in the configuration files from the module. Its purpose is different from defining a database table schema, and they cannot be use for defining custom tables used from third-party modules.


You must enable the Node Export Feeds module and the Feeds module on the D7 site and import the nodes via the Feeds user interface from the D6 site.

Make sure you enable the Feeds Import and Feeds Admin UI modules as well on the D7 site


This is funny. I just answered a question about MySQL 5.5 being slow in the DBA StackExchange. You will have to configure it to perform better. It is not automatically configured for high performance by default.


Good afternoon.

1) install the devel module.

2) Install the modules, devel, kint.

3) change your code for the following:

function my_module_redirect_alter($redirect) {
   dpm($message = "redirect_alter worked!");
   kint($redirect);
}

4)  try to perform a process such as updating a node and when redirecting, you must show the messages.

Note: dpm() and kint() are functions of the devel module to inspect a variable


Try to theme a specific page using template.php and a sub theme

This

if ($path = 'node/131')

should surely be

if ($path == 'node/131')

Nevertheless this should not affect use of page.tpl.php.

Is your subtheme working at all, do templates get loaded from subtheme at all?

Your path is /sites/all/themes/progressive/progressive_sub. Does that mean the parent theme is at /sites/all/themes/progressive? If so, maybe try to give the subtheme a separate folder.


Is it possible to publish from my local computer a node in my drupal page remotely?

Do you already know this module : https://drupal.org/project/gammu
It seems to fit your needs :

  This module support Gammu database using same or separate Drupal database, even located on different server.

And it's provide with example.

Hoping that help.


can hook page alter also do all the things that hook form alter can do..?

Not, for sure hook_page_alter can't do everything that hook_form_alter (or other form alter hooks) can do.

Form alter functions allow to alter the form itself, its structure, values and valid values, submit and validate handlers, etc. This is because they are fired early in the Form API workflow. When Form API ends its work there's a render array that Drupal can render as HTML code.

After all form alter hooks are done (and any other code that generates the page content) comes hook_page_alter, but the form is done. Any alterations you make will be unkown for the Form API layer, most of the times resulting in strange validation errors form Form API (for example the 'Illegal Choice has been detected').

What you see in the hook_page_alter is not a form but the render array of a form: Here you can't modify submit or validate handlers, options of a select wiidget or add new elements in a multiple element field.

From hook_page_alter:

  If you are making changes to entities such as forms, menus, or user
  profiles, use those objects' native alter hooks instead
  (hook_form_alter(), for example).


Linux Drush install error: Undefined class constant 'MYSQL_ATTR_SSL_CA' in phar:///usr/local/bin/drush/lib/Drush/Sql/Sqlmysql.php, line 56

In my case, not all of the PHP packages made it though the Ubuntu upgrade to 16.04 (which now runs PHP 7 by default).  I needed to add the missing one, and then Drush started working again:

sudo apt install php-mysql

Or for php5 users

sudo apt install php5-mysql

on very recent Ubuntu/Debian distributions.

For PHP 7.1:

sudo apt install php7.1-mysql

For PHP 7.2:

sudo apt install php7.2-mysql

You can search for your version using this:

apt-cache search php-mysql


Change register button label when certain field is selected

First of all you don't need to check if isset is equals 1.

Then I think you must use the form_state or do this with jQuery, like this:

if(document.getElementById('checkbox-is').checked) {
  $("#submit-id").text("Jetzt registrieren");
}

UPDATE: I have edited your code to look like this:

(function ($) {
  $("#edit-field-registrierung-als").change(function() {
    if ($(this).value == "2") {
      $("#edit-submit--2").val("Registrieren");
    }
  }
}) (jQuery);


How do I properly delete a field collection?

The code you've shared is correct. The problem is that when we attach a Field Collection field to "User" entity the Host Entity of Field Collection is not set.

Because of which when we delete a Field Collection Entity programmatically the Host Entity field value (i.e. User in this case) is not updated with deletion. This causes Drupal to load Field collection which doesn't exists in system.

Rewriting the deletion code below:

use Drupal\field_collection\Entity\FieldCollectionItem;

// Load all field collections to delete.
$field_collections = FieldCollectionItem::loadMultiple(array(1, 2));
foreach($field_collections as $field_collection){
  // Delete field collection.
  $field_collection->delete();
}


Trigger a pop-up or recenter in Openlayers (version 7.x-2.0-beta5) from outsite the map

If you are using the standard popups that come with OL, you can make use of Drupal.openlayers.popup.popupSelect.clickFeature().

The way I did this was to assign an html attribute "nid" to each node in the list of nodes that you are going to use for the click navigation.  You can grab the nid from the clicked node any way you like, this is just the way I had done it.

So, now you have your list of nodes with an nid attribute and your map full of markers.  Here's one way you can use Drupal.openlayers.popup.popupSelect.clickFeature() to open the popup when you click one of the nodes in your list:

Make sure namespace exists:

Drupal.settings.nid = Drupal.settings.nid || [];
Drupal.settings.getAllFeature;

Make Drupal aware of all layers features:

function my_map() {
  var all_layers = Drupal.openlayers.popup.popupSelect.layers;
  for(var key1 in all_layers) {
    var current_layer = all_layers[key1];
    var all_features_in_layer = current_layer.features;
    for(var key2 in all_features_in_layer) {
      var current_feature = all_features_in_layer[key2];
      Drupal.settings.nid[current_feature.attributes.nid] = current_feature;
    }
  }
}

Function to grab the map object:

function getMap() {
  return jQuery('.openlayers-map').data('openlayers');
}

Click function for each node in your list of nodes:

jQuery('.eachNodeInYourList').click(function(e) {
  var nid = jQuery(this).attr('nid');
  show_popup(nid);
});

Show the popup on the map:

function show_popup(nid) {
  if (Drupal.settings.nid) {
    var feature = Drupal.settings.nid[nid];
    Drupal.openlayers.popup.popupSelect.clickFeature(feature);
  }
}

Make sure a layer is visible: (get the layer name from the "Title" field on the views overlay)

function activate_layer(aLayer) {
  var ol = getMap();
  var layer = ol.openlayers.getLayersByName(aLayer)[0];
  layer.setVisibility(true);
}

Initialize:

if (jQuery('.openlayers-map').length > 0) {
  my_map();
  activate_layer('myLayer');
}


According to your description, you want to automatically add the class to all lists within the CKEditor content for better theming.

I suggest not doing so within the CKEditor. Use a custom text filter instead. This avoids users accidentially forgetting to add the class manually and keeps your database stored contents cleaner.

The custom filter could parse the content and automatically add the classes when the text format is rendered. A good guide on getting started with creating custom text filters is this one: https://www.lullabot.com/articles/creating-a-custom-filter-in-drupal-8

In your process method you should use a simple DOM parser to add classes to all ul tags (not tested though, just for illustration):

namespace Drupal\my_module\Plugin\Filter;

use Drupal\Component\Utility\Html;
use Drupal\filter\FilterProcessResult;
use Drupal\filter\Plugin\FilterBase;

/**
 * Drupal 8 filter to automatically add class to unnumbered lists.
 *
 * @Filter(
 *   id = "my_lists_filter",
 *   title = @Translation("My lists filter"),
 *   description = @Translation("Automatically adds my_class to unnumbered lists."),
 *   type = \Drupal\filter\Plugin\FilterInterface::TYPE_MARKUP_LANGUAGE,
 * )
 */
class MyListsFilter extends FilterBase {

  /**
   * {@inheritdoc}
   */
  public function process($text, $langcode) {
    // Create DOM document.
    $dom = Html::load($text);

    // Get all UL tags.
    $lists_query = '//ul';

    // Get DOM nodes from XPath query.
    $xpath = new \DOMXPath($dom);
    $nodes = $xpath->query($lists_query);
    // Whether we have results.
    if ($nodes->length > 0) {
      // Iterate over list elements and add our class.
      foreach ($nodes as $node) {
        $classes = explode(' ', $node->getAttribute('class'));
        $classes[] = 'my_class';
        $node->setAttribute('class', join(' ', array_unique($classes)));
      }
    }

    return new FilterProcessResult(Html::serialize($dom));
  }

}


How to handle a lot of simple unique URLs (for click's statistics)?

A great module to aliases auto-generation is PathAuto. It will allow you to define patterns to your url's using tokens, things like:

article/[title-raw]

will generate:

www.example.com/article/my-blog-post

Once you install the module, go to:

Administration > Configuration > Search and metadata > URL aliases, in the "Patterns tab" (admin/config/search/path/patterns).


In a view, how can I display all sub categories of a given taxonomy term with content from each sub category?

This isn't a great answer, but after a couple days of trying to do this myself, the best I could figure out was to use Views Field View (I think that Views Grouping Row Limit would probably work too, but it's still in dev).

Create a basic node view that lists off your five movie node titles (along with any other teaser-like content you'd like), set your page to limit to five entries, and set the contextual filter to the movie's taxonomy term.

Then, make a view that shows taxonomies belonging to the vocabulary (movies). Set the contextual filter to "taxonomy term: parent term"), and output the tid (hidden) and term title. That'll make a list of your parent terms, so now add a views_field_view (set it to use your first view for input, and the tid for your argument).

Again, there's got to be a better way than this, as I'm sure it's going to create some real system overhead.

Pleeeease, someone come up with a better answer!


Have a look at:

ctools_custom_content_type_admin_title

/**
 * Callback to provide the administrative title of the custom content.
 */
function ctools_custom_content_type_admin_title($subtype, $conf) {
  $settings = ctools_custom_content_type_get_conf(ctools_custom_content_type_content_type($subtype), $conf);

  $output = t('Custom');
  $title = !empty($settings['admin_title']) ? $settings['admin_title'] : $settings['title'];
  if ($title) {
    if ($settings['custom_type'] != 'fixed') {
      $output = t('Custom: @title', array('@title' => $title));
    }
    else {
      $output = $title;
    }
  }

  return $output;
}

If the admin title is used, and the custom content type is not set to 'fixed' (see ctools_custom_content_type_get_conf), it will use your user input admin title for admin display there.


Include third party JS library into my drupal module

You still put them in the libraries folder (now you can also use a top-level /librariesfolder).

You need the libraries module, just like in 7.x. I'm also not 100% sure how well it works now in 8.x, in the JW Player module, I'm just using it to detect the location of the files: http://cgit.drupalcode.org/jw_player/tree/jw_player.module?h=8.x-1.x#n206


Feed import of 20,000 nodes. How to batch up 1000 at a time?

Which version of Drupal are you using? I haven't checked on Feeds for Drupal 8, but Feeds for Drupal 7 (unless it's changed in the last few years) has a hard-coded item limit of 50. If you're importing from a CSV, your node architecture is probably pretty simple. You could try the Feed Import module instead of Feeds, in my experience it's better suited for very large imports.


First of all, I want to point out that since this issue got closed in December, ctools got much better support for handling fields in access rules.

With that said, $contexts, have a data value, which is either an object, or an array of objects, depending on whether your plugin requires one or more contexts.

To make the code easier to read, I usually do something like this: $node = $context->data;

Brief example code:

function contact_info_pane_content_type_render($subtype, $conf, $args, $context = NULL) {
  $block = new stdClass;
  $block->content = '';
  $node = $context->data;
  $block->content .= count($node->field_email) > 0) ? $node->field_event_mail['und'][0]['email'] : '';
  $block->content .= count($node->field_phonenumber) > 0) ? $node->field_event_phonenumber['und'][0]['safe_value'] : '';

  return $block;
}


change FILTER CRITERIA for display (in views)

The Filter criteria didn't get applied properly because both Displays had the same name. It is required that both View displays have different names to be able to apply filters to only one Display.


How do I theme repeating dates output field?

Using template_preprocess_field seems to do the trick. You can either put this in your themes template.php or in a custom module.

function YOUR_THEME_preprocess_field(&$variables) {

    $most_repeating_dates_to_show = 5; // set limit of how many repeating dates is acceptable to show

    if($variables['element']['#field_name'] == 'field_date') { // Put your actual field name where it says "field_date"

        $num_repeats = count($variables['items']); // get count of how many repeating dates there are

        if($num_repeats > $most_repeating_dates_to_show) {

            $nid = $variables['element']['#object']->nid; // get the nid of the parent node

            // set the title of the link to show how many repeating dates there are
            $link_options = array(
                'attributes' => array(
                    'title' => t('See all :num repeating dates', array(':num' => $num_repeats))
                )
            );

            $link = l('Has multiple dates', 'node/'.$nid.'/repeats', $link_options);

            $variables['items'] = array(0 => array('#markup' => $link)); // here we overwrite the whole array of items so only our link will show

        }

    }

}

I've added a bit of extra functionality turning your text "Has multiple dates" into a link that links to the full list of repeating dates.


Rule to send out content of newly created forum-topic or comment

Using rules, you can send the URL of the updated content as per the solution provided by @mohit_rocks, but I was not able to find a solution to send the content / body (full / teaser) in the mail, using rules.

If you wish to send the content of the body too, you'll need to take help of the Notify module.

Steps to enable the send mails with the content of forum/topic in mail with the help of notify module:

Download and install notify module.
Under admin > people > permissions, set give the permission of access notify to the user role you wish the mails to go to. Note: The users of these roles need to enable the notification to enable receiving of the mails. You can keep this role limited to admin and let admins decide who receives the mail by following next step.
Go to admin > config > people >notify and enable notification for forum content type:  If you set time less than the time of your cron run, still the mail will be sent on cron run.
Go to user > uid > notify (replace uid with the the user id of the user). Admins can go to admin > people select edit against any user, and go to Notification settings tab and check the following options:   You can check the Title + Body + Fields under Detailed settings section to send the values in fields as well.
To check the list of users who will receive the mails, go to admin > config > people > notify > users:
That's it! Now the selected users should start receiving the notifications mails with content!

Note: If you have revisions enabled for the content type, and want to be notified when the content is edited, then check this feature request I've made at the module's issue queue. I've also created a patch for the same. If you have such requirement, then you can test the patch. If you post your findings on the issue, it'll be appreciated!


You can change the settings at admin/settings/apachesolr.

If your server has enough capacity, I'd run the cron more often and increase the limit.

Check also this thread and be sure to disable core search indexing.

Not sure though about indexing newer nodes first.


How to select nodes without taxonomy terms from a vocabulary in views?

yes i think so.. for me it works when i select 'has taxonomy term' and next option 'is empty'


Goto /admin/structure/block/ configure your superfish menu block

Scroll down to the bottom and locate "Show block on specific pages"

select this option " Only the listed pages "

and define the paths of the pages on which you want superfish menu to appear.


Yep! This is entirely possible and a very common use case.

If you check out the field.html.twig file in the classy base theme of core, it has the following contents:

{#
/**
 * @file
 * Theme override for a field.
 *
 * To override output, copy the "field.html.twig" from the templates directory
 * to your theme's directory and customize it, just like customizing other
 * Drupal templates such as page.html.twig or node.html.twig.
 *
 * Instead of overriding the theming for all fields, you can also just override
 * theming for a subset of fields using
 * @link themeable Theme hook suggestions. @endlink For example,
 * here are some theme hook suggestions that can be used for a field_foo field
 * on an article node type:
 * - field--node--field-foo--article.html.twig
 * - field--node--field-foo.html.twig
 * - field--node--article.html.twig
 * - field--field-foo.html.twig
 * - field--text-with-summary.html.twig
 * - field.html.twig
 *
 * Available variables:
 * - attributes: HTML attributes for the containing element.
 * - label_hidden: Whether to show the field label or not.
 * - title_attributes: HTML attributes for the title.
 * - label: The label for the field.
 * - multiple: TRUE if a field can contain multiple items.
 * - items: List of all the field items. Each item contains:
 *   - attributes: List of HTML attributes for each item.
 *   - content: The field item's content.
 * - entity_type: The entity type to which the field belongs.
 * - field_name: The name of the field.
 * - field_type: The type of the field.
 * - label_display: The display settings for the label.
 *
 *
 * @see template_preprocess_field()
 */
#}
{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
  ]
%}
{%
  set title_classes = [
    'field__label',
    label_display == 'visually_hidden' ? 'visually-hidden',
  ]
%}

{% if label_hidden %}
  {% if multiple %}

      {% for item in items %}

{{ item.content }}

      {% endfor %}

  {% else %}
    {% for item in items %}

{{ item.content }}

    {% endfor %}
  {% endif %}
{% else %}

{{ label }}

    {% if multiple %}

    {% endif %}
    {% for item in items %}

{{ item.content }}

    {% endfor %}
    {% if multiple %}

    {% endif %}

{% endif %}

Most themes extend classy as a base. If not, they extend stable by default. Both have a field.html.twig file in their theme folder. Every field in your site will render with this template by default, unless a more specific template is provided by creating a new file and giving it a specific theme name suggestions, which are mentioned in the comments of the file above.

If you copy this file to your theme, you can then override this markup for your theme.

If you enable twig debugging, it will inject template suggestion names into the source as you view the page. These will allow more granular control over field level markup and help figure out what filenames and their order of specificity are in order to override template output.

Let's say you have a field called Company. For this field, you want the label to be an H3. One of the possible template suggestions would be field--field-company.html.twig. If you create that file and place it in your theme, you can do:

{#
/**
 * @file
 * Theme override the Company field.
 *
 * Available variables:
 * - attributes: HTML attributes for the containing element.
 * - label_hidden: Whether to show the field label or not.
 * - title_attributes: HTML attributes for the title.
 * - label: The label for the field.
 * - multiple: TRUE if a field can contain multiple items.
 * - items: List of all the field items. Each item contains:
 *   - attributes: List of HTML attributes for each item.
 *   - content: The field item's content.
 * - entity_type: The entity type to which the field belongs.
 * - field_name: The name of the field.
 * - field_type: The type of the field.
 * - label_display: The display settings for the label.
 *
 *
 * @see template_preprocess_field()
 */
#}
{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
  ]
%}
{%
  set title_classes = [
    'field__label',
    label_display == 'visually_hidden' ? 'visually-hidden',
  ]
%}

{% if label_hidden %}
  {% if multiple %}

      {% for item in items %}

{{ item.content }}

      {% endfor %}

  {% else %}
    {% for item in items %}

{{ item.content }}

    {% endfor %}
  {% endif %}
{% else %}

{{ label }}

    {% if multiple %}

    {% endif %}
    {% for item in items %}

{{ item.content }}

    {% endfor %}
    {% if multiple %}

    {% endif %}

{% endif %}

Note where I changed the label div to an h3. The top part of the if statement is only if you set the label to Hidden in the Display settings of the content type.

Suppose you always want a label to display for Company, you can simplify the template further:

{#
/**
 * @file
 * Theme override the Company field.
 *
 * Available variables:
 * - attributes: HTML attributes for the containing element.
 * - label_hidden: Whether to show the field label or not.
 * - title_attributes: HTML attributes for the title.
 * - label: The label for the field.
 * - multiple: TRUE if a field can contain multiple items.
 * - items: List of all the field items. Each item contains:
 *   - attributes: List of HTML attributes for each item.
 *   - content: The field item's content.
 * - entity_type: The entity type to which the field belongs.
 * - field_name: The name of the field.
 * - field_type: The type of the field.
 * - label_display: The display settings for the label.
 *
 *
 * @see template_preprocess_field()
 */
#}
{%
  set classes = [
    'field',
    'field--name-' ~ field_name|clean_class,
    'field--type-' ~ field_type|clean_class,
    'field--label-' ~ label_display,
  ]
%}
{%
  set title_classes = [
    'field__label',
    label_display == 'visually_hidden' ? 'visually-hidden',
  ]
%}

{{ label }}

   {% if multiple %}

   {% endif %}
   {% for item in items %}

{{ item.content }}

   {% endfor %}
   {% if multiple %}

   {% endif %}

After clearing the site cache, Drupal should pick up on this new template file, and render any instance of the Company field with it, getting your new label markup. But note, now that you do this change, setting the Company label to hidden in the future will have no effect! We removed the logic - just to illustrate.

That's the nuts and bolts of whats going on and how you can adapt and theme field output, or nodes, taxonomy, user, paragraphs, views, etc.

If you have a lot of fields and this seems overwhelming right now, there is a module called Display Suite that places a lot of this into the admin UI on the field display settings form. If you are new to Drupal 8, twig, etc - Display Suite is a fine starting point because it will accomplish the same thing, just without much, if any, coding.

For Display Suite check the documentation here about fields and labels.

Furthermore, I recommend Drupalize.me's excellent series on theming in Drupal 8. It will help accelerate your knowledge of theming much faster.


If you are caching the whole page (which is off by default in D7) then BLOCK_NO_CACHE will not make a difference on a block. Because while the block is not cached, the page is.

I think what you may want is the esi api module it allows you to use ajax to render the blocks.


Resolved this by writing my own module implementing hook_views_pre_render and manually changing $view->result.


You will not be able to use a route, as /no-js would be its own route. Instead, you should use Url::fromUri. You should be able to use:

Url::fromUri('internal:/profile/publications/' . $user->id() . '/nojs');


Drush on windows 10 gives an error - Command pm-update needs a higher bootstrap level to run

My experience is that these kind of tools are more easier to install on a Linux based system (ports of this programs to Windows are always limited in their capabilities). Luckily, the Windows 10 Anniversary update includes "Ubuntu on Bash on Windows 10", which allows you to natively run terminal-based Linux applications and Bash commands in Windows. Using this feature you can simply follow the native tutorials/install instructions.

To install this Bash shell in Windows 10 (after installing the Anniversary Update), you have to enable the developer mode (go to Settings > Update and Security > For developers). Then in the start menu search for the application: "Turn Windows features on or off" and with this application enable the "Windows Subsystem for Linux (Beta)". A reboot of your computer will follow and after this search in the start menu for "Bash" and follow the instructions. Once completed, you can use the program "Bash on Ubuntu on Windows" to start up your Linux shell.

With apt-get you can install php5 (don't forget to use sudo here), from there you can follow the install instructions of Composer and/or Drush.


Here is a good tutorial to change all the user pages.  http://drupal.org/node/350634.   For E-Mail edit the $variable['form']['x']


How to disable panel cache for user menu?

Drupal has a lot of caching levels so you might need to "peel" each one off to know which level is caching the results. Since you're authenticated, it's not the page cache. And since you mentioned that you set the panel to "No Cache", then it's not the panel cache either.

You're probably facing the block cache here. You can either modify the block caching definition in code using hook_block_info_alter (see hook_block_info for the different caching levels), or use Block Cache Alter module to do that same thing via the admin interface.


form jquery events fired multiple times after using AJAX

Can we unbind the click event when click event happens and just add the click event again after we receive some responses from Ajax.

The idea is something like this:

jQuery('.node_form .form-radio').live('click', function(event) {
    jQuery(this).unbind('click');
    //make some ajax calls and if it returns something. We will bind the click event again.
});


Why doesn't the view read cookies on AJAX refreshment?

I figured out that an ajax view already has argument stored in drupalSettings.views.ajaxViews["views_dom_id:..."].view_args

So the view gets this argument and use it instead of default argument from cookie. So we need to change the value of argument as well as cookie.


I suppose this can be done, but it won't be easy. There will be quite some components and you will have to write some code. Disclaimer is that I have not tested anything of this code, but I hope this to be useful to you.

This example is based on the commerce_funds_withdraw_action() on line 932 of the Commerce Funds Withdraw Module, part of Commerce Funds.

Most important is this part, which performs the actual transfer using PayPal Mass Pay (Read the integration guide for details about PayPal business accounts and contacting customer support to enable the feature.):

$response = commerce_paypal_api_request($payment_method, $nvp);
if($response['ACK'] == 'Success') {
  $withdraw->status = 'Transfered';
  $amount_paypal = $withdraw->amount;
  $withdraw->amount = commerce_currency_decimal_to_amount($withdraw->amount, $withdraw->currency_code);
  commerce_funds_withdraw_save($withdraw);
  $amount = array(
    'amount' => $amount_paypal,
    'currency_code' => $withdraw->currency_code,
    'reference' => $withdraw->uid,
  );
  commerce_funds_debit(user_load($withdraw->uid), $amount);
  drupal_set_message(t('Money were successfully transferred to @user_email.', array('@user_email' => $user->mail)), 'status');
}

If we remove all commerce funds transaction tracking, we are left with:

$response = commerce_paypal_api_request($payment_method, $nvp);
if($response['ACK'] == 'Success') {

  // Deduct credits from the account here, or do it in Rules later.

  drupal_set_message(t('Money was successfully transferred'), 'status');
}

The actual communication with the API is handled by commerce_paypal_api_request(), a function of the Commerce PayPal module, which requires 2 parameters;

$payment_method: The payment method instance array associated with this API request.
$nvp: The set of name-value pairs describing the transaction to submit. (See MassPay API Using NVP of the API documentation.)

Since there is no offical payment method to use, we create a custom payment method option:

$payment_method = array(
  'settings' => array(
    // Fill these to match the data configured with PayPal
    'server' => '',
    'api_username' => '',
    'api_password' => '',
    'api_signature' => '',
    'log' => array(
      'request' => FALSE, // Log outgoing request TRUE/FALSE.
      'response' => FALSE, // Log response from PayPal TRUE/FALSE.
    ),
  ),
);

And the NVP:

$nvp = array(
  'METHOD' => 'MassPay',
  'EMAILSUBJECT' => 'Withdraw',
  'CURRENCYCODE' => $currency_code,
  'RECEIVERTYPE' => 'EmailAddress',
  'L_EMAIL0' => $receiver_email,
  'L_AMT0' =>  $amount,
);

Now for getting this all together in a custom module and a Rules actions:

Create a rules_paypal_deposit folder for your module, with the following files:

rules_paypal_deposit.info:

name = Rules PayPal Deposit
description = Deposit funds to a paypal account using rules.
core = 7.x
dependencies[] = rules
dependencies[] = commerce_paypal

rules_paypal_deposit.module:

<?php
/*
 * This function performs the actual transfer
 */
function rules_paypal_deposit_do_deposit($receiver_email, $amount, $currency_code) {
  $payment_method = array(
    'settings' => array(
      // Fill these to match the data configured with PayPal
      'server' => '',
      'api_username' => '',
      'api_password' => '',
      'api_signature' => '',
      'log' => array(
        'request' => FALSE, // Log outgoing request TRUE/FALSE.
        'response' => FALSE, // Log response from PayPal TRUE/FALSE.
      ),
    ),
  );

  $nvp = array(
    'METHOD' => 'MassPay',
    'EMAILSUBJECT' => 'Withdraw',
    'CURRENCYCODE' => $currency_code,
    'RECEIVERTYPE' => 'EmailAddress',
    'L_EMAIL0' => $receiver_email,
    'L_AMT0' =>  $amount,
  );

  $response = commerce_paypal_api_request($payment_method, $nvp);
  if($response['ACK'] == 'Success') {

    // Deduct credits from the account here, or do it in Rules later.

    drupal_set_message(t('Money was successfully transferred'), 'status');
  }
}

rules_paypal_deposit.rules.inc:

<?php
/**
 * Implement hook_rules_action_info()
 */
function rules_paypal_deposit_rules_action_info() {
  $actions = array(
    'rules_paypal_deposit_actions_deposit' => array(
      'label' => t('Transfer funds to a PayPal account'),
      'group' => t('Rules PayPal Deposit'),
      'parameter' => array(
        'receiver_email' => array(
          'type' => 'text',
          'label' => t('E-mail to transfer to.'),
        ),
        'amount' => array(
          'type' => 'decimal',
          'label' => t('Amount to transfer (format: 12.34)'),
        ),
        'currency_code' => array(
          'type' => 'text',
          'label' => t('3 Letter currency of the transfer, see the PayPal documentation', array('@url' => url('https://developer.paypal.com/docs/classic/mass-pay/integration-guide/currency_codes/'))),
        ),
      ),
    ),
  );
  return $actions;
}

/**
 * The action for rules_paypal_deposit_actions_deposit
 */
function rules_paypal_deposit_actions_deposit($receiver_email, $amount, $currency_code) {
  rules_paypal_deposit_do_deposit($receiver_email, $amount, $currency_code)
}

You can choose to add the PayPal API settings server, api_username, api_password and api_signature as Rules parameters as well and add the parameters to rules_paypal_deposit_actions_deposit() and rules_paypal_deposit_do_deposit(). Or just define them in the code.

I really hope this is of use to you. It was written in a bit of spare time because I thought it was a nice puzzle. Do not get mad if it doesn't work ;)

Obviously this needs proper testing on the PayPal API sandbox first.


Grouping Taxonomy terms by their parents

Hope I'm not too late, but maybe others will find this helpful...

If I'm understanding the question correctly, this is what you do:

Add two taxonomy name fields to your view display—one excluded from display, the other not.
Add a relationship of "Taxonomy term: Parent term" (under Advanced) and then attach it to the field excluded from display.
Under in the view's format settings, group by the excluded field with the relationship.

Note: If the parent terms are being printed twice (not just as group headers), make sure you excluded the field with the relationship and check "Require this relationship" in the relationship settings.

I don't know if this works with tertiary+ levels. Probably not. In which case there's most likely a module.


Strict URL alias checking with optional 404 redirect

You can use the url_inbound_alter hook to verify if the internal path of the request matches the used url alias. If not, trigger a 404.

function YOURMODULE_url_inbound_alter(&$path, $original_path, $path_language)
{
    if ($path === $original_path) {
        // path is same as url alias - don't do anything
        return false;
    }

    $alias = drupal_get_path_alias($original_path);
    if ($alias && $alias === $original_path) {
        // alias is same as url alias - don't do anything
        return false;
    }

    drupal_not_found();
    drupal_exit();
}

I've tested on some projects which are using the most common contrib modules (Pathauto, Globalredirect, Views, Sitemapxml, Wysisywyg, ...), and I don't have the problem. Url alias verification is strict and returns 404 for non existing aliases. But I'm able to reproduce it with custom menu callbacks (custom code or views).


Drupal 7 Services -- hook_services_request_postprocess_alter() does not identify the requested resource

if you take a look to $args array, you can find your node type, for example I have a content type "video", my $args are like this:

Array
(
    [0] => 2
    [1] => *
    [2] => Array
        (
            [type] => video
            [uid] => 92
        )

    [3] => 2
)

Then $args[2] has the content type (because I set it like a parameter in my resource:
http://site.local/api/v1/node?parameters[type]=video&parameters[uid]=92&pagesize=2&page=2


Token are not working in my content type fields (they show as they are)

You can try using the Token Filter module.

I'm not sure if it will do exactly what you want, but it is a way to have Tokens rendered in your node, if at least in the body text of the node.


Display data basing on the group permission

user_access is for core permissions, I.e. those added through hook_permission. For organic groups’ own permissions hook, you need to use the complementary og_user_access:, eg:

if (og_user_access($group_type, $gid, 'rulesprm')) {
  ...
}


MSSQL Incompatibility with Organic Group Views Filter Handlers

I fixed it by changing Line 13 to:

->groupBy('r.name')
->groupBy('r.rid')
->groupBy('r.gid')
->groupBy('r.group_type')
->groupBy('r.group_bundle')


Printing printer friendly version of nodes in bulk

While the print module doesn't have much of an API, you can look at print_controller_html() to see how it renders printed pages:

$query = $_GET;
unset($query['q']);

$html = theme('print', array('node' => $node, 'query' => $query, 'format' => $link['format']));
drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
drupal_send_headers();
print $html;

For your purposes, you can changes a few arguments to the theme function and wrap it around a loop of nodes you wish to print. Something like

$html = '';
foreach($nodes as $node) {
  $html .= theme('print', array('node' => $node, 'query' => $_GET, 'format' => 'html'));
}

The theme function makes use of a template that you can override in case you want alter the HTML printed in a significant way.


Views show table of titles of last nodes for each content type

Use a View and code to embed that View for each content type.

To get the same View as what I created, import the View I've pasted here: http://pastebin.com/2xQx7BPs

Instead of having anything hardcoded, you can achieve this as follows:

Quick and Dirty

Enable the "PHP filter" module.
Create a Basic Page.
Use "PHP code" as the Text format in a Basic Page with this Body

Paste this:

<?php
    $content_types = node_type_get_names(); // get all content types
    $ct_machine_names = array_keys($content_types); // we just need machine names
    foreach ($ct_machine_names as $ct_name){ // loop through, adding them as an argument to the View
      echo views_embed_view('latest_node_by_type', 'block', $ct_name);
    }
?>

Proper Way

There are a few ways to achieve this instead of using the "PHP filter". Using a custom block in your own module isn't difficult. My favorite resource that explains this is located here:
http://kahthong.com/2013/06/create-your-own-custom-drupal-block-programmatically

Follow the directions, and replace the last block with something like this:

<?php
    function _YOUR_MODULE_BLOCK_ABC_CONTENT() {
      $output = '';
      $content_types = node_type_get_names(); // get all content types
      $ct_machine_names = array_keys($content_types); // we just need machine names
      foreach ($ct_machine_names as $ct_name){ // loop through, adding them as an argument to the View
        $output .= views_embed_view('latest_node_by_type', 'block', $ct_name) . '<br/>';
      }
      return $output;
    }
?>


How to shadow a core function used in two different tests files?

Wrap it in a !function_exists()

See core/tests/Drupal/Tests/Core/Render/Element/MachineNameTest.php for example:

<?php

namespace Drupal\Core\Render\Element;

if (!function_exists('t')) {

  function t($string, array $args = []) {
    return strtr($string, $args);
  }

}

That said, t() as a specific example is deprecated and should not be used in classes, use the StringTranslationTrait/service instead and you can actually inject it.


Drupal module to hide part of body field initially

You can do this using a jQuery plugin. See this drupal/stackoverflow response.

The jquery project page for readmore. Other jquery modules can do this as well such as Expander. Expander looks newer and more supported (off hand).

You could just add this file to your site's theme folder and theme info file. You probably want to not use Teasers anywhere and just rely on the JS readmore links for a CSS selector targeting your node body content. Your theme may have a more specific selector.


Does it make sense to develop a fantasy sports management system by creating or extending entities?

Drupal 6 has a module called League Site that might be useful to have a look at... I don't think it has been ported to 7 yet but it has an awful lot of functionality for league sports right out of the box.


multistep module to create multistep registration form

From my experience, CTools works great for multistep forms using the CTools form wizard. I've already used it successfully but never tried with user registration.

You can follow a nice tutorial for that case here:
Multistep registration form in Drupal 6

Another tutorial:
Intro to Drupal 6 Multistep Form Domination Using Chaos Tools

Happy coding :)