Drupal 7.x Development - Naming conventions

I'm a bit surprised that you haven't found anything on the internet that could answer your questions. Here is an article about coding standards for Drupal.

Anyway, here are several things I always do with naming, functions and directories (that doesn't mean it's the best conventions):

The only directory you should work in is ./sites (please never ever edit something in the other directories).
The contribute modules you download should be placed in ./sites/all/modules/contrib
The custom modules that you develop yourself should be placed in ./sites/all/modules/custom
When you create a custom module, chose a simple and suitable name of it, preceded by the name of your project (better), for example myproject_blog.
The .module and .info files should have the same name as your module's, for example myproject_blog.module and myproject_blog.info. It will automatically make the relationship between them.
All the functions that appear in your .module file should be named by your module's name, for example myproject_blog_revision_publish().
If your custom module needs a table in your database, the name of your module has to show up somewhere, for example $schema['myproject_blog']. If you need more than one table, keep the prefix and add some explicit suffix.
Idem for the custom themes in ./sites/all/themes.

If I forgot something, just ask ;)


Sales Tax Exemption for an Authorized User?

After looking at the code I figured out that this module isn't about conditions to provide exemptions, it's about conditions to apply the tax. So yes, to make it work you have to check all of the roles for which you want the tax applied while leaving out the role(s) for which tax should not be applied. It might also be necessary to apply a patch and add a setting.


How to add a "read more" link on User profile teaser display?

This you can do using Views and providing the code for Link on User page, follow following steps.

1. Creating the Complete User profile at default Drupal account page:

1.1 Add the all the fields on the Default user-profile what you want on fullDisplay(Admin/Configuration/Account setting/Manage field). So any user when creates a account, he will have all section to fill-out. For example My Full user-profile has the following fields.

Name
Picture
Bio

2. Create the teaserDisplay

2.1 Hide the fields which you do not want on the teaserDisplay. So, on the User-profile setting page(Admin/Configuration/Account setting/Manage Display), now hide what you do not want to show on Teaser Display. Now for my setting I want to Hide Bio. So I will just hide this field at Manage Display.

So current user-profile field settings are:

Name
Picture
Bio - Hidden

Now, till this stage, we set our Drupal's default account page as teaserDisplay but simultaneously we created those fields which we want on fullDisplay, hence we kept hidden but we will display all those hidden fields using Views.

3. Create the Views-fullDisplay

3.1 Create a new view page, Select USER under Views setting. Under pager, choose 1 item.
3.2 Now on the setting page, add all following setting as shown in teh following image. So here we are accessing that Bio field which we hide on User profile page.

Contextual filter setting: Under contextual setting select User: User ID and under that select Display all results for the specified field.
Path: Now as shown in the view set the path /user/%/view-page. I have kept last part here, /view-page as I was just trying previously, you can change to full-profile, but you have to change that at all places.

4. Setting the Link on the teaserDisplay page (so we can re-directed to fullDisplay)

To provide the link, the link should take the User-Id from the URL and can able to pass that User-Id in views URL, so Views contextual filter can provide the result of that User, from where we have redirected. Hence, to solve this I raise separate question and you can follow answer as shown below. I am not providing answer as you have to just copy from there.

@ShawnConn has provided answer for how to add link on user-page. Full Credit goes to @ShawnConn for this answer.

How to get current path for user profile field?

5. Output Image:

teaserDisplay- Default User Page

Full Display - Views with bio field

Now, this way you can add as many as field you want, just hide them so they does not display on teaser display and show in views so they display on fullDisplay page.


Access to only few fields of a content type for specific user

Field Permissions will let you assign different permissions to a field based on role.

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


$fields is undefined - custom theme creation

The $fields variable will be available for theming only if you have selected to display fields  instead of content, check under format section of view.

Secondly, the $fields variable is not available if your template file is views-view.tpl.php, you have to use views-view-field.tpl.php or if you want theme only a specific field, you can use views-view-field--fieldname.tpl. php.


Advanced Aggregation: Should I disable core's aggregation?

Should I disable core's aggregation?

No; AdvAgg uses the core aggregation setting as part of its own on/off switch. If core aggregation is disabled, AdvAgg aggregation is implicitly disabled.

In fact if you do disable it, you get this helpful error in the status report:

You can tell whether or not AdvAgg is producing your files from the path - it will contain /advagg_(css|js)/.


Instead of using exposed filters for this, I think it will be easier to make separate views displays with overridden filters. Then either use quicktabs to display the different filter options, or make each one a page display with a path and output the links to the filter displays in the headers.


I would suggest, you use hook_form_alter() and then check for laptop users. If laptop users are on form then make #required false for these two fields.

Example:

$form['title']['#required'] = FALSE;

Note: FYI Avoid using unset() in such type of scenario either set the #access property or #required property to FALSE. This keeps them in the form build tree, which avoids problems if other modules try to access or alter that information.


How can I render a token within a token via rules mail action?

Using tokens within the body of a node, combined with using [node:body] in a Rules Action, will only result in the token being included as is (without rendering). However, based on what you're trying to do, you may want to have a look at an entirely different approach to achieve your goal ...

Enable the Forena module (disclosure: I'm a co-maintainer), and have a look at Active Users Email (using FRX syntax), which is one of the samples included in the module (which can be used to eMail a template message body to all registered users).

These are the parts in this FRX file that are relevant to the question here:

The datablock drupal/active_users, which is (just) an SQL statement that looks like so:

--ACCESS=access administration pages

SELECT uid, name, mail, login, status

FROM {users}

WHERE status=1 order by name
The frx:foreach="*", which will cause an iteration for each row included in the results of the data block, for everything inside that div (related to the datablock).
The div with class="email-body", which starts with Dear {name}, and which includes a replacement token indicated with {name}.
The line with <frx:doc type="email" />, to enable document format "Send eMail".

After you enabled the module, and visit the relative path at /reports/drupaladmin.sample_active_users_letter, this is what will happen:

Run the SQL query (as contained in the datablock).
Iterate over each of the results returned by the datablock (SQL statement).
For each iteration resolve all the tokens (i.e. as within that Dear {name}).
Display how the eMail will actually look like (for each iteration).
Add link (upper right) titled "eMail". If you actually click that "eMail" link, a confirmation screen will be shown with these details:

number of eMails that will be eMailed (= number of rows in the datablock).
radio button to either send an eMail, or actually send all eMails.

With the above in mind, this is what you'd need to get it to work for your case:

Clone the delivered sample, and tune it as detailed below.
Adapt the datablock to retrieve the desired data (columns), similar to what your view is doing. Or create a new one that fits your needs and use that one instead. Make sure to include the data related to your field_ef_email and field_ef_first_name.
Adapt the From, To and Subject to fit your needs.
Use whatever tokens you need, anywhere in the Body of your eMail. E.g. to replace that Dear {name}. If you need more, or other, data, just add an appropriate name to your datablock (as an extra column). As a sample, here is part of an FRX file I created to transform webform submissions into some kind of followup-eMail to each of those who submitted the form:

Hello,

thank you for using our form (with node id = {node}) to submit your feedback (with submission id = {submission}). You're now confirmed via the eMail Id you entered (= {fieldvalue}) to receive eMails from us.

We'll get back to you shortly for an additional followup eMail.


Drupal 8 migrate language: switch all nodes to the default lang

You need to change your language selection criteria in this admin setting:

Admin -> Configuration -> Regional & Language -> Language / Detection and Selection Tab

You can turn off or configure the URL settings as you want.  With no standard detection, the default language should be shown.

You probably want to turn on the administration language detection option.  This allows admin users to select their preferred admin language.


Getting a list of altered fields when saving a node

The simple way of recalculating and update field without any effect of other field is hook_entity_update or code like display here.

<?php
$entity_instance = entity_load('entity_name', array($id));
$entity_instance->field_myfield[LANGUAGE_NONE][0]['value']= 5;
$entity_instance->save();
?>


Drupal extra subdomains for some special nodes

Have you looked at the Domain Access module?

  The Domain Access project is a suite of modules that provide tools for
  running a group of affiliated sites from one Drupal installation and a
  single shared database. The module allows you to share users, content,
  and configurations across a group of sites such as:

  example.com
  one.example.com
  two.example.com
  my.example.com
  thisexample.com <-- can use any domain string
  example.com:3000 <-- treats non-standard ports as unique

  By default, these sites share all tables in your Drupal installation.
  The Domain Prefix module (for Drupal 6) allows for selective, dynamic
  table prefixing for advanced users.

Basically you can assign a Node across any number of configured subdomains you've made drupal aware of.


Fields on images, displayed on edit page

I did similar with creating photo albums connected to a content type using the field_collection module. This way you can easily customise whats added very quickly as you are essentially creating a new type of entity (think of it as having an article entity and attaching a new photograph entity which has its own image, caption and credit fields).


Is there any way of removing (or unflagging) all of a user's flags?

You have to find out the event for expiring the roles, there you can unset the flag programmatically. However with other approach you can also add a check the role of user you are sending email to.

Here goes the steps:

Install rules_conditional module. This module allows to add
extra conditions inside the rules action.
Please check the screen shots.

Configurations as in following screenshot.

Remember to have the nesting structure as in screenshot.


How to count the number of post by author in D7?

The result of db_query() should now be iterated over directly, db_fetch_object() isn't part of Drupal 7.

You could also make use of the fetchField() method to get the result of your COUNT query:

$uid = $node->uid;
$args = array(':uid' => $uid);
$count = db_query('SELECT COUNT(nid) FROM {node} WHERE uid = :uid', $args)->fetchField();

print "
$node->name has submitted $count source code / articles.
";

The above example uses the preferred method of passing arguments to a database query, it's safer than including them directly in the query string.

If you did want to loop over the results (for a query with more than one row/field) you'd do it like this:

$result = db_query('SELECT * FROM {node}');
foreach ($result as $row) {
  $nid = $row->nid;
}


Hide a list of blocks from Panelizer in-place editor (IPE)

One of the options is to extend the IPE controller to remove the unwanted blocks from display. Here are the code changes:

Route subscriber:

  mymodule.route_subscriber:
    class: Drupal\mymodule\Routing\RouteSubscriber
    tags:
      - { name: 'event_subscriber' }

Update the IPE controller:

<?php

namespace Drupal\mymodule\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Drupal\mymodule\Controller\MymoduleIPEPageController;
use Symfony\Component\Routing\RouteCollection;

/**
 * Subscriber to update IPE controller.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    /* \Symfony\Component\Routing\Route $route */
    if ($route = $collection->get('panels_ipe.block_content_types')) {
      $route->setDefault('_controller', MymoduleIPEPageController::class . '::getBlockContentTypes');
    }
  }

}

Controller:

<?php

namespace Drupal\mymodule\Controller;

use Drupal\panels_ipe\Controller\PanelsIPEPageController;

/**
 * Extends IPE controller for site specific customization.
 */
class MymoduleIPEPageController extends PanelsIPEPageController {

 /**
   * {@inheritdoc}
   */
  public function getBlockContentTypesData($panels_storage_type, $panels_storage_id) {
    // Assemble our relevant data.
    $types = $this->entityTypeManager()
      ->getStorage('block_content_type')
      ->loadMultiple();
    $data = [];
    $blocks_blacklist = $this->getHiddenBlockList();
    /** @var \Drupal\block_content\BlockContentTypeInterface $definition */
    foreach ($types as $id => $definition) {
      if (in_array($id, $blocks_blacklist)) {
        continue;
      }
      $data[] = [
        'id' => $definition->id(),
        'revision' => $definition->shouldCreateNewRevision(),
        'label' => $definition->label(),
        'description' => $definition->getDescription(),
      ];
    }

    return $data;
  }

 /**
   * List of blocks not available to add via PIE.
   *
   * @return array
   *   An array of block IDs.
   */
  protected function getHiddenBlockList() {
    // Remove UUID and title fields from the list.
    return [
      'entity_field:node:uuid',
      'entity_field:node:title',
    ];
  }

}


Why the label of "subject' field in comment-form not be translated and how can I do the translation in a better way?

I finally found a solution to enforce translation of 'Subject' label in hook_form_alter which can make code more clear:

function mymodule_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {

  if($form_id == 'comment_comment_forum_form') {
    $form['subject']['widget'][0]['value']['#title'] = t('Subject');

  }

}


You can use the plugin manager to fetch a plugin. You only need to find the correct plugin manager service:

$type = \Drupal::service('plugin.manager.service'); // Fill your own plugin manager service.
$plugin_definition = $type->getDefinition('plugin_id'); // Fill needed plugin id.


Yes it is possible, but that's a quite broad question. And it depends a little bit what exactly want to achieve and where.

Basically when you have the node object of page B you also have the field value of the reference field, which will be a node ID. The node ID of page A. You can take this node ID to load node A – node_load($nid).

Then you have the node object of node A. And from there you'll get the field value of the file field which most likely is a file ID. This file ID now can be taken to build the path to the file – file_load($fid).


How to create a custom node template in drupal8 rendering a view within a node page?

Here is how you can add the view, use a block view.

Then go to Blocks, and place a block in content.

Select your view block

In configure click on pages, then type the url of the pages you want it to show. So you put your tags url here. Use the * so it shows in all of them.

Just noticed I missed a / at the start, so it should be /taxonomy/term/*


Prepopulate node-add form with search terms?

I don't know of a module that solves exactly the problem you're describing out of the box, but you might be able to come close with Entity Reference View Widget and/or Node Reference URL Widget.


Ways to specify different versions of nodes?

In this case, go with taxonomy terms. That way you can organize content around a taxonomy term, one for each version. You can even tag content that is applicable to multiple versions just by selecting taxonomy terms.

Then, you could create a view that says "give me all of the content related to version X" and you'd be able to see those. Plus if you ever wanted to do more than "just nodes" e.g. other entities or bundle types, you can just add the field to those bundles and go on your merry way. Plus, since taxonomy terms are entities, you can add fields and content to those terms and build pages that surround those terms.


Development to staging to production process

This is a good start, drupal 8 has inbuilt configuration import/export functionality: https://www.drupal.org/docs/8/configuration-management/managing-your-sites-configuration

You could automate/speed up the process abit by adding the exported configs to your git repository and using drush to create them

But its especially: do an export on your dev which will generate config files all zipped up. Then do an import on production which allows you to review the changes before actioning them


How to hide empty ratings using Rate module?

How would people rate the item the very first time if the widget is hidden?

Look in Rate module's template folder for rate-template-fivestar.tpl.php. Copy it over into your theme's template folder then make changes.

I think the variable $count might be available (Number of votes), so you could print out a message if $count is 0 to say that the item has not yet been rated.


How to get distinct nodes for a view and its attachments?

You can achieve you requirement by following below steps.

Under view Advance setting, click on Query settings.
Now select Distinct checkbox.


How to enable revisioning for user photo (user/profile field)?

The User Revision module would probably be your best bet

Add revision support to users and fields like there is for nodes.
For the moment all field from {users} have revisions, except for password

The picture property is contained in the users table so this module should do exactly what you're looking for.
The issue of a UI for accepting or declining a photo should go in another question otherwise this one will become too localised.


Assuming that you use proper fields that keep the relevant information (either in nodes or custom entities), it is possible that this can be achieved with Views exposed filters (the slider will require some client-side programming). For more search features, you can also use the Search API without needing to get into the complications of Apache Solr.


How do I include special characters in a path alias?

The ampersand (&) is a reserved character in URLs because it is usually input as part of the query string.  Some more info.
Most special characters can be used in URLs with the settings you described in your question, but & is an exception.  Either just live with %26 as the encoding or rewrite the title to not use the & symbol, which is reserved.
This is not a Pauthauto problem; it's a URL problem.


There is Simplenews module

  Simplenews publishes and sends newsletters to lists of subscribers.
  Both anonymous and authenticated users can opt-in to different mailing
  lists. HTML email can be sent by adding Mime Mail module.

Read documentation


Any imageslider for my homepage. am using drupal 5.21 on my website

You can try using Jquery slideshow module which support Drupal 5.x

Project page says

  This module creates a javascript slideshow using the Cycle plugin for
  Jquery. The slideshow is created from multiple imagefields of a node.
  There are settings to change the type and speed of transitions.
  Settings also exist to use Imagecache presets for the images.


Views to display nodes based on ACL permission

According to: https://www.drupal.org/node/1255426, Drupal 7 does not have db_result function. You have to replace it with db_query().

Code which worked in my special case:

<?php
global $user;
$query = db_query("SELECT GROUP_CONCAT(CAST(an.nid AS CHAR) SEPARATOR ',') FROM {acl_user} au INNER JOIN {acl_node} an ON au.acl_id = an.acl_id WHERE an.grant_view = 1 AND au.uid = :uid", array(':uid' => $user->uid));
$result = $query->fetchObject();
return reset($result);
?>


How do I recreate the system.site configuration element?

I solved it with Drush.

To get around the UUID mismatch I uncommented the UUID field in system.site.yml and ran drush cim. After that I specifically set the UUID by running drush cset "system.site" uuid "my site id".


Why is my rule that reacts on event "After updating an existing user account" firing twice?

It sounds like some other module code is calling a user_save on hook_user_update triggering the rules event a second time.


Find out which fields to modify on drupal view for a module

I think you can do what you need with hook_views_pre_render.

Here is what you can do to find out what the data you need to manipulate looks like:

Install & enable the devel module - https://drupal.org/project/devel
Create a custom module (if you haven't already)
Add a function based on HOOK_views_pre_render(&$view)
In your function, use the dpm function like so: dpm($view);
Reload the page with the view you want to alter
Explore the data rendered through Krumo which is provided by devel

So, ultimately, your function will start something like this:

function your_module_views_pre_render(&$view) {

  if (($view->name == 'viewname') && ($view->current_display == 'displayname')) {

    dpm($view);


How can I clone all field values when creating a node translation (entity_translation) programmatically?

I ended up doing it manually via code:

function _populate_translation_values($node, $targetLanguage) {
  $fields = field_info_instances('node', $node->type);
  foreach($fields as $fieldName=>$fieldInstance) {
    $fieldInfo = field_info_field($fieldName);

    // only process translatable fields
    if (!$fieldInfo['translatable']) continue;

    // ignore fields which are complicated to copy - could be fixed in the future
    if (in_array($fieldInfo['type'], array('field_collection'))) continue;

    // skip fields which already have a value in the target language
    if (isset($node->{$fieldName}[$targetLanguage])) continue;

    // skip fields which don't have a value in the source language
    if (!isset($node->{$fieldName}[$node->language])) continue;

    // copy value
    $node->{$fieldName}[$targetLanguage] = $node->{$fieldName}[$node->language];
  }
}


Taxonomy hierarchy via separate dropdowns

You probably won't be able to do that without some custom code.

An existing module for the purpose is Simple hierarchical select:

  Simple hierarchical select defines a new form widget for taxonomy
  fields to select a term by "browsing" through the vocabularies
  hierarchy. The widget is available in node forms and as Views exposed
  filter.

https://www.drupal.org/project/shs

There is also the more full featured module Hierarchical select


Requiring the existence of a Drupal installation for all of your other non-Drupal PHP projects isn't something I've come across before...but you can bootstrap Drupal to make the watchdog() function available like so:

define('DRUPAL_ROOT', '/path/to/drupal/installation');
include_once(DRUPAL_ROOT . '/includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

watchdog('my_module', 'A message');


I use workbench, which accomplishes the same thing as workflow.  There is a module in the workbench collection called Workbench access that I use to send content to specific editors in the workflow.  I use it for my school newspaper so that writers moderate content to the editors of their specific section (i.e. news, sports, arts, lifestyle, etc.) then the Editors send the content to me for final approval and publication on the site. Hope this helps!


How to show Forms in nodes stored in the node tables

What do you mean "generate form on the fly"? As in: the form for page "page/form" doesn't exist in a canonical state but is generated based on variables such as date/url/taxonomy? Or is it just the default values for the form etc?

In anyway: the options to have a form on a page are:

Hardcode HTML into the node content, e.g. <form><input> etc
Use hook_menu to create the page and use the form API
Use hook_menu to create the page and use the straight HTML
Use hook_nodeapi to add a form to the content with the Form API
Use hook_nodeapi to add a form to the content using HTML
Use a module such as webforms to add the forms

I would suggest either 2 or 4. When you say that hook_menu generates these plages "on teh fly": that's not true. hook_menu is only run on cache clear, and assuming you're using caching then the generation of forms isn't going to make much difference to your server. This may be a case where you're sweating about optimisation unnecessarily.

Using Form API gives you a load of tools that you'd otherwise have to handle yourself - validation, submission, sanitising, standardising, etc.


Drupal Rest Service - Create node problem

Yes.. finally I got solution for my problem. Here is the solution.

In JSON format, Here is the correct way to handle LIST type fields

"field_select_options":{"und":["4"]}

(Initially I tried "field_select_options":{"und":[{"value":"4"}]} which results error in response.)

Thanks, I got the solution from https://drupal.org/node/1971484


Cannot delete / re-install sharethis module

I had the same problem previously, turns out I had copied the module inside itself.
Duplicating modules inside modules directory might give this error.


How to organize webforms on (admin/content/webform) into groups

I solved my own question.

Ended up creating a new Administration View of type content for only webforms. I then added the field 'Content: Term Group' which I added to the Webform Content type which is a term reference. I should mention I already created a new Taxonomy Vocabulary and gave that vocabulary three children taxonomy terms. From then it was as simple as noticing that 'Term reference' showed up when I hit Edit on a specific Webform so I can select one of the taxonomies. Then I changed the Format Setting 'Grouping field Nr.1' to 'Term Group' and thats it! Now my custom link (/admin/content/webform-groups) page shows all the webforms separated into separate boxes with their respective Term ID name above.


Adding an img inline with the content only on a specific page

Have you tried creating a block with your context, restricting the block to that one page, and then assigning the block to the correct region?

Your regions will depend on your theme.


How to delete files when the node that displayed them is deleted?

It's a revisions thing. I guess it makes sense. If you have revisions enabled for that content type, it keeps all your old files on the server (associated with old revisions), so replacing a file definitely is harder. If you try to remove it and add it again to the node, the name/link is updated, as I mentioned in my question. Since a file with that name is kept on the server and there is a name duplication, it adds those "_0", "_1" etc suffixes to future uploaded versions of that file's name.

I understand why this is happening though, since the whole point of revisioning is being able to revert to any past version of the page.

The work-around is that you can actually delete the old revision from the 'Revision' or 'Moderate' tab (if using Workbench Moderation) that contained the file you're trying to replace. Then upload it again, and the name should then match without you having to go back and edit any links pointing to that file.

Hope that makes sense and that it helps somebody else too!


How to display content for specific user

Add an explicit relationship to the user, and mark it as required. After that you will be able to add a new filter criterion to your view: User: Current.


Pseudo-fields and custom entity properties from additional schema

You may have to override the form submit handler, or at a minimum add you're own submit handler in addition to the default. As long as the submit handler starts with an entity passed through the $form_state, you could add your own handler to fire before the final handler that saves the entity and set your properties there.

While I don't have a ton of experience working with entities and hook_entity_load etc, you may get more milage from extending and overriding the default entity controller for product and overriding the load, save, and delete methods.


Views Contextual Filter by Day and Night

your approach is correct.

You can do one thing..Just create a view and contextual filter in view for radio field.
use hook_views_pre_view() hook to add arguments.

function MODULE_NAME_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'myview' && $display_id == 'page_1') {
    $current_time = date('H'); //24hrs format
    if ($current_time >= 8 && $current_time <= 20) {
      $args[] = "value of day radio button";
    }
    else {
      $args[] = "value of night radio button";
    }
  }
}

Hope this will help


How do I check if a block region is empty?

An update on this. I used the solution at https://drupal.stackexchange.com/a/73685/56728 as follows

  module_load_include('inc', 'block', 'block.admin');
  global $theme_key;
  $blocks = block_admin_display_prepare_blocks($theme_key);
  //test for a named block's (here the help block) visibility
  foreach($blocks as $block){
    if($block['delta'] == 'help' && $block['region'] != -1){
      sdpm($block['delta']. " is visible!");
    }
  }

This detects whether the block is visible or not, but does not quite do what I'm after which is to test for the visibility of a given block on the current "page" for the current user. That to me sounds like what block_list() does, but I'm stumped by block_list() as I mentioned above. My "solution" also very likely not the most elegant way of doing things so any help from experts out there would be greatly appreciated. Nat


Services 3.0 Json string reveived with underscores

http://php.net/manual/en/language.variables.external.php

When PHP receives POST/GET it replaces dots in keys with an underscore. I would look at the app receiving the data and see if you can work around it there.


In case you don't find a better way (doesn't look like there's an existing Drush command), here's a pretty simple solution cobbled together from various functions in the module:

$solr = apachesolr_get_solr();
$nids = array(1, 2, 3, 4, ...);
foreach ($nids as $nid) {
  $solr->deleteById(apachesolr_document_id($nid));
  db_update('apachesolr_search_node')
    ->condition('nid', $nid)
    ->fields(array('changed' => REQUEST_TIME, 'status' => 1))
    ->execute();
}
apachesolr_index_set_last_updated(REQUEST_TIME);

Untested, use with caution!


You can change the title label by editing the node type settings by going to Admin > Content Types > (type) > Edit. No code needed, and this can be exported to configuration.

I’m not even sure what your code is trying to do, but you don’t need it.


Custom url is not working with drealty listing

Using the url() function should give you what you need:

<a href="<?php print url("drealty_listing/$id"); ?>"><?php print t('More Detail'); ?>

The url will be converted automatically to the alias.


You can enable your installed modules here.

/admin/modules

and your theme here

/admin/appearance

You can double check to make sure the modules & theme are really there by navigating to your site modules & themes folder.

/sites/all/modules
/sites/all/themes


How do I print line breaks and HTML in a watchdog message?

However, this gives me a value for Message that doesn't have any line breaks and ignores my HTML
 and \n

As well it should :)

You've wrapped the HTML message in a
 tag, whose job is simply to preserve everything within as literal text, so that the browser won't interpret it as HTML. To fix, just remove the
 tags. If there's a possibility the email content could have been user-submitted, run it through filter_xss() first with an appropriate list of permitted tags, to avoid pain when you view the log message.

At the same time, \n isn't an escape char in HTML, so that's treated literally and rendered as text. It's an escape char in PHP, but it won't affect the outcome here as browsers collapse multiple whitespace chars into a single space anyway.

You could use PHP's nl2br to convert \n to
 automatically if the message content was dynamic, but since you're using a literal string, you might as well just be explicit and use
 instead of \n when you want a line break.

This is a basic working example:

$message = [
  'subject' => 'test subject',
  'body' => ['
some content
On a new line
'],
];

$allowed_tags = array('div', 'a', 'table', 'br', 'etc...');
$output = '!subject
The following email was not sent:
Subject:
!subject
Body:
!body';
$args = array('!subject' => filter_xss($message['subject'], $allowed_tags), '!body' => filter_xss($message['body'][0], $allowed_tags));
watchdog('MYMODULE', $output, $args, WATCHDOG_ALERT);

It's worth noting that the list view of the watchdog messages strips out HTML, so without the spaces after the first !subject and not sent:, some of the message will run together and make it harder to read at a glance.


Show Comment Form on its own Page or Popup

You can accomplish this using an extra node template for the page where the comment form is displayed:

In your theme file create an extra template suggestion for the comment form:

function HOOK_theme_suggestions_node_alter(array &$suggestions, array $variables) {
    $route_name = \Drupal::service('current_route_match')->getRouteName();

    if($route_name === 'comment.reply') {
        $suggestions[] = 'node__commentform';
    }
}

Create an extra node template node--commentform.html.twig, and remove just about everything. You probably want to leave the node title, but otherwise there's nothing you need there:

  {{ title_prefix }}
  {% if not page %}

      {{ label }}

  {% endif %}
  {{ title_suffix }}

The comment form is rendered outside this template, so you don't need any of it.


Make drupal cck field behave as "an add more button"?

This functionality is not available out of the box. But it's something people have been asking for (repeatedly) since at least D6 CCK 2:

Enable 'add more' button for non-unlimited fields.
Provide "Add more values" button for fields (and multigroups) with fixed number of multiple values
'Number of repeats' uses 'Add more' button
"Number of Values to Display" option for CCK fields

User goron has developed a contrib module for Drupal 7 called Multivalue Settings.

But be aware - from the module description page:

  Warning: this module is still very buggy. Actually, it only works in
  very few use cases. I suggest to only attempt using it with core
  fields (not fields from contrib modules). Even this may not work.

And it hasn't been updated in over a year.

Screenshot of Multivalue Settings functionality:


I s there a way I can show node teasers but don't allow access to full content?

To prevent users from access the node you can disable the "View published Content" permission but that will disable it for all node types. If you like to disable it just for one node type you can checkout the content_access module.

You can use a view of content to display the teasers.

In the format section use the format "Unformatted list" and choose your content display Teaser.

If you use a page for the view, you should also check the page access in the page settings section of the view.

I'm not sure if you need the following (It depends on how you prevent the node access):

In the advanced section under query settings you can disable sql-rewriting. This allows you to disable the node_access check. But take attention to this:

"Disabling SQL rewriting will omit all query tags, i. e. disable node access checks as well as override hook_query_alter() implementations in other modules."


Why return AccessResult::allowed() ends up with "Access denied"?

Although I've checked for other modules using hook_node_access, I forgot to check for hook_entity_access as well. It turned out that the "content moderation" module is denying access. Thanks @4k4 for making me revisit this!

Just for the record, if you need to see which other modules are using a certain hook, you can use something like this:

function mymodule_module_implements_alter(&$implementations, $hook) {
  if($hook == 'node_access') {
    //do whatever you need to do (e.g. use kint($implementations) to see what other modules are using this hook)
  }
}


Redirect for anonymus user doesn´t work from Controller

Try this

<?php

namespace Drupal\testmodule\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\RedirectResponse;

class EntityChecker extends ControllerBase {

  public function redirectToFront($bundle, $label) {
    $response = new RedirectResponse("/");
    $response->send();
  }

}


How do I automatically get the "Automatic alias" option checked for the content type?

After you define the pattern of the content type path, it will be checked automatically when you add the node of that content type.

The path is admin/config/search/path/patterns.


Annoying general behavior: the width of the text-input-fields, when editing a node, can be up to 2X your screen's width / decentered

With the help of the adept question by @J.Reynolds

Might solve this issue: (did so for me)

Just change the administration theme a couple of times

This can be changed at Appearance >> Administration

To which you can navigate manually using the administrative overlay
Or to which you can arrive directly, by default, via www.Your-Website-Domain/#overlay=admin/appearance


Change date formate in drupal admin tables (log, content listing, edit pages, etc)

From /admin/config/regional/date-time you can change the way dates are shown. This applies to the whole site though.


After reading the documentation of the module it looks like you need create a custom content type with at least one date field and then create your view to use that content type.


How to convert a D7 db_query object to string?

I can't see any benefit to doing that, are you sure you're not trying to get the OFFICE_ID value like this?:

$office_ids = db_query('SELECT OFFICE_ID FROM sage.OFFICE');
foreach($office_ids as $office) {
  ...
  // Depending on your database settings this might actually be lower case, i.e. $office->office_id
  $path = 'office-' . $office->OFFICE_ID;
}


Attach jQuery behavior to AJAX loaded content

Ok I managed to make it work.

Drupal did try to re-attach the behavior on my content after it was added by AJAX, but my selectors were starting from too "early" in my DOM - as such, when drupal.attachBehavior got called by the system, it couldn't find the right selector.

Example :
My DOM look like this :

        <input ... class="input1" />
        <input ... class="input2" />
        <input ... class="input3" />

My jQuery selector looked like this
    $('#product-add-to-cart .class1 input.input1").hover(...);

As I understand, FormAPI was replacing what was INSIDE #product-add-to-cart .class1, while the context passed to Drupal.attachBehavior only had part of this markup (the input elements..) : hence    $('#product-add-to-cart .class1 input.input1").hover(...); couldn't return anything in this context.

I replaced my jQuery $('#product-add-to-cart .class1 input.input1").hover(…); with
$('input.input1").hover(…); and it works like a charm.


Field for if the current user is a member of the organic group

There is no field or direct method to show "If the current user is member of the group or not". In your case I have found a solution here:

Create a view - showing list of all groups(you have already created).
Add new Relationship - OG membership: OG membership from Node group
Add new field - (OG membership from node group) OG membership: Group ID (Group ID), you can exclude it from display.
Add new field - Global: PHP (you have to enable Views PHP module for this field) and put below code in this field:

<?php

global $user;
$account = user_load($user->uid);
$ugrpid = $account->og_user_node['und'][0]['target_id'];

if($row->gid == $ugrpid){
  echo "Already Subscribed.";
}else{
  echo "Not member of this Group.";
}

?>

This is how my view look like( Screenshot ).


If using Drupal 6, ensure these edits are within the settings.php file, as this is where the translation will take effect.

If using Drupal 7, there are a few reasons why this may not work. Most usually, if the text you are translating contains anything that needs to be substituted (i.e. using %user:name etc.), then the text will be substituted before being passed to t(), and as such will not work! Also, the functionality of t() in Drupal 7 for attributes and variables is limited, so perhaps an additional module will be helpful.

For solutions using additional modules: Place the text in a basic page,  you can then use Entity translation to handle the languages and translation. @pedrosp also suggests that "to avoid SEO duplicated content issues, install Rabbit hole module and use the redirect to your panel page for those nodes."

Also, i18n has some solutions to tranlsate text within panels. It may take some playing around with however, to match the intended functionality of your site.

Finally, @Letharion has shared before some custom code to "force" a title to become translatable, perhaps playing with this to focus instead on where you would like your translatable content would also help:

/**
 * Implements hook_panels_pane_content_alter().
 */
function HOOK_panels_pane_content_alter($content, $pane, $args, $context) {
  if ($content->title) {
    $content->title = t($content->title);
  }
  return $content;
}

Hope this is of some assistance!


How to format database fields in a report created with Forena?

When you're "developing" a report (= Specifying the various report options), you have a choice to do so using either of the following features:

Use the WYSIWYG Report Writer, something novice Forena users typically do, or end users that are granted permissions to "develop" their own reports (and which get saved in Forena's typical '.frx' files).
In this case, you should look at Fields (within the WYSIWYG tutorial), located also at /reports/help.reportingwysiwyg#fields in your own site.

"Code" your own reports in the XHTML language used in Forena (saved in '.frx' files), which is called "FRX Report Writing". This is what the real power users will want to do, since it gives them the full XHTML power to build any report.
In this case, you should look at Fields (within the FRX tutorial), located at /reports/help.reportingwysiwyg#fields in your own site.

Be prepared: there are quite some options to pick from ...


Good looking contributed themes for Drupal 6

While not definitive, looking at the list sorted by number of installs is probably a good place to start regarding coding standards, and wide support.

Further filtering this list using some of your keywords like 'starter', 'css3', 'html5', etc should help you find what you are looking for.


Create a new revision automatically on edit

To enabled automatic revision creation go to the content type page (admin/content/node-type) and select edit for whatever content type you wish to have revision created automatically.

Under the workflow fieldset there's going to be an option "Create new revision" make sure you check that box and save your content type settings.

Now under your permissions (admin/user/permissions) be sure to not to give your users the "administer nodes" permission. This will prevent them from overwriting that option.


Simply add your library here in your's my libraries.yml file

 bootstrap-scripts:
 js:
bootstrap/js/affix.js: {}
bootstrap/js/alert.js: {}
bootstrap/js/button.js: {}
bootstrap/js/carousel.js: {}
bootstrap/js/collapse.js: {}
bootstrap/js/dropdown.js: {}
bootstrap/js/modal.js: {}
bootstrap/js/tooltip.js: {}
bootstrap/js/popover.js: {}
bootstrap/js/scrollspy.js: {}
bootstrap/js/tab.js: {}
bootstrap/js/transition.js: {}
bootstrap/js/transition.js: {}

Your-sub-theme/js/jquery.countdown.min.js: {}

Your-sub-theme/js/auction-timer.js: {}

**No need to define it separately also place your js file at correct folder path should be eg:Your-sub-theme/js/jquery.countdown.min.js then clear cache **.


How do I download a specific version of a module?

We can use following code to download latest stable release :

drupal mod modulename --latest

if we want to select a specific release other than latest then we can go for

drupal mod modulename --unstable

hope this will help.
https://docs.drupalconsole.com/en/commands/module-download.html


PHP - If a field has a certain text value then print something

There's no syntax error in the second code sample, if you're getting a syntax error it's not coming from those lines.

The best way to get values from an entity is with field_get_items():

$items = field_get_items('node', $node, 'field_room');
if (count($items) && check_plain($items[0]['value']) == 'Value1') {
  // Do something
}

But unless you have some sort of multi-lingual issue the code you've got should do exactly the same thing as that, so the problem might be elsewhere.


Web service APIs returns HTML content instead of JSON response

For the postman section of your issue: /user/login?_format=json is a POST request (not get as in your screenshot) and the body should be JSON not x-www-form.


Drupal features recreate issue with CCK fields

I faced the same issue today. After a lot of searching, I found the following patch.
https://www.drupal.org/node/2210241

I was able to solve this using the patch provided.
Can export the conditional field settings (along with content-type & fields) in a feature.
In my case the dependent is a Date field & dependee is a boolean field.

Conditional field 7.x-3.0-alpha1
features 7.x-2.2


I can't change permissions for text filters

This is a usability quirk of D8, in the Drupal Form UI the default format type for formatted text fields isn't configurable; it's dynamic based off form element properties (set by a developer), user role permissions, and the filter module settings (see form code)
By default, the fallback format (Plain text here) won't show as an option. There are a few things you can do here:

Set Plain text as the highest priority filter, if you want it to be the default for all formatted text fields.
Enable the always_show_fallback_choice config option (e.g. drush config-set filter.settings always_show_fallback_choice true), if you just want the format to be available.
Use the Allowed Formats module, if you need some type of per-field configuration.


Multiple currency  displayed in ubercart product page

Take a look at Ubercart Currency Conversion. From the project page:

  This module converts prices of ubercart products from one currency to
  another currency. The target currency will be selected as follows

  Administrators can select the currency and force all prices to be
  automatically converted
  If the above is not set, then the currency is determined based on
  user's address
  If the above is not possible, then the site's default currency is
  used.

  The module depends on Currency module.


Using Adaptivetheme subtheme how to have fixed width left column?

From the AdaptiveTheme documentation:

Sidebar Units and Widths
You can use any combination of units - meaning you can set a percentage width on the page and pixel widths on the sidebars. In some layouts you can only set the width on one sidebar because the second sidebar wraps below the main content and becomes a full width horizontal region - useful in smaller screen displays.

Example screenshot:

If you're using Panels, however, you're going to have to modify the CSS/theme code yourself.  You can either make your own new layout (just look at the code-- AT is pretty well documented) or just override the part that is making the layout fluid.  Note that doing this is almost certainly going to break the "responsiveness" of AT.


Why isn't this Config API Code saving options?

This is wrong:

'#default_value' => \Drupal::config('config.factory')->get('author_config'),

It should be:

'#default_value' => \Drupal::config('my_config.config')->get('author_config'),

This is the entire form:

$form['author_config'] = array(
  '#type' => 'textfield',
  '#default_value' => \Drupal::config('my_config.config')->get('author_config'),
  '#title' => 'Author of Config',
  '#required' => TRUE,
);
$form['language'] = array(
  '#type' => 'radios',
  '#title' => 'Language',
  '#default_value' => \Drupal::config('my_config.config')->get('language'),
  '#options' => array(
    'EN' => t('English'),
    'SP' => t('Spanish'),
    'FR' => t('French'),
    'DE' => t('German'),
  ),
);
$form['drink'] = array(
  '#type' => 'select',
  '#title' => 'Select your drink',
  '#default_value' => \Drupal::config('my_config.config')->get('drink'),
  '#options' => array(
    'RB' => t('Root Beer'),
    'SD' => t('Sunny Delight'),
    'WR' => t('Water'),
    'OJ' => t('Orange Juice'),
  ),
);

Probably using $this->config the problem will be solved too


Aggregation and grouping with dates and integers

I was able to accomplish by setting my aggregation differently. I set it to sum and with value checked it began to work as documented. thanks. Let  me know if anyone is having trouble with aggregation its kinda tricky getting to function properly thanks!


Render an entity in a string and return it through an AJAX callback in a custom form

The code in my question is OK. The problem was caused by a conflict by calling the form from hook_preprocess_field(). I changed the hook, and I am calling the form from template_preprocess_block() and the AJAX callback of the entity gets fine.

4k4 put me on the right track. Thank you.


You could do this with a preprocess function. The code here works for full views only (it won't work e.g. in a view of multiple teaser nodes).

function THEME_preprocess_html(array &$variables) {
  $router = \Drupal::routeMatch();
  $node = $router->getParameter('node');
  if (is_numeric($node)) {
    $node = \Drupal\node\Entity\Node::load($node);
  }
  if ($node instanceof \Drupal\node\NodeInterface) {
    $variables['node_object'] = $node;
  }
}

Now you can use {{ node_object }} in your html.twig.twig, e.g.:

<html>
<head>
  {% if node_object %}
    {% if not node_object.field_css.isEmpty %}
      <style>
        {{ node_object.field_css.value|raw }}
      </style>
    {% endif %}
    {% if not node_object.field_js.isEmpty %}
      <script>
        {{ node_object.field_js.value|raw }}
      </script>
    {% endif %}
  {% endif %}
  ...

And yes... don't try this at home kids ;-P


I think you were on the right track.

Check out this issue comment: http://drupal.org/node/685956#comment-4412688

It links to a GitHub repo, from which you can find a fork at https://github.com/blackice2999/jquery_countdown/tree/7.x-1.x that appears to contain a Drupal 7 port.

Try that.


What worked for me was:
verride the 'shopping cart block' view with custom template
    block--cart-blockNameInClonedView.tpl.php(referece themer-info for
    exact name).

Populate the 'vars' array with total number of items and total amount of a shopping cart in block preprocessor function as following:

function THEME_preprocess_block(&$vars, $hook){
    if ($vars['block']->region == 'cart_in_header') {
            if ($order = commerce_cart_order_load($vars['user']->uid)) {
                $wrapper = entity_metadata_wrapper('commerce_order', $order);
                $bazar_cart = array();
                $bazar_cart['total-qty'] = commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types());
                $price_raw= commerce_line_items_total($wrapper->commerce_line_items, commerce_product_line_item_types())['amount'];
                $bazar_cart['total-price'] = substr($price_raw,0,-2).'.'.substr($price_raw,-2);

                $vars['bazar_cart'] = $bazar_cart;
            }
      }
}

In custom block template file, the variable '$bazar_cart' is available to plug the values(total items and total amount of cart) as you wish in the html structure


I hope you cleared cached
I hope u added css under [themename].library.yml
If still not working plz use rewrite result add your custom html.


ajax_command_invoke addClass changes lost after form validation

Yes, the IDs of an element change when it's being reloaded using AJAX. That's supposed to be a feature. :/ You might try using a class to target your textareas instead.


Issue with drupal_add_css, can do it by nid but not by alias

arg() doesn't work with path as far as I know. I'm sure there are better aproaches to doing this, but I found a bit of a hack.

if(strstr($_SERVER['REQUEST_URI'], "web-portfolio")) {
  drupal_add_css(drupal_get_path('theme', 'mythemename') . '/css/slider.css', 'theme');
}

I wouldn't use this however its not really the Drupal way. You are adding CSS for a slider, I guess that slide is made with views. You could just make your drupal_add_css call from the views template. That way you'll have it even if you change the path.


Good Drupal distribution to start with Workflow?

Note: I don't know what you mean by "better", and also I don't know what you are comparing to.

NodeStream is my employers distribution. We base nearly all of project off it, and we try to keep much of our work in the open, to ensure that everyone can use it. We have support for the Workbench module and its workflow.

There was a presentation about how we work with NodeStream and built on top of it during the Barcelona devdays 2012, but as far as I can tell, no videos have been posted from there yet, so I can't link to it.


How to expose filter for entity reference as dropdown in the Search API view?

Try to use TYPE => String. This work for me.


Yes, this has been addressed by the core maintainers. You are safe if your module doesn't use any APIs deprecated until Drupal 8.8/8.9:

Drupal 8.8 was the final release to introduce new deprecations that will be removed in Drupal 9

A quote from the Drupal release team: https://groups.drupal.org/node/535670
You should wait to remove deprecations introduced in Drupal 9 until you prepare for Drupal 10 and don't need Drupal 8 support any longer.
So beginning with Drupal 8 you can manage compatibility for two Drupal versions  at the same time.


How do I set up both a landing page and front page?

It’s as simple as sheena_d already commented on your answer. Define /landing as your home page and link your logo and home button to /phront. Done!


As others have said, there is no "correct value". But if you are really stuck; a fairly simple way to choose is to consider how often content on your site will change, and then divide that by 2.

So if you expect your content to update every 24 hours: 24 / 2 == 12 hours. So set your cache to 12 hours. If you aren't sure how often content will change, set it to a slightly lower value. Is performance is very important, or if your site will be getting a lot of traffic, set a higher value.

You may also want to look at non Drupal caching options such as Cloudflare, varnish cache & memcache. But that's a whole other thing.


Module's new release not showing link to download

Drupal.org automatically create download file for the module's revision, so you need to wait for the same.


Is it possible to get node template suggestion per views row on Drupal 8

This is probably not a simple task for a template name suggestion, because at the time of rendering the node is unaware of where it is placed in the view.

So a better approach might be to use two different view modes, one for the first and one for the rest of the nodes. Then use a row style plugin to switch the view modes, for example the module Views Parity Row.

If this is only to apply CSS, then don't try to add row classes to the node. Add them to the views row container and target elements inside of the node with multiple CSS selectors.


I would recommend that you base your solution on the ckeditor_link module. To use this module, you will of course need to be using ckeditor for your wysiwyg editing.  If this is not a problem, then users will be able to use a new "Internal Link" URL type when creating links.  Typing in the node title of the target will make a link to node/1234, and this link will be transformed into a link to the node's path alias at render time.  Now, your internal links will automatically change if you edit the path alias of the node; there is nothing else you need to do to manage them.

For external links, I would make a new node type for external links, and make a landing page for each one.  Use a link field on the landing page to hold the external link, and put boilderplate text in your template for that content type.  Once you've set this up, you can again use the ckeditor_link module to target your landing page.  If you don't like the idea of a landing page and you're a little handy with coding, you could make your own version of ckeditor_link for external links, and modify its input filter to render the URL of the target link instead of the URL of the landing page.


Link templates are defined in the entity class. For webform_submission:

 *   links = {
 *     "canonical" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}",
 *     "access-denied" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/access-denied",
 *     "table" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/table",
 *     "text" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/text",
 *     "yaml" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/yaml",
 *     "edit-form" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/edit",
 *     "notes-form" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/notes",
 *     "resend-form" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/resend",
 *     "duplicate-form" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/duplicate",
 *     "delete-form" = "/admin/structure/webform/manage/{webform}/submission/{webform_submission}/delete",
 *     "collection" = "/admin/structure/webform/submissions/manage/list"
 *   },

Source: https://git.drupalcode.org/project/webform/blob/8.x-5.x/src/Entity/WebformSubmission.php


How to change the Zen theme to a single sidebar layout?

In page.tpl.php, at line 109 and line 110, delete the sidebar you don't want

In style.css change this class
.region-sidebar-second{
float:left;width:20%;margin-left:0%;margin-right:-20%
}

to be
.region-sidebar-second{
float:left;width:20%;margin-left:0%;margin-right:-20%;display:none;//add a display:none
}

and change .two-sidebars #content {
float: left;
width: 60%;
margin-left: 20%;
margin-right: -80%;
}

to be

.two-sidebars #content {
float: left;
width: 80%; //change 60% to 80%
margin-left: 20%;
margin-right: -80%;
}


This section resides in a controller in the parent module:

$plugin_items = [];
// Call modules that implement the hook, and let them add items.
\Drupal::moduleHandler()->alter('flot_examples_toc', $plugin_items);
if (count($plugin_items > 0)) {
  $output['plugins'] = [
    '#title' => 'Plugins',
    '#theme' => 'item_list',
    '#items' => $plugin_items,
  ];
}

And this resides in the child [module].module file.

use Drupal\Core\Url;

function mymodule_flot_examples_toc_alter(&$item_list) {
  $options = [
    ':one' => Url::fromRoute('flot_spider_examples.example')->toString(),
  ];
  $item_list[] = t('Spider Chart (with spider plugin)', $options);
}

The parent creates an array and passes it to the children by reference. They can alter the array by adding elements to it. The parent then adds it to the render array.


Confused about choosing between line items and product attributes

If you made it all attributes (fields) on the products, created a product with each possible variation and referenced them all in a single node, it would work with the commerce add to cart form out of the box.

Commerce would create a select list for each attribute, which might not be exactly what you want, but that should be possible to handle with some form alter.


This is a known issue in Drupal 6 and 7 for that matter. It is not cleared when running cron. You can safely delete all rows that has expired.

DELETE FROM {cache_form} WHERE expire < now();

should do the trick.


You can set the visibility of a block in the block page (admin/structure/block).
In the visibility tab select 'Show for the listed pages' and in the 'Pages' just add /category. Use /category/* to display the block in all the pages.


TL:DR; you need to overwrite the link_generator to change this behavior.
Drupal 8 uses the link generator for this. You can take a look at
Drupal\Core\Utility\LinkGenerator::generate if you want to know the code behind it all.
The key part is this:
elseif ($url->isRouted() && $url->getRouteName() === '<nolink>') {
  $generated_link = new GeneratedNoLink();
  unset($attributes['href']);
}

If you take a look at GeneratedNoLink you will see
/**
 * This class holds a <span> generated from the <nolink> route.
 */
class GeneratedNoLink extends GeneratedLink {

  /**
   * {@inheritdoc}
   */
  const TAG = 'span';

}

So you need to implement your own no link class and not unset the href and everything should be fine. Doing so you more or less need to copy most of the logic in Drupal\Core\Utility\LinkGenerator::generate to determine when no link should be used.
Note
Links/urls can be generated in various ways, some use link_generator, some use url_generator, some use the link RenderElement. In your case it looks like  the link_generator is used, but that could be changed by custom theme/module.


As per your requirement Timefield module will be the best choice(considering that you are using Drupal 7)

  Timefield is a Field API field for storing simple non-timezone time
  values, with an optional end time, utilizing a simple JQuery
  timepicker widget for input. Normally, you will want to use a Date
  field for all date/time values; however, this field is for use when
  you don't want to implement a Date field or have time values that are
  not dependent on the Gregorian Calendar, i.e., when Year, Month
  granularity is irrelevant.


How to add delete link for imported content type

Although I am agains editing db directly, the simplest solution would be do edit table in your database.

find 'node_type' table and under 'custom', for your content type, change 0 to 1.


How do I hide one word from a view result column

Since I want to display an item from two different tables, I used an if-else statement.

if ($row->state == 'published') {
  echo "$date";
}
else {
  echo "$row->state";
}


One way to resolve this is by creating required feeds page with views.

Then add this generated feed pages link manually through Global Text area field of appropriate view in footer using HTML anchor tag. Separate links will be displayed inside each view footer of QuickTabs as per setup.


How to list all inactive modules on a multisite?

I am not sure of a way to do this programatically, but you could install http://drupal.org/project/enabled_modules and cross-reference the lists.


How can you sort taxonomy terms based on number of times used, in a view?

Create a new view
limit to taxonomies "show taxonomies of term all"
Add a relationship "Taxonomy term: Content with term"
Use aggregation
Add field "Content: Title"
Aggregation type "Count"
Change label to something like "number of times used"
Add Sort criteria "Content: Title"
Aggregation type "Count"
Sort to whatever you like

it should look like this:


I need to add a date to a calendar without creating a node

I would use the Automatic Entity Label module to hide the title field on the form, and automatically populate it with a title. It can work with tokens, so you could configure it to generate node titles like "Event on [node date]".


I ran into this issue myself. I got it to work in the following way:

function mymodule_mail_alter(&$message){

  $message['from'] = "do-no-reply@example.com";
  $message['headers']['From'] = 'Name TO SHOW <do-no-reply@example.com>';
  $message['headers']['Sender'] = $message['headers']['Return-Path'] = $message['from'];
}

However, like you,  I thought adding $message['from'] = 'myemail@gmail.com'; is the way to go and I think it should -Perhaps other folks can chime in and let us know if this is a bug?

In any case, it seems drupal does more processing and checks to verify the from email address and if it does not pass all the checks it sets it to the sitemail, or the mail library just use the other headers. Note I think this behavior may differ based on which mail library you are using. In my case, and I presume in yours, its PhpMail.php.

The solution above worked but I am not sure if it's the most appropriate or if it would work for others who are using different mail managers..


remove 'publishing options' and other settings from node/add

hook_form_alter() or use CSS if you don't care if the values are overridden.


I know it is a bit late. But I had the same problem and ran into this page. So here is how I solved it. It is with my own case, but solution is generic, I hope it will help someone.

I join wootoon_cached_sets twice, the key in $data['whatever'] is only the alias in the query. The actual table is given by the table property. This is confusing because if ignored, this property defaults to the table key.

I end up With the following query:

LEFT JOIN {wowtoon_cached_sets} wowtoon_cached_sets_main
ON   wowtoon_owners.toon_key = wowtoon_cached_sets_main.toon_key
AND  wowtoon_cached_sets_main.active = '1'
LEFT JOIN {wowtoon_cached_sets} wowtoon_cached_sets_second
ON   wowtoon_owners.toon_key = wowtoon_cached_sets_second.toon_key
AND  wowtoon_cached_sets_second.active = '0'

Using the below code:

  $data['wowtoon_cached_sets_main']['table']['group']  = $data['avatar']['table']['group'];
  $data['wowtoon_cached_sets_main']['table']['join'] = array(
      'avatar' => array(
        'left_table' => 'wowtoon_owners',
        'left_field' => 'toon_key',
        'field' => 'toon_key',
        'table' => 'wowtoon_cached_sets',
        'extra'      => array(
          array(
            'field'    => 'active',
            'value'    => 1,
          ),
        )
    )
  );

  $data['wowtoon_cached_sets_second']['table']['group']  = "second spec";
  $data['wowtoon_cached_sets_second']['table']['join'] = array(
      'avatar' => array(
        'left_table' => 'wowtoon_owners',
        'left_field' => 'toon_key',
        'field' => 'toon_key',
        'table' => 'wowtoon_cached_sets',
        'extra'      => array(
          array(
            'field'    => 'active',
            'value'    => 0,
          ),
        )
    )
  );

  $data['wowtoon_cached_sets_main']['spec'] = array(
          'field' => array(
            'field' => 'spec',
            'title' => t('Spec'),
            'click sortable' => TRUE,
            'help' => t('wowtoon_cached_sets Spec'),
            'handler' => 'views_handler_field',
    ),
  );
  $data['wowtoon_cached_sets_second']['spec'] = array(
          'field' => array(
            'field' => 'spec',
            'title' => t('Spec 2'),
            'click sortable' => TRUE,
            'help' => t('wowtoon_cached_sets Spec 2'),
            'handler' => 'views_handler_field',
    ),
  );


admin/user/rules is not a path in a regular Drupal install, so you must have some module that does this for you. Since you tagged your post with domain-access I can only guess that the one. You should start looking into the settings of whatever module holds that path.


How to load a node given a menu link id?

Something like:

if ('entity.node.canonical' == $link->getRouteName()) {
  $params = $link->getRouteParameters();
  $nid = $params['node'];
}


How to dynamically manipulate canonical entity URLs

Is there a service specifically for generating canonical URLs I can
decorate?

Yes, for a route based handling of outgoing canonical links you can use OutboundRouteProcessorInterface::processOutbound
For example like core implements the dynamic route <current>.
/core/lib/Drupal/Core/RouteProcessor/RouteProcessorCurrent.php
  public function processOutbound($route_name, Route $route, array &$parameters, BubbleableMetadata $bubbleable_metadata = NULL) {
    if ($route_name === '<current>') {
      if ($current_route = $this->routeMatch->getRouteObject()) {
        $requirements = $current_route->getRequirements();
        // Setting _method and _schema is deprecated since 2.7. Using
        // setMethods() and setSchemes() are now the recommended ways.
        unset($requirements['_method']);
        unset($requirements['_schema']);
        $route->setRequirements($requirements);

        $route->setPath($current_route->getPath());
        $route->setSchemes($current_route->getSchemes());
        $route->setMethods($current_route->getMethods());
        $route->setOptions($current_route->getOptions());
        $route->setDefaults($current_route->getDefaults());
        $parameters = array_merge($parameters, $this->routeMatch->getRawParameters()->all());
        if ($bubbleable_metadata) {
          $bubbleable_metadata->addCacheContexts(['route']);
        }
      }
      else {
        // If we have no current route match available, point to the frontpage.
        $route->setPath('/');
      }
    }
  }


If it seems spammy, then maybe use Drupal to block the IP address (settings.php or admin) but if it's only a few and they look okay and genuine it could be users from the same college or company behind a proxy server.

If it you still want to block someone you could add an additional validate function to the user registration form and include an IP check in there.


render() only works because of EarlyRenderingControllerWrapperSubscriber, which should have been removed by now:
 * In other words: this just exists to ease the transition to Drupal 8: it
 * allows controllers that return render arrays (the majority) and
 * \Drupal\Core\Ajax\AjaxResponse\AjaxResponse objects (a sizable minority that
 * often involve a fair amount of rendering) to still do early rendering. But
 * controllers that return any other kind of response are already expected to
 * do the right thing, so if early rendering is detected in such a case, an
 * exception is thrown.
 *
 * @see \Drupal\Core\Render\RendererInterface
 * @see \Drupal\Core\Render\Renderer
 *
 * @todo Remove in Drupal 9.0.0, by disallowing early rendering.

So don't use any render method. Ajax renders HTML content automatically and so makes sure to catch all metadata which bubbles up.
BTW in a module handling AJAX responses you don't need to bubble up attachments through Twig:
{{ attach_library('focal_point/drupal.focal_point_preview') }}

You can add them directly to the Ajax response:
$response->addAttachments(['library' => ['focal_point/drupal.focal_point_preview']]);


I believe you are  using Captcha module..

Go to admin/config/people/captcha
Enable "Add CAPTCHA administration links to forms" and "Allow CAPTCHAs and CAPTCHA administration links on administrative pages"

Go to node edit page you see setting like below

Enable captcha for form


How can I place an entity content field value in header markup?

The essence of the problem is how to move a value from the field template preprocess to the html theme preprocess. I did this by using a one-off static variable function, provided by a helper module:

/*
 * Generates a static variable in the scope of the page request
 * to set instantiate like
 *  $var = &p2p_helpers_ogimage_function(); $var = 'my value';
 *    to read the var,
 *   instantiate without.
 */
function &p2p_helpers_ogimage_function() {
  $var = &drupal_static(__FUNCTION__);
 if (!isset($var)) {
    // generate contents of static variable
    $var = NULL;
  }
  return $var;
}

Then I can do the rest in the THEME.theme file.

In the field template preprocess hook I can do this:

/**
 * Prepares variables for blazy.html.twig templates.
 */
function p2p_bootstrap_preprocess_blazy(&$variables) {
  $url = p2p_helpers_ogimage_function();
  if (!$url) {
    $url = &p2p_helpers_ogimage_function();
    $url = $variables['url'];
  }
  ...

This will fill check if the variable is already set, so it only sets it once for the first image in the field.

Then in hook_preprocess_html:

$url = p2p_helpers_ogimage_function();
if ($url) {
  $ogimage = [
    '#tag' => 'meta',
    '#attributes' => [
      'property' => 'og:image:secure_url',
      'content' => $url,
    ],
  ];

  $variables['page']['#attached']['html_head'][] = [$ogimage, 'og:image'];
}

Does anyone see any better way to do this?


man. Have you solved yet? There's this custom module that even someone with basics of programming could do. But it is not perfect, you will have to make an extra view and stuff... https://atendesigngroup.com/blog/removing-duplicate-content-across-multiple-drupal-views


How to make user profile image reflect a transparent background?

If the image background is transparent when you hover over it, then the picture has transparency, and must be a .png or .gif file.

Therefore the white background must be down to CSS

In Chrome or Firefox, right click on the image and select "Inspect Element". Find the CSS controlling the div or img, and change the CSS from

.picture {
   background:#FFFFFF;
}

to

.picture {
   background:none;
}


How can I add code that will call the javascript within a block every minute?

You will need to use JavaScript's setTimeout() function:

To elaborate, place the code that calls your ad server inside a JS function.

Then, use setTimeout(), as demonstrated in the website I linked to, to call it at every x interval.


How to add v1 when specifying the URL of an API?

All I had to do was to add another argument and clear the cache.

"args" => array(
   array(
     "name" => "version",
     "optional" => false,
     "source" => array("path" => 0),
     "type" => "string",
     "description" => "The API version."
   ),
   array(
     "name" => "id",
     "optional" => false,
     "source" => array("path" => 1),
     "type" => "int",
     "description" => "The id of the course to retrieve."
   )
),


Entity difference between fields defined in the entity itself and the external fields

The 'internal' fields are base fields, defined in the entity type definition. The 'external' fields are bundle fields, defined in configuration, which can be exported and imported to yaml, and is configurable in UI.

Content entities that have no bundles can have bundle fields, for example the user entity. In this case the id of the bundle is that of the entity.

More information https://www.drupal.org/docs/8/api/entity-api/introduction-to-entity-api-in-drupal-8, especially this chapter https://www.drupal.org/docs/8/api/entity-api/defining-and-using-content-entity-field-definitions.


Sort Node Queries by an entity reference field within a field collection item

Solved it myself. I added one more join,

$query->join('taxonomy_term_data', 'fee', 'cfs.field_subject_target_id = fee.tid');

Then order by

$query->orderBy('fee.name', 'ASC');

Then the result was ordered alphabetically by the taxonomy name.


There is an option in feed import module settings (admin/config/services/feed_import/settings), where you can set to import your RSS when the cron runs ("Cron import" checkbox).

If you do not have access to crontab, you cannot schedule cron from server side, but if you set cron interval at admin/config/system/cron, cron will be also triggered on, when the time elapses and there will be site visitors on your page (cron will be triggered by one of the site visitors).

Source here.

Edit:
If you would like to run cron each 5 minutes (or other custom interval), you will need custom module and implement hook_init(), which is executed on every page load, when the module is active. See the example:

function mymodule_init(){
  //get variable content (last cron run time), if not exists, return 0
  $last_cron_run = variable_get('mymodule_cron_run', 0);

  //if it was more than 5min before
  $five_minutes = 5 * 60;
  if($last_cron_run + $five_minutes < time()){
    //run cron
    $result = drupal_cron_run();

    //do with $result what needed

    //set last cron run time to variable
    variable_set('mymodule_cron_run', time());
  }
}


Post It Everywhere just one click and your content will be posted to:

Facebook
Twitter
LinkedIn
FriendFeed

The most common way to make your site popular is by posting your content to different social networks. Here is a new and simple way for publishing content to different social networks.

  Features:

  The link "Post it Everywhere!" will be displayed with every node type(the admins select). This link will be used to post on all the
  networks
  Authenticate Once, Use Forever: The users don’t have to authenticate every time when they login to the site or want to post
  content. Each user will authenticate himself only once and these saved
  settings will be used to post in the future.
  The users will not be moved to other sites to post the content (as it happens in various modules that users are redirected to that
  social network on which they want to post).
  The user names and passwords of users are not saved for this purpose so no risk for security and spoofing.
  Facebook Connect API is used to send posts to Facebook and OAuth is used to connect to LinkedIn, Twitter and FriendFeed. OAuth API can
  be downloaded from this link.
  End users can update their settings at anytime.


ubercart template email addresses hard coded in template

There are 2 components here: capture/store a setting for you email & insert it into your template.

Since it's a part of your template settings, I'd suggest hook_form_alter() the order template setting form to capture/store a variable:

function MYMODULE_form_uc_order_settings_form_alter(&$form, &$form_state, $form_id) {
  $form['MYMODULE_uc_order_template_email'] = array(
    '#title' => t('Template Email'),
    '#default_value' => variable_get('MYMODULE_uc_order_template_email', 'test@example.com'),
    '#description' => t("Template Email"),
    '#type' => 'textfield',
  );
}

The next component is to take that variable an inject it into your template. Using the example above, the variable MYMODULE_uc_order_template_email will now be available. Use a pre-process function to insert a email variable into template. Add this to your theme's template.php:

function MYTHEME_preprocess_uc_order(&$variables) {
  $variables['my_email'] = variable_get('MYMODULE_uc_order_template_email', 'test@example.com');
}

Lastly, copy over uc-order--customer.tpl.php to your theme directory (so UC updates don't wipe away your customizations), flush the cache (to pickup the new template), and, insert $my_email into your uc-order--customer.tpl.php copy.


How to set an error message with Javascript?

The drupal_set_message() works by storing the messages into a session and displays when the page is reloaded.

If you want to show an error message through javascript, include js in your module (if working with some module).

You could simply append an error message on some event

    jQuery(document).ready (function(){
    jQuery(".error-message").append('
Error message to be displayed
');
});

It will simply display an error message. You can apply further Js code as desired output.


Create view gallery, with page for every image

If I understand the question properly, something like this should work...

if the url is user defined, create a field using URL. If not, the answer depends on the requirements of the URL.

1 per page: set the pager to limit 1 per page

Link:

add the link field, set to exclude from display
add the image field as normal, exclude from display
create a Global Text, with  tag, using the image field and link field as replacement patterns


How to change the title of a modal window?


How do I embed a node creation form inside a view

Hope this will help you,

In Drupal 7 you can achieve by the following steps

You can embed a node creation form inside a VIEW

Either in VIEW Header or you can created a new VIEW and attach it to your VIEW

For this example I am embedding inside Views Header. Embedding inside Views Header will be the better options. Click to Add Views Header

Select Global: Text area

Add the PHP code and don't forget to change the Text Format to PHP

PHP code

<?php
    module_load_include('inc', 'node', 'node.pages');
    $node_form = node_add('node_type');
    print drupal_render($node_form);
?>

Note :

Don't forget to replace node_type in the PHP code.
Use hook_form_alter for node form redirection, as after the node creation the form will redirect to node detail page. If you want to redirect to your page then use $form_state['redirect'] = 'mycustompage'; reference
Enable PHP Filter module using admin/modules

Set the Permissions for this module by enabling "Administrator" for Execute PHP Code as follows:

If any one has better solution, please share it.


Customize the appearance of sharing articles to social media

Welcome to StackExchange!

Assuming you are using D8, here are some instructions (D7 would be similar but slightly different).

The metatag module has some submodules to help with various metatag usages.  You will want to also enable the metatag_open_graph module. This will let you set the og* metatags.

First step in this is to go to the Content Type definition (structure->content types) for the page type (article?) you want to have metatag info on.  You will need to select the Manage Fields option.  Here you need to add a new field.  Use the "Use an existing field" option and add the MetaTags field to the content type.

Repeat this for any other content types you want to have Metatag info added to.

Once you have done this, you can go into the configure / search and metadata / metatag screens and define the defaults you want either globally or for the specific content type.  You can use "tokens" to indicate items from the node values.  E.g. [current-page:title] or [node:field_featured_image] and the like.  There is a browse available tokens to give you some guidance here.

Additionally, now that you have the metatag field added to the content type.  You can also manually modify the metatags for any single node if you have the rights to modify the metatag info.

This can be done while editing the node and opening the MetaTag tab (generally at the bottom of the form).

To keep facebook and twitter happy I think you generally need the title metatag, og description field and the og image field set.

Good luck.


If I'm not wrong by default the form redirect the user in the page where it was generate. But, if you want change it you can use the function drupal_get_destination and add it to your action="" simply by changing the $form['#action'] in your code.


Installation fails with missing "file" -plugin error

Yeah, got this sorted.

The reason for this strange behavior was unsurprisingly misconfigured field in some entity's baseFieldDefinition method.

Someone had used in display plugin configuration "file" instead of correct "file_generic" and for some reason this hadn't been triggered before this. The app has been live for about 6 months and gone through numerous updb's and entity-updates.

This was a nice one. I'll just leave this here in case someone has same mistakes :)


Creating a form with GET bypases the validation and submit

Have the page or form check for the presence of your variables, using drupal_get_query_parameters(), and if present, perform validation checks and get results from the external API, and display.

For example,

$params = drupal_get_query_parameters();
if ( isset($params['cat']) ) {
  //validate $params['cat']
    if ( myValidationCheck($params['cat']) ) {
      $results = myExternalAPIGetResults($params['cat']);
      $form['results'] = myResultsDisplay($results);
    }
  }


What's the difference between drupalSettings and settings parameter in behaviors?

The thing to remember is that behaviors can fire both on page load and on AJAX requests.

Upon page load, the global and the parameter passed to the behavior should be identical.

During the course of page interaction, and depending on the AJAX commands, the settings parameter may be different when it fires.

When writing behaviors in Javascript, always use both the jQuery context to scope selectors, and the settings variable that get passed in to be safe and future proof your code even if you aren't using AJAX.


Control content access based on field value in user profile?

User Relationships module seems to be the answer:

  User Relationship Node Access lets users control access to their content based on relationships


At the moment, the Drush unit tests have some intermittent failures. I wouldn't worry too much about the failure. I'd recommend Drush 8 for Drupal 8 use.

UPDATE: I looked into the test failures, and it looks like they are related to fact that Drupal 8.1.x is now the recommended version of Drupal, whereas the Drush 8 tests are still assuming 8.0.x.  These test failures have been fixed in the master branch, but not back-ported to the 8.x branch yet.  The failures are caused by problems in the tests, not by problems in Drush; they should be fixed shortly, but will not cause you any problems in the meantime.


advantages of drush bam vs. drush sql-dump / drush sql-connect

There aren't giant differences between the two approaches. Here are a few small differences:

drush sql-dump uses mysqldump program in the background and so is must faster than the pure PHP approach taken by BAM.

You can easily skip tables with sql-dump as well. See the help for this command.

Finally, some folks might want to use sql-sync which does all of these steps in one command. It works faster than sql-dump+sql_connect when one of the machines is remote. It also includes optional data sanitization.


How can I force users to provide a reason when cancelling their accounts?

Here you go, alter the user_cancel_confirm_form.

function MYMODULE_form_user_cancel_confirm_form_alter(&$form, &$form_state, $form_id) {
  $form['reason'] = array(
    '#title' => t('Reason'),
    '#type' => 'textarea',
    '#description' => t('We are sad to see you go, why do you want to leave?'),
    '#required' => TRUE, // force to input
  );

  $form['#submit'][] = 'user_cancel_log_reason'; // add custom submit handler
}

function user_cancel_log_reason($form, &$form_state) {
  $reason = $form_state['values']['reason'];
  // do whatever with the reason, e.g watchdog
  watchdog('user', 'User cancel reason:' . $reason);
}


How to give blocks a meaningful name in the views overview page?

Currently your description is empty, you can add a description to your view which will help somewhat.

Click on the edit view name/description button


How can I programmatically enable permission for anonymous users to view comments on a single node?

There are a couple ways to handle this and it depends on when you want to make the change.

What you'll want to change is $node->comment to one of the following:

COMMENT_NODE_CLOSED
COMMENT_NODE_HIDDEN
COMMENT_NODE_OPEN

You could use a hook_node_presave() function to change the value prior to saving based on some logic.  Or you just need to get access to the node object through other means like node_load().  Just make sure to save the node if you're loading it up to make the change.


Eventually worked out how to do this: use Content Profile module to extend the user account with a node of a custom type, and then create a free tag for that node type.


Posting the main url of drupal site on facebook wall

You have a two part question here.

One, the best way to deal with OG info on your site is with the Metatag module:

  The Metatag module allows you to automatically provide structured
  metadata, aka "meta tags", about a website. In the context of search
  engine optimization, when people refer to meta tags they are usually
  referring to the meta description tag and the meta keywords tag that
  may help improve the rankings and display of a site in search engine
  results. In addition, the module provides support for meta tags (Open
  Graph Protocol from Facebook, Twitter Cards from Twitter) that allow
  control of how content appears when shared on social networks.

When you install and enable this, you can customize what OG info appears where, and it has full token support for dynamically creating the meta elements pages on a page's content.  You can also hardcode values for specific cases, like the home page.

The second part of your question has to with the fact that FB heavily caches page contents.  The provide a debug tool for dealing with this:

https://developers.facebook.com/tools/debug/

In addition to seeing exactly what OG info it is pulling in about a URL you provide, it has the side effect of clearing the cache for that particular URL.


Replace the settings.php with the default.settings.php and re-run the installer.

Use the same database credentials and it should detect that there is an existing installation and say the installer cannot continue. However, you should be able to view the site normally once the installer cannot continue.


The following answer is from Drupal 7 post, long time ago but I guess the methodology is still the same.

Basically in your views template you can specify that logic.

https://www.drupal.org/node/1932102#comment-7182640

if (row is even)
  // display order 1
else {
  // display order 2
}

Update: There is port of the views conditional module available on github.

https://github.com/anandtoshniwal93/views_conditional/blob/master/README.md
You can reuse it in your view like that....

Views Conditional field (if row is even)

  print rewrite field 1 (which is the first combination order)

Viws Conditional field (if row is odd)

  print rewrite field 2 (which is the second combination order)


The error message doesn't show up if you go to the image field settings and, under Image preview style, select a value that actually exist or None.
For some reason, there are several values in that field that don't match with any file in the filesystem; when the code checks this, it finds no such version of the image and emits an error.


How can we go to particular #div on a page using drupal_goto()?

You just use the second argument the function takes.

drupal_goto("fsaclientservice/viewreservation", array('fragment' => 'add-reservation-note-form'));

Notice that in the code I wrote here, 'fragment' is a literal string you need to use as it is, and 'add-reservation-note-form' doesn't have any leading #.
The documentation for that parameter is in url() because drupal_goto() calls that function to build the URL.

  $options: (optional) An associative array of additional options, with the following elements:

  'query': An array of query key/value-pairs (without any URL-encoding) to append to the URL.
  'fragment': A fragment identifier (named anchor) to append to the URL. Do not include the leading '#' character.
  'absolute': Defaults to FALSE. Whether to force the output to be an absolute link (beginning with http:). Useful for links that will be displayed outside the site, such as in an RSS feed.
  'alias': Defaults to FALSE. Whether the given path is a URL alias already.
  'external': Whether the given path is an external URL.
  'language': An optional language object. If the path being linked to is internal to the site, $options['language'] is used to look up the alias for the URL. If $options['language'] is omitted, the global $language_url will be used.
  'https': Whether this URL should point to a secure location. If not defined, the current scheme is used, so the user stays on HTTP or HTTPS respectively. TRUE enforces HTTPS and FALSE enforces HTTP, but HTTPS can only be enforced when the variable 'https' is set to TRUE.
  'base_url': Only used internally, to modify the base URL when a language dependent URL requires so.
  'prefix': Only used internally, to modify the path when a language dependent URL requires so.
  'script': The script filename in Drupal's root directory to use when clean URLs are disabled, such as 'index.php'. Defaults to an empty string, as most modern web servers automatically find 'index.php'. If clean URLs are disabled, the value of $path is appended as query parameter 'q' to $options['script'] in the returned URL. When deploying Drupal on a web server that cannot be configured to automatically find index.php, then hook_url_outbound_alter() can be implemented to force this value to 'index.php'.
  'entity_type': The entity type of the object that called url(). Only set if url() is invoked by entity_uri().
  'entity': The entity object (such as a node) for which the URL is being generated. Only set if url() is invoked by entity_uri().


Javascript/jQuery fail after AJAX Referesh

The CSS id may change on ajax refresh.

E.g edit-product-id, edit-product-id-1

Make sure your js can target the new form markup.


how to get parent tids of a taxonomy term

In $ancestors you'll find an array of the parent terms starting with the term $tid itself:

$ancestors = \Drupal::service('entity_type.manager')->getStorage("taxonomy_term")->loadAllParents($tid);
$list = [];
foreach ($ancestors as $term) {
  $list[$term->id()] = $term->label();
}


How to convert an HTML website to Drupal 7 nodes?

You don't necessarily need a module to add a content to drupal. Just simply create a content of type page and add your content. To help you with formatting, you may want to install the WYSIWYG module to help you with formatting.


Commerce billy mail: how to attach multiple files to an email

I found out, how to attach multiple Attachments:

  $attachments[] = array(
    'filename' => 'MyDoc.pdf', // can use any alias name here
    'name' => 'MyDoc.pdf', // required for mandril and other libraries.
    'filemime' => 'application/pdf', // mime file type
    'type' => 'application/pdf', // required for mandril and other libraries
    'list' => TRUE,
    'filepath' => 'sites/default/files/mail_attachments/MyDoc.pdf',
  );


How can I allow all users to access only a certain type of entityform?

In filter. Just add.

  content: type => is one of (put check mark on all those content types
  you want. )

And then add permission for that view.

The another way is.

Go to permission section under people admin menu.
Navigate to node section.
You will find your content type name with VIEW,EDIT,DELETE permission
with each users.
Just put check mark for the user you want to them able too see.

Hope this will work.


How do i create a payment method+gateway with a custom function called by the gateway to determine whether payment is successful?

The answer, is that uc_payment_process() needs to be called in hook_order() when the $op variable is 'submit' with the payment method ID as the first argument.

The missing link to bring payment methods, gateways and actual payments together is as follows:

<?php

/**
 * Implements hook_order
 * This is the bit that actually gets the method/gateway-combo into gear
 * when an order is submitted in the checkout process.
 */

  function uc_securepaytoken_order( $op, $arg1, $arg2 ) {

    switch( $op ) {
        case 'submit':

          if($arg1->payment_method == 'sptoken') {

            // Attempt to process the payment
            $pass = uc_payment_process( 'sptoken', $arg1->order_id, $arg1->order_total, $data, TRUE, NULL, FALSE);

            // If the payment failed, store the data back in the session and
            // halt the checkout process.

            if(!$pass) {
            $message = 'We were unable to process this payment. Please verify your details and try again. If the problem persists, contact us to complete your order';
            return array(array('pass' => FALSE, 'message' => $message ));
            }

          }

        break;
    }
}

?>

The next "gotcha" is that the return value from uc_payment_process() is only TRUE if your callback function defined by the gateway returns an array that looks something like this (but with success = TRUE). Check out the uc_credit module for more clues.

<?php
$result = array(
    'success' => FALSE,
    'comment' => 'Invalid transaction type',
    'message' => 'Invalid transaction type',
    'data' => array(
        'module' => 'uc_securepaytoken',
        'transaction_id' => 0,
    ),
    'uid' => $user->uid,
    'log_payment' => 0,
);
?>

For further reading check:

http://api.lullabot.com/uc_payment_process - API Reference
http://www.commerceguys.com/resources/articles/122 - Post explains uc_payment_process() and a few other UC API concepts but no explicit reference to hook_order() unfortunately :(


How to add a Library as a dependencies in another Library?

You can add another dependency by using custom module

function hook_library() {
  // Library One.
  $libraries['library-1'] = array(
    'title' => 'Library One',
    'website' => 'http://example.com/library-1',
    'version' => '1.2',
    'js' => array(
      drupal_get_path('module', 'my_module') . '/library-1.js' => array(),
    ),
    'css' => array(
      drupal_get_path('module', 'my_module') . '/library-2.css' => array(
        'type' => 'file',
        'media' => 'screen',
      ),
    ),
  );
  // Library Two.
  $libraries['library-2'] = array(
    'title' => 'Library Two',
    'website' => 'http://example.com/library-2',
    'version' => '3.1-beta1',
    'js' => array(
      // JavaScript settings may use the 'data' key.
      array(
        'type' => 'setting',
        'data' => array('library2' => TRUE),
      ),
    ),
    'dependencies' => array(
      // Require jQuery UI core by System module.
      array('system', 'ui'),
      // Require our other library.
      array('my_module', 'library-1'),
      // Require another library.
      array('other_module', 'library-3'),
    ),
  );
  return $libraries;
}