How to clear unused files from the database and the filesystem?

Drupal should be taking care of this for you. The pattern that modules should be following is:

When you're adding a new file call file_save() (or a function that calls calls it) then call file_usage_add() to let the system know it's being used.
When you're done with a file call file_usage_delete() to release it then call file_delete($file, FALSE). The FALSE indicates that it should be deleted only if nothing else is using it.

So unless you've got a buggy module there probably aren't to many unused files sitting around but if you wanted to check it you could run the following query:

select fm.* from file_managed fm
left join file_usage fu on fm.fid = fu.fid
where fu.fid is null

I ran that on a test site and noticed that the devel_generate module isn't properly registering usage of the user's pictures when it creates them. You might notice similar things.


Load all/multiple fields from entity of certain type

You should be able to use either get or getFields on your entity object if it is derived from ContentEntityBase.

See: https://drupal.stackexchange.com/a/232219/57

So, after you load the entity:

$fields = $my_entity->getFields();

Or:

$foo = $my_entity->get('bar')->value;


Mulitple image upload field widget working on custom content nodes but not on user nodes

It was an administration template problem...

It works in bootstrap, but not with 7 theme, but it does with Stark.

I thought that the Drupal 7 theme would be bullet proof, I guess not...

So always best to test various admin themes to see if that is the problem in the future.


No wysiwyg filter present in text format

I recommend you to do the following:

first add new text format from admin/config/content/formats
then check the correct options for your new custom text format
now go to wysiwyg configuration page admin/config/content/wysiwyg
you should see your new custom text format along with dropdown list to choose TinyMCE editor
make sure to select TinyMCE editor and click save

Note: in order for you to see/select different text format you need to have more than one text format (other than Plain text)


How to get the mock of current user in PHPUnit test?

In Drupal, unit tests (UnitTestCase or \PHPUnit_Framework_TestCase, sometimes) are really best when you have a class that doesn't have a lot of dependencies or when you can really predict what the dependencies do so you can mock them.  Typically, you mock individual methods, and not try to do everything.  When you find yourself mocking too much, or with complicated mocks, it is best to rework your test as a kernel test (KernelTestBase or KTB for short).

A KTB will boot a minimal Drupal environment, and then you can enable modules and choose which config and schema you want installed (enabling the module doesn't automatically do this).  These are still PhpUnit tests, so you can run that that way and have full access to providers and other PhpUnit features.  Many modules in core also define extensions of KTB to provide setup and additional features (eg, EntityKernelTestBase and ViewsKernelTestBase).

KTB tests are not as fast as UTC tests, but still quick and not as slow as functional tests (BrowserTestBase).  Core has tons of examples.

In your case, since it seems like you need users and nodes, you really want a KTB.  Since both are entities, there is really a lot you would need to mock and you will go down the rabbit hole quickly trying to do this because of the dependencies.

See also Types of tests in Drupal 8.

A few answers to your specific questions.

Users are content entities (so are nodes), which use a lot of services.  And, they aren't all properly injected (the base Entity class uses a lot of helper methods that access the global \Drupal class to get services).  In addition EntityManager is deprecated and got broken up in different services; so a lot of its methods are really helper functions for the other services.  To to a UTC, you would have to start mock these helper functions.  I do not think there is a way around this.

Based off your test snippet, you are really best starting off with a KTB.


Very close. In a hook_update_N:

// Drop all primary keys.
db_drop_primary_key('table_name');
// Add primary keys.
db_add_primary_key('table_name', array('field_a', 'field_b'...);

See db_drop_primary_key and db_add_primary_key for details and links to usage.


Simple Access module may come to your rescue. Do check it out.


Add 'Last modified by ...' footer to each page

I think you should be able to do this with something like this, note that this is only pseduo code and is not tested:

 // get the user that made the latest modification
 // for a node of type 'page'
 function getLatestPageUpdater() {
     $query = "SELECT n.changed, u.* FROM node n
               INNER JOIN users u ON u.uid = n.uid
               WHERE n.type = 'page'
               ORDER BY changed DESC
               LIMIT 1";
     return db_query($query)->fetch();
 }

Then in your page.tpl.php you could do like this:

 <?php $user = getLatestPageUpdater();
       if($user):
 ?>

Last edited <?php print $user->changed; ?> by <?php print $user->name; ?>

 <?php endif; ?>

Like @tostinni pointed out Drupal doesn't track the last editor of a node, so the above code would always display the original author of the node. If you're using node revisions I think you should be able to do something like this (again this is only pseudo code and is not tested):

function getLatestPageUpdater($node) {
  $query = "SELECT u.name
            FROM node_revisions nr, users u
            WHERE nr.uid = u.uid
            AND nr.nid = ".$node->nid."
            ORDER BY timestamp DESC
            LIMIT 1";
  return db_query($query)->fetch();
}

<?php if($node->type == "page"): ?>
<?php $user = getLatestPageUpdater($node);
      if($user):
?>

Last edited <?php print $node->changed; ?> by <?php print $user->name; ?>

<?php endif; ?>
<?php endif; ?>


Automatic Validation Using drupal_form_submit

Field validation is made only against node form submission, so you need to imitate this in your code.

If you are using Drupal 6, try this solution:https://stackoverflow.com/a/6471821/1387163

For Drupal 7 solution can as following:

$node = new StdClass();

$node->type = 'my_type';
node_object_prepare($node);

// assign node field values here ...

$form_state = array (
  'node' => $node,
  'values' => (array)$node,
);
$form = drupal_get_form($node->type. '_node_form', $node);

node_form_validate($form, $form_state);

$errors = form_get_errors();

if ($errors) {
   // ...
} else {
   // ...
}


See this WEALTH OF DOCUMENTATION on Dynamic Queries in D7 ... it will answer EVERYTHING :) .... in all seriousness :).

To add SUM(blah) as foo you want to add an SQL Expression to your Select clause with addExpression().

To add Group by COLNAME you want to use groupBy() with your db_selection, see group by docs.


How to make disqus load avatar picture instead of user picture?

As seen in above code you can use disqus_user_data_alter hook to change disqus data in your custom module...

function YOURMODULENAME_disqus_user_data_alter(&$data) {
  global $user;
  $user_picture_default = variable_get('user_picture_default', '');
if (!empty($user->field_profile_picture[LANGUAGE_NONE][0]['fid'])) {
  // Load the file -- Change field_profile_picture with your field name
  $file = file_load($user->field_profile_picture[LANGUAGE_NONE][0]['fid']);

  // Note the style name is "profile_picture" as explained in your question,
  // not "profile_pic" which was in your original code
    $data['avatar'] = !empty($file->uri) ? $file->uri : NULL;
  }
  elseif (!empty($user_picture_default)) {
    $data['avatar'] = variable_get('user_picture_default', '');
  }
  if (isset($data['avatar'])) {
      $data['avatar'] = file_create_url($data['avatar']);
  }
}


By using xdebug and vdebug (plugin for vim), I am able to step into the code and ping point the issue.

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

I put a watchdog: watchdog('bug_cron', '
'. print_r($module, true). '
'); inside.

// Iterate through the modules calling their cron handlers (if any):
foreach (module_implements('cron') as $module) {
      // Do not let an exception thrown by one module disturb another.
      try {
        // NOTE: put a watchdog and look at your log message.
        // You should able to see which module causes issues.
        watchdog('bug_cron', '
'. print_r($module, true). '
');

        module_invoke($module, 'cron');
      }
      catch (Exception $e) {
        watchdog_exception('cron', $e);
      }
    }

It is the search module causes issues. Disable it, then uninstall the setting via the drupal menu GUI, then it is fixed, but I am not sure why search module causes issues.

Updated at 2015-05-26

It turns out my module uses hook_url_inbound_alter + drupal_goto caused issues. It is not easy to debug, because there are couple of side effects.


You can achieve this in several ways with a script we can call, for example, ckeditor_settings_modifier.js containing:

CKEDITOR.on('dialogDefinition', function(ev) {
  var dialogName = ev.data.name;
  var dialogDefinition = ev.data.definition;

  if(dialogName == 'table') {
    var info = dialogDefinition.getContents('info');
    info.get('txtWidth')['default'] = '100%';
  }
});

This script should be added in one of these places through libraries:

only in the theme of your website (if you use it also for editing)
in your administration theme in order it works in normal node edit mode, and in your website theme in order it works in quick edit mode
in a custom module in which you can use for example some conditional rules that control the loading of the script.

In any choosen settings it is important to declare the dependency on the core/ckeditor.

This is the case of a module (my_module containing a js folder with ckeditor_settings_modifier.js), in my_module.libraries.yml:

ckeditor_settings_modifier:
  version: 1.x
  js:
    js/ckeditor_settings_modifier.js: {}
  dependencies:
    - core/ckeditor

in my_module.module:

/**
 * Implements hook_preprocess_page().
 */
function my_module_preprocess_page(&$variables) {
  // add ckeditor_modifier in case the user has the role of administrator
  $roles = Drupal::currentUser()->getRoles();
  if(in_array('administrator', $roles)) {
    $variables['#attached']['library'][] = 'my_module/ckeditor_settings_modifier';
  }
}

It works on Drupal 8.4.4 and CKEditor 4.8


How do I get the base URL from the feed content?

A way to do this would be to override the proprocess function get the domain like this:

function MY_MODULE_preprocess_views_view_field(&$variables) {
  $field = $variables['field'];

  if ($field->field == 'MY_LINK_FIELD_NAME') {
    $url = $variables['field']->getValue($variables['row'])[0];
    $parse = parse_url($url);
    $variables['output'] = $parse['host'];
  }
}


I can't enable SimpleTest due to open_basedir restriction being in force

Sorry that i don't comment... have not enough points

Be shure u have the right php.ini, on some systems reside more then one.

Check with a phpinfo() file, after config change reload and look at the phpinfo() page if it is really disabled.


URL to access a private file within Drupal 7

The function you want to use is file_create_url().

You pass a stream wrapper path to your file, in this case it starts with 'private://'.

The value that you pass to the function is 'private://relative/path/to/file.txt'.

The relative path is based on the private files folder.


How do I avoid having to clear the cache when changing a module configuration parameter?

You need to set the cache tag to invalidate your output if the configuration changes. That's as easy as adding this to your render array:

$element['#cache']['tags'] = $config->getCacheTags();


Short: If your "menu" was actually a taxonomy tree, it would almost trivial to do what you want, and much more, as most contrib modules operate on a entity basis.

Longer: This answer will mostly be applicable to someone that does not already have a menu structure created, so for some people, it will be of little use.

While displaying a Drupal menu in essentially any way is certainly possible, the menu system in Drupal is rather aged compared to a lot of other functionality.

Generally, whenever you wanna do fancy stuff, I would recommend you avoid the menu system completely. You can even disable it completely in D7. Yes, this type of setup will require more work initially, but is a lot more flexible.


Views filter on field being either empty or equal to uid

I found the way to fix this. The answer is twofold:

First create two filters: one for the field being empty and one for the field being equal to the string "uid". Then as a Filter Criteria option, choose And/Or, Rearrange and add the Or condition:

This is the result:

Second implement hook_views_query_alter() to replace the "uid" string we added earlier with the actual user uid:

/**
 * Implements hook_views_query_alter().
 *
 * Search for 'personal' field to be empty or equal to uid.
 */
function example_views_query_alter(&$view, &$query) {
  if ($view->name == 'myview') {
    foreach ($query->where as &$condition_group) {
      foreach ($condition_group['conditions'] as &$condition) {
        if ($condition['field'] == 'table.field_quality_personal' && $condition['value'] == 'uid') {
          global $user;
          $condition['value'] = $user->uid;
        }
      }
    }
  }
}

That's it!


How can I pass display exposed filter in views-view-unformatted.html.twig?

Try using Views Exposed Filter Blocks.

Use the Twig Tweak module and embed the exposed filter block in your template with code like this: {{ drupal_block('views_exposed_filter_block:my_view_id-my_views_block_id', wrapper=false) }}.
You can also just place the exposed filter block in any region.


How to customize drupal_mail() error messages

drupal_mail() uses drupal_set_message() to push error messages on mail failure. The only way to suppress those messages is by altering drupal_set_message() output. Depending on the how/why, there's a couple of tacts to take.

One way to do this is a blanket suppression via the Disable Messages module that lets suppress messages based on a few different criteria.

  Gives a site owner options to disable specific messages shown to end
  users. The core drupal message system as offered by drupal_set_message
  is an excellent way for modules to send out messages to the end users.
  However not all drupal site owners are keen to show all the messages
  sent out by drupal core and all modules to their users. This module
  gives site administrators a reasonably powerful way to filter out
  messages shown to the end users.

Another, more surgical way, is to manipulate the $_SESSION['messages'] variable which contains the array of pending messages to render, following the execution of drupal_mail().


At least from my point of view the API of search api is pretty good documented in the .api.php file. There is a plugin type called "callback" which allows you to filter out stuff with configuration. This and the callback_bundle_filter.inc should give you enough to provide a patch :)

And don't forget to add your include file in the .info file


Is it a bug? blog-View read more button reference to home page

The problem here is 2 issues:

You're missing a field on your view to reference. In order to reference the Node ID in your view you'll need to add the field Content: ID so that it can be referenced in replacement patterns. It will also need to be ordered before your body field so that its value can referenced. You can use the Exclude from display option if you do not want it appearing in your view.
The format for token replacement has changed with D8. It's now Twig-like: {{ field_name }}. By default the Content: ID field should use the field name nid so your More link path value should be /node/{{ nid }}.


Where to adjust number of returned results on the /admin/people page? I know, don't hack core

Install the Admininstration Views module; it converts that page to a View, which you can edit and set up with paging of your choice.


Drupal 7 Rules : How to get Node Object (from Custom PHP) after a node event is triggered?

you can use watchdog("<pre>".print_r($node,true)."</pre>",'debug');then see the log in admin/reports/dblog
also you can define your own action use  hook_rules_condition_info().
This link may help.


I could be going blind or it could have been a page refresh that was needed...

You create a new node and select "create a new directory listing"

Really straight-forward...


Conditionally display one of two fields in Display Suite?

Use the field formatter conditions module: https://www.drupal.org/project/ffc

This will give you the same options that you have on a blocks (and more). So you can show the field based on any url pattern just as you would blocks:

http://cl.ly/image/2A2Y373Y3e1J

Hope this help.


Webform is not necessary for the tasks you've outlined.

Simply create a content type, and grant the Anonymous user role access to create content of that type.

To have 'hidden' fields which the admin can still edit, you can either hide those fields with CSS, deny access to them via the #access property through a hook_form_alter(), or use the Field Permissions module to restrict access to those specific fields. Note that the Field Permissions module has some performance implications.


No, there is no such function.

See my comment at Language support for entity fields.


How to make exposed filter show results on another page?

In Advanced section :
EXPOSED FORM
Exposed form in block:No -> set it to yes


Why is the test runner not picking up tests for a contrib module?

If I look at https://www.drupal.org/project/cache_register/issues/3184391 , there is no option for me to test/retest a patch.
That tells me that you don't have testing configured for your project. To do that, you need to go to https://www.drupal.org/node/3183102/qa and choose "Add test / retest", then configure a test with the Drupal version, PHP version, database type/version that you want and choose when the test gets run. Once you submit that new test, it should immediately run. If you select "issue testing default" when you configure the test, then that configuration will run for Needs Review patches in your issue queue, and that will be the configuration that will run if someone in the issue queue manually triggers a test.
I don't see anything obviously wrong with the tests themselves, but it is clear that you don't have tests configured to run so it doesn't matter if the tests are working or not ...


How to check condition and print a value using views-view-field--viewname.tpl.php?

I'm also unable to check the condition for the fields:

<?php if($fields['field_some_field_name']->content == 'Test') { } ?>

That is probably because in actuality:

$fields['field_some_field_name']->content =
Test

Therefore,
Test
 is not equal to Test

So what you could do is use raw instead, as raw has no html/markup around the value.

<?php if($fields['field_some_field_name']->raw == 'Test') { } ?>

else, you could still use content with the PHP striptags() function

<?php if(striptags($fields['field_some_field_name']->content) == 'Test') { } ?>

Or else, you could still use your original <?php print $fields['field_some_field_name']->content; ?> but as long as you strip all the markup added by views as shown in my answer to "Is there a more performant alternative than overriding template files?".


Trigger download after clicking on submit on webform

May you could inject a little JavaScript into the Webform and redirect the user to the file download.

Or set the webform's confirmation redirect to point to the uploaded file.


Which hook is invoked when pressing the remove button with widget image?

This message is coming from node_form_submit.
That function subsequently calls node_save which in turn calls the following hooks:

// Let modules modify the node before it is saved to the database.
module_invoke_all('node_presave', $node);
module_invoke_all('entity_presave', $node, 'node');
...
module_invoke_all('node_' . $op, $node);
module_invoke_all('entity_' . $op, $node, 'node');

where $op is one of 'update' or 'insert'.


Pathauto doesn't work anymore when i change the default language

This happens because the table url_alias has a language property that doesn't match anymore with the default language. Try to change the language code to your default language or delete the information. (Of course, make a backup before in case of).


You need to implement and use your own EntityEditForm - is this the case ?
Then skip to the last code block :D

Otherwise you'll need to accomplish this first.
See this answer (Overriding an entity add/edit form through alterroute) for an approach to 'inject' a custom form. Here the crucial code to it (adapted to NodeForm):

modules/custom/form_overwrite/form_overwrite.services.yml

services:
    route_subscriber:
        class: Drupal\form_overwrite\Routing\RouteSubscriber
        tags:
 - {name: event_subscriber }

modules/custom/form_overwrite/src/Routing/RouteSubscriber.php

 <?php

/**
 * @file
 * Contains \Drupal\form_overwrite\Routing\RouteSubscriber.
 */

namespace Drupal\form_overwrite\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
     if ($route = $collection->get('entity.node.edit_form')) {
  $route->setDefault('_entity_form', '\Drupal\form_overwrite\Form\NewEditForm');
     }

   }
}

modules/custom/form_overwrite/src/Form/NewEditForm.php

<?php

namespace Drupal\form_overwrite\Form;

use Drupal\node\NodeForm;

/**
 * Form handler for the node edit forms.
 */
class NewEditForm extends NodeForm {}

There you make sure the #ajax is set, like:

<?php

public function form(array $form, FormStateInterface $form_state) {
   ...
   $form['actions']['DESIRED_EXISTING_ACTION'] = array(
      ...
      '#type' => 'submit',
      '#ajax' => array(
        'callback' => '::ajaxSubmit',
        'event' => 'click',
      ),
      ...
    );
   ...
}

and overwrite the ajaxSubmit function, adding the CloseModalDialogCommand, like:

public function ajaxSubmit(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();

    if ($form_state->getErrors()) {
      ...
    }
    else {
      ...
      $response->addCommand(new \Drupal\Core\Ajax\CloseModalDialogCommand\CloseModalDialogCommand());
    }

    return $response;
  }


how to stream video on-site generated from link preview in a text area?

Opengraph Filter module provides this: template_preprocess_opengraph_filter()

You can implements it in your custom module or theme for reading the video url. Then you can use the video url to output the player.

function mytheme_preprocess_opengraph_filter(&$variables) {
  $key = 'video';
  if (isset($variables['metatags']['og'][$key])) {
    $video_url = $variables['metatags']['og'][$key];

    // more code to operate $video_url.
    // dpm($video_url);
  }
}

You can start with it. It would be a long story if you want to load the video after clicking the thumbnails. I would suggest you to split the question into multiple specific questions for different step. It is more easy for other to provide answer and also for those who is looking for answer. Thanks.


The Message module aims to provide specifically this functionality. It requires some configuration, as it is, like many good modules, created to work as a platform to build on, rather than as a direct solution.


Custom Block - How to get additional variables

You can create custom block and you can render variables using block view function

function MODULENAME_block_info() {
    $blocks = array();
    $blocks['top_five_adverts'] = array(
        'info' => t('Top Five Adverts'),
    );
}

function MODULENAME_block_view($delta = '') {
    $block = array();

    switch ($delta) {
        case 'top_five_adverts':
            $block['subject'] = '';
            $block['content'] = theme('top_five_adverts_list', array('data' => getAdverts()));
            break;
    }
    return $block;
}

function MODULENAME_theme() {
    return array(
            'top_five_adverts_list' => array(
            'variables' => array('data' => null),
            'template' => 'theme/top_five_adverts_list',
        ),
    );
}

Create top_five_adverts_list.tpl.php in theme folder of that module


How to add a custom Save &  button to Node Add/Edit form?

Got it :D

Adding

'#submit' => array('mymodule_course_form_submit'),

To the submit button worked. Like this:

$form['actions']['save_add_lesson'] = array(
  '#type' => 'submit',
  '#value' => 'Save & Create a Lesson',
  '#name' => 'op',
  '#submit' => array('mymodule_course_form_submit'),
  '#redirect' => 'node/add/lesson',
  '#weight' => 1000
);

function mymodule_course_form_submit($form, &$form_state) {
    $nid = mymodule_node_save_no_redirect($form, $form_state);

    $form_state['redirect'] = 'node/add/lesson';
    unset($_GET['destination']);
    drupal_static_reset('drupal_get_destination');

    if($nid != -1) {
        $_SESSION['mymodule_course_nid'] = $nid;
        drupal_redirect_form($form_state);
    } else {
        // Failed to save Course...notify user
        drupal_set_message('Failed to save Course Content', 'error');
    }
}


It's very easy if you have the Token module installed. On the file field edit page you'll see something like this:

The big table is a list of tokens that you can use in the path for the file. By default there are tokens available for current user, current page, current date and a couple of others.

For example you could have a path such as users/[current-user:name], in which the token would be substituted for the current user's name. You just need to click in the text box you want to add the token to and then click the links in the table, it will auto-fill for you.

Hope that helps


Is there a module equivalent for Suggest a Friend for Drupal 7?

Very powerful social networking module for creating inner social network for Drupal 7 is User Relationships.

It is well supported so i guess you can accomplish what you need.


Look at webform conditional or update your webform to >4.0-alpha2.

I have done a 2-way or 3-way branch on a form with a few sub-pages of questions for each branch. It's kind of a pain but its very doable.

Webform results will show you only the answers they had to complete depending on conditions and validations.


Access row value in template_preprocess_views_view_fields(&$variables)

values is protected, so you have to use the get() method:

$variables['row']->_entity->get('field_file_pdf_upload')->target_id;

For the field object this shortcut is available (this is not standard OOP and works for fields only):

$variables['row']->_entity->field_file_pdf_upload->target_id;


Make variables created in preprocess_page hook available to content type templates

I was able to accomplish this by placing the code into the preprocess node hook instead of the preprocess page. Like so

mytheme.theme

function mytheme_preprocess_node(&$variables){
    $myblock = \Drupal::service('plugin.manager.block')->createInstance('myblockid',[]);
    $variables['myblock'] = $myblock->build();


You can add additional submit callback function to the registration form, then assign user's email to a session so you can call it on the destination page.

Add the following line after $form['#action']

$form['#submit'][] = 'custom_user_register_submit';

Then add this function to your custom module

function custom_user_register_submit(&$form, &$form_state) {

  $_SESSION['custom_user_mail'] = $form_state['values']['mail'];
}

Then call $_SESSION['custom_user_mail'] on any page you want.


How to create a page category of products in Commerce 2?

Unfortunately, this is an issue with Drupal core itself and the Views module.

As you mentioned right now the taxonomy term views in core has Content: has taxonomy term ID which only work with nodes.

It should be Entity: has taxonomy term ID so it can handle other entities such as Drupal Commerce products

There's an issue in Drupal core/views here that you can read about it, for the time being there's a module that will help you out with this situation.

Commerce: Product taxonomy filter

  The Module extends Taxonomy module from Drupal core and provides a new
  contextual filter "Product has taxonomy term ID (with depth)".

Note that the contexual filter has to know your entity reference machine name


Drupal Migrate - Link fields from an XML Source

So, the solution is to not use arguments, but instead, fix up the record using the prepare() method:

In the constructor:

//IMPORTANT - DO this source mapping without a destination mapping (NULL)
$this->addFieldMapping(NULL, 'organization_title')->xpath('/record/organization/title');

$this->addFieldMapping('field_organization', 'organization_url')->xpath('/record/organization/url');

Then, create a method named prepare():

function prepare($node, $rec) {
      $node->field_organization[LANGUAGE_NONE][0]['title'] = $rec->organization_title;
}

As of today (Nov 30, 2011), you must have the 7.x-dev version of the link module installed, not the "stable" 1.0 version, in order for link fields to work at all!

Whew!


In Drupal 7, Views 3, we added text-align: center to our stylesheet:

.item-list .pager {
    text-align: center;
}

And to make it only apply to one specific view:

.view-id-my_view_name.view-display-id-page_1 .item-list .pager {
    text-align: center;
}


How can I implement a feature to change settings?

1) If you made the changes in only views then only export the view form your local development and import it in your production server

or

2) If you added an new field in content type then goto admin/structure/features/create select the field from FIELD INSTANCES (x) (field_instance) and module will select the dependency automatically then add Name in GENERAL INFORMATION and download and upload it in your module folder and enable it and then follow the 1 point

Note: First try it on your another test development and then on production


How can I save what filters a user wants when viewing a view?

If your view is using exposed filters, there is a "Remember search" option in the View configuration. This stores the search parameters in the session, and should give you the expected effect. Admittedly, I'm thinking of Views 2, and I just assume the setting is available in Views 3 as well.


Node Update not showing to anonymous user even after clear cache

You have set the value of Expiration of cached pages to 1 hour

Expiration of cached pages tells the External Caches for how long they can server the old version of a page.

In your case browser is the External Cache and it assumes that it can show old content for an hour. So it doesn't even make a call to you website when you request the page.

You can see the changes after an hour or clear all your browser caches to see the new changes.

More Explanation


Link a Page to another Page using Views and taxonomy

You first need to create your other page, using Views, with a path pattern similar to the following:

projects_by_sector/%tid

This page can then be configured to display only content of type Projects and the fields you need (Title, Image, Sector Category, etc). Most importantly, you need to configure a contextual filter with the following configuration:

For the "Content: Sector Category" field
"Provide default value"
"Raw value from URL"
"Path component" => 2 (this follows from the example URL above)

Now back in your existing Views page for the Sectors list, you need to do some field rewriting. This can be done in a number of ways, the easiest would be to add the Sectors Taxonomy reference again as a field and do the rewriting on that field. You can do these using the following steps:

Add the "Content: Sector Category" field
Save with the default configuration
Rearrange your fields and move the new field below/after the "Content: Title" field. This is important so that the replacements token [title] will be available for the rewriting.
Hide the "Content: Title" field by selecting "Exclude from Display" on its configuration
Configure the new "Content: Sector Category" field
Select "Plain text" as "Formatter"
Expand "Rewrite Results"
Select "Rewrite the output of this field"
Enter the following in the "Text" textarea to use the title of your sector
[title]
Select "Output this field as a link"
Enter the following as the "Link path"
projects_by_sector/[field_sector_category-tid]

This is a rough idea, you need to tune your views page accordingly, but the end-result should be what you asked for. Hope this helps!


cron.php initiates a call to function drupal_cron_run() (in common.inc) which will finally make all calls to all cron tasks.

/**
 * Executes a cron run when called
 * @return
 * Returns TRUE if ran successfully
 */
function drupal_cron_run() {
.
.
// Iterate through the modules calling their cron handlers (if any):
module_invoke_all('cron'); // This will call all cron functions defined in modules(enabled)
.
.
}

dblog_cron() will get invoked by module_invoke_all('cron') This is responsible for clearing old entries in your watchdog table. If this function does not suit your requirements you can use Ultimate Cron to disable it alone. This is a good admin tool to manage your cron jobs. Then you can write your own cron task in another module and enable it.

function dblog_cron() {
  // Cleanup the watchdog table
  $max = db_result(db_query('SELECT MAX(wid) FROM {watchdog}'));
  db_query('DELETE FROM {watchdog} WHERE wid <= %d', $max - variable_get('dblog_row_limit', 1000));
}

Note : This is wrt Drupal 6. in D7 module invoke is slightly different


How to disable shipping for ONLY virtual products and not if combined with physical

Commerce Shipping has a couple of ways you can approach this. The simplest is to set the weight of your virtual products to zero, they won't be assessed shipping charges, and they won't affect any weight based calculations.

EDIT: Alternatively, you can use Commerce Rules Extra to add conditions that exclude your virtual products in the conditions for your Flat Rate.


It looks like you could use:

print $content['field_subtitle']['0']['#markup'];

or else just

print render($content['field_subtitle']);


I find it's generally easier to track down CSS selectors by disabling CSS aggregation and then using your browser's inspector feature. This will give you a file and line number to reference for tracking down the selector in question. Often times, you may be able to simply copy-and-paste the selector in question into your subtheme and edit it as needed.

You'll always want to make your CSS and template changes in the subtheme; don't touch the base theme just like you wouldn't touch Drupal core to make code changes. This ensures that if there is an update to the base theme, you can apply it without losing all of your customizations.

Many base themes already have a CSS file structure or directory in place to help you figure out where to put your selectors. If not, the architecture is very much up to your personal preferences. You could put everything in one file if there are only a couple of changes, but most people use some sort of systematic CSS architecture, such as SMACSS, to keep things organized on more complex projects. Alternately, it might make sense to you to mirror the file structure already found in the base theme. You normally don't need to copy all the CSS files from the base theme, just create files to hold any new or customized selectors as needed.

If you haven't yet, check your base theme for a README file, or look at their online documentation for more hints on properly customizing it using a subtheme.

Follow-up, more specific to SASS and Foundation theme:

If you're looking for the SASS file that a selector comes from, the easiest way to trace that down is by enabling SASS source map generation in the subtheme's Gruntfile.js. Add sourceMap: true, to the sass options in grunt.initConfig() similar to this:

grunt.initConfig({
  ...
  sass: {
    dist: {
      options: {
        outputStyle: 'compressed',
        sourceMap: true,
        includePaths: ['<%= global_vars.theme_scss %>', '<%= global_vars.base_theme_path %>/scss/'].concat(bourbon)
      },
  ...

You may also need to enable loading of CSS source maps in your browser's settings (See the "Enabling source maps in the browser" section from http://thesassway.com/intermediate/using-source-maps-with-sass.

Using source maps to trace back to the specific selector from your OP, it seems to be located in path/to/themes/zurb_foundation/scss/foundation/components/_top-bar.scss. Looking at the base theme's SASS, you can see it utilizes variables for determining the padding and line-height properties:

.top-bar-section {
  ...
  li {
    ...
    &:not(.has-form) {
      a:not(.button) {
        padding: 0 $topbar-link-padding;
        line-height: $topbar-height;
        background: $topbar-link-bg;
        ...
      }
    }
  ...

And those variables are defined elsewhere in the base theme (do a text search to find them) with the !default property:

$topbar-height: rem-calc(45) !default;
...
$topbar-link-padding: ($topbar-height / 3) !default;

This means they can be set to something else in your subtheme's SASS before they are used in the base theme's SASS in order to override the base theme's defaults. I can't tell from the OP, but I'm guessing changing the value for $topbar-height might accomplish both changes you are attempting to make. Doing things in this way (overriding !default variables from the base theme) is less likely to cause alignment issues elsewhere in the theme, so it's generally the preferred methodology (assuming the theme is doing a good job of utilizing SASS, which seems to be the case for the ZURB Foundation base theme)

In order to do this in your subtheme, I'd recommend either adding the variable overrides to your subtheme's scss/base/_init.scss file, or creating a new scss/base/_overrides.scss file and editing the main theme SASS file at scss/your_theme_name.scss to @import "base/overrides" it just below the existing @import "base/init".

For example, try adding this to the bottom of the subtheme's scss/base/_init.scss file to double the top bar's height:

$topbar-height: rem-calc(90);


We use metatags_quick for our websites with no problem. You must make sure you've checked the tickbox "Use path-based meta tags" in admin/config/search/metatags_quick under the fieldset GLOBAL SETTINGS (it might be collapsed by default)


Count of the number of nodes tagged with a particular status

To do this without code, I think you'd need a view for each category and then in the footer or header, choose "Global: Results summary" and build your message there using the tokens. I saw you post about colours elsewhere so if you have a separate block for each, you can then theme each one as you wish.

If you set the view to "Display All Items" and then add css .viewname .view-content {display:none;} or a custom module to hide the results, it should work nicely.

You could then use some caching to minimize the performance hit.


How to use hook_init in a custom module?

Some suggestions:

Is the module enabled? Silly question, but I've forgotten to do that before.
hook_init implementations won't get called until you clear the cache. Did you clear the cache?
I will sometimes put a drupal_set_message('this line'); in various parts of the code to see if that's getting called. In situations where a drupal_set_message isn't helping, I sometimes will put a asdf() so I can get a "fatal error, call to undefined function" message. Then it's really clear whether or not the code is getting called.
If the hook_init is not being called and the module is enabled and cache was cleared, then it's probably mis-spelled. The function should be named based on the name of your module: If your module is mymodule.module then the function name is mymodule_init().
It's possible that the path you are using isn't quite right. Does the file really exist there? I would try: drupal_set_message(drupal_get_path('modules', 'myInfo') . '/myScript.js'); so you can see the path and confirm that it's right.
There's some good documentation on Managing JavaScript in Drupal 7 though perhaps you've already read that page.

Good luck!


View nodes in a listing only, not on their own?

I believe you could use the node_view hook.  In that hook you can check for the node type (set) and view mode (full) and add your logic.  If you're using a reference field to relate the set to the match then you could probably redirect the user back to the match.

When you're listing sets on the match page you could also not render them as links a user doesn't try to view the set directly.


How does Drupal ensures that the one time unique URL used to reset user password does not get transferred away inside the http_referer header?

At this point in time, it doesn't.

There's an issue to fix this in Drupal 8, after which it will (hopefully) be ported back to 7. Patches are currently awaiting review.


You should use hook_node_presave if you want to change a field's value as the hook is invoked from node_save() before the node is saved to the database. And as leymannx stated, make sure you clear the cache before implementing a new hook.


How to update a biblio field with Entity Metadata Wrapper?

The Bibliography module isn't using D7's field API. It's misleading since the module's manage fields UI (/admin/structure/types/manage/biblio/fields) does make it appear as if it's using the field API; however it installs its own database schema for storing data for Bibliography nodes.

As such, Entity API's EMW isn't much help in your case.


Keep in mind l() passes the text through check_plain which escapes the HTML characters for display.

So, there's no need to double escape the link with another check_plain later.

Pass the raw text, including the single "&" through as the link text and output it as such, that way it should be fine.


Path Breadcrumbs adds unwanted space in link path, why and how can I avoid it?

HM There was a space before the opening php tag in the custom token value field, I really hate spaces. I think spaces should be exchanged with a X ;)


How to calculate user scores based on 3 variables to assign an appropriate text label?

A possible answer is to trigger Rules Actions based on a combination of Rules Events that happen asynchronously, and optionally after they were repeated multiple times. Which also requires some type of recording of the progress being made. Pretty challenging specs, but there is a solution (module) for it, as further explained below.

Goals module

You may want to look at the Goals module (disclosure: I'm its maintainer) as a possible alternative. To start using it only requires typical administration tasks (configuration), though it does come with various hooks also for custom module development (if you want to).

Since the Goals module is entity based, it has out-of-the-box integrations with modules such as Views, Rules, Flag, etc.

Requirements mapping

  I need to calculate a score for users in D7 based on 3 variables and then assign an appropriate text label and a CSS class.

calculate: that's what Goals will do for you, by recording the progress made on the completion of each task required to reach a goal.

3 variables: that sounds like 3 tasks to be completed to achieve 1 goal.

assign an appropriate text label: you can optionally attach a (custom) image to each goal. The goals completed by a user, can be shown on a Views block included with Goals, with title "Your completed goals".

  So, using data from Voting API, time ago joined, and number of nodes published, it needs to select and display one of 15 text labels such as "Promising newcomer, reliable veteran, etc".

using data from...: if you can think of a Rules Event to discover these events, you use the appropriate Rules Action (provided by Goals) to record progress on the completion of a task. E.g. if 1 such task would be to "create 10 nodes of type XYZ", then each time such nodes are saved (there is a Rules Event for it!), then Goals will record so. And if 10 such nodes were recorded, the task is considered completed. And if all tasks of a specific goal or completed, then the goal is reached.

Here is a screenprint of a rule to record a task activity about posting comments:

15 text labels: that sounds like 15 goals you'd have to configure using the admin interface of the Goals module (no custom coding involved).

More details

For more details about the Goals module, refer to my answer to "How to implement gamification in a Drupal site and award incentives?".


How to create a includes folder inside sites/all/module/custom/

In one of your custom modules, just create a directory includes and place your .inc files inside it.

To use the .inc files in your .module file, you can use module_load_include.


Drupal: user directory shows blocked users

From your query and the default Block User account user settings option available to the Site Administrator per User:

Simply add into your SQL query WHERE clause the following:

and users.status <> 0

and this will change your user list to NOT include blocked users.


Custom layout for a field in Drupal 7 with using a term id and term name

After looking at https://www.digett.com/insights/change-output-single-field-drupal-7-node I realised that you can use $variables['element']['#items']

term id
$variables['element']['#items']['0']['tid']

term name
$variables['element']['#items']['0']['taxonomy_term']->name


Drush pm-update: How can I stop it from trying to update more recent dev releases?

Basically, this sounds like a bug that should be addressed in the drush issue queue.  I'm guessing this is recent; it used to be that Drush would never go from dev to stable unless you used pm-download.  Now it is being a bit overzealous.

As a workaround, you can use the --lock option to stop Drush from updating the module at all (drush pm-update --lock=heartbeat), but this will also exclude newer dev releases as well.


The only way I can think of is to implement hook_form_alter() and add the "#access" property to the form fields you don't want to be accessible from the user.
Normally you should use code similar to the following one, but every function that returns FALSE when the current logged-in user should not access the form field would work too.

$form['form_field']['#access'] = user_access("access form_field");

The permission the code checks can be any of the permissions the module implements, or other modules implement.


Searching for pager in the issue queue of Views XML Backend shows that the plugin can output the info you want.

You should be able to add to the Header region of the view a Global Results Counter which shows text like "Viewing X of N to M records". All of this is done in the Views Administration UI for your View.

You could then call the page via curl or via views_embed_view using php programatically to pass and or set the page number and records per page as needed to get the results you want.


My submit function for the node form doesn't execute

In node forms the submit callbacks from #submit are not executed. Instead, there are executed submit from #submit property of submit form element.
You should add the submit in this way:

$form['actions'][$action]['#submit'][] = 'yrv_event_trainer_submit';

Here is an example too.


How can I display author name, picture and signature when viewing a full node in D6?

Figured it out. To add a $user_signature variable to your node.tpl.php file, add this function to your template.php file:

function YOURTHEME_preprocess_node(&$vars, $hook) {

  $account = user_load($vars['uid']);
  $vars['user_signature'] = check_markup($account->signature, $account->signature_format);
}


taxonomy with image field is not translating

I tried wolverine's answer but it didn't worked for me, it caused error "#build_id not defined" so I changed it a little, I don't know if it's right solution but it worked for me.

Add only this code in your module:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
    if (($form_id == 'taxonomy_form_term') && (!isset($form_state['triggering_element']) || $form_state['triggering_element']['#id'] != 'edit-delete')) {
        if (!isset($form_state['storage']['rebuilding'])) {
            $form_state['storage']['rebuilding'] = TRUE;

        } else {
            $form_state['no_cache'] = TRUE;
        }
    }
}

Hope it's helpful for someone.


How to Get Views field template to be used in replacement patterns?

If you make this field the displayed field it will take the theme adjustments. Do your rewrite and replacement patters on this field, put it at the end of the field list and exclude the others.  If this field is used as a replacement pattern the theme will not be applied.


Does Drupal resave the photo even if it's already the correct size as your Image Style?

I ran some Md5 tests and sadly it does recompress it again even if it's already the correct dimensions. Is there some way to prevent this? Uncool.


Moving or creating many product variations

Question 1:
until some awesome person posts a different answer, I'm afraid the answer to this is to use "commerce_bpc" to generate all your variations, and then attach your variations to the product by writing a standalone script.  See below.
Question 2:
you can attach variations to a product after they've been created with "commerce_bpc".
field_data_field_product is the table that links variations to products.
Adding new rows where "field_product_product_id" is the variation you want to attach to a product will attach the variation to the product.
also,  add the same row to:  field_revision_field_product and clear cache.


I will try again:

you can var_dump($_POST); to get all posted variables on the site and know the array index in which your application POST's


Drupal 7 in subfolder behind reverse proxy, login not working

As I understood, the #action on the page /user is generated by request_uri, the default action of each form, except for few form that are block (check if the user_login block has the same problem).

I can advise you, to check your PHP config in Report -> Status report and then click on the PHP version an try to find the REQUEST_URI information, this can be different from what you are expecting (I guess /drupal/user).

To fixe it, I see only two solutions, submit an issue (or check if that issue already exists) or the second its to use the hook_form_alter and replace the #action by something like that.

$form['#action'] = url(current_path(), array('external' => FALSE));


How to make drush un-install modules without confirmation

Drush has a -y option, that accepts all questions with a yes. Use that.


How to sort randomly two or more nodequeues in Views but keeping nodes position?

I finally got the solution. It's just about grouping nodequeues.

At fields, select "Nodequeue ID" field. Then you can group by this field at Format options.

To mix nodequeues without altering the nodes sorting within the queue just sort by:

Nodequeue: Position (to keep queue order)
Global random (only nodequeues blocks will be mixed)

I hope this helps.


How can I use PHP to print a view in the content area of a page?

As a starting point I would have the function return the view rather than attempting to print it. Try:

 $content['view'][] = views_embed_view('profile_show_user_interests','show_interests_own', $participant->uid);

and then render it in the page at the proper place. (views_get_view might be better in this context.)


How to export comment fields (or other settings) with Features?

I Managed to do this with the help of the Strongarm module.

In the variables table there are fields like:

comment_xxxx_xx_[content_type_name_here]

for example:
field_bundle_settings_comment__comment_node_my_content_type
comment_default_per_page_my_content_type
..etc

I just selected all of them. It would be better of course to work out what is stored where.

Also in Features in field instances I found fields like:
comment-comment_node_my_content_type-comment_body
..

In Features field_base I found something called comment_body

Exporting those seemed to be everything.
(Not too convenient to hunt fields and whatnot and maybe miss something..)


You should add to your ~/.bashrc file the additional PATH, e.g.:

# Add a Composer's global bin directory if exists.
which composer >/dev/null && export PATH="$HOME/.composer/vendor/bin:$PATH"

It should come first before your other drush. See my full .bashrc for details (bash4 syntax).

Alternatively install drush by specifying COMPOSER_BIN_DIR, like:

COMPOSER_BIN_DIR=/usr/local/bin composer global require drush/drush:dev-master

Assuming that /usr/local/bin is already in your PATH.


Manage Display Field Label not changing: inline does not work

Solved!

I used Firefox Developer Edition tools to find the relevant css code in a working theme.
I copy/pasted this piece of code into the styles.css file of the theme of my choice and adjusted the class-names (single dash instead of double-dash and double-underscore).

To tidy up I should make a subtheme with my adjustments and leave the theme as it is.

I made even a little improvement to the original code: label will be aligned to left of the column and content to the right (I am using Display Suite to divide the content into a column view)

.field-label {
  font-weight: bold;
}
.field-label-inline .field-label {
  float: left; /* LTR */
}
.field-label-inline .field-items {
  float: right; /* LTR */
}
.field-label-inline .field-label,
.field-label-inline > .field-item,
.field-label-inline .field-items {
  padding-right: 0.5em;
}
[dir="rtl"] .field-label-inline .field-label,
[dir="rtl"] .field-label-inline .field-items {
  padding-left: 0.5em;
  padding-right: 0;
}
.field-label-inline .field-label::after {
  content: ':';
}


How to change values views exposed filter based upon view results?

Here is sample exposed filters form altering: http://www.tylerfrankenstein.com/code/drupal-alter-views-exposed-filter-form

Maybe you can call a function which returns fake nodes twice?

So in hook_views_pre_render():

$fake_events = get_fake_events();
add_fake_events_to_rows($view->result);

and calling it in hook_form_alter() too:

$fake_events = get_fake_events();

Any problems with working that way?


How to use "user logged in" as an access argument for a MENU_CALLBACK?

access arguments is for the arguments that will be passed to the callback function...you need to use access callback instead:

'access callback' => 'user_is_logged_in'

Since user_is_logged_in() doesn't take any arguments, you can safely remove access arguments for your menu item.

Your current code works for the admin account only because the default access callback is user_access(), which bypasses the access check for user 1.


For achieving this goal you have to implement hook_nodeapi

In presave operation you can get desired value.

Example code you can get from the D6 release of the Examples for Developers module.


#markup is replacing colon in <gcse:search... tag with space

Use an inline template:

  return [
    '#type' => 'inline_template',
    '#template' => '<gcse:search queryParameterName="query" resultsUrl="{{ url }}"></gcse:search>',
    '#context' => [
      'url' => Url::fromRoute('cn.search', [], ['absolute' => TRUE]),
    ],
  ];


I got it, in my liste_sections($form, &$form_states)

$checkbox_col1 = array(
    '#type' => 'checkbox',
    );

$checkbox_col2 = array(
    '#type' => 'checkbox',
    );

$checkbox_col3 = array(
    '#type' => 'checkbox',
    );

after that, add those variables to the rows :

$rows = array();
    foreach($res as $sql){
        $rows [] = array(
            'sections' => $sql-> name,
            'affichable' => array('data'=>$checkbox_col1),
            'News' => array('data'=>$checkbox_col2),
            'online' => array('data'=>$checkbox_col3),
            );
    }


Selectively purging views from varnish cache

If the views are blocks you can use something like http://drupal.org/project/block_refresh and set a short expiration for the ajax callback that module uses.

If you want to get more advanced, you could strip the JS stuff out of that module and use its ajax callback, then use edge-side includes to have varnish pull in the block content dynamically.


How to disable a module dependents module? Not the module but the feature

If you mean

  Can I disable/uninstall the BEF module without first disabling/uninstalling the BEF Test Content module (or any other modules that depend on it)

Then no, that's not possible.

"Dependency" means that one module cannot function without the other. In this case, the BEF Test Content module will be unable to function unless the BEF module is also installed and enabled.

Drupal understands this constraint, and makes sure the you can't break your site by removing functionality from one module that is required by another.

If you mean

  Can I disable/uninstall the BEF Test Content module without disabling/uninstalling the BEF module

Then yes, you can either disable/uninstall it through the UI as normal, or use Drush. BEF doesn't have a dependency on BEF Test Content, so Drupal won't stop you from removing it.

The only caveat to that is if there are other constraints introduced by the BEF Test Content module. For example, if it provides a field type which is in use, the module cannot be disabled until the field is detached from all entities. But the admin UI will tell you explicitly if that's the case


How to generate more than one pdf from a node?

Print module doesn't support choosing multiple templates and content from the page. You'd have to create a custom module for that which isn't a trivial task.

If you can't code, maybe you can restructure your Reservation page in a way to use different Content types that reference each other (Entity reference). One CT for client info, the other for owner info and a third one for agent info.

You can use Views to display all that info on one page, all together. But Print module would apply to each node separately, so you'd be able to have that separate.

It may be that info you want to show overlaps between PDFs. You'd have to come up with a custom solution for anything more complicated like that.

Maybe you can combine different solutions for different PDFs.

Check out Entity Print, Printing any Drupal Entity to PDF.


How to prevent installing module in already installed module?

How about this?

Create a central module that implements hook_module_preinstall
Follow some naming convention for the modules which should not coexist, or simply gather their names in a list
Use your naming convention or the list of module names in your hook to detect installation of one of these modules. Also, implement the logic for counting the number of such modules that are already enabled in the system.
Conditional on one such module arriving as an argument to hook_module_preinstall and the count of existing enabled modules of this kind being greater than 0, throw a custom Exception in order to block the installation of the said module.
Most importantly, add your central module as a dependency to all of your modules that you wanna control in that way.

Very theoretical answer. :-)
May it be of help to you!


How to clear already rendered "drupal messages" after successful ajax submit?

You can do it in two ways,

First One,

function hook_preprocess_page(&$vars) {
  //if(CHECK FOR THE FORM PAGE)
  $vars['show_messages'] = 0;
  $_SESSION['messages'] = '';
  // END IF
}

Second One is

at the end of the form submit callback write the code like below

unset($_SESSION['messages'])

or

$_SESSION['messages'] = '';


Configure Panels That Uses View With Entity Reference For User Profile

The %user portion of your URL is called an argument.  Your final screenshot shows that argument and that you can use %user_uid in your page.  So that's the context handled.

Instead of a page or block, make a content pane for your view, you will need to enable the Views content panes if you haven't already.

In that content pane, set your argument to From context and choose User->User ID from the dropdown.  This tells the view where to get the information for your contextual filter (which looks ok I think).

Once you have saved that, go back to your page in page manager and insert the view pane as content, it will ask you where to get its argument from, choose Argument 1 because that will refer it to the %user portion of your URL.


Check if there are any elements with a certain class in the form array of unknown depth

You can try this for your recursive function.

function containsClass($array, $class) {
  if (is_array($array)) {
    if (in_array($class, $array['class'])) {
      return true;
    }

    foreach ($array as $element) {
      if (containsClass($element, $class)) {
        return TRUE;
      }
    }
  }

  return FALSE;
}

The problem with your function was that it's not returning the result of containsClass() when it's called recursively. However, you only want to return the value if it's TRUE, which is why I added the conditional to check that. Finally, after all items have been looped through, if no TRUE value is found, FALSE should be returned.


How to use an user profile custom field using Rules?

... since the Field select list has disappeared and custom fields are hidden in the Data selector suggestions.

The above is a partial quote of your question. IMO that's not correct. Instead it should say "... since the Field select list does not appear yet and custom fields are not shown yet in the Data selector suggestions".

And similar to the (my) answer to the question you linked to: those or some of the things that are still missing in the most recent D8 version of Rules. Refer to #d8rules status update November 2017 to get a better understanding of the current status of Rules for D8.

One never realizes what has been done, only what remains to be done ... So start here if you wonder how to contribute.


Override theme function for menu callback

After a lot of googling, I found a nice solution to my problem.

First, one needs to register its menu with callback (in a custom module):

function MY_CUSTOM_MODULE_menu() {
  $items = array();
  $items['my_link_url_path/%'] = array(
    'title' => 'content title',
    'page callback' => 'MY_PAGE_CALLBACK',
    'page arguments' => array(1),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
   );
   return $items;
}

Then the HTML content you want to be in the lightbox has to be printed in the callback function (you can define this function in your custom module file) as follow:

function MY_PAGE_CALLBACK($MY_PASSED_ARGUMENT = NULL) {
  print 'This is my HTML content displayed in the lightbox: Arg = ' . $MY_PASSED_ARGUMENT ;
}

The trick comes from the fact that you do not return, but print directly the output. No theme layers will be processed.

Just add your link somewhere (with the lightmodal rel attribute if you are using Lightbox2 (http://drupal.org/project/lightbox2):

Click me

This will display 'This is my HTML content displayed in the lightbox: Arg = 345' in a lightbox.

Note: don't forget to empty the cache when changing your menus...


Drupal How to add javascript to ctools modal popup

You must use: ctools_ajax_command_attr('selector','attr','value'); do perform any kind of actions in popup. For more you can read: http://drupalcontrib.org/api/drupal/contributions!ctools!includes!ajax.inc/7


Can't get preprocess_node function to override items

If you look at node.tpl.php, the title is being printed like this:

<?php if (!$page): ?>

<a href="<?php print $node_url ?>" title="<?php print $title ?>"><?php print $title ?>

<?php endif; ?>

As you can see that's using the $title variable, not $node->title.

There's a one-to-one mapping between the array keys of the template's variables, and names of variables available in the template file. If you have $variables['my_awesome_var'] in the preprocess function, that variable will be available as $my_awesome_var in the template file.

So with that in mind, all you should need to do in your preprocess function is this:

function mythemename_preprocess_node(&$variables) {
  //Profiles
  if ($variables['type'] == "child_profile") {
    $variables['title'] = 'Test';
  }
}

To complete the thought - you could also change the node template to print $node->title instead, and your current code would work fine. But since the original template file uses a separate $title variable, it would be better to stick to convention and use that method.


The easiest way I think is this:

Install the views, views_bulk_operations, and admin_views modules.
Go to the content listing (admin/content).
Filter the results to get the nodes you are interested in.
Check the checkboxes next to the node (there is also an option to select all).
Select "Change author" from the operations dropdown and click the "Execute" button.
Select the user you want to change the author to and click the "Next" button.

Admin views uses views bulk operations to override the default drupal administration views with something a lot more useful.


View item duplicates based on total views

Solved it by removing Node count: node id I used the wrong fieldto display the id


jquery script on view not working when filtering with (ajax on) 'better_exposed_filters' module

Thanks to Clive answer i have solved out the problem embedding to my theme script file :

 Drupal.behaviors.betterExposedFilters = {
    attach: function(context) {  }}

now having:

 (function ($) {
Drupal.behaviors.betterExposedFilters = {
        attach: function(context) {

    $('.node-photos-teaser').mouseenter(function() {
        $(this).addClass('photos-hover');
    }).mouseleave(function() {
        $(this).removeClass('photos-hover');
    });

        }}
})(jQuery);

renders compatible the JQuery from my theme with ajax from betterExposedFilter module


From Where to Put the Module Files:

  Manual import location

  If you import a module 'manually', you should place your module in that same default recommended location, HERE:

  [d8-root]/modules/HERE

  [Themes: [d8-root]/themes/HERE]

It's a good idea to keep custom and contrib modules separate, hence Drupal Project putting contributed modules into their own folder; following on from that, there's a pretty common convention to place custom modules under [d8-root]/modules/custom/. But you don't have to, you can use whatever hierarchy you like under /modules, Drupal will pick up anything it finds recursively.

After it's in place, don't forget to enable the module, or it won't do anything.


I have installed contact module and SMTP Authentication Support but do not appear in Structure tab

You should install the devel module from http://drupal.org/project/devel and after that you can select rebuild menu or flush all cache function. (From the devel menu)
If i doesn't work, maybe there was some problems with your installation. You should disable and enable these modules again or run update.php script.


You can use the form_api #after_build property to set a callback where you can manipulate the individual radio button elements (not the grouped "radios" element).

function your_form(&$form, $form_state) {
  $form['radios1'] = array(
    '#type' => 'radios',
    '#title' => 'Radios 1',
    '#options' => array(
      0 => 'zero',
      1 => 'one',
    )
  );

  $form['radios2'] = array(
    '#type' => 'radios',
    '#title' => 'Radios 2',
    '#options' => array(
      0 => 'zero',
      1 => 'one',
    )
  );

  $form['#after_build'] = array('your_form_after_build_function');

  return $form;
}

function your_form_after_build_function($form) {
  $form['radios1'][0]['#states'] = array(
    'checked' => array(
      ':input[name="radios2"]' => array('value' => 1),
    ),
  );

  $form['radios1'][1]['#states'] = array(
    'checked' => array(
      ':input[name="radios2"]' => array('value' => 0),
    ),
  );

  $form['radios2'][0]['#states'] = array(
    'checked' => array(
      ':input[name="radios1"]' => array('value' => 1),
    ),
  );

  $form['radios2'][1]['#states'] = array(
    'checked' => array(
      ':input[name="radios1"]' => array('value' => 0),
    ),
  );

  return $form;
}


There are some issues in the views queue that can help out with fixing these issues. This issue is very similar to the issue you are having (Empty rounded numeric fields not hidden properly). It has a patch that should fix the issue that has been reviewed and tested by the community but has not made it into dev yet. You could either patch views or write your own numeric views handler to fix this issue.


Unlike other rules my custom Commerce Fees rule is executing on every cron job

I take from the rule export that you're using Commerce License Billing? Well, if you are, then likely it is applying the fees whenever doing it's billing calculations.

Commerce Fees defines it's own rules event that fires off when an order refresh occurs. Order refreshes are done by calling commerce_cart_order_refresh(). When you load an order, a hook_commerce_order_load() gets invoked and commerce_cart has a commerce_cart_commerce_order_load() hook that refreshes orders if certain criteria are met:

The order hasn't been refreshed in this request.
The order is a shopping cart.
The order is the latest revision.
The order can be refreshed. (Commerce 1.9 added new rules to add performance by regulating this better.)

Long story short: It sounds like your install is working fine and in general unless you have thousands of rules firing on every page request, there is little to worry about. Rules are effectively just a wrapper around plan PHP functions. Your cron is running and a new order is being generated or refreshed in some way and so the rule fires.


{% set uri = item.url.toString %} will also work.


The user ID field on Drupal is auto-incremented, so you don't want to import your ID values into that field. It's much better to add an original_id field to retain the legacy user IDs.


You can download bootstrap package and include it in your theme folder.

and go to admin/appearance/settings/bootstrap
then go to 'Advanced' and change CDN provider to custom.
give your local bootstrap css,js urls.

if you need to import it to a custom theme you can add it the bootstrap package like below.

your_theme.info

stylesheets[all][] = css/bootstrap.css
scripts[] = js/bootstrap.min.js

define the regions you need in your custom theme info file.

remmber to use the 'https://www.drupal.org/project/jquery_update' module for JS.


Sounds like a job for field_collection and entityreference

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


How to create a 'most popular content' view?

After activating the "Statistics" core module and checking the "Count content views" option in /admin/config/system/statistics, as you mention, you can select "Total views" as sort criteria (see screenshot).


How to create a custom field that gets URL counts from LinkedIn on external articles?

I managed to create a custom module for this with specific fields for twitter an linkedin. The module will call the JSON function every time the node is saved.

Additionally, a cron has been set up to be run every 5 minutes and re-save the nodes which make the node to be updated with the right count.


User register endpoint showing notifications

Base on you're working with RESTful API and does not need these messages anymore you can disable them ( all of them or parts of them based on what you don't want)
by  Disable message module :

Gives a site owner options to disable specific messages shown to end users. The core drupal message system as offered by drupal_set_message is an excellent way for modules to send out messages to the end users. However not all drupal site owners are keen to show all the messages sent out by drupal core and all modules to their users. This module gives site administrators a reasonably powerful way to filter out messages shown to the end users.

Features

Filter out messages that match a full text string exactly.
Filter out messages that match a regular expression.
Permissions to specifically hide all messages of a given type from any role.
Disable all filtering for specific users.
Disable all filtering for specific paths.
Apply filtering only for specific paths.
Debug system to get messages in the HTML without showing it to the end users.

or another solution is  on the theme prevent it got rendered by  this solution : https://www.drupal.org/forum/support/installing-drupal/2011-01-23/how-to-turn-off-error-messages


That would need a combination of SelectQuery::addExpression(), and SelectQuery::having(), e.g.

$query = db_select('tn_api_users', 'u')
  ->fields('u', array('row_id', 'name', 'email'))
  ->groupBy('name')
  ->having('name_count > 1');

$query->addExpression('COUNT(name)', 'name_count');

Output:

SELECT u.row_id AS row_id, u.name AS name, u.email AS email, COUNT(name) AS name_count
FROM
{tn_api_users} u
GROUP BY name
HAVING  (name_count > 1)


How do you export forum topics from one drupal installation to another?

If your environments can communicate via rsync then use
drush sql-sync

Check the syntax www.drushcommands.com/drush-7x/sql/sql-sync to see how to pass a list of tables via the tables-list parameter.

else just use mysqldump.


You can just go to "Structure > block layout" from the admin bar. This will default to your current default theme but along the top of that page it will list out all other active themes and "Seven" will be one of them

Click that and the block listing will now be for the Seven theme and you can add/remove blocks like you can normally except it will now be for the Seven theme

You wouldn't be able to place a block midway through the form but you could add a block above/below the form


Attaching Google PHP Library to custom module

I advise using composer to do this.

First, you need to pull in the library:

composer require googleads/googleads-php-lib:dev-experimental

The reason you want the experimental branch is it has added PSR-4 support and namespaces to its various classes. The master branch does not have these changes.

Then, to use any of the classes in your own class files, you need to use use statements.

use Google\AdsApi\AdWords\AdWordsServices;
use Google\AdsApi\AdWords\AdWordsSessionBuilder;
use Google\AdsApi\AdWords\v201605\cm\OrderBy;
use Google\AdsApi\AdWords\v201605\cm\Paging;
use Google\AdsApi\AdWords\v201605\cm\Selector;
use Google\AdsApi\Common\OAuth2TokenBuilder;

class MyController extends ControllerBase {

  // code...

  public function foo($args...) {
    $adWordsServices = new AdWordsServices();
    // code...
  }

}

Check the README in that branch (not the master) for more examples.

https://github.com/googleads/googleads-php-lib/tree/experimental

composer require (run it from the root of the application) will add this package to the list of dependencies.

If you are shaping this module to someday be a contributed module on drupal.org, you can add your own composer.json file to the custom module folder, and add this Google package as a dependency of the module. When users run composer require drupal/drupal_rollers_module - it will automatically fetch the Google library as well for them.

One last thing, the example above is kinda not so great (instantiating a new object in a method) and what you really want to do is have dependency injection provide that for you. I haven't taken a deeper look at the Google library you want, but you would need to define some services that pull in those classes in order to get to that point. Feel free to open another question later or peruse the ones already discussing DI.


How do you set the #options paramater for checkboxes and radio buttons?

The only thing I could suggest would be to try using '#type' => 'radios' and '#type' => 'checkboxes' instead of radio and checkbox. I believe radio and checkbox without the s on the end only show one option as more of an on off option.

Try having a look at Forms API for more explanation


Node Field must be expecting date field value in unixtimestamp format while the custom form will return the value in the format mention as '#date_format' => 'Y-m-d'. View of your form submit values will look like.

You should run the submit date value through strtotime() to get the unxtimestamp value for it before assigning it to node field.

$node_wrapper->field_due_date6->set(strtotime($form_state['values']['comment_date']));


How to create a single page checkout for donations but standard cart/checkout for for other ecommerce?

You can use Commerce Buy One Click module.
The Project page says

Commerce Buy One Click Module allows customers to checkout directly
from the product page with just one click, skipping the annoying
checkout steps.

For more info go through the module documentation.


The wrapper of Text field is changing after adding a new item in a field collection

I have find a solution. I add this code to ajax function and it solves my issue.

$index=0;
    $index= $form_state['triggering_element']['#field_parents'][2];

  return $form['field_smart_objectives']['und'][$index]['field_smart_objective_task'];

Thank you


Create videoplayer shortcode module for drupal 7


How can I show children in the taxonomy teaser views of parent/grandparent terms?

You can try adding taxonomy as a hierarchical structure like

Term 1
Term 1-1
Term 1-2
Term 1-3

Term 2
Term 2-1

Then you can get the display using either

Taxonomy Menu Trails

And css as you wish.

Good Luck.


The problem was that the views folder was on the ROOT/modules folder, and not on the ROOT/sites/all/modules folder.


Custom Drupal (Block)Module not showing in Blocks

Code looks fine to me, except for the sometimes funky indenting :)

Your function lta_hoa_timeline() just returns ... in example code. If your actual code contains a whole of stuff instead of ... and you have trouble getting that to work/display, it might have something to do with the inclusion of CSS/JS files. At the very least you should see the title of the block appear.
But if ... is your actual returned content, it should work.

Verify that you've put your block in a region, that your theme displays that specific region, and that your block is not restricted to any specific page/role/.. , and you should see your block.
As suggested above, switch to a default theme, put block in a standard region like sidebar left, and turn off all restrictions


using a custom module, how to add a  tag after the theme's css files

Everything you add with drupal_set_html_head() is added before the CSS styles added with drupal_add_css(). In fact, the page template outputs them using the following code.

<head>
  <?php print $head; ?>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $scripts; ?>
  <script type="text/javascript"><?php /* Needed to avoid Flash of Unstyled Content in IE */ ?> </script>
</head>

$head and $styles are initialized in template_preprocess_page() with the following code.

$variables['head'] = drupal_get_html_head();
$variables['styles'] = drupal_get_css();

As drupal_add_css() is used to add all the CSS styles used by a theme, including the ones defined in its .info file, you can change the order the CSS styles are added by changing the page template. If it would contain the following code, everything added with drupal_set_html_head() will come after everything added with drupal_add_css(). I would not suggest doing this, if not after verifying it doesn't cause any problem.

<head>
  <title><?php print $head_title; ?></title>
  <?php print $styles; ?>
  <?php print $head; ?>
  <?php print $scripts; ?>
  <script type="text/javascript"><?php /* Needed to avoid Flash of Unstyled Content in IE */ ?> </script>
</head>

Notice that with Drupal 7, you can use drupal_add_css() to use inline CSS style too: Just pass the CSS styles as first argument, and pass array('type' => 'inline', 'weight' => 100) as second argument. You need also to use the group property. In that way, you don't need to alter the template file just to add your CSS  styles after the ones added by Drupal.
Generally, it is preferable to add the CSS styles in a file; in that way, they can be aggregated/compressed.


Change / Set Node Reference field in hook_form_alter

With Clive's help, I was able to figure out the array structure I needed. To set the node ID for a Node Reference field (References Module) in hook_form_alter, this structure worked for me:

$form['field_name'][LANGUAGE_NONE]['#value'][0] = {node id}


Where is the 'display post information on' settings?

It's under "Structure > Content Types > your content type  > edit > Display > Settings."


Content Encoding Error - The page you are trying to view cannot be shown because it uses an invalid or unsupported form of compression

Looking in the log file there were some FastCGI references, but in ISPConfig I had PHP-FPM selected. Once it was switched to MOD-PHP all of my problems disappeared.
I can't even.


For drupal 8, use the following.
In the 'scripts' section of your composer.json, add

"post-drupal-scaffold-cmd": [
  "patch -p0 < patches/htaccess.patch"
]


Module to display file from an SVN repo?

Have a look at
Version Control API with Version Control API -- Subversion backend

I didn't use it but you can try

  This module provides an implementation of the Version Control API that
  makes it possible to use the Subversion revision control system.

P.S. Drupal 5 and 6 only


Drupal Commerce hide cart to non authenticated users

A quick fix might be to write a tiny custom module that overrides the access callback for the cart page:

function MYMODULE_menu_alter(&$items) {
  $items['cart']['access callback'] = 'MYMODULE_cart_access';
}

function MYMODULE_cart_access() {
  if (user_is_logged_in()) {
    return user_access('access content');
  }

  return FALSE;
}


Why are my fields are out of order when viewing?

Reordering the fields for the content type only affects the edit/add form. To change the order of how they display (and other things, such as label display/placement) you need to go to Structure -> Content Types -> [Your content type name] -> Manage Display -> Default.


How can I set up the media file selector for an image with the image styles in the same row?

You can use the Formatter Field module to choose an image style per entity

  The formatter field module provides a mechanism for specifying a formatter and formatter settings to be used for displaying a field, on a per-entity basis. By default, Drupal provides formatters and settings per entity bundle, but in certain situations it is necessary to choose the formatter at the entity level.

But I don't think anything exists to choose a formatter per delta of a field. You'd probably need to look at coding that one yourself. The Formatter Field module would be a good place to start to get ideas for the code.


Drupal7 provoking ajax error in Views (installed in sub folder)

I have found that my problem is distinct: the AJAX request has included the www in front of my domain meanwhile I have set the default without www.

So I had to change in settings.php the base_url FROM 'http://www.mydomain.com' TO 'http://mydomain.com'

Cheers


Limit entity reference widget to unique references

I don't think the Entity Reference module ships with this feature. But the entityreference unique module should be sufficient for your need. It is in alpha mode, so I would check the issue queue to see if there are any security/critical issues with it before using it on a production env.


Showing all results of custom content type in every page

The simplest solution would be to to call views_embed_view in the page--front.tpl.php file (page-front.tpl.php in D6).

The more complex solution I would go with, is using Panels everywhere, and expose the View as a content pane.


Ubercart need to pay depends on user role

This question has been solved and just want to put the solution here to help someone has the same interests!

Download the uc_purchase_order module, http://drupal.org/project/uc_po

And give the permission to the user role you want them to purchase through purchase order.


Create view containing all content containing taxonomy terms in free text?

If I understand correctly, you want to have one page that will display nodes grouped by taxonomy term they belong to so that the result is like this:

Term 1

article 1
article 2

Term 2

article 2
article 3

Term 3

article 1
article 3

To achieve that:

Create a view to display all content of [content type name] and select the node fields you want to display in place of article 1,2,3 (probably title of the node at least).
Add relationship "Content: Taxonomy terms on node" and decide which taxonomy you want to narrow down the display.
Under View field, there should be now a list of Taxonomy related fields. You probably want to add field "Taxonomy term: Name". Exclude that field from display.
Under View  format settings, select to Group By that taxonomy field.


Login form on restricted page doesn't accept login credentials

A possible explanation for what is happening is that this is implemented via some custom rule, created with the Rules module (at least that's how it "could" have been implemented with a rather basic custom rule).

So if you have the Rules module enabled in your site, you may want to do some Rules debugging, as explained in my answer to "How can I display the value of a variable inside a condition?".


Drupal 8 - How to Reference Flags Twig Template without showing full content?

FOUND IT

Alright guys, so it's simple.

You reference the flag this way in your Twig Templates:

{{ content.flag_machinename }}

Cheers.


You can create custom VBO action by implementing hook_action_info() hook. Here are some useful links which can help you achieve what you want:

Views Bulk Operations development guide (Drupal 7)

Programmatically adding and removing roles to users in Drupal
HOWTO assign a user to a role programatically

additionally, Examples module can help you to learn about Actions.


Allow downloading files from private filesystem when paths to files are built without Drupal

Here are a few modules that should help you configure the way files are served.

Storage API module. It provides advanced file storage and serving options; such as to upload or serve from a separate server, via ftp, etc. It's my favorite option. I currently use it to host all files on a separate server.
CDN module. Designed for CDN related tasks, but can be used in your case to specify an alternative file location for specific file types.
Remote Steam Wrapper module. Not sure if this will work for private files. It makes it easier to serve external files.
Media Mover module. Provides advanced file serving possibilities, i.e. get files from a FTP server, provide file tokens for authentication, get files from CCK fields, etc. It's only available in development version.

Update

If you want to do it via custom code, use field_view_value() function to pull the URL from the field. Use file_create_url to create URL for streaming. You'll also need to use hook_file_download to allow the file to be downloaded; otherwise you will get a page not found.

Update

If I understood correctly, you have a field, where you enter the file name (i.e. myFile.pdf), and you rewrote its field theme (field--field_myfield.tpl.php) to generate the full location of the file. The problem here, is that you cannot include hooks/functions within a theme. Your solution would be to construct the file location in a custom module or template.php.

Example of rewriting the field value via template.php. Replace MYTHEME with your theme name.

function MYTHEME_preprocess_field(&$vars) {
  if($vars['element']['#field_name'] == 'field_myField') {
    $filePath = '/secret/location/' . $vars['items']['0']['#markup'];
    $vars['items']['0']['#markup'] = file_create_url($filePath);
    return;
  }
}

If you want to check for permissions, use hook_file_download.


How to use Form API #attached and module's own scripts with jQuery Multi module?

Solution seems to be to hack jQuery Multi module.

First, we want to add module-provided libraries to the list in configuration options. Function responsible for it is jqmulti_get_available_libraries():

/**
 * Returns available libraries to be used in the admin form.
 */
function jqmulti_get_available_libraries() {
  $libs = libraries_get_libraries();

  unset($libs['jquery']);
  foreach ($libs as $key => $value) {
    $libs[$key] = $key;
  }
  return $libs;
}

To display module-provided libraries, we need to add following line:

$libs += module_invoke_all('library');

Of course now it looks ugly:

List is long and hard to understand, because these are machine names only. Red colour used to distinguish element I added by hand after taking screenshot, it's all black folks.

Form element is defined in jqmulti.admin.inc, but it's the only place that ever uses jqmulti_get_available_libraries(), so we may stay inside it instead, to limit changes to narrow area. If we change this:

  foreach ($libs as $key => $value) {
    $libs[$key] = $key;
  }

to this:

foreach ($libs as $key => $value) {
  if(isset($value['title'])) {
    $libs[$key] = '' . $value['title'] . ' ' . @$value[version] . ' (' . $key . ')';
  } else {
    $libs[$key] = '' . $key . ' (' . $value . ')';
  }
}

output will get a lot more readable:

Again, blanked a project-related row but it is there all right.

But now the fun part begins. I can save, but logic is all wrong:

  Warning: scandir(sites/all/libraries/product_form): failed to open dir: No such file or directory in jqmulti_find_all_js_files() (line 180 of /var/www/sites/all/modules/jqmulti/jqmulti.module).
  Warning: scandir(): (errno 0): Success in jqmulti_find_all_js_files() (line 180 of /var/www/sites/all/modules/jqmulti/jqmulti.module).
  Warning: Invalid argument supplied for foreach() in jqmulti_find_all_js_files() (line 181 of /var/www/sites/all/modules/jqmulti/jqmulti.module).

Error is located in function jqmulti_find_all_js_files($dir) function. Obviously module still tries to use old way of scanning /sites/all/libraries even when I clicked a library that is not there. Function is called from jqmulti_get_library_files($library, $reset = FALSE) that blindly assume all files are in 'sites/all/libraries'. First, it's a bug in it's own right, second it's not sufficient. We need to change:

$base_path = 'sites/all/libraries';

to something smarter. For example:

if(isset($libraries_libraries[$library])) { // Give precedent to old way
  $path = $libraries_libraries[$library];
} elseif(isset($module_libraries[$library])) {
  $path = NULL;
  $files = array_keys($module_libraries[$library]['js']);
} else { // Fallback to the old way, for what it's worth
   $path = $base_path . '/' . $library;
}

As you can see, if module gave us files already, there is no need to play with $path, we may use it directly. So code below needs to be wrapped in if.

That's all, now it works. Without conflict with Views, but with all jQuery Multi's own issues, some especially urgent for me.


Using jQuery to copy some content from div to input value - value displays nicely but there`s no value in html

The value attribute for text inputs determine the initial value, it does not change when the user inputs something in the field or when it's changed by JavaScript.

If you are experience some error, it's most likely something else that's the problem.


As it currently stands it is not possible for Drupal to run a pure MongoDB installation with Drupal. Drupal has made a lot of progress towards abstracting out database connectivity into a central model layer with Drupal 7 and Drupal 8 promises even more. However it is still a work in progress and while a majority of the functionality is available as MongoDB backend, as it stands today a few of the components remain dependant on SQL.

As most of the work to port Drupal to MongoDB has been towards scalability and performance, it is possible to have a site where public page views are 100% on MongoDB. Performance benchmarks on a MongoDB backed Drupal instance are quite impressive.


Stuff added to  not included in cached version

This is a totally valid question in my opinion. Using the PHP input filter (or eval() in general) is almost never a good idea, but the fact that this code only runs once is not intuitive.

That said, I actually can't reproduce this.

My first thought was that the rendered HTML was being cached in the cache_filter table. But by default, the PHP Input filter is not cached in the cache_filter table. php_filter_info() from php_module:

function php_filter_info() {
  $filters['php_code'] = array(
    'title' => t('PHP evaluator'),
    'description' => t('Executes a piece of PHP code. The usage of this filter should be restricted to administrators only!'),
    'process callback' => 'php_eval',
    'tips callback' => '_php_filter_tips',
    'cache' => FALSE, // <- This is set to FALSE in the module
  );
  return $filters;
}

My next guess was that the anon user Page Cache was somehow ignoring the fact that those functions had been called. But I tested both drupal_add_html_head and drupal_add_js (the latter with both an external file and inline JS) and even for anonymous users, the JS was loaded and executed on all page views with and without the page cache enabled. I also tried all of these scenarios in the default body field and with a field added with the Field API.

I guess that means that my answer is one of the following:

Something is overriding php_filter_info() to set 'cache' => TRUE
You have an additional layer of caching that's causing this on your server
Something else???


how to validate email id is already register or not

This can be done with hook_form_alter:

function module_(&$form, &$form_state, $form_id) {
  $user_login_forms = array('user_login', 'user_login_block');
  if (in_array($form_id, $user_login_forms)) {
    $form['#validate'][] = 'my_validate_function';
  }
}

function my_validate_function(&$form, &$form_state) {
  $name = $form_state['values']['name'];
  // Drupal 6:
  if (!db_result(db_query("SELECT COUNT(*) FROM {users} WHERE name = '%s';", $name))) {
    // User doesn't exist
  }
  // Drupal 7:
  if (!db_query("SELECT COUNT(*) FROM {users} WHERE name = :name;", array(':name' => $name))->fetchField()) {
    // User doesn't exist
   }
}

It's better to query the DB directly in this case than than using user_load as it hooks into other modules as well.


restrict user access to sub domain if assigned to another sub domain

the Domain Bonus module can help you solve this problem.

  The Domain Bonus is group of modules that extend functionality of Domain Access module.

check the "Domain Bonus: Login restrict" sub module


Can I get Entity Cache Tags from a Route?

Adding my eventual solution based on @No Sssweat's comment.

I created a method in a service like:

public function getEntityFromRoute(RouteMatchInterface $route_match) {
  foreach ($route_match->getParameters() as $param) {
    if ($param instanceof EntityInterface) {
      return $param;
    }
  }

  return FALSE;
}

Then I have code like the following where I'm not entirely sure what entity type may be providing the route:

$route_entity = $MY_SERVICE->getEntityFromRoute(\Drupal::routeMatch());
$cache_tags = [];
if ($route_entity !== FALSE) {
  $cache_tags = $route_entity->getCacheTags();
}

Then I create my render array using the cache tags.


How to get the value from the url in the function argument?

What you are looking for is either:

arg() function:

  Returns a component of the current Drupal path.

  When viewing a page at the path "admin/structure/types", for example,
  arg(0) returns "admin", arg(1) returns "structure", and arg(2) returns
  "types".

or Callback Arguments:

function mymodule_menu() {
    $items['abc/def'] = array(
      'page callback' => 'mymodule_abc_view',
      'page arguments' => array(1, 'foo'),
    );
    return $items;
  }

When path 'abc/def' is requested, the page callback function will get 'def' as the first argument and (always) 'foo' as the second argument.


Submitting a form with AJAX causes page reload but only on mobile

Solved:

I have just downloaded the latest development version of jQuery Update module and the problem was solved. It has to do with this module nothing else.


drupal 7 programatically close comments in custom node type

$node->comment should be an integer (not an array). Acceptable values are:

COMMENT_NODE_CLOSED
COMMENT_NODE_HIDDEN
COMMENT_NODE_OPEN


How to vary classes depending on content type?

Not sure about page.html.twig. Would have to dig around...

In node.html.twig:

{%
  set newClassNameVar = [
    node.type.entity.label == 'Program' ? 'Program' : 'Not Program'
  ]
%}

or:

{%
  set newClassNameVar = [
    node.bundle == 'content__type' ? 'set-yes-class' : 'set-no-class'
  ]
%}

use debug such as {{ dump(_context | keys) }} to see what is available and best suits your use case.


Blur text or words in posts for anonymous users

How about the Blurry module?

  Overview

  This module can make your text fields blurry.


Empty View does not display "No results behavior" for admin

I had somewhat complex filter criteria that was causing the issue for admin.
One would think that this should not cause an issue, but it seems to.


How do I alter a message in the message queue independent of site language?

You can compare messages using the t() function, as it will localize both messages and compare them.
Just use the original text in English you want to find and wrap it in t() function. E.g.:

if ($message == t('This is a sample message')) {
  // Alter the message/perform additional processing.
}


How do I move a Drupal site from WAMP server to a live server?

You should check your user privilege on your production server because you can't do this action.

This thread deals with your problem : https://stackoverflow.com/questions/8838777/error-1044-42000-access-denied-for-user-localhost-to-database-db