I've tried using both and I can say this: it depends on your situation.

Currently, the stable 7 release of the ApacheSolr Integration module can only index nodes.  So if you have non-node entities that you need to index, you have to use the still in progress multientity patch for it.  ApacheSolr Integration can store a lot of different data of content when configured properly.

The Search API does index entites and has a lot of wonderful stuff written for it.  However, Search API only fetches the id of the data you are searching for.  This means to load any more data other than the ID will require an entity_load, hitting your database or whatever caching layer you put in place.  For search-heavy sites, this might not be the most optimized solution.

Here is a great presentation given at drupalcon chicago about the ApacheSolr Integration module, minute 16 for mentions to Search API.


The answer is to filter by content type:

{
  nodeQuery(
    filter: {
      conditions:[
        {operator: IN, field: "type", value: ["global_content"]},
      ]
    }
  ) {
    entities {
      ...on NodeGlobalContent {
        title
        body {
          value
        }
      }
    }
  }
}


560 tables isn't that much (D7 produces a lot more because of one field => 2 tables) but 150 content types is a lot, that's for sure. This will result in huge caches that Drupal needs to carry around all the time.

I assume that site uses content types to store any kind of data, including internal stuff that isn't displayed?

Using content types for anything that is displayed on the website usually makes sense, you also get a lot of integration for free (e.g. views). However, having a huge amount of content types, doesn't scale well as you found out so you might want to go through your content types and convert some of them to custom tables.

In Drupal 7, it is common to define entities for custom data structures, especially things that are not content (see drupal commerce, search api and so on for examples).

There, is, however, no official or technical limit of content types that you can have. I'd recommend using xhprof to profile the site, if you can e.g. show that the site is using a huge amount of memory because of that, that might be a good argument.


views 3: select only one value from a multivalue field

It under the "multiple field settings" in the settings of your image field.

You should choose "Display all values in the same row", separation mark: "", display 1 item, offset 0. (translated from my own language so names might be a bit different)

UPDATE
You will need to display fields rather then the whole node though. (I don't know how you did this before)


How to display view with context filters as a block in sidebar?

I got it!

Create views block type display that requires context filters.
Create block with PHP filter content type.
Put into it code:

<?php
  $node = menu_get_object();
  $field = field_get_items('node', $node, 'field_NAME');
  echo views_embed_view('VIEW_NAME', 'block_1', $field[0]['value']);
?>

(this eventually can be moved into custom module to avoid using PHP filter)


Can not see test modules in module install page

Test modules are under module_name/tests/ or module_name/tests/directory and can be enabled by TestDiscovery service. As ExtensionDiscovery::scan() calls TestDiscovery::getExtensions() method with $include_test flag TRUE.

The flag can be overridden by settings:
    if (!isset($include_tests)) {
      $include_tests = Settings::get('extension_discovery_scan_tests') || drupal_valid_test_ua();
    }

See also ExtensionDiscovery::scanDirectory
 and RecursiveExtensionFilterIterator::acceptTests()

For manually enabling and testing a test module, it could be moved under modules directory (from /tests) and move back once development done to enable it via test.


In my case, I was able to solve this by taking the response from Drupal.ajax and just parsing it myself into the command I needed to run:

                google.maps.event.addListener(marker, 'click', function() {
                    console.log(this.nid + this.title); //#DEBUG
                    $.ajax({
                        url: 'search-map/ajax/' + this.nid,
                        success: function(data,status){
                            for (var key in data) {
                                if (data[key].command == 'invoke') {
                                    console.log(data[key].arguments[0]); //#DEBUG
                                    $(data[key].selector).html(data[key].arguments[0]);
                                }
                            }
                        },
                    });
                });


Autopopulate "Postal Code" from taxonomy in Location module

I think the only way to do this is with a custom module.

You would implement hook_form_alter to disable (or hide altogether) the location postal code on the node form.

You would then implement presave op of hook_nodeapi (drupal 6) or hook_node_presave (drupal 7) to fill in the location data.

If you don't know PHP, you could also add some custom javascript that changes the location postal code when the taxonomy drop down is changed.


Any way to create a permissions-like sea of checkboxes?

Are you looking for Node Permission Grid module ?

This will give permission grid like


how to send variable from .php file to .js file?

You should use drupal_add_js() in your module, there is no need to output the variable in your .tpl.php:

drupal_add_js(array('YOURMODULE' => array('testvar' => $testvar)), array('type' => 'setting'));

And in your JavaScript, you can the access the value in Drupal.settings.YOURMODULE.testvar:

alert(Drupal.settings.YOURMODULE.testvar);

Direct usage of global variables (as suggested in your code sample) is a discouraged practice in JavaScript as it clutter the global namespace. Also, if your code is triggered on page load, check the "Behaviors" section in Managing JavaScript in Drupal 7 documention (the whole page is worth reading).


Programatically created node type does not display title field

Drupal does not display the title field in the manage display page by default.

You would have to use Display Suite Module and enable a layout for the page to get the title and other fields to display in the Manage Display page.


The views slide show in Drupal 7 in my opinion is even better than in 6 as it start right of the bat with the jQuery Cycle library and that alone will give you a lot of nice effects plus all the extra tools like pagers, counters and controls.

Check the last tutorials on the modules pages page to learn more about the installation and configuration including the thumbnail pagers.


Programmatically get View Custom Image filed url

Your field_image_ads looks like an entity reference field, so try this:
$entity->field_image_ads->entity->getFileUri();


How to keep Drupal site code in version control in sync with production code when using drush updates on servers?

You really have two options:

Assuming you are deploying code to your test server by cloning your code base from a service like github then you can always go in the reverse direction for security patches. You can patch your test servers (or even Prod, though thats not recommended) directly, commit the patched changes to your local git repo on your test server and then push that commit to your remote repo on github. On your local development server you can now pull from your remote git repo on github and everything is in sync.
Alternatively (and probably less optimal) you can patch your code on your test server directly AND you can simultaneously apply the same patch to your local code base. This way the same changes should be made in both places. This method is DEFINITLY not as good because it makes A LOT of assumptions about how well you are keeping everything in sync, but it can work.


How do I exclude a node from an entity reference field?

Welcome to Drupal Answers :)

You are right, you can do that with the help of a Relationship and a Contextual filter, but details are important.

In your Latest articles Views add the Relationship named something like Content referenced from field_myERfield for your featured article field. Be careful about the wording there because there are two Relationships available for the same field, you want the "backwards" one. Don't require the Relationship, otherwise you'll get no results if your home page isn't an article type.

Add the Contextual ID filter and set it to use the Relationship you've just added. Provide default value and choose Content ID from URL. Under Validation choose Content and Article, and other options that make sense in your case.

Then under More choose Exclude. That is how you exclude the currently featured article(s) from the latest articles list.

If you don't choose Exclude you'll only see the featured article in the results.


The best practice is to find some way to implement your feature that does not require patching the original module.  Sometimes this is not possible due to lack of available hooks to provide the functionality that you want.

In these instances, you can try out some of the patch-management solutions, such as bandaid or drush-patchfile, which might help you out here.

Sometimes, though, the changes made in the security update will prevent your patch from applying cleanly; in this case, you have no choice but to re-roll the patch, and figure out what changes need to be made to get it working again.  This makes your site maintenance much less convenient, so it's always best to try to work with the module maintainer, and see if you can get your feature added as a standard part of the module, or, failing that, perhaps get the maintainer to add the hooks that would be needed to add in the feature without patching.


How to do some calculations using fields within a Field Collection field?

You can do it by using Computed Field.
The sentence
$sum = 0;
$wrapper = entity_metadata_wrapper($entity_type, $entity);
foreach($wrapper->field_FIELDCOLLECTION as $collection) {
$sum += $collection->field_SUBFIELD->value();
}
$entity_field[0]['value'] = $sum;


Why doesn't my token redirect to the previous url?

If you want to Redirect to previous drupal page after login, you can try this.

print l("Login","user/login",array('query' => drupal_get_destination()));

see drupal_get_destination


Sounds as if you are looking in the wrong place to integrate your module with Drush.

You need to create a drush folder within your custom module and create a YOURMODULE.drush.inc file inside with appropriate Drush hooks.

Here's an example code:

/**
 * Implements hook_drush_command().
 */
function boilerplate_drush_command() {
  $items['boilerplate-hello'] = array(
    'callback' => 'boilerplate_hello_command',
    'description' => dt('Sample Drush command for boilerplate module.'),
    'bootstrap' => DRUSH_BOOTSTRAP_DRUSH,
    'arguments' => array(
      'name' => dt('Optional. A name which will be greeted upon running the command.'),
    ),
    'aliases' => array('boilerplate-hi'),
  );

  return $items;
}

/**
 * Implements hook_drush_help().
 */
function boilerplate_drush_help($section) {
  switch ($section) {
    case 'drush:boilerplate-hello':
      return dt('Sample Drush command for boilerplate module. It will just greet you, optionally with a name you provided.');
  }
}

/**
 * Command to download the Chosen plugin.
 */
function boilerplate_hello_command() {
  $args = func_get_args();
  $name = (!empty($args[0])) ? $args[0] : FALSE;

  if ($name) {
    drush_log(dt('Hello @name!', array('@name' => $name)), 'success');
  }
  else {
    drush_log(dt('Hello there!'), 'success');
  }
}

This will allow you to run the command using drush boilerplate-hello or drush boilerplate-hi (alias). If you pass an argument, for example drush boilerplate-hello ninjascorner it will take it as an argument, which is the functionality you need.

This is taken from my Drupal module boilerplate. The Drush integration from there is working, so you can install the module and play around with it to see how it works.


ajax path is not supported anymore I think. It would need to be a route.

Why do you need a path? The common way to do this is to have a #submit callback on that form element, then just that will be called.


How do I move a site from a server to another one?

In a nutshell, moving a Drupal website from one host to another is just a matter of moving the files and the database, and then connecting the two.

However, there are several things you need to consider:

Server environment should be as close as possible to each other. This way you will avoid any errors that are a result of having different software/configuration on production and development servers. Compare PHP version, MySQL version, Apache modules, and setup of all of these components.
File permissions need to be set up properly. I've seen problems caused by this dozens of times. In short, the Apache user needs to have enough permissions to access and work with your Drupal website. Otherwise, it won't be able to write and even read files in some cases. Read more about how to secure correct file permissions here.
If you do this manually via FTP, make sure that all files are transferred. It often happens that one of the files wasn't uploaded completely. This usually results in broken Drupal site and random errors. Other ways to migrate a D8 website are Drush, Git or simply zipping the whole directory and using wget on the other server to transfer it directly from server to server.
You will need to clear all caches. Preferrably you won't have CSS/JS aggregation and page caching turned on when you migrate the database. You can do this through SQL/phpMyAdmin. See this answer for more information.
Update trusted hosts in /sites/default/settings.php file.
Once you can access your website, update the temporary directory path at /admin/config/media/file-system, as well as any other settings (e.g. of contrib modules) that store server paths/domain name.

See also docs on migrating a D7 site. Most items are still applicable for D8.

If you follow the guidelines above, you will avoid most issues. If you still have problems after migration, post here the exact log messages you're receiving.

Regarding the error you already posted: I'd make sure that all files are there, and that your cache is cleared before doing anything else.

Hope this helps.


For Drupal 7, a better style is to use field_get_items. E.g.:

<?php
  $body = field_get_items('node',$node, 'body');
  print $body[0]['value'];
?>


How do I move conditional library includes out of a twig template?

Attaching libraries in Drupal 8 should be done by either attaching the #attached attribute to render arrays or by adding them to the info file to be added to all pages.

For example let's say I have a custom form class that needs my custom javascript and/or css files.

class MyForm extends FormBase {
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['#attached']['library'][] = 'my_module/my_library'
    return $form;
  }
}

If you want to attach a library to an element you didn't initiate then you will need to use an alter hook for that specific element.
If you want to attach a library based on other conditions then you can use the hook_page_attachments(array &$attachments) function


Conditional clauses with Entity field Query

In the alter hook, you should not be calling execute(). You don't want to run the query at this point, just change it.

function mymodule_query_or_alter(QueryAlterableInterface $query) {
 $or = db_or()->condition('field_a',$term->tid)
       ->condition('field_B', $term->tid);
 $query->condition($or)
}


Drupal 6 - Using node_view and display comments

You probably need to use the node_show() function instead; it outputs the node as well as its accompany comment thread and comment form. node_show() relies on node_view() to print the node itself, but also calls comment module's code to build the rest.

One good rule of thumb for tracking down these scenarios is to visit the api.drupal.org site, look up the function that you're using to output a portion of the information you need, and look at the functions that also call it in Drupal core.


This issue has been fixed in the latest dev release of the Webform module.

https://www.drupal.org/project/webform/issues/3015020


What permission restricts access to run updates in Drupal 7?

The permission is Administer software updates


How to implement search autocomplete for specific content types?

Create a new view of content. Click on + Add  select Autocompletion Callback and add a path/url to it.

In Filter add Type filter so only shows certain content types.

In /admin/config/search/search_autocomplete edit the search block

For WHAT - WHAT TO DISPLAY IN SEARCH AUTOCOMPLETE SUGGESTIONS? change this to your view's autocompletion callback.

For more info read the documentation.


Yes , this is good idea, in one of my past work we do something like this, dedicated  drupal core but with separate content .


Permission creating taxonomy terms per vocabulary

For Drupal 6, this looks like the module for you: Vocabulary Permissions Per Role


Programmatically create user in another Drupal site

One clean way to do this is using a web service with the services module. You could then expand to being able to create users through javascript or another server without direct access to that database.

It's easy to make your own resources to do exactly what you want.

It comes with native support for core functions, including registering users using the user resource. It's worth mentioning that the maintainers are happing to add new resources that support handling core functionality.

There's also other modules that extend services to provide single sign-on for example.


How to print the relative url or node id for each referenced node in twig?

You probably need to work more in UI to configure what is in {{ content }} and then render the fields as they are.

If still necessary you can use {{ node }} respectively {{ paragraph }} to access all field values, see How to retrieve value of hidden field in twig?, but you can't access the url directly. You have to build this with the help of the raw database value target id, see How to print the URL path of a referenced node using paragraphs?.

BTW the result is the same as the entity method toUrl() would provide, only that this method is blocked by the twig sandbox policies. As a third (least favourable) option you can change this, too, see https://stackoverflow.com/questions/40091324/allow-new-methods-in-sandbox-policy-in-twig-drupal-8


Lock Workbench content until moderation state change

There is a really cool module called Rules Forms that could help here.
https://drupal.org/project/rules_forms

You have to set it up so that it works with your particular content type. See admin/config/workflow/rules/forms
Create a Rule and set two Events "XX node form is being built", and "XX node form is being validated", where XX is your content type
Set an Action called "Set an error on the form" and then choose "Title" for lack of something else, and then enter a message about this node being locked.
Set up the conditions as needed - probably need to check the user id and the state of that node - this is the part where I can't help without seeing your particular site.

If you don't set any conditions, nobody will be able to create or edit nodes of this type until you do.


Take a look at https://www.drupal.org/node/2492033 and check if your links to anchors are with or without a path. You could maybe use Void Menu to make special links without path.

As an alternative to this module I recommend to take a look at: Jquery Localscroll


EntityManager is deprecated moving forward.  The following can be used instead:
$entityFieldManager = \Drupal::service('entity_field.manager');
$fields = $entityFieldManager->getFieldDefinitions($entity_type, $bundle);

Whereas $entity_type can be 'node' and $bundle can be 'article'


Importing Nodes to D7 with all custom fields

The Feeds module (sucessor to the FeedAPI module) has that functionality built in.

For your needs specifically it offers:

Import or aggregate CSV files
Create nodes, users, taxonomy terms or simple database records from import
Granular mapping of input elements to Drupal content elements


Allow comments only for author of the node and certain role

You can probably unset the comment form using hook_form_alter on the basis on certain condition:

function MODULENAME_form_alter(&$form, &$form_state) {
  if ( $form_id == 'comment_form') {
    global $user;
    if (!user_access('administer nodes') {
      // Form alter here to unset comment form
      unset($form);
    }
  }
}


For an action that is caused by an event I would use the Rules module.

Create new rule

Set rule name, etc.

Set event to act on - saving new term

Set a condition - term is in vocabulary album

Set action - add menu item

These options may not all appear with just Rules.  You may need additional rules modules to get some of these events, conditions, or actions to be available (I think there is one for menus and one for taxonomy, but they may be built in to rules i can't remember.).

Take what I said as a starting point to put you in the right direction.  Definitely sounds like what you want can be done with Rules.


How can I give a list_string BaseFieldDefinition in a content entity a default starting value?

You can use setDefaultValue method:

BaseFieldDefinition::setDefaultValue([['value' => 'red'], ['value' => 'green']])

That will also work for entities not created in the UI.


What will happen if I restore backup DB with empty session table?

The main issue is that people will need to log in again.

A side effect of this is that any session data that your site may have saved for users will also be gone.  This is usually a nuisance, and not a major problem, though.

Personally, I have never had any problems caused by either not restoring {sessions} or manually clearing out the table, either via DELETE FROM {sessions} or a drush command.


Configuration management is a major initiative in the upcoming Drupal 8. Here's Dries talking about it.

In D7, you'll need cTools and Features and Strongarm. And here's a comparison of staging/deployment tools.


Field Permission Issue even without Field Permission Module

Sorry to trouble you guys, but I figured it out just now. It was really a silly mistake from my side, but I had been hitting my head ever since.

Anyways, turned out that I had not provided the permission to the user for that particular text format!! The article was created by admin using "Full HTML" but the user had no permission for that format.

Anyways, I figured it out using a hack method which was really cool.

The text box was showing this message when it denied permission :

This field has been disabled because you do not have sufficient permissions to edit it.

I copied this and searched for this complete sentence in the contributed as well as core modules' directory. The "culprit" was filter.module. The function which was doing this was properly commented and said that "deny the users with no permission to the given text format".


change the date format to dd/mm/yyyy in views of the webform

Visit admin/settings/date-time/formats in you instance & add a custom date format. See PHP manual for the options which you can.

Use your created date format to show the field value wherever you want like views.


you should always use some or the other Mail Transfer Agent (MTA) like Postfix, which helps in managing queue in-case of emails getting lost


Difference between theme.info and drupal_add_js ( jquery-2.0.3 )

Generally speaking you should avoid adding third-party libraries directly from your module. If all modules would do that, your site would end up with multiple loads of jQuery/Modernizr/Backbone/etc.
First see if there is an existing module for that, and if not - use Libraries API to declare a dependency in your custom module and then load the script afterwards. This way if some other module depends on the same library and declares dependency through Libraries API, Drupal will load only one file automatically, avoiding conflicts.
For jQuery, check out jQuery Update module. Drupal itself uses jQuery for forms and other elements, so it is not enough that only your module or theme work on the latest jQuery. All core widgets, effects and AJAX calls need to be ported for specific version. That's why  jQuery Update module exists - it upgrades the version of jQuery and loads updated Drupal scripts instead of the original ones, so the site does not break.
Regarding the differences between drupal_add_js() and adding a script filename in the theme.info, here's a summary:

When you add a script to theme.info file, it will be automatically loaded for all pages displayed with your theme. This means that if you are using an administrative theme, such as Rubik, your script will not be loaded on pages where you use that theme.
With drupal_add_js() you can load a JS file only when you need it (e.g. only on certain pages, for certain roles etc.).
drupal_add_js() also provides you with additional functionality, such as inline JS for variables.

Hope this helps.


Allow anonymous users to subscribe to newsletter/mailing list

Sounds like your site can not send e-mails for whatever reason.

The default newsletter settings require to confirm a subscription, you can disable that in the newsletter settings, optionally also only for testing until you've figured the e-mail problem out.

Unconfirmed subscriptions aren't displayed in the UI, that's why you can't see anything.

Instructions on how to use and configure Simplenews can be found in the README.txt and the online documentation.

Note: You're asking a lot of different questions, and your actual problem (sending e-mails being broken) has nothing to do with initial question (you might not have known that, so that's ok). Remember that you're supposed to accept a (single) answer as the correct one, how can you do that if you ask multiple, different questions?


How do I integrate queries to legacy databases?

Welcome to Drupal (and also Drupal answers) :) Glad to hear that you've chosen Drupal.

Although the scope of this question is pretty big, I'll try my best to answer. Feel free to ask more questions.

You might want to first check out whether Drupal fits in your requirements. You can check Case Studies of different sites which were built (from scratch or migrated) on Drupal. See if it gives you any idea.

If Drupal does fit into your requirement (mostly it does), you can check if there is any Drupal distribution present which is closer to your requirement (e.g. Commerce Kickstart distribution is a customized Drupal installation which is modified to provide features for a typical e-commerce site; while OpenPublish distribution is for news/articles publishing).

You don't need to develop a module per page. If you come across any requirement, there is a popular saying which goes "There's a module for that", which just means that there is a possibility that someone else who faced the same problem came up with the solution in the form of a module. You can search the list of modules on the official Drupal.org site, or drupalmodules.com, or just google it ;-)

You might also check for the Migrate module, which provides out of the box support to migrate sites powered by other technologies to Drupal (with some customization).

If you get any queries in your Journey to Drupal Land, you're always welcomed here on StackExchange's Drupal site :)


Taxonomy formatter that shows a list of links to related nodes

You set up a contextual filter on the View Block to Content: Has taxonomy term ID.

So we need to hand this view a term ID. Since we're going to be calling this block using Context. There won't be a default value given in the URL. Therefore we have to give it one.

Select

Provide Default Value
Load default filter from node page, that's good for related taxonomy blocks
Choose your default vocabulary


How to remove "catalog" from Ubercart Catalog View URL

Logical we can't change the way the catalog link generation of Ubercart. The format must be catalog/term_id (with default way) and catalog/term_name (With pathauto module). For me the only thing we can deal with that is creating the URL Aliases manually.


Errors when Taxonomy is chosen in node's Term Reference field

This EntityMalformedException: Missing bundle property on entity of type node errors seems to rear its ugly head in a lot of different contexts.

In my case it was a configuration of the view that showed the related nodes that had a couple of filters set wrong.

I had a relationship to related articles, but then in the filter section, Relationship was set to "Do not use a relationship" instead of using the related article. Setting the correct setting on the filter fixed the issue.


This is a known bug in Drupal core for 6.x and 7.x


Using a custom field as a sub-field in another custom field

Basically, the question is how to use a custom field in another field as a property.
In an entity a custom field is added by using BaseFieldDefinition::create(). However a property of a field type is added by DataDefintion::create() or MapDefinition::create() and only basic types are defined (in DataDefintion class) to be used as DataDefintion. So It doesn't look like it is possible to have a custom field in another custom field.
References:

Fieldable field explains the problem of having a field inside a field
Entity API explains how each data type and field type are defined.
Same issue filed in d.o at #2874458


How to disable links in taxonomy term node fields

If I understand your question correctly you can change it on the 'Manage Display' tab of your content type, make sure to select 'Teaser' at the top right

If you're using the build in article type it is at admin/structure/types/manage/article/display/teaser


Can the Devel Generate module generate content for all possible permutations and combinations?

To my knowledge there is no such feature in the Devel Generate module.

Therefor, as an alternative, I recommend to use a (rather basic) custom module for creating such nodes (so without using Devel Generate).

The article about How to programmatically create nodes, comments and taxonomies in Drupal 7 contains great example of how to do so. Here is a summary of that article (about how to programmatically create a node):

  Initialize a node object
  Add body field
  Add custom fields
  Add file / image field
  Add a term to a node
  Save a node

You probably don't need the "add file" and "add term", and simply have to repeat the "add custom fields" a few times (for each of your 3 fields), and then "you" are in full control of which permutations/combinations you actually want.


You could try adding an 'event' item to the ajax array in your FAPI code. The form needs to know when to trigger the ajax callback. The FAPI documentation says you don't have to specify it explicitly but try 'event' => 'change', and see if that works for you. Since you are not specifying it, perhaps the default one that Drupal uses is not right for a select type.

See https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x#ajax_event


Add JavaScript to a page without access to core files?

If the developer has granted your user role access to the appropriate input formats and and has it configured to allow JS then yes, you can.

You may see a select box under one or more of the fields that allows you to select a filter such as "filtered HTML", "Full HTML" etc..

This is however normally locked down to prevent content editors from breaking a site, so I would be surprised if your limited role had access to unfiltered HTML/JS input.

A quick way to test if it works would be to add <script>alert('test');</script> in the box and save/refresh the page.


Try using the panels module.  Although it will require some learning, you can use the Panels module to "override" the way nodes are displayed (you can choose from all nodes or overriding specific content types, specific user roles, etc.)

Using this approach, you can make a "page" view display as a block.  In fact, with Panels, you can basically use any content in Drupal as a  "block."  This power does come with some complexity but it should allow you to do what you want with some experimenting.


Import multiple node reference from CSV using feeds

I would recommend you the Node Import module for Drupal 6. It's very powerful and works great with references.


Use different view modes for your entity (node).  Each view mode (also called a build mode) can have different template (.tpl.php) files.  Use hook_entity_view_mode_alter to decide which view mode to use (based on your user's selection).

You can use the View Modes module to create custom view modes.


Label for Child in Simple Hierarchical Select by using a module

I guess this is possible by Client side hierarchical select.

Let me know if there is any other option.

Thanks.


How do convert mysql query with sub queries to a db_select version?

I found the answer, see below. (I added a few more fields as well)

  $sub_query_1 = db_select('field_data_field_address_2', 'addr2');
  $sub_query_1->fields('addr2', array('field_address_2_value', 'entity_id'));

  $sub_query_2 = db_select('ms_order_adjustments', 'a');
  $sub_query_2->fields('a', array('display', 'oid'));

  $sub_query_3 = db_select('field_data_field_company', 'comp');
  $sub_query_3->fields('comp', array('field_company_value', 'entity_id'));

  $query = db_select('ms_order_products', 'p');

  $query->fields('p', array('id', 'oid', 'type', 'amount'));
  $query->fields('o', array('oid', 'uid', 'status', 'order_type', 'created'));
  $query->fields('u', array('uid', 'mail', 'name'));
  $query->fields('fn', array('field_first_name_value'));
  $query->fields('ln', array('field_last_name_value'));
  $query->fields('adr1', array('field_address_1_value'));
  $query->fields('city', array('field_city_value'));
  $query->fields('state', array('field_state_value'));
  $query->fields('zip', array('field_zip_code_value'));
  $query->fields('pa', array('field_address_2_value'));
  $query->fields('pa2', array('display'));
  $query->fields('pa3', array('field_company_value'));

  $query->leftjoin('ms_orders', 'o', 'o.oid = p.oid');
  $query->leftjoin('users', 'u', 'o.uid = u.uid');
  $query->leftjoin('field_data_field_first_name', 'fn', 'u.uid = fn.entity_id');
  $query->leftjoin('field_data_field_last_name', 'ln', 'u.uid = ln.entity_id');
  $query->leftjoin('field_data_field_address_1', 'adr1', 'u.uid = adr1.entity_id');
  $query->leftjoin('field_data_field_city', 'city', 'u.uid = city.entity_id');
  $query->leftjoin('field_data_field_state', 'state', 'u.uid = state.entity_id');
  $query->leftjoin('field_data_field_zip_code', 'zip', 'u.uid = zip.entity_id');

  $query->addJoin('LEFT', $sub_query_1, 'pa', 'u.uid = pa.entity_id');
  $query->addJoin('LEFT', $sub_query_2, 'pa2', 'o.oid = pa2.oid');
  $query->addJoin('LEFT', $sub_query_3, 'pa3', 'u.uid = pa3.entity_id');

  $query->condition('p.id', 'RM11', '=');

  $result = $query->execute();


Different CSS file when in development mode

You can specify two different libraries in mymodule.libraries.yml. Then in your mymodule.module file attach the one that matches your current deployment env:

function mymodule_page_attachments(array &$attachments) {
  if (PRODUCTION) {
    $attachments['#attached']['library'][] = 'mymodule/lib_prod';
  } else {
    $attachments['#attached']['library'][] = 'mymodule/lib_dev';
  }
}

I am using code like this to decide on which deployment level I am:

  public static function getDeploymentStage() : string {
    // lazy cache
    static $ds = null;

    if (null == $ds) {
      if (isset($_SERVER['SERVER_NAME'])) {
        switch ($_SERVER['SERVER_NAME']) {
          case 'anwalt-seiten.de':
          case 'www.anwalt-seiten.de':
            $ds = AsdentBaseService::DS_PROD;
            break;
          case 'stage.anwalt-seiten.de':
            $ds = AsdentBaseService::DS_STAGE;
            break;
          default:
            $ds = AsdentBaseService::DS_DEVELOPMENT;
            break;
        }
      } else {
        $ds = AsdentBaseService::DS_DEVELOPMENT;
      }
    }

    return $ds;
  }

Note that any drush command will run in dev-mode here.
You can also use $settings from settings.php or any environment variable instead.


Node template suggestion stopped to work for new content types

This was due to the strange Caching issue, source of which is yet unknown to me. It may me somehow connected to APC caching, or to nodeaccess cache. I am not yet sure.

After nervous session of clearing different layers of cache, i somehow get it to work.


how to create Views exposed filter with fields from custom table

It should depend on how you are exposing the field to views, make sure views know about field  and filter handler, so as an example in your hook_views_data() your title field should be exposed in following way -

// name field
$data['exposed']['title'] = array(
    'title' => t('Title'),
    'help' => t('title for record'),
    'field' => array(
        'handler' => 'views_handler_field',
    ),
    'filter' => array(
        'handler' => 'views_handler_filter_string',
    ),
 'sort' => array(
        'handler' => 'views_handler_sort',
    ),
);


Have you checked: How to Add a jQuery UI Dialog to Drupal 7?

There is also Drupal 7 jQuery (Popup e ui.dialog), in Italian.


Cache Backport not loading correctly. Unable to change cache.inc location?

The Domain module was in fact responsible for this. I moved include './sites/all/modules/domain/settings.inc'; to the very end of my settings.php file and everything started working.

I then added the following code to ensure a different cache_prefix for each of the domains.

$thishost = $_SERVER['HTTP_HOST'];
$site_arr = explode('.', $thishost);
$sitename = $site_arr[1] . '_';
$conf['cache_prefix'] = $sitename;

Credit for that code goes to Drupal 6 APC with domain access module not working for (sub-)domains. In fact, now that I look at that page again, I notice that he has the domain access include on the last time, too. Audible sigh. Don't know how I didn't notice that before.

It also appears that if you want to move Domain's settings.inc to the bottom, you need to make a tweak to that file. Modify modules/domain/settings.inc so the domain_settings_setup_ok function looks like this:

function domain_settings_setup_ok() {
  static $state = NULL;
  if ($state === NULL) {
    if (!empty($conf['cache_include'])) {
      $state = TRUE;
    }
    else {
      $state = !function_exists('cache_get');
    }
  }
  return $state;
}

That is an adapted version of the patch for D7 discussed at https://drupal.org/node/1240472.


How to show the parent and child taxonomy term?

Views can do this. Views is a UI for sql searches so you are setting the definition for the query that will be made of the content database.

Create a view to display a taxonomy term with a page with a path configured along this line category/%. The % is a wildcard that will make the view respond to any value applied in the URL that matches this format.
Set up your display and any filters desired.
Define a relationship (third column of view UI page) and set it to taxonomy term: parent. This tells the view to look at the parent field in each taxonomy term searched. (Note that Drupal includes a field for each term that identifies its parent, but not its siblings or children).
Next we tell the view to interpret the wildcard from the URL we used in the path for the view: Define a contextual filter (above the relationship selection) and set it to a taxonomy:termID. In the form, set the relationship to Parent in the drop down box. This tells View that the term being called in the URL will be applied as a filter for the 'parent' field of the taxonomy terms as they are searched.
Finally we must complete refining the contextual filter. You can tell the view what to do if it does not find an answer in that section of the form if you want, but we must tell it what to do if it does find solutions in the query. To do so check the validation check box. Set the Validator to Taxonomy term and select the vocabulary that applies to your hierarchy. Then select either Term ID or Term name converted to term ID as the Filter value type. If the value you are passing in the % is a term ID, then you are done. If the passed value is a term Name, then you may want to check the box to convert dashes to spaces. IF you have multiple word term names, the URL will have dashes, which do not match the actual spaces in the term name. This little correction makes them agree so a test succeeds.
Finally go to the preview area and enter the name or ID for a term you know has children and you should get the list of children terms. Use the sorting settings to arrange them in whatever order you need.

Good Luck!


Why can I choose the widget for grouped filters, but not exposed?

I can see two possible solutions to this problem:

Solution 1: Better Exposed Filters

Install the Better Exposed Filters module. There are over 31,227 sites using it at the moment. Don't let the fact that it is in alpha hold you back unless your organization has a policy preventing you from using alpha releases.

Solution 2: Custom Code

If you cannot use Better Exposed Filters for some reason, then write a hook_form_FORM_ID_alter() to modify your views exposed form the way you want.

Sample code

Create a hook_form_FORM_ID_alter() in a custom module. In the example below, the module name is custom_general.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function custom_general_form_views_exposed_form_alter(
  &$form,
  FormStateInterface $form_state,
  $form_id
) {
  $view_data = $form_state->getStorage('view');

  // Content administration.
  if ($view_data['view']->id() === 'VIEW-ID') {
    // Analyze the structure of your form with kint().
    // Say, the field that matters to you is "field_foobar".
    // kint($form); exit;

    if (isset($form['field_foobar']) {
      $form['field_foobar']['#type'] = 'select';
      $form['field_foobar']['#multiple'] = FALSE;
      $form['field_foobar']['#size'] = 1;
      // TODO: Do other things as necessary.
    }
  }
}


The HTTPRL project provides you with a non-blocking HTTP client.

$url = url('http://admin.com/synch/index.php', array('query' => $query));
$username = 'admin_os';
$password = 'admin_pass';
$basic = base64_encode($username . ':' . $password);

httprl_request($url, array(
  'blocking' => FALSE,
  'headers' => array(
    'Authorization' => 'Basic '.$basic,
    'Host' => $_SERVER['HTTP_HOST']
   ),
));
$request = httprl_send_request();


How to upload files which are other than English names?

Have a look at the Transliteration module. Here is a quote from its project page:

Provides one-way string transliteration (romanization) and cleans file names during upload by replacing unwanted characters.
Generally spoken, it takes Unicode text and tries to represent it in US-ASCII characters (universally displayable, unaccented characters) by attempting to transliterate the pronunciation expressed by the text in some other writing system to Roman letters.

Here is a sample of what this module does for "file names":


The main performance problem with tokens is the token UI/token browser. You can disable that by overriding theme_token_tree() and returning an empty string. What I once did on a site is replace it it with a link that was able load the browser using ajax, but even that didn't help anymore on a site with ~300 fields and lots of references.

Pathautho/Token don't depend on entity.module?


disable administrator role in add user form

You can create a module that uses a hook, something like

function remove_admin_role_choice_from_add_user_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['account']['roles'][3]['#access'] = FALSE;
}


How to limit number of "Promoted to Front Page" option for each user/role

You can achieve above by writing a small custom module in Drupal... Steps are outlined below to achieve the same.

Create install file and define schema hook with table name as user_promote_counter with below fields
uid, timestamp, nid
Using hook_node_presave($node) update above table with a record of uid, timestamp, nid of the node updated whenever promote is set to true so that you can track only promoted to front page actions.
Use hook_node_validate($node, $form, &$form_state) in your custom module to verify current user who has promoter role exceeded the limit of 5 by querying above table using timestamp and uid columns. Raise an error if limit is exceeded. That will prevent user to promote more than 5 nodes per day.


How to prevent userpoints from repeating

You could put a field on the User entity called something like field_points_attributed and hide it from the authenticated users using Field Permissions.

Then set an action on your rule, so that as well as adding the user points, it also changes the value in the field to something like "yes" or "attributed".

Lastly, add a condition to check the value of that field, and ensure it doesn't say "yes" or "attributed".


in drupal 7 's view, how to comment without redirecting to content type page?

There is an Ajax comments module you can use to post comments without refresh and this post shows how to combine it with views.


How can I see what variables are available on the loaded page via the devel PHP Execute block?

Drupal loads all variables into $variables.

So in the PHP block just load: <?php dsm($variables); ?>.

For dsm to work you need the Devel module installed.


Custom entity - BaseFieldDefinition for entity reference field

The easy solution is to create the field via the interface instead of creating it as a base field. Drupal core still have some issues with basefields not working exactly the same way as config fields (fields created as config via interface). Views is missing various integration, the same goes with date fields.

In your case, where you have a multi valued field, it would be store the same way, the only difference is the table name (ENTITY__FIELDNAME vs FIELDPREFIX_FIELDNAME).

If you really want to use base fields, you can make up from the missing integration by handling it yourself in a custom EntityViewsData class for your entity. Having done this in the past, my advice would be to just create a config field, since that is working pretty well, and doesn't change anything on the way the field is store in the database anyways.


No, it won't be recognized by Field API. By default Drupal uses Field Api and Field Storage API to store field data. It creates two tables for every new field which you create from Field UI (field_data_* and field_revision_*). If you are able to create your own Storage for Field Api then you can use it... Here are some resources:

Field Storage API
Useful discussion


What is the true impact of Panels Everywhere on theming and layout duties?

From my own findings:

Yes. In fact, one can set a site template which (more or less) replaces the concept of regions.
No, one should set a site template and not forget to have a Page Content pane.
None, except for the site template itself. Eventually, some can be set on the Page Content too.


How to link fields from a Content Type to an Entityform field

Thinking of this leads me to the following conclusion. You want to hand over the tablet, meaning it should not be logged in as an administrator or by any other means allow people to see and edit more then then allowed.

So you could do this with simple comments.

Create a content type of event in which you have fields for the date, the name of the event, the location and the recruiter (author?).

Then edit the content type and navigate to this tab:

Here you can add comment fields, including the name and any other information you want from the person. Give anonymous users permission to create comments, but not view them and you are done.
Later if you log in, an admin can edit the comment and add notes.

Another solution would be the webform module. More or less allowing you to create any type of form on any type of node. It comes with a wide variety of fields and a clear admin interface, also allowing exports etc.
Adding notes can be achieved by editing the submission as well.

UPDATE:

I always thought entity forms were for backend forms. You can attach one to a node folloing this tutorial: http://www.sixmiletech.com/content/embedding-entiyform-node

That should solve your entity reference stuggles.

Summary of the video would be to create an entity reference field on the event-node. Configure it to reference to Entity form type(s). On the manage display tab of the content type configure the entity reference to 'Render the entity`.

Now create a node, select the right entity form type and save. You now have a node with an attached form.


Using rules, how do I assign an action to a vbo list item based on its position in the list?

I should have posted this as my answer and not as a comment to my question.  As stated above, the answer would be entity-list:0 token.


This is exactly what the String Overrides module is for.

If you only need just a couple strings, you can also use settings.php.  See this section:

/**
 * String overrides:
 *
 * To override specific strings on your site with or without enabling locale
 * module, add an entry to this list. This functionality allows you to change
 * a small number of your site's default English language interface strings.
 *
 * Remove the leading hash signs to enable.
 */

You don't want to use Rules, because although you can add a new message with a rule, the old message will still be there as well (which isn't what you want, I assume).


Views + Search API not properly sorting by Commerce Price (seems random)

Resolved. Not sure exactly what is/was going on but the price sorting is now working. There was another identically named commerce price field in Views. Adding that field and removing the first one fixed the issue. I know, something unusual appears to be going on but at least the sorting is working now.


How to programmatically load a rendered view exposed filter block

The block content entity is not the block entity that is required there.

The actual block entity is a configuration entity. Use the \Drupal\block\Entity\Block::load method to load it.

Try the following:

$bid = 'exposedformview_nameview_display_name';
$block = \Drupal\block\Entity\Block::load($bid);
$render = \Drupal::entityTypeManager()
        ->getViewBuilder('block')
        ->view($block);
return $render;


You do not need the "Node" Item type. Using the "Content" is going to index all your nodes.


Remove added URLs after link when printing a page

a[href]:after { content: none !important; }

update

The CSS :after selector inserts something after the content of each selected element(s).

Use the content property to specify the content to insert. content: none is for explicitly preventing the after selector (pseudo-element) from being generated (really only used to override another style that would have generated content).

a[href]:after { content: none !important; } will mean remove content after each link.


Switching from Search API Database to Solr

You will need to switch search server for your search index. But I think your view can stay as configured now as it targets a index (which only will change server).

You will also need the module Search API Spellcheck. Then add the "Search: Spellcheck" field to the header of your view. This will output the message “Did you mean "something" in the header if a suggestion is returned by Solr.

You will find the setting for which server your index should use under your index.


Can taxonomy terms contain special characters e.g. ampersands, apostrophes and dashes?

They are safe to use, however you may have issues with your url paths. so in your url if you have a term Theology & Scripture", it becomes this: 'theology%20%2526%20scripture. This kind of urls are not good for search engine optimisation.

You can however use the pathauto module, to correct this issue.

  The Pathauto module automatically generates URL/path aliases for
  various kinds of content (nodes, taxonomy terms, users) without
  requiring the user to manually specify the path alias. This allows you
  to have URL aliases like /category/my-node-title instead of /node/123.
  The aliases are based upon a "pattern" system that uses tokens which
  the administrator can change.


How to "close" from view standard taxonomy page

Luckily there is module for that: Disable Term Node Listings

By default, on taxonomy term pages, Drupal will display a list of nodes (teaser build mode) that are tagged with that term. Disable Term Node Listing allows you to selectively disable node listings on taxonomy term pages by vocabulary.
Disable term listings for a particular vocabulary by going to the edit page [/structure/taxonomy/[vocab_machine_name_here]/edit].


How to edit every node of a content type on cron run?

You would need to implement various hooks.

hook_cron: It will get called on every cron run. Here you could load every node in the system using node_load(), edit whatever properties of the node you need to edit, and then save each edited node using node_save().

However, note that both loading and saving a node is an expensive process, and if you have a site with many nodes, your site would become very slow, unstable, or even unusable on every cron run (which can sometimes happen as often as every 15-30 minutes). In other words, I would be very cautious with whatever you are trying to accomplish.


How to create an average out of 3 Fivestar Fields?

Yes, You can able to do that using hook_node_presave

You can read three field values rating using $node and set using below command

$node->field_name_of_your_fourth_field[$node->language][0]['rating'] = $average_value;


You don't want FileField Sources, you want to use a Node Reference field on the node you want to reference the file on, and you want to change the display of the node reference field with either a Custom Formatter (that you'd need to write yourself) or a standard FileField via the Formatters 4 Node Reference field module.

To change the display of the Node Reference you would want to goto the Display Fields page on your Content Type and select the new Formatter from the dropdown.

A brief demo of what you could potentially do for this sort of system can be seen at: http://www.youtube.com/watch?v=qBXoN25guic


Commerce line item fields - getting value

You can do it using list_allowed_values function

  $field = field_info_field('field_name');
  $allowed_values = list_allowed_values($field);


Enforcing minimum number of characters for #autocomplete_path

Here's two approaches:

Replace the entire autocomplete.js with your customized version

/**
 * Implements hook_js_alter
 * Replace autocomplete.js with customized version
 */
function MY_MODULE_js_alter(&$javascript) {
  $javascript['misc/autocomplete.js']['data'] = drupal_get_path('module', 'MY_MODULE') . '/js/autocomplete.js';
}

Override Drupal.ACDB.prototype.search with a custom version

Copy to theme script.js or module js file, as long as it's added after /misc/autocomplete.js it will override it.

(function($) {

/**
 * Performs a cached and delayed search.
 *
 * Override adds minimum text string length for lookup.
 * See /misc/autocomplete.js for original function.
 */
Drupal.ACDB.prototype.search = function (searchString) {

  // Minimum search string length
  var min = 3;
  var db = this;
  this.searchString = searchString;

  // See if this string needs to be searched for anyway.
  searchString = searchString.replace(/^\s+|\s+$/, '');
  if (searchString.length <= min ||
    searchString.charAt(searchString.length - 1) == ',') {
    return;
  }

  // See if this key has been searched for before.
  if (this.cache[searchString]) {
    return this.owner.found(this.cache[searchString]);
  }
  // Initiate delayed search.
  if (this.timer) {
    clearTimeout(this.timer);
  }
  this.timer = setTimeout(function () {
    db.owner.setStatus('begin');

    // Ajax GET request for autocompletion. We use Drupal.encodePath instead of
    // encodeURIComponent to allow autocomplete search terms to contain slashes.
    $.ajax({
      type: 'GET',
      url: db.uri + '/' + Drupal.encodePath(searchString),
      dataType: 'json',
      success: function (matches) {
        if (typeof matches.status == 'undefined' || matches.status != 0) {
          db.cache[searchString] = matches;
          // Verify if these are still the matches the user wants to see.
          if (db.searchString == searchString) {
            db.owner.found(matches);
          }
          db.owner.setStatus('found');
        }
      },
      error: function (xmlhttp) {
        alert(Drupal.ajaxError(xmlhttp, db.uri));
      }
    });
  }, this.delay);
};
})(jQuery);


Composer shows "nothing to update" but there is a new version of the module

Thanks to @Neograph734 for pointing me in the right direction.

I needed to require Drupal 8.4-rc2 and drush 9, and then Commerce 2 arrived automatically.

Drush 9 appears to be a requirement for the 8.4 core update.


Activate an existing menu item through code

I would recommend using the Context module. You can setup rules for when a menu item is active such as content type or menu path which will save you from writing related code.

This might make it easier to understand as well for someone inheriting your site.


Alphabet sorting does not work properly with unique characters

I ended up with writing my own module. It uses hook views_query_alter and change SQL query little bit. Module does not have any settings in UI but hardcoded variables so you need to adjust it in order to solve issue with sorting.

<?php

/**
 * @file
 * Implements hook_views_query_alter().
 *
 * it adds 'COLLATE utf8_language_ci' to languages that are not supported by default
 * so far there are only few languages we have issues with.
 */
function views_collate_sorting_views_query_alter(&$view, &$query) {
  // views where we want to enable collation
  $views = array(
    'dictionary_overview'
  );

  // exit if the current view is not specified
  if (!in_array ($view->name, $views)) {
    return FALSE;
  }

  // define list of languages we support
  $map = array(
    'da' => 'utf8_danish_ci',
    'sv' => 'utf8_swedish_ci',
    'nb' => 'utf8_danish_ci',
    'es' => 'utf8_spanish_ci',
    'pl' => 'utf8_polish_ci',
  );

  // get current utf8
  $l = $GLOBALS['language']->language;

  if (!array_key_exists ($l, $map)) {
    return FALSE;
  }

  // get current utf8 language which we are going to add to all sort fields
  $utf8 = $map[$l];

  // add COLLATE utf8_xx_ci to all sort criteria
  $orderby = &$query->orderby;
  foreach ($orderby as &$order) {
    $order['field'] .= ' COLLATE ' . $utf8;
  }
}


Drupal 7 uses strip_tags directly in plenty of places (theme.inc, common.inc, etc.).

If there was an equivalent, core would use that instead, so you can safely assume that you should use strip_tags when you need the functionality it provides, not a Drupal-specific method.


How is cron being called? (drush, wget, manually run).

node_delete requires the permission delete to actually execute the delete queries.

Depending on how you run cron will depend on the result, for example if cron is run from wget then it's run as an anonymous user therefore nothing will happen as hopefully anonymous user can't delete content.

If you try calling cron from status report while logged in as uid 1 then it should delete fine.


How do I set BCC in the email I am sending?

Your hook_mail implementation needs to set the subject/body for the email to send; $params is just passed for context.

Given your first snippet, this should work:

function mymodule_mail($key, &$message, $params) {
  switch ($key) {
    case 'test_email_form':
      $message['headers']['Bcc'] = $params['Bcc'];
      $message['subject'] = $params['subject'];
      $message['body'][] = $params['body'];
      break;
  }
}


selecting a referenced node from 1000's of nodes

If you truely need to have a design that needs that many nodes to be referenced, you need to either have data integrity (Make sure that the nodes have proper titles so they can be found with the AC widget), or instead you need to build your own and more advanced widget.

The AC widget is not build for referencing 10.000's of nodes, if that is your need, you should create your own widget, that allows the users to input more data and thus easier find the address node they need. With CCK you can build your own widget.

Building a widget is in itself no small task, and building one that can handle these needs will not be any easier. There are a bunch of blogs with guides on how to do this, and you can look at the CCK module to see how it does it to get a better understanding.

Update:

I don't know what this Area 1-4 is all about, but my hunch is, that this could be built more clever to avoid this mess, I could be mistaking, but it seems like a flawed design, if a user needs to pick a reference from a list of 10.000's.
One way to deal with this, would be to let the user actually enter the address, and behind the scenes search for it. If it exists create the reference, if not create the node with the info and then create the reference.


Is there a git repository for Drupal releases only?

Drupal releases are marked with a corresponding "tag" within the repository. When you clone a git repository, you get all the tags and branches along with it. Running the following command from within the repository will checkout the version 7.8 tag:

git checkout 7.8

To list the available tags, type git tag. To list all available branches, type git branch -a.


Create a custom layout (https://drupal.org/node/1936980)
Comment (or remove) the "breakpoint" in the scss (or sass).


What complications are there if I switch Mysql to MariaDB? Any Drush issues?

As you say, Maria DB is a drop-in, completely transparent replacement for MySQL. Its releases coincide with the same major/minor version of MySQL so it's pretty much always in tandem as far as features are concerned. It reads the standard MySQL binary data files, uses the standard systen my.cnf, and even has a drop-in replacement for InnoDB.

The idea is that as far as your application is concerned it thinks it's connecting to a MySQL server. It uses MySQL drivers, issues full MySQL statements, and receives responses exactly as the MySQL server would send. Your app(s) won't know the difference.

I've been using Maria for a while now for Drupal sites (also using Drush extensively) and haven't had a single problem to date. If you're running *nix upgrading is just a two minute job.


You may want to try to alter it with a preprocess function:

function example_preprocess_field(&$variables) {
  $field_name = $variables['element']['#field_name'];
  if ($field_name == 'field_example_field') {
    // Your code here.
  }
}

I ran a test to modify $variables['element']['#attached']['js'] but Drupal didn't recognize the changes to the element. Not sure why. So, you may have to use drupal_add_js.


drupal_http_request with basic authorization receives 401 response

If you're using Drupal 7, then I'm fairly certain you're supposed to put everything after the URL into a single options array instead of positional arguments. This was done so you can pass some arguments without passing all of the preceding ones.

https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_http_request/7

drupal_http_request($url, array(
  'headers' => $headers,
  'method' => 'POST',
  'data' => http_build_query($data)
));

should work.


Please refer these modules, would be helpful

nodesinblock and nodeblock


Drupal 8: how can I "eager load" Entities referenced via EntityReferenceFieldItemList field

This doesn't exist in Drupal, you can't load entities of different types at once, the best you can do is load all referenced entities of the same type at once, which is what referencedEntities() does.

Each entity type has its own storage handler which doesn't know anything about other entity types, as far as those handlers are concerned, those other entities might not even be in the database but stored in MongoDB or text files.


Drush rsync command failed: No such file or directory

Make sure the string containing the directory does not have extra blank spaces at the end. Trim it if possible. I was getting a similar message when I was using the option --files-from=myDirList and I have some spaces after the directory name inside the myDirList.


Remove header and footer of the page when export node to pdf using print module

Go to

Home » Administration » Configuration » User interface » Printer, email and PDF versions

then in SETTINGS page, check option none in FOOTER OPTIONS tab.


Maybe this help others.
If you are using drupal with a temporary URL on a hostgator server, follow this link
http://support.hostgator.com/articles/specialized-help/technical/drupal/using-drupal-with-a-temporary-url


Should a splash page linking to other multisite instances also be a multisite instance or a bare HTML page?

If you need more flexibility on the long run, you better create a separate website for the global domain. Keep in mind that it will require extra resources on your server.

If your global landing page is simple you can consider the option to only use a HTML page. Keep in mind that this will give you less options on the long run.


Yet that's true. If you want to use apachesolr for your own you have to run a java server.

Alternative there are some services which you can pay to host apachesolr for you.
Some examples:

acquia
drupalconcept


One way of doing it is by using the Views Bulk Operations module. There is a patch which has recently been committed and offers the "Add to cart" action over here: http://drupal.org/node/1553700

Once your view is built (fields only) you can add a Content VBO field and choose the Add to cart action from there. In theory, redirection to the cart can be done by including the ?destination=cart parameter when calling the View which should be honored once the form is submitted. However, at the moment this appears to only add one item and redirecting rather than all items that have been selected.


Webforms Ajax File Upload Issue with IE7 and IE8

I've managed to solve this weird issue, the root cause was relatively easy to find once you have the correct tools to debug. Which is an issue in IE7/8. My issue was related to Adaptive Image Styles, and it now works with that disabled.

The answer here: IE8 Debugging (stack overflow) helps equip us with a bit better debugging capability in IE8.

Set a watch on e, and check to see what the error throws to see if that gives any hints in where to look next.

Now the problem I specifically encountered comes from /misc/ajax.js so open up this file and make the following changes starting line 239:

//try {
    if (ajax.form) {
      // If setClick is set, we must set this to ensure that the button's
      // value is passed.
      if (ajax.setClick) {
        // Mark the clicked button. 'form.clk' is a special variable for
        // ajaxSubmit that tells the system which element got clicked to
        // trigger the submit. Without it there would be no 'op' or
        // equivalent.
        element.form.clk = element;
     // }

      ajax.form.ajaxSubmit(ajax.options);
    }
    else {
      ajax.beforeSerialize(ajax.element, ajax.options);
      $.ajax(ajax.options);
    }
  }
  //catch (e) {
    // Unset the ajax.ajaxing flag here because it won't be unset during
    // the complete response.

    ajax.ajaxing = false;

    alert("An error occurred while attempting to process " + ajax.options.url + ": " + e.message);
  //}

This removes the try/catch since they were obscuring where the error was coming from in the IE inspector. Now set breakpoints on each one of those variables and set a watch on ajax. Hit upload on your page and continue through the errors checking each variables, then as it hits an error the Console should take you to which ever file is throwing the error.

Hope this helps you.


How do print term image field as background style attribute in views-view.tpl.php?

You can achieve this with row style instead. Go to your views advance settings then click on theming information and look for appropriate name for row styling and write something like this.

$uriImagefromView = $row->field_field_image[0]['rendered']['#item']['uri'];
$urlImagefromView = file_create_url($uriImagefromView);

This will give you the url to the path of that image. Now you can easily render it as background.

If you want to render your background image in particular size you created in image style you can do like this

$resized_url = image_style_url('<style_name>', $uriImagefromView);


The $language_content variable is not set to the language used for the currently shown node, but it contains the value set by the language negotiation providers.

See language_initialize(), which is the function that initialize that and other variables, and that is called from the following code.

  // Ensure the language is correctly returned, even without multilanguage
  // support. Also make sure we have a $language fallback, in case a language
  // negotiation callback needs to do a full bootstrap.
  // Useful for eg. XML/HTML 'lang' attributes.
  $default = language_default();
  foreach ($types as $type) {
    $GLOBALS[$type] = $default;
  }
  if (drupal_multilingual()) {
    include_once DRUPAL_ROOT . '/includes/language.inc';
    foreach ($types as $type) {
      $GLOBALS[$type] = language_initialize($type);
    }
    // Allow modules to react on language system initialization in multilingual
    // environments.
    bootstrap_invoke_all('language_init');
  }

The language negotiation providers are the ones you set in admin/config/regional/language/configure.

If none of the provider is enabled, which what happens by default, that variable will be set with an object for English language.


make sure these settings are set:

remember last selection & caching


In the hook YOUR_MODULE_form_CONTENT_TYPE_node_form_alter() fill the field (that outputs in the  ckeditor) with your HTML, like:

$form['field_body'][LANGUAGE_NONE][0]['value'] = $your_html;

You also need to make sure, that the  tags get saved, by adding these tags to allowed ones for your ckeditor!


How to render content with  in twig to create paragraph

1) It's bad security practice to use |raw. See How do I get the raw field value in a twig template? for proper/safe way to do it.

2) I am confident that  {{ content.field_name }} or {{ entity.field_name.value }} is printing  your <p> tags. If you right click and inspect element, you should see them in the HTML. Your issue must be CSS related perhaps the p { ... } CSS code have an inline or a float in them.


Enable/ Disable elements under 'edit' depending on role

As I understand your question, you need the Field Permissions module. From the project page:

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

This will allow you to grant permission for editing certain fields to a specific user role.


The file names are not transliterated on upload

File names are not URL aliases. Pathauto has never had any sort of integration with files at all.


#upload_validators missing error message

I was able to resolve the issue using the solution posted here.

As I understand it, the issues is caused by an ID being used more than once. To fix this, you can implement an #after_build callback that ensures the upload fields will have unique IDs.

To summarize...

Add an #after_build callback to the managed_file field:

$num_docs = 3;

// Build the number of name fieldsets indicated by $form_state['num_docs'].
for ($i = 1; $i <= $num_docs; $i++) {
  $form['managed_file'][$i] = array(
    '#type' => 'managed_file',
    '#title' => 'Managed File' . $i,
    '#progress_indicator' => 'throbber',
    '#progress_message' => 'Upload successful!',
    "#upload_validators"  => array("file_validate_extensions" => array("doc")),
    '#upload_location' => 'public://doc/',
    '#after_build' => array("MODULE_file_managed_fix_duplicate_id"),
  );
}

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Submit'),
);

Create the following callback:

function MODULE_file_managed_fix_duplicate_id($element) {
  if ($element['#id'] === $element['upload']['#id']) {
    $element['#id'] = drupal_html_id($element['#id']);
  }
  return $element;
}

Once I did that and cleared all my caches, the javascript errors went away and the error messages starting working.


How to hook bundle create/read/update/delete events?

So here's the best I can find so far. It's not great.

Create: There's hook_field_attach_create_bundle, but it doesn't automatically get called any time a bundle is created. Seems that every module for every entity with bundles has to call field_attach_create_bundle($entity_type_name, $bundle_type_name); every time a bundle is going to be created/saved, else the hook doesn't know about it. It seems not to do anything except call the hooks - I've seen modules that forget to add this line.
Read: I can't find an equivalent here (no big deal I guess as it's not clear what 'reading' a bundle would mean - accessing info on it?)
Update: The closest I can find is hook_field_attach_rename_bundle. Not great.
Delete: There's hook_field_attach_delete_bundle. Like ..._create, it needs to be called in the code, so some modules' entities might not call it. But it appears that field_attach_delete_bundle() actually handles the deletion of field data, so it's less likely to be forgotten or overlooked.


How can I limit the days returned in the date module to today's and future dates only?

I worked this out shortly after posting, but it required a little bit of "hacking" of the date module.

To get this working I added a new '#settings' variable onto the date_popup type so it would look like ..

$form['ratesDateSelect'] = array(
'#title' => 'Arrival Date',
'#type' => 'date_popup',
'#default_value' => '',
'#size' => 21,
'#maxlength' => 100,
'#date_flexible' => 0,
'#date_year_range' => (date('Y')) . ':+5',
'#attributes' => array('autocomplete' =>'off','readonly' => 'readonly'),
'#description' => '',
'#value' => array('date' => $date),
'#date_format' => 'D d M Y',
'#required' => FALSE,
'#settings' => array('minDate'=>'0'),
);

on the form element and then I added this code into date_popup.module (around line 336) after the settings array.

$user_settings = $element['#settings'];
foreach($user_settings as $setting_key => $setting_val) {
    $settings[$setting_key] = $setting_val;
}

This allowed me to inject javascript settings/options so that I can restrict the dates returned from now into the future.

Ryan


Page template for specific path: page--about.html.twig

You don't say if /about is a different content type or just a node.

If it's a node, you need to use the format:

page--node--1.html.twig

Replace 1 with the about page node id.  See the d.o. page for reference info.

If you are trying to have a template for an about content type.  You need to add code to your theme like this:

function THEME_NAME_theme_suggestions_page_alter(array &$suggestions, array $variables) {
  // Add content type suggestions.
  if ($node = \Drupal::request()->attributes->get('node')) {
    array_splice($suggestions, 1, 0, 'page__node__' . $node->getType());
  }
}

See this d.o page for more info.


How to add a region block to the custom template contact form page?

I used twig_tweak module to load and render a block on any where in Drupal.
Read more on the module docs:

https://www.drupal.org/docs/8/modules/twig-tweak/rendering-blocks-with-twig-tweak


Feeds: How to import content from multiple xml files

D7

You can import a series of files by using the File upload fetcher and enabling the option "Supply path to file or directory directly" on the fetcher settings.

Steps:

Select the File upload fetcher, enable the option "Supply path to file or directory directly".

Store the XML files to import in the public or private directory. On Administration > Configuration > Media > File system (/admin/config/media/file-system) you can see which paths are configured for the public or private file system.
On the import form, enter the path to the directory with XML files. If you placed these for example in a folder called "mydir" on the public file system, enter public://mydir.

Public file system

Import form

D8

In the D8 version of Feeds you would select the Directory fetcher. The next steps would be similar as for the D7 version of Feeds.


8 - Manually adding a user field will delete all programmatically added user fields

You just need to move the hook implementation into the .module file.

It works on install in the .install file because that file is included in the request, and when Drupal looks for hook implementations, it can find it.

Wen you're not installing, e.g. when adding fields through the UI, the .install file is not included so the hook won't be found, and Drupal will consolidate the info it has by removing those fields.


google analytics are killed after "cookie control" instalation

That's pretty much what Cookie Control is for.

On May 26th 2011 a new EU originated law came into effect that requires website owners to make significant changes to their sites and may fundamentally change the whole web browsing and shopping experience for everybody.This Cookie Law is amended privacy legislation that requires websites to obtain informed consent from visitors before they can store or retrieve any information on a computer or any other web connected device.
Cookie Control does just that, presenting users with clear information on whether cookies are present, linking to your privacy policy (where you should have specific information about what cookies are in use), and advising users on how to adjust browser settings and what cookies mean for them.
Features

Compact pop-up with dark and light colour themes.
Prevent users logging in until cookie consented.
Other modules can integrate with cookie callbacks (see below).
Configurable message and read more message.
Link to an admin defined privacy policy node.
Only apply cookie consent restrictions to specified countries or whole world.

3rd Party Module Support
A sub-module is bundled with Cookie Control which will disable Google Analytics from tracking a visitor until they give consent. Upon accepting cookies their first visit will be logged, along with any further page loads.

Emphasis mine.
So if you want to track people who do not consent for being tracked, you need to stop obeying the law - by disabling or modifying modules that makes your site law compliant.
If you in fact disabled CC module
and GA is silent, then if you have no (or not much) new users, or you haven't cleared your caches, or ISP caches, then yes, it can last up to a week (usually a day or two). Try uninstalling this module, not only disabling, too. If it lasts longer than about a week, and GA can't even detect you when you browse from a browser you are sure never seen CC-enabled version on your site, then you are in trouble and it might be worth to compare your site (especially HTML, JS and headers output) with a backup from before first CC installation. But it would be a bug in Cookie Control, and you should report them in issue queue, not here.


How to message or invite a group without joining it?

As answered in Get notification message in groups, you use Message Subscribe based on your criteria.

You expose the Message Notify for users, but only difference is here you use a custom module to conditionally display that notification form. If the user has already issued a notification, don't display the form. You should be able to search back through the message log to check if the user has previously notified about this message. Be careful you are not clearing out your message log too often in this case.

If you need to clear out your message log, then you may need to use Flag module to flag that the user has already notified about this job post. i.e. - mark the message / job post as flagged whenever a notification has been sent. Only display the Message Notify form for non flagged entities.


comment body size in hook_form_comment_form_alter

You can use the #rows and #cols properties to define the height and width respectively:

$form['comment_body'][LANGUAGE_NONE][0]['#rows'] = 10;
$form['comment_body'][LANGUAGE_NONE][0]['#cols'] = 50;


Additionally, is using a Field Widget the best way to accomplish this?

I would say yes, it's more work than a hook, but it makes things configurable most times hidden in a form alter hook. The result is the same. You can add to the form array additional render elements like div containers or attributes to the input element itself. Based on this add a theme suggestion, in case you want to add more markup in a template. See this answer from @Kevin.


How to remove the create prefix text when adding new content?

You can use hook_form_FORM_ID_alter().

You could also use hook_form_BASE_FORM_ID_alter() or hook_form_alter() if you preferred or it fit better with your other custom code and requirements.

You would do something like this in a custom module:

/**
 * Implements hook_node_FORM_ID_alter().
 */
function MODULENAME_form_ask_a_qustion_node_form_alter(&$form, &$form_state) {
  // Only change the title on the add form, not the edit form.
  if (empty($form['nid']['#value'])) {
    drupal_set_title('Ask a new question');
  }
}

Or if you want to do multiple content types:

/**
 * Implements hook_node_BASE_FORM_ID_alter().
 *
 * Alter all node forms.
 */
function MODULENAME_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Only change the title on the add form, not the edit form.
  if (empty($form['nid']['#value'])) {
    $title = '';
    switch ($form_id) {
      case 'ask_a_qustion_node_form':
        $title = 'Ask a new question';
        break;
      case 'other node type_node_form':
        $title = 'Other title';
        break;
    }
    if ($title) {
      drupal_set_title($title);
    }
  }
}

There is also the node add title module that allows you to set the title of the add form per content type.
At a quick glance over the code of that module though I see a few issues so I personally wouldn't use it at this stage, although I will open some issues to try to get them fixed.


Try to use any of these modules. I hope any of these modules solve your issues :

NodeSymlinks

  This is useful when you want to have the same page reachable though
  multiple menu items, each with its own URL, menu trail and breadcrumb
  path.

Menu Trail By Path

  Menu Trail By Path sets the active-trail on menu items according to
  the current url.


Place or attach permanent file to the node edit form

If it's a PDF, you might also want to look into Fill PDF.


Problem with using ksm($entity) in hook_entity_insert()

Found another post that provides a solution to my problem:
How to preserve kint output upon form submit redirection?

In my case, while

ksm($entity)

would display nothing, or show errors,

ksm($entity->toArray())

seems to display correctly.

I'm a bit baffled myself why this happens, and will continue to investigate.


Fixed, the problem was that the translations did not have the correct context linked to the translation.


How do I use 2 different taxonomy view modes on one node page?

The problem is that the view mode is also part of the cache keys and you would need to update them as well to avoid that both view modes are cached under the same cache id.

  Is there possibility to disable render cache for specific node and/or
  fields?

Yes, this is another possibility, you can disable caching of specific entities, in this case taxonomy terms, by removing the cache keys, which are in the #cache property. It's easier to manipulate this array in PHP, but this should also be possible in Twig. You can try to get #cache with the filter |without('keys') and merge it later with first and second.

You can also try to remove #cache completely from the second rendering

{{ second|without('#cache') }}

because all relevant cache metadata should bubble up already from the first rendering of the taxonomy term.


try the context module and use node as the context and blocks as the reaction. you should be able to figure out the rest :)


log / capture all the queries executed in drupal

You want Devel.

It has a lot of helpful tools for Drupal developers, including a helper function to print a summary of all database queries for each page request at the bottom of each page. The summary includes how many times each query was executed on a page (shouldn't run same query multiple times), and how long each query took.


Node tagged with more than one taxonomy, how to keep expanded the specific taxonomy menu the user has used to reach a node

I've done this in my modules hook_init() implementation by using sessions, menu_get_object and menu_tree_set_path(). Here's some example code showing my general approach:

function mymodule_init() {
  // Save the active path for users when on taxonomy term pages.
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && arg(2)) {
    $_SESSION['mymodule_path'] = $_GET['q'];
  }
  // The user is on a node page.
  if (arg(0) == 'node' && arg(1)) {
    $node = menu_get_object();
    // Assuming all the nodes in the taxonomy menu are of the same specific type.
    if ($node->type == 'mynodetype') {
      if (isset($_SESSION['mymodule_path'])) {
        menu_tree_set_path('menu-mymenu', $_SESSION['mymodule_path']);
      }
    }
  }


You have two options:

You can use Display Suite module. A sub-module Display Suite Search allows you to change the way nodes are displayed for search results.
You can use template_preprocess_search_result() together with a copy of modules/search/search-result.tpl.php in your theme. Read thoroughly the comments in the search-result.tpl.php as they will help you understand what is going on and what is available to you.
You can define variables this way: $variables['your_value'] = $variables['result']['node']->field_sample[LANGUAGE_NONE][0]['value']; and use it in the .tpl file like this: print $your_value;.


Generate and email coupon code to customer after they purchase full price item

In Drupal just about anything is possible but you'll need to provide more context otherwise people won't answer you.

Drupal 7 or 8?
Are you using Commerce or Ubercart?

In any case, the Rules module might be what you are looking for. It has the ability to act on different events.


Mix taxonomy and node title in ordering in a View

I would try Views Tree.

Edited: To use Views Tree, the genres would have to be a content type and the books would the use entity reference. It will do an alphabetical list as OP asked but it's unsuitable for his requirements.


Is it possible to autoplay a video when using module media_youtube, and perform an action when the video ends?

The module developers hid these options well!

Click on Configuration (or Structure depending on versions)
Click on File Types
For Video, click on manage file display
For the display you are using (Default, Link, Preview, etc..), click on the YouTube Video tab under Display Settings.
Check the box called "Autoplay video on load"


How to show single pop-up for whole guest session

You can use one cookie, if is the first time to the user enter into your page then create a cookie, when the user change of page you will check if the cookie exists and if exists don't show up the ad.


Your description is very confusing, I hope I was able to understand your problem in the end.

You've framed it as if you're applying the exposed filters and then looking at the views results. But in the end you're looking back at the Exposed filters.

The module that can help you is Views Selective Filters.

  you get dynamic dependent filters, that is, when the value of one filter is changed, the list of options of the selective filters are updated accordingly to the trimmed down result set.


printing an entity reference field in a special display mode

See my explanation in How can you render fields from an entity reference in node templates? [Drupal 8], which touches that topic as well.

In short, not with content, that can only contain a field once, at least without additional modules (not sure if display suite or so can do this). But you can call the view() mode on the field with either the of a view mode from where to pick the configuration or pass it the desired configuration directly. The structure is the same as what stored for the configuration in the entity view display config entities for a field.

Not sure about the exact twig syntax for the array, the view display would be like this: `{{ node.field_ref_entity.view('teaser') }}. You could also prepare it in preprocess and then just print a variable if building that configuration array is too tedious in twig.


How can I display the vocabulary description?

An attachment is the cleanest way to do this using the Views Admin UI. Attachments can be re-ordered in the region they are placed in the parent view.

Another way to do this which requires code is to use hook_views_pre_view() and to create a blank Views Header Area in your views admin area -- then in code via hook_views_pre_view() set the content of that area using PHP to the description of your taxonomy term. But I would recommend trying to stick to the Views Admin for creating your views, as the more custom code you put in files/modules the harder your site is to maintain or change.


This variable Drupal.settings.basePath is provided by drupal.js, just make sure the page includes this js file.(right click view source code to check)

If this did not work, you can create your own variable and use it on the client side:

You can add your custom.js file into your file .info
scripts[] = custom.js or drupal_add_js(drupal_get_path('module','my_module'). '/custom.js');
Use preprocess function in a custom module

    function moduleName_preprocess(&$vars){
             global $base_url;
             global $user;
          drupal_add_js(array('moduleName' =>
      array(
        'basepath'=> $base_url,
        'another_variable' => $user->uid
           ),'setting');
        }

access the variable into your js file :

  var basepath = settings.moduleName.basepath;

that should be it!


View a log of administration configuration changes for Drupal 7?

There's nothing in core, no.

One option from contrib is to use the Journal module

  Journal module adds additional fields to all forms in a Drupal site to allow developers and site administrators to record and track all changes that have been performed to setup a site or alter its configuration.

It's not automatic (that would be too complicated, forms can obviously do just about anything and it's not obvious enough from context what every action is to be able to label it automagically), so you need to trust that your editors will fill it out correctly.

But you can make it required/able to be bypassed based on user roles, so it's a good solution to the problem.


Custom text in a View that Links to a PRODUCT (not a node)

Option A)

You could add another Title and then simply override the title so it says Register Now by Rewriting the results of the field.

Option B)

Add path as a field and exclude from display.

Add a  Custom Text and checkmark display this field as a link and use {{ path }} as your url.


What do I need to pass to the Image class as the first parameter?

$image = \Drupal::service('image.factory')->get($image_path);

See the whole usage


How to translate blocks content (created with views module) in drupal 6?

You can add a filter to your view, under the Node translation group that will make your view filter out nodes that don't belong in the default or current language.

Edit You may need the i18n views module to see some of the options in the screenshot.


How do I change the capitalization formatting of my Taxonomy terms programatically?

It's fairly easy to cobble some (admittedly inefficient) code together that will convert a string to title case while ignoring certain words (you'll have to choose the words yourself though):

function _MYMODULE_custom_title_case($string, $blacklist = array()) {
  // Split the words into an array
  $words = explode(' ', $string);

  $new_words = array();
  foreach ($words as $word) {
    // If the word isn't in the blacklist, capitalise it.
    if (!in_array($word, $blacklist)) {
      $word = ucfirst($word);
    }

    $new_words[] = $word;
  }

  // Join the string back up and return it.
  return implode(' ', $new_words);
}

Then you can simply load all of the terms in your vocabulary, change the title, and save them:

$vid = 1; // Vocabulary ID
$terms = taxonomy_get_tree($vid); // Get the terms

// User the pathauto blacklist
$blacklist = variable_get('pathauto_ignore_words', array());
foreach ($terms as $term) {
  // Update
  $term->name = _MYMODULE_custom_title_case($term->name, $blacklist);

  // And save
  taxonomy_term_save($term);
}

I confess to not having tested that so use a bit of caution! If you've got a lot of terms you might want to split it up into batches to avoid hitting a PHP timeout.


Alter views 'Has taxonomy term' filter Programatically using views_get_view

I managed to achieve this using the following

$view = views_get_view('list_control');
$view->set_display('block_1');
$view->set_arguments(array($current_node)); // Remove current NID
$view->set_items_per_page($pager_count); // Set pager Items

// Set filter based on $tags.
$filter = $view->get_item($display_id, 'filter', 'tid');
$filter['value'] =  $tags;
$view->set_item($display_id, 'filter', 'tid', $filter);
$view->pre_execute();
$view->execute();


Not able to post comment anonymously: getting 403 error

Thanks  tyler.frankenstein. Thanks for suggesting angular-drupal.
I integrated it with my agularjs ui and its working superb.

I gone through angular-drupal code and found that it need X-CSRF-Token in header for write operation. Accordingly i modified my CORS setting

*|*|POST,GET,PUT,DELETE|Origin, X-Requested-With, X-CSRF-Token, Content-Type, Accept|false

And used agular-drupal method to save comment. Here is my code.

//register drupal service as provider/injector
.factory('$drupal',['drupal', function(drupal) {
  return drupal;
}])
.
.
.
//inside controller

.controller('HomeCtrl', function($scope, $stateParams,$http,$state,$drupal) {

  $drupal.node_load(27).then(function(node) {
    console.log(node.title);
    alert(node.title);
  });

  var comment = {
  nid: 27,
  subject: 'Hello world',
  comment_body: { und: [ { value: 'How are you?' } ] }
};
$drupal.comment_save(comment).then(function(data) {
    alert('Created comment: ' + data.cid);
});

Other way to achieve this without angular-drupal is to generate x-csrf-token using get request "/?q=services/session/token" and then set it in header for your post request.

Thank you.


This is a good question. To clarify it first, Hook is a function. But it is a function that is named in such a way, that other modules and themes can override it with their own versions.

For example:

Your module 'custom_node' has a function that adds information to
the custom node. That function is called 'custom_node_add_data()'.
Soon after you release the module, you realize, that other people
liked it, and they are asking you to implement a way for them to add
their custom data to a custom node, from their custom modules, so
that they dont have to hack yours.
So what do you do? You make your 'custom_node_add_data()' a hook.
You name it 'hook_add_data()', and then you add your own overrides
in 'custom_node_add_data()'.
Under the hood, Drupal finds the declared hooks, and searched for
functions in all code base that serve the hook formula, where the
'hook' is replaced by the module name.

Thus, profit! Custom modules can now override your hook function with their own code. They 'hook in' to what your module does, because now their hook function will be called.

Hooks allow to replace initial module's functionality with your own functionality in procedural code. In OOP code, like in Drupal 8, hooks are being replaced by subclassing and implementation of interfaces. Some hooks fill still remain in theming.


How to customize how field is displayed in view

If you just want to rewrite the file field in Views to something like

All you have to do is

add that File Field in Fields section
Inside the File Field configure, select "URL to file" on Formatter
Inside the File Field configure rewrite results section, check the "Rewrite the output of this field" and rewrite something like "" on Text area. Then click Apply.


On feeds, how to access ORGANIZER source

In writing the question I came across the answer and want to share. I was using the wrong hook. Instead I used:

function my_hook_date_ical_mapping_sources_alter(&$sources) {
// Add the "ORGANIZER" iCal property to the mapping sources.
$sources['ORGANIZER'] = array(
'name' => t('Organizer'),
'description' => t('The ORGANIZER property.'),
'date_ical_parse_handler' => 'parseTextProperty',
);
// Add "ORGANIZER:CN" parameter to the mapping sources.
$sources['ORGANIZER:CN'] = array(
'name' => t('Organizer: CN'),
'description' => t("The CN parameter of the ORGANIZER property: the organizer's Common Name."),
'date_ical_parse_handler' => 'parsePropertyParameter',
);
}

Note that I'm pulling both the Contact's Name and the mailto field.

This is a hook provided by the date_ical module. I basically copied the example found there.


"Your command line PHP installation is too old" But it's not?

The command line version of php (CLI) and the one used by your webserver (reported by hostmonster info) are not necessarily the same. Run php -v in a terminal to see which php command line version is installed.


Passing variables via template.php for search module

Adding fields programatically

Use plain old dpm($variables); in your search-results.tpl.php file to check variables.

And yes, the preprocess function is where to add in extra information, you can use something like:

$variables['custom'] = field_view_field($entity_type, $entity, $field_name)

field_view_field prevents you from having to load the whole node and takes care of languages etc for you.

Adding fields in the UI

Go to the Manage Display tab for the content type in question and scroll down to CUSTOM DISPLAY SETTINGS.

Turn on the Search result checkbox and save, then go to the Search Result sub-tab.

Arrange your fields how you wish them to show in search results - note that fields aren't available to the template file unless they are displayed in the Manage Display tab, this might be the root cause of your problem.