How to create toggle effect using jQuery?

If you prefer to handcraft you can create a template (look inside your Views template suggestions) and paste inside this code. Then using functions like views_get_view_result() you can fetch views field and use them inside it.

<?php
    drupal_add_library('system', 'ui.accordion');
    drupal_add_js('jQuery(document).ready(function(){jQuery("#accordion").accordion();});', 'inline');
    ?>

Section 1

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Section 2

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

Section 3

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.


This is a good example where Rules module can help you. I myself probably just write some custom code, since that's easy for me. But if you don't want to/can't do this, Rules can help you.

You can setup a rule, that is executed when a new user is created that will create a content of the chosen type. With tokens you can populate the values needed.

Using Rules can be a bit complex, but it's very powerful.


How to translate the book pages content using the Book Translation module?

If I understood your question correctly, you need to enable translations for the "Book page" content type.

Go to /admin/structure/types and click on "Edit" next to the content type you use for storing the book pages.
Under "Publishing options" make sure that "Multilingual support" is set to "Enabled, with translation".
Save the content type.
After you save this, you can go back to the edit page and configure extended language options in "Multilingual settings" tab.


You just need to make sure the library is added to the request.

For example, to include the library on every page:

function THEME_page_attachments_alter(array &$attachments) {
  $attachments['#attached']['library'][] = 'colorbox/colorbox';
}


How can I tell boost cron run to delete a file

First you need to set a flag which indicates that new fields are added. Can be a variable_set() or something similar thats stores values in DB whenever new fields are added.

In your hook_cron() you should check if the flag is set or not. If set clear Boost cache using boost_cache_clear_all(). Unset the flag once cache is cleared.


what is "field_create_field" and "hook_field_info"? is there difference motive

function field_create_field is used to create a field. When you debug this function you will get $field array with the id property filled in.

function hook_field_info defines Field API field types. For more info refer here.

For more clarification you can simply debug both these functions then you will get the all basic differences.


Programmatically trigger rules action component

if its a rule action component than it should be called by

 rules_invoke_component('name', $other_parameters..);

while rules_invoke_event() is suppose to trigger an event on which you might have different rules to act on.


Fresh install with minimal: missing manage display even with field_ui turned on

For displaying Manage Display tab on content page you have to install Display Suite module.

On drupal core no such module or configuration  that display this tab on content page. So you didn't forget anything for this.


After removing MODULE-Name_views_default_views() in file MODULE-Name.views_default.inc, the view was exporting in another feature/module just fine.

My learning is that if you rename views that are part of some feature/module say X then these views become impossible to export from any another feature/module Y unless you manually delete them from the MODULE-X-Name_views_default_views() in MODULE-X.views_default.inc file


How do I pass a PHP variable to Drupal.settings global javascript?

calling drupal_add_js in hook_init is a fairly standard response to this kind of question, as is hook_boot.

hook_init is used for setting up things required by the page - but doesnt run on cached pages.

hook boot is used for code that has to run on cached pages as well as uncached pages.

The way I usually debug this kind of thing is with the javascript console. In chrome, open the console and type

Drupal.settings

hit enter and it should print out the whole settings object for you to inspect. This will let you see what you have.

I suspect the problem may be down to when hook_page_build gets fired on admin pages if Im reading your question correctly.

Uncaught TypeError: Cannot read property 'my_var' of undefined

means that

Drupal.settings.MY_MODULE

evaluates to undefined. It could be at any level.
so try the javascript console trick and see what you find (is Drupal there.. is drupal.settings there).

you could also try

(function ($) {
    Drupal.behaviors.MY_MODULE = {
    attach: function(context,settings) {
    alert("test");
    alert(settings.MY_MODULE.my_var);
   }
  }
})(jQuery);

which is more keeping with how it is documented for behaviours on drupal.org


Profile 2 display field on my account page

you can enable profile2 pages, that comes with the core of profile 2

That module will add different pages per profile types in the user account. so your users can select their profile and check for the fields they filled during registration


How may I simplify the registration process

You could do it using Flag and Views.

Once you create a node flag, then all the user needs to do is click on the node flag to register to the event/interview.

If you need to know which users have registered for an event, in Views, simply add a relationship of flag (can't remember the exact relationship name, but I am sure you can figure it out, might be "users who flagged").


You will need to install the module on each site using the same UA# (assuming these should all be tracked under the same account).

All you need to do is select One domain with multiple subdomains for everything to track properly.


The class that registers the Twig service is CoreServiceProvider which, in CoreServiceProvider::register() (the method that every service provider needs to implement), uses the following code.

  // The 'request' scope and service enable services to depend on the Request
  // object and get reconstructed when the request object changes (e.g.,
  // during a subrequest).
  $container->addScope(new Scope('request'));
  $this->registerTwig($container);
  $this->registerModuleHandler($container);

The class used for the Twig service is not the Twig_Environment class that Symfony implements, but a subclass of it (TwigEnvironment) implemented by Drupal.

The other registered service is twig.loader.filesystem, which uses the Symfony's Twig_Loader_Filesystem class.


Content Type Fields, populate field with usable data when adding new content

Don't worry you don't need to start again, this is such a common use case there are actually 3 modules out there that you can choose between.

Entity Reference
References (can be considered deprecated in favour of entity reference).
Relation (allows for complex relationships, probably overkill for your case)

All 3 will allow you to add a field to your track content type that references an album node. You can choose from a select list, radio/check buttons or autocomplete widget out-of-the-box but I'm sure there are add-ons available if you need them.


How can I print a custom message for unpublished nodes upon submission?

First, you should be using the current -dev version of Rules - that will make it much easier to do what you want.

Second, for the "Node is of type" condition, switch to the data selector for the first entry then select "node" from the data selector. This is the data object "node" that was created. For the content type, enter the machine id of the content type using the direct input mode (the default).


How do I implement a reverse node reference using References?

You can use https://www.drupal.org/project/cer
You can then setup the reference both ways so when you add a reference on the first piece of content CER can add the back reference to the other piece of content.
Another option is to add a rule which will do this for you but CER is pretty solid when dealing with larger sites.


Is it possible to extend an existing contributed module?

If you're using core's configuration sync to manage your site's config, you should be able to update this through the UI, then export your site's configuration to the sync directory, e.g. drush cex sync. This will create a new file in the config sync directory for the updated config which can be safely committed along with your other changes. While deploying, you'll need to import the synced configuration, e.g. drush cim sync to import the UI change on your second environment.
Configuration files in a module's config/install directory are only read from that location when the module is installed. That configuration file shouldn't change at all here and there's no reason for it to.


How can I copy a body field from one node to another node?

Use hook_ENTITY_TYPE_prepare_form if you want to change a field value before the form is built for an existing node:
<?php

use Drupal\node\NodeInterface;
use Drupal\Core\Form\FormStateInterface;

/**
 * Implements hook_ENTITY_TYPE_prepare_form() for node entities.
 */
function mymodule_node_prepare_form(NodeInterface $node, $operation, FormStateInterface $form_state) {
  if ($operation == 'edit') {
    if ($node->id() == '6716') {
      $node->field_vertragsinhalt->value = $getcontract;
      $node->body->format = 'full_html';
      // don't save the node yet, it will be saved after submitting
    }
  }
}

For the more common case of setting field values when creating new nodes see Pre-populate an entity reference field (media image) when creating a node


How do I get all the menu items below a certain parent?

I am using this function in my code for D7 to do this exact thing. Your code looks like it should work, but it is slightly different than what I have. Honestly I haven't visited this part of my code in a while. Hope this helps.

/**
* Returns an array of all menu items under a parent.
* @param string $title Menu item title.
* @param string $menu Menu name.
* @return array
*/
function MODULE_submenu_tree_all_data($title, $menu = 'main-menu') {
  $tree = menu_tree_all_data($menu);
  foreach ($tree as $branch) {
    if ($branch['link']['title'] == $title) {
      return $branch['below'];
    }
  }
  return array();
}


Create a content view, filter by your gallery content type, add the image field, add the field  "Content: Published" (to let you know if content is published). Then add  "Bulk operations: Content" (you need to install Views Bulk Operations module). In the field settings you should select the option "Publish content" and "Unpublish content". You should now be able to bulk publish and unpublish the image galleries.


Is there a compelling reason to track sites.php with version control?

We track it. You can have more than one entry in sites.php that points to the same site, so we have one for the production site and then a few more for development purposes.

The file is not sensitive itself, because if you give someone the ability to read the contents of .php files on your webserver, then you have bigger problems! I'd say try and find reasons NOT to keep it under version control.

I have to say Gisle's suggestion of manually logging changes to files seems to be a bit more effort than I'd normally want to put in, to get round a problem that's not really a problem for me to begin with!


You can do this by updating code on system.module file. Below are the code :

   function system_send_email_action_validate($form, $form_state) {
       $form_values = $form_state['values'];
       $has_tokens = count(token_scan($form_values['recipient'])) > 0 ? TRUE : FALSE;
       if (!valid_email_address($form_values['recipient']) && !$has_tokens) {
          form_set_error('recipient', t('Enter a valid email address or use a token e-mail address such as %author.', array('%author' => '[node:author:mail]')));
       }
}

For any help, I have refer you to this PATCH.

This is not working directly try to do it manually.


Filter search results based on user field

Okay, I found the answer. If my keys are A,B,C, I can return A+B+C to return all nodes marked with either A, B, or C. Basically, you need to concatenate the keys you want with + and that will achieve the desired effect.


Views exposed filters do not display in front end

Mb it's because there is no result. In that way you will see exposed form on edit page, but view will not be displayed on front because it's empty (so, there is no need to display exposed form for user and it's hidden).

Try to go on your view's edit page to No results behavior and make it display some text to see if view has no result


You should use Entity module. in this module no matter what the language of the website is you can use entity_metadata_wrapper command to get the fields value. here is an example of my project where field_article_writer and title are fields of article content type:

function MYTHEME_preprocess_node(&$variables){
switch ($variables['node']->type){
    case 'article':
        $suggest = "page__node__article";
        $variables['theme_hook_suggestions'][] = $suggest;
        $wrapper = entity_metadata_wrapper('node',$variables['node']);
        $variables['title']= $wrapper->title->value();
        $variables['writer']= $wrapper->field_article_writer->value();
        break;
    }
}

Now in page--node--article.tpl.php, $title and $writer hold their correspondent value.


How to display event's views block inside another content type's content section with only events related to that content alone?

You can use theentity reference and rules modules for this.

First, add entity ref fields to both singers and events. Then, create a rule so that, when an event is created, which refers to a singer, the singer gets updated with a reference back to the event.

Your singer nodes should therefore have references to all the events that refer to that singer. In the display settings for the singer nodes, you can render the referenced nodes as, say teasers.


How do I add drupalSettings info from an AJAX callback

In Drupal 8, as you've discovered, drupal_add_js() has been removed.

There are two things you need to do this:

1) You cannot add JS in an ajax callback. It was a bad practices in D7, and cannot be done at all in D8. You'll need to add the JS in your form definition, not the ajax callback.

2) You add JS through a two-step process. The first is to create a new library in the *.libraries.yml file. Add a dependency to core/drupalSettings`. Then, in your form definition, you add your setting like this:

$form['some_element'] = [
  '#markup' => '', // required to render the element
  '#attached' => [
    'libraries' => [
      'some_library', // The library you created
    ],
    'drupalSettings' => [
      'modulename' => [
        'zip_code_success' => TRUE,
      ],
    ],
  ],
];


How to apply multiple sort criteria on views?

One of the solutions can be using 2 views and use one view as footer attachment to the other view

View 1 with sort criteria 1 (no of items 3)
View 2 with sort criteria 2 (no of items 3)

For View 1 footer, use View 2


How can I develop a custom theme from scratch?

Hello World

It seems that the current version of your theme works as designed: empty templates that result in a blank screen, that's exactly what "I" would expect. Try adding "Hello Umair" in any of those empty files, and see what you get next.

Start from an example

A much more effective approach however might be as suggested by longboardnode : copy from whatever theme you like, and apply the "same-as-except"-strategy.

Start from a base theme

Or maybe create a subtheme from your favorite base-theme (Omega, Zen, Bootstrap, ... there are plenty to pick from).

Follow the instructions in the documentation

An extremely basic example you may want to look at: Create a new custom theme with CSS alone. And if you're ready for it, study the Theming guide, especially the Theming Drupal 6 and 7 child pages of it.


How would I use DATEDIFF(), NOW(), and BETWEEN in a db_delete() query?

You can use DeleteQuery::where(), e.g.

$args = array(':arg1' => $foo, ':arg2' => $bar);
db_delete('note_dates')
  ->where("DATEDIFF('start', NOW()) BETWEEN :arg1 AND :arg2", $args);
  ->execute();

That'll give you

DELETE FROM {note_dates}
WHERE  (DATEDIFF('start', NOW()) BETWEEN :arg1 AND :arg2)


Using ctools modal framework instead of those [insert-fancy-word-here]box JS library. Kudos.

Ctools module uses js/modal.js inside ctools module folder to attach Drupal Ajax events to links with ctools-use-modal class. That is all.

I can think about a few approaches.

1. Do not make them modal-enabled in first place.

If you are calling the ctools_modal_text_button() or the function that adds modal-compatible markup, you can wrap it with an if statement.

<?php
if (drupal_is_front_page()) {
  print ctools_modal_text_button(t('Open the modal'), 'my/path/nojs', '');
}
else {
  print l(t('Open the modal'), 'my/path/nojs');
}
?>

If you are using a block, cache modes DRUPAL_CACHE_PER_ROLE and DRUPAL_CACHE_GLOBAL won't be compatible with this. DRUPAL_CACHE_PER_PAGE would work, but I doubt caching this block would improve performance. It can rather have a negative effect. DRUPAL_NO_CACHE would be best.

If you are hardcoding block contents, you can create two blocks, with different visibility settings based on the path.

2. Change the JS or CSS.

If you can't change the PHP, you still can change the JS and/or CSS.
A CSS solution would be the easiest. Print both modal and non-modal links, and if the body tag has not-front class, you can hide the modal links.

.not-front .ctools-use-modal {
  display: none;
}

You can un-ajax links as well.
Here is a sample code:

(function($){

    Drupal.behaviors.zzzzzz = {
        attach: function (context) {
           $('.not-front area.ctools-use-modal, .not-front a.ctools-use-modal', context).once('ctools-use-modal', function() {
        var $this = $(this);
        $this.click(Drupal.CTools.Modal.clickAjaxLink);
        // Create a drupal ajax object
        var element_settings = {};
        if ($this.attr('href')) {
          var base = $this.attr('href');
          Drupal.ajax[base] = new Drupal.ajax(base, this, element_settings);
          delete Drupal.ajax[base]
        }
      });
    }}
})(jQuery);

There are other questions about Drupal behaviors and using jQuery with Drupal 7. Basically, above code finds modal links from non-front pages, and removes the Ajax properties defined in Drupal.ajax, so clicking the item does not trigger the modal.


I can't see any screenshot.

It seems that your problem is with url and if it is then
go for Path Auto module.

The Pathauto module automatically generates URL/path aliases for various kinds of content (nodes, taxonomy terms, users) without requiring the user to manually specify the path alias.


How to convert the Drupal View Query to MySQL query?

Try the Views Show Query  module

This module shows real SQL query in Views UI during live preview.
'Real query' means it is rewritten by query_alter hooks. For instance, node access checks are added, so this requires selecting the user on behalf of which the query is supposed to be executed. So the module adds 'User ID to show final query' field in views preview form. You must enter numeric user ID in this field to view the real SQL query.
This module makes it possible to show SQL query not only during live preview, but when the view is executed normally. You can add footer to the view with the following PHP code:

<?php
$rows = array();
$view->exposed_input['views_show_query_uid'] = 1;
views_show_query_views_preview_info_alter($rows, $view);
drupal_set_message($rows['query'][0]);
?>

OR
There another module called Query Coder which Convert SQL query to Drupal Database abstraction layer code.


Automatically cycle through full-page nodes

I tried to implement this feature and I had almost achieved it. To try-out, click any preview button in this page, you can see the content cycling through nodes.
I suppose you want to cycle through a list of nodes generated by a View.
Procedure:
I used Views navigation module to preserve the list of nodes generated in a View. It also preserves the order of those nodes in cache.
In script:
(function ($) {
  Drupal.behaviors.module = {
    attach: function (context, settings) {

      //Posts the current position of node and Views-navigation cache ID - on clicking 'next' button
      $("body", context).on("click", ".next", function() {
        var pos = $(this).attr('data-pos');
        var cid = $(this).attr('data-cid');
        $.ajax({
          type: 'POST',
          url: '/navigation',
          dataType: 'json',
          data: 'pos='+pos+'&cid='+cid+'&dir='+dir+'',
          success: DoWhateverWithNextNode
        });
      });

    },
  };
})(jQuery);

In module:
//Menu callback for 'navigation'
function get_next_node() {
  if($pos = $_POST['pos']) {
    module_load_include('inc', 'views_navigation', 'views_navigation');

    $result = views_navigation_get_result($_POST['cid']);
    $max_index = count($result) - 1;
    $pos = ($pos > $max_index) ? 0 : (($pos < 0) ? $max_index : $pos);

    if ($nid = $result[$pos]) {
      $next_node = node_load($nid);
      return drupal_json_output($next_node);
    }
  }
}

In DoWhateverWithNextNode(data), you are required to increment 'data-pos' for '.next' element by 1. So that you can cycle through nodes.
P.S. This code may not be a working version. I just provided you an overview of my implementation.


Is it possible to export only specific content types?

Take a look at the Node export module.  From the project page:

  This module allows users to export nodes and then import it into
  another Drupal installation, or on the same site. The idea is similar
  to the way you export/import Views or Content Types.


Two appropriate options:

Use node_delete_multiple function instead of the node_delete(). I guess you need to do this only once, so this might be a faster solution if your server can execute the whole process at once (ie enough memory, not too many fields/modules, etc.).

$query_node = db_query("SELECT n.nid FROM node n,status s WHERE s.entity_id = n.nid  AND type = 'employees' AND s.field_employee_status_value = '2' AND n.status = '1'");
$result_node = $query_node->fetchAll();

$nids = array();
foreach($result_node as $node) {
  $nids[] = $node->nid;
}
// Delete everything at once.
node_delete_multiple($nids);

You can also use Administration Views with Views Bulk Operations. You can filter the nodes based on what you need and then perform operations on all rows. This will process the deletion as a batch process. Downside is that you might need to install 2 additional modules if you don't have them already.


Zen theme not showing second level menu items

Edit your page.tpl.php

Edit the section where the primary_links are printed to show the whole primary links menu instead of only showing the first level links of your primary links menu.

<?php if (isset($primary_links)) { ?>
     <div id="primary_menu">
<?php print theme('menu_tree',variable_get('menu_primary_menu',0)); ?>
     </div>
<?php } ?>

In Drupal 6

<?php
$menu_name = variable_get('menu_primary_links_source', 'primary-links');
print menu_tree($menu_name);
?>

Drupal 7

<?php

    $menu_name = variable_get('menu_main_links_source', 'main-menu');
    $tree = menu_tree($menu_name);
    print drupal_render($tree);
?>


The URL that the Drupal modules need is different than the one on which you browse the Solr server as an admin. Thus, for you, assuming 8983 is server port, it should be:

xx.xx.xx.xx:8983/solr/corename


You can use array_unshift to make sure your validation is called first:

array_unshift($form['#validate'], '_custom_validator');


How to default checkboxes to checked while maintaining custom return value

Sorry for such a late response but it is possible, I ran into this same issue using 8.5.3 the below configuration worked for me.  You just have to use both together, i successfully passed numbers, text, bool (becomes 0 or 1), and arrays through #return_value.  The class was just for formatting, you can leave that out if you're not using it.

'checkbox_1' => [
    '#type' => 'checkbox',
    '#title' => t('Checkbox 1'),
    '#default_value' => 1,         // Default to checked
    '#return_value' => "checked",  // Return the value if checked
    '#attributes' => ['class'=>['check_group']],
],
'checkbox_2' => [
    '#type' => 'checkbox',
    '#title' => t('Checkbox 2'),
    '#default_value' => 0,         // Default to unchecked
    '#return_value' => "checked",  // Return the value if checked
    '#attributes' => ['class'=>['check_group']],
],

Output will look like this if you dpm($form_state->getValues()) in your submit or validate function.

Array
(
    [checkbox_1] => checked
    [checkbox_2] => 0
)


Probably corrupted database by deleting records from node / node_revision

Oh dear, as you suspect that's not great. The outlook is probably quite bleak I'm afraid, a few vague possibilities:

If you know exactly what you deleted manually, restore it manually.
If you're able to restore a backup to another database, and cherry pick the records you deleted from that to be restored manually to the original DB, and depending on what damage those missing records have done in the meantime, that would possibly be an option.
If restoring the whole database from a backup is an option, do that.
If you know the IDs of the nodes you deleted, stick some dummy data with the appropriate IDs into the node/node_revision table, then call node_delete_multiple with the IDs so the system deletes them properly (clear the cache first).

The main problem with deleting straight out of the node table is that you leave a lot of orphaned data elsewhere - Drupal has no enforced referential integrity apart from some 'soft' checks in code for certain operations.

The most important thing to take away from this is never touch the database unless you're 100% confident what you're doing is safe. But I reckon you've probably learned that already :)


Custom token [node:customtoken] not available in rules action 'set a data value'

1) The easy, but dirty way:
You can nest your tokens in an existing type (see http://drupal.org/node/1714418#comment-6468184). Eg, in hook_token_info() do:
  return array(
    'types' => $types,
    'tokens' => array(
      'site' => $my_tokens,
    ),
  );

Your tokens will appear under "Site information"
2) The harder, but cleaner way:
Define your own rules data type with hook_rules_data_info()
function mymodule_data_info() {
  return array(
    'vub_events_data' => array(
      'label' => t('My Module Data'),
      'group' => t('My Module'),
      'token type' => 'my_module',
      'property info' => array(),
    ),
  );
}

and use this in your hook_token_info() implementation.


You can use the required by role module: https://www.drupal.org/project/required_by_role to make sure the publishers have to add an image. The downside is publishers will need to upload an image, even when not publishing.


Commerce Recurring Framework - Get active subscriptions?

For Drupal 7:
Yes, you can find the data at the {commerce_recurring} database. With each recurring entity the user id has saved (uid column).

Here's an example how to get all subscription (recurring entities) from a user.

$uid = 1; // the user id
$result = db_query('SELECT * FROM {commerce_recurring} WHERE uid = :uid', array(':uid' => $user_from_order->uid));

Now you can loop over the subscriptions / recurring entities.


You can run just drush updb -y on your site folder.


Construct POST data and send it to an external page

This is a PHP question, really. But here's an answer: http://wezfurlong.org/blog/2006/nov/http-post-from-php-without-curl/

Many many caveats; read the comments.


How do I add a favicon to my custom theme?

You can add a favicon by just adding a favicon.ico (or .png or .gif or other valid  favicon file type) to the root of your custom theme folder.

If you'd like to have your favicon stored in a custom location, see the method described here: (Change default favicon programmatically)

Edit:

If you simply want to give your theme the ability to change the favicon, without providing one yourself, you can add the setting to your theme settings folder by adding a /config/install/THEMENAME.settings.yml file to your theme, with the following settings:

features:
  favicon: true
favicon:
  use_default: false


Changing the html and order of system fields(pass/email/locale/etc) of user edit form

The reason the template method was not working on my site was the result of a caching issue.

To use a template file for the user profile form you can put this(or find the existing implementations of the hooks) in your template.php:

function yourtheme_form_user_profile_form_alter(&$form, &$form_state, $form_id) {
  $form['#theme'] = 'user_profile_form';
}

function yourtheme_theme($existing, $type, $theme, $path){
  return array(
    'user_profile_form' => array(
      'render element' => 'form',
      'template' => 'templates/form--user_profile',
    ),
  );
}

Template file name, in this example, becomes form--user_profile.tpl.php


The picture property of the user entity is the file ID (a reference to the fid column in the file_managed table).

You can load the file explicitly with file_load() like so:

$file = file_load($user->picture);

And render it to an image using theme_image():

$image = theme('image', array(
  'path' => $file->uri,
  'alt' => 'Some alt',
  // etc...
));

Alternatively you could dispense with the above and just use the handy theme_user_picture() function:

$image = theme('user_picture', array('account' => $account));


Behavior to use .insertAfter() on load + after each ajax call?

In Drupal ajaxComplete() is not required, as Drupal executes each iteration of Drupal.behaviors.*.attach() whenever an ajax call is complete. This function receives an argument, context, which on page load contains the entire contents of the document, and on AJAX calls contains the new part of the DOM being inserted into the page. This piece of the document can be parsed for the elements you are searching for. These two APIs are combined with jQuery.once() to ensure that code is not executed on any piece of the DOM more than once.
Example:
(function ($, Drupal) {

  /**
   * Does something.
   *
   * @param DOMelement context
   *   Contains a the full document on page load, or new parts of the
   *   DOM being inserted into the page after ajax calls.
   */
  function doSomething(context) {
    $(context).find(".some_dom_element").once("arbitrary-key").each(function () {
      // Do some stuff a single time on each instance of .some_dom_element that
      // appears on the page, both on page load and after any ajax loads.
    });
  }

  Drupal.behaviors.someArbitraryKey = {
    attach: function (context) {
      doSomething(context);
    }
  };
}(jQuery, Drupal));

Note that if you create your own ajax calls, you will need to pass any new parts of the DOM to Drupal.attachBehaviors():
$.ajax({
  url: '/path/to/ajax/callback',
  complete: function (data) {
    var newContent = $(data);
    // Pass the DOM element the jQuery object contains,
    // not the jQuery object:
    Drupal.attachBehaviors(newContent.eq(0));
    newContent.insertAfter($("#some_element"));
  }
});


FastCGI should be fine, however...

Your .htaccess may be replaced each time you upgrade Drupal, depending on how you upgrade files.  If you do it manually, you need to diff the new one with old one, and determine if there are any changes and merge the changes.

In actually think all of those settings should be the defaults now in the stock PHP php.ini-dist, but I am not positive about the mbstring ones.

It is very probable that your permissions of your files directory (eg, sites/default/files) is messed up.  Double check that Drupal can read, write, add, and remove files.  The status page should show any problems, but you need to test all cases.

But, one common configuration with FastCGI with shared accounts is that Apache runs as your account user.  This would mean that the site files and the files directory would be owned by the same user.  This is a security consideration to keep in mind.  Preferably, the site files should not have write access by the webserver; write access should be as limited as possible.  You can "solve" this be revoking write access from your user account (ie, make files 444 and dirs 555) except for sites/default/files, but this is a major hassle.

If a host did that to me, I would be EXTREMELY upset.  The provider should have warned you ahead of time so you could prepare, and also given you a test account so you could properly test things out.

Personally, I always recommend true VPS accounts to clients who want to run Drupal.  The only time I would consider shared hosting are cases where the provider specializes in shared Drupal hosting.


Get user list according to node field value

I think you are getting close. When you use ajax in Drupal, you have to return a render array with commands. In your case it looks like you would want ajax_command_replace.

Two additional steps should get you up and running.

First, built an html string instead of using print_r to try and send content back to the client.

    $return_html = '
';
    while ($record = $result->fetchAssoc()) {
              $return_html.='
' . $record['name'] . '
';
            }
    $return_html .= '
';

Then create the ajax object and render array to send back to the client

 $commands[] = ajax_command_replace('#my_selector', 'some html here');
 return array(
      '#type' => 'ajax',
      '#commands' => $commands,
    );

In this example, you would need to have a div on your page with an id of 'my_selector' that would receive the new html.


How to I create a backup of my content ONLY?

Node export is the best option to take backup for contents. One click export, import for the particular content types.

  This module allows users to export nodes and then import it into
  another Drupal installation, or on the same site.

  Using this module you can save yourself a lot of time setting up new
  websites that have similar nodes to websites you've already made,
  migrating nodes to new Drupal versions, or between
  development/staging/production sites.

  You will need the same content types for the imports to work (unless
  using Feeds to import), and ideally relevant compatibility with
  fields, and modules.


You need to add a field in view with name
Content: All taxonomy terms
Display all taxonomy terms associated with a node from specified vocabularies.
That will display all terms associated with a node


I would suggest You to check views export functionality (admin/structure/views/view/name-of-some-view/export). There you should get the view object.

Then, copy this object to your form_submit function, replace desired values with form values and call $view->save() function. The view should be created (or updated, if such machine name exist.)


Drupal 7 - div popup inside the overlay (node/123/edit)

The code is fine, problem was with jquery version.


Setting the video's width to 100% via CSS should make it fit whatever width you've given its wrapping cell or div.

Check out the FitVids module / library for an all round solution to making videos behave better on responsive sites.

http://drupal.org/project/fitvids

http://fitvidsjs.com


Responsive Grid View appearing in single column

You need to apply some css rules to the output. Basically, assuming each div of the grid has a views-content class, give that class a float:left and some margin. Or if you use a responsive theme already, set the correct classes to the output in Views UI...

As per the Views Responsive Grid:

  In order for the columns to work you'll need to specify the class name
  of your columns. For example, if your theme utilizes a grid, like
  Twitter Bootstrap does, you would specify "span3" as the column
  class(making sure to use the correct span size). This will make sure
  your column adhere to the grid in your Bootstrap based theme.


How do I create a sticky navigation bar in Open Social?

Seems like you're over-complicating it by re-writing things that bootstrap already does.  The stock bootstrap theme and most of it's subthemes should have a setting in the theme for setting a fixed nav bar.

See Appearances -> Theme settings -> Components -> Navbar.  There is an option for fixed top navbar.

If that does not do what you want, there is also the Bootstrap Affix plug-in which should be part of the standard drupal bootstrap theme.

See:  This W3school page for details.


how to create shell command 'd' as equivalent to 'drush'?

If you are using Drush-5 (recommended), then see examples/example.bashrc for a bunch of very useful ways to enhance your experience in your shell when using Drush.  Installation instructions are in the file.  One of the things it does is create an alias 'dr' for Drush; if you wanted this to be 'd' on your system, it would be easy enough to make that change.


How can I specify language for Parent Item options on node create/update page?

I have a similar problem, I have decided that I don't want to ajax reload the form when the language is changed because things like entity relationships (which is my current problem) don't work even then.

My advice is to force the language of the editing / adding node to be the same as the interface. For creating/ adding this is easy you set it for the content type when you edit the multilingual settings. The translation interface redirects correclty and the content creation too (it expects you to be in the language you want to create).

So with that option you would be on the safe side, EXCEPT when you are in pages like "find content" and use the edit link or write the url by hand.
What I am trying to do now is to force a redirect when you try to edit the link by a url like /node/223/edit. This is something that should be possible with hook_menu_alter.I would force a redirect to [language of the content]/node/223/edit.

I would have thought that there was a better possibility but I have found none. I will be monitoring this question to see if someone has a better idea or there is a much better solution out there.


"Please select category" as default value in a select list

For adding text to your input field, write a custom module and place the code in there

function yourmodule_form_alter(&$form, &$form_state, $form_id){
    if($form_id == "your_form"){
     $form['some_element']['#attributes']['placeholder'] = t('Select Category');
}


Adaptive Theme: give the option to user to switch between fluid and fixed layout in specific nodes

Assuming that you did not heavily modify the base structure of Adaptive Theme, you can explore using a custom solution to do this.

For example you can add a button like this in a block's contents (using the Raw HTML input format):

<button id="toggle-width">Toggle Width</button>

then a new class in your CSS to override the max-width property in .container (this is where the max-width is set in Adaptive Theme):

.page-full-width { max-width: none !important; }

and then add some jQuery to your button:

$( "button#toggle-width" ).click(function() {
  $( "#page" ).toggleClass( "page-full-width" );
});


Pass URL alias info to default value of Webform field

You can get the URI with $_SERVER["REQUEST_URI"] and remove the "q=content/" string from it.


When creating a custom form, how does one store the data in drupal db and then retrieve for display?

A specific answer: you can use sumbit hook to store data. see Submitting Forms: http://drupal.org/node/751826

A general answer: follow this guide related with creating, theming, validating, submitting, storing data, and understanding the flow in Drupal 6 forms: Form API Quickstart Guide http://drupal.org/node/751826

to retrieve data you can use these guidances:

db_query documentation http://api.drupal.org/api/drupal/includes--database.pgsql.inc/function/db_query/6

Database abstraction layer http://api.drupal.org/api/drupal/includes--database.inc/group/database/6

also you can review Examples module http://drupal.org/project/examples specifically the module dbtng_example to database examples or page_example to build a static page add your retrieved information. please note that dbtng_example module is only for Drupal 7, but reviewing this module you will have more ideas about what to review in Drupal 6.

also could be useful the "Module developer's guide" to dive in tutorials/examples about how build forms and retrieve data using modules http://drupal.org/developing/modules


You can do something quite close to that with views.  When you set up your view (or just use the one that comes with the Calendar module and clone it and start editing your new copy).

Just make sure you go to the Calendar settings and choose 'Week' as your Calendar type:

Of course, you have to choose which fields to display for your event type and here's what you'll roughly end up with:

I've added css to my theme to change the look of this calendar page, and that's probably a separate topic.  Most of the functionality you want is available through the calendar module... just set your type!!

Hope this helps.

================= EDIT =========================

So, after reading your comment, here's how I'd modify the solution above.  Same calendar, but choose 'Day' as the calendar format.  Then under the 'Header' section, add a Header and choose "Global: text area".  Here, using php, we can output links to how many ever days you need before and after today's date... since this doesn't happen automatically.  You'd need to enable the php filter module to make this possible.

So, using the 'php filter' format for the global text, you can add the following code (I would check it to display even for empty views...):

<?php
print( "" . date('l') . " | ");
print( date("l",strtotime("+1 days")) . " | ");
print( date("l",strtotime("+2 days")) . " | ");
?>

The above just prints out today's week day, then tomorrow and the day after.  You can change to suite your needs.  I've also only printed the first one as a link.  You see, the day calendar format can be navigated by just going to /2012/11/23 to get to Nov. 23rd of this year, etc.  Very easy to figure out the links, so you can build your own menu using php in the header.

This is the output you'd get, and of course, you can always beautify with css:


Passing a Taxonomy term via URL to add content form in Drupal 7

You can use the module Prepopulate ; latest release is dev but I use it on a production site and it works like a charm.

If it doesn't work tell me, there are two other solutions : send an arg in the URL to the form (and then use Panels or the php template) and JavaScript (I can give you the code if you need it).


Is this correct usage of hook_node_view()?

Is there a lower level menu router hook which I can use?

Yes, there is - you would need to use hook_menu_alter() to achieve this. Here's the code you should use:

function YOUR_MODULE_menu_alter(&$items) {
  $items['node/%node']['page callback'] = 'YOUR_MODULE_node_page_handler';
}

function YOUR_MODULE_node_page_handler($node) {
  // If the node is unpublished, redirect the user.
  //
  // Note: I would recommend adding an extra check so administrators and
  // users who can manage the nodes are not redirected. This way, they can
  // work with unpublished nodes.
  //
  // This is what you would use instead in that case:
  // if ($node->status == NODE_NOT_PUBLISHED && !user_access('administer nodes')) {
  //
  // This will work for ALL users on the site, including the administrators.
  if ($node->status == NODE_NOT_PUBLISHED) {
    drupal_goto('<front>', array('query' => array('errCode' => 1)));
  }

  // Let the core node handler serve the request otherwise.
  return node_page_view($node);
}

Notes:

You should do this through a custom module instead of the theme.
Bear in mind that this might interfere with functionality of other modules, as well as workflows. See my comments and alternative version of the code.
Use drupal_goto() for redirection instead of setting the location in header.

Hope this helps.


See this drupal.org documentation page called How to add a column with dynamically generated action buttons in a View. hook_views_default_views_alter has essentially nothing to do with this task. Optionally an easier path is like Rules with Views Bulk Operations if you can live with like a checkbox per row, and a dropdown for the operation selection.

The more custom a look, or outside of Drupal's default behavior you deviate. The more work you have to do.


There might be better way to do this, but one method would be to run an #after_build function that will alter the first '' placeholder date label option to your liking. For example:

/**
 * Implements hook_form_alter().
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  $form['dob'] = array(
    '#type' => 'date_select',
    '#title' => t('Date of birth'),
    '#default_value' => '',
    '#date_format' => 'm-d-Y',
    '#date_label_position' => 'within',
    '#date_year_range' => '-100:+0',
    '#required' => TRUE,
  );
  $form['dob']['#after_build'][] = 'MYMODULE_myform_dob_after_build';
}

// Alter the date component option so the first placeholder element has the new label.
function MYMODULE_myform_dob_after_build(&$form, &$form_state) {
  $form['day']['#options'][''] = t('Day');
  $form['month']['#options'][''] = t('Month');
  $form['year']['#options'][''] = t('Year');
  return $form;
}


Not sure you can do this with facets.  Facets by definition show only options that exist in the current query results.  There is no guarantee that a content_page type will be among the search results for a term.

You may want to consider using an exposed view filter (the views_block_filter_block module lets you turn this into a place-able block).  This would show all content types and can have a default type selected if the filter has none.


If you insist on programming this, and not use and configure contrib modules -

If fields were added to entity bundle via drupal admin UI

You can use hook_form_alter() or hook_form_FORM_ID_alter, and in the code there have the particular field populated with desired default value.

hook_form_alter() would be invoked for all forms and you would have to have an if condition to target just the desired form id.
hook_form_FORM_ID_alter() would be invoked for particular form.

If field was attached using Field API code (not the case for this question)

You would have an implementation of hook_field_attach_form() to attach fields to your MembeshipRequest entity. It would be in that hook implementation that you would set a #default_value to the desired form field.

Code to use in either of the cases above

$form['foo']['bar'] = array(
  '#type' => 'textfield',
  '#title' => t('foobar'),
  '#default_value' => _func_to_get_default_value($member_id),
  '#description' => t('something something'),
  '#size' => 60,
);
// NOTE: Replace foo/bar with the particular field etc.


Do I need to create a database table or are there already tools on offer?

Unless you need some additional styling or processing of data, the easiest way is to Embed a spreadsheet using Google Docs. You don't need any module for that.

If you need to have that data in Drupal as well, then check out Feeds Excel or this thread on drupal.org. The latter relies on the PHP Excel reader class which you should use in your custom module.


Page Title is enabled (or disabled) on a per content-type basis.

You should be able to go to http://mysite.com/admin/content/types/product and enable it using the checkbox in the following fieldset:


aborted prematurely while running update #7204

I did more digging and found it is because the wysiwyg module was disabled. I enabled it and the update worked.


One contextual filter based on two entity reference fields

Of course I solve this immediately after I post it after hours of trying. If you're in the same situation, it appears the only solution is to use https://www.drupal.org/project/views_contextual_filters_or .

Configure the view as described above. Then additionally, under Query settings, check Contextual filter OR.

The UI of this module leaves something to be desired but it works so long as all your contextual filters should relate to each other as OR.

The second missing piece was that I was testing this in the view UI using the preview. I was passing the NID of the Location as an argument. What I missed is that because I have two contextual filters I actually need to pass the NID twice like this: "2173/2173". When the view is actually used on the page, the NID is retrieved from the URL and the fact that there are two contextual filters becomes irrelevant.


There are a couple of modules to create entities (nodes etc) inline i.e in the parent form, when it's being created itself.

When you save the form, it creates the entity AND the entities that are referencing it, but it's up to you to create the entity structure and references to achieve what you want.

I can vouch for References Dialog

However, I think you are making it too complex and you only really want one node type (kids) with an unlimited field (height), if that is your real scenario.

For example you easily create a custom form with three (or loop for x) fields and when it saves it adds the result to existing nodes, eg :

// Get and render the form somewhere.
$form = drupal_get_form('kids_height_form');
print render($form);

/**
 * Form constructor.
 */
function kids_height_form() {
  $kids = array(2210, 2043, 2038);
  $entities = entity_load('node', $kids);
  // dpm($entities);
  foreach ($entities as $kid) {
    $id = $kid->nid;
    $form["height_$id"] = array(
      '#title' => 'Height this week for $id',
      '#type'  => 'textfield',
    );
  }
  $form['submit'] = array(
    '#type'  => 'submit',
    '#value' => 'Submit',
  );
  return $form;
}

/**
 * Form submit handler for kids_height_form().
 */
function kids_height_form_submit($form, &$form_state) {
  $kids = array(1, 2, 3);
  $entities = entity_load('node', $kids);
  foreach ($entities as $kid) {
    $id     = $kid->entity_id;
    $height = $form_state['values']["height_$id"];
    $count  = count($kid->field_height[LANGUAGE_NONE]);
    $kid->field_height[LANGUAGE_NONE][$count + 1] = array('value' => $height);
    entity_save('node', $kid);
  }
}

The top bit prints the form, the form constructor simply create as many text fields as there are node ids in the array and the submit handler does the same loop except also adds the result to a new delta for the height field and saves the entity.

You can also achieve this with EntityMetaWrappers and may be a bit neater but the process is very similar. (this is untested by the way and will need work to suit your needs);


limit db_select query by the value of a specific field

Scott's answer and Triskelion's comment are both spot on, but there are also a couple of other solutions that are worth mentioning.

Query the database for some node IDs that match a condition, load them using node_load_multiple(), and inspect the field data:

$nids = db_select('node', 'n')
  ->fields('n', array('nid'))
  ->condition('status', 1)
  ->condition('type', 'salesforce_contacts')
  ->condition('n.title', 'Abouzeid')
  ->orderBy('title', 'ASC')
  ->execute();

$nodes = node_load_multiple($nids);

foreach ($nodes as $node) {
  $title = $node->title;
  $created = $node->created;
  // etc.

  if ($field_items = field_get_items('node', $node, 'field_account_id')) {
    $account_id = $field_items[0]['value'];
  }
}

Use an EntityFieldQuery to query the nodes. This method has the advantage of being able to add conditions based on fields, as well as just the columns available in the node table.

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->propertyCondition('type', 'salesforce_contacts')
  ->propertyCondition('status', 1)
  ->propertyCondition('title', 'Abouzeid')
  ->propertyOrderBy('title')

$results = $query->execute();
if (!empty($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));

  // Loop through the nodes as in the above example.
}


How do I translate view's page path alias?

On my multilingual Drupal 8 sites, I go to /admin/config/search/path/add for adding URL alias, which asks you to select a language for this alias.

Is this what you were looking for?


If the module is tungcan.module, then the implementation of hook_views_api() (necessary to load the include files used from the module to integrate with the Views module) should be tungcan_views_api(), not test_views_api().

If, vice versa, the module is test.module, then tungcan_views_data() should be renamed to test_views_data().


Allow the user to send emails to all or selected rows in a particular views display

I wrote an answer somewhat similar to this functionality.

https://drupal.stackexchange.com/a/195228/53677

Basically, you could create an entityform with an entityreference field for emailable users and a field for your email message.

Then on your view page, provide an email button and use jQuery to create a link to pre-populate the users you want to email. Use Rules to loop this on entityform save.

The link to the form would have to look like /eform/submit/email-form?field_email_uids=10,12,15,201

It's a bit more work but can give a really nice interface if done right. Your view can be anything as long as you can grab the UIDs.

Or you could just hide the fields you don't want with css / jQuery.

Edit: Adding instructions for the jQuery part

Here's a very basic example of the finished result. This can be added to any view setup.

You can of course decide to not use checkboxes and perhaps add a border or background etc. to the whole row. You can do anything you like with jQuery and .parent()etc. to go up the DOM and add/remove classes.

Views Custom Text Field: (The UID and Name fields are hidden above. I use font-awesome on this install. You can use ✓ or something else instead of the )

 [name]

Views Footer Custom Text Field:

Send Email

jQuery:

$('.email_box').click( function() {

    // Check if it's clicked + add / remove classes
    if ( !$(this).hasClass('email_checked') ) {
        // Add Class
        $(this).addClass('email_checked');
    } else {
        // Remove Class
        $(this).removeClass('email_checked');
    }

    // Call function below for Email Link
    build_link();

});

// Get all boxes that are clicked and add their value tags to the link
var build_link = function() {
    var email_uids_array = [];
    // Loop checked and add UIDs to array
    $('.email_checked').each( function() {
        email_uids_array.push( $(this).attr('value') );
    });
    // Split array into uids
    var uids = email_uids_array.toString();
    // Create link
    var link = '/eform/submit/email-form?field_email_uids=' + uids;
    // Alter the Email link's href
    $('#email_link').attr('href', link);
};

Some CSS so it makes sense to the user:

.email_box {
  border: solid;
  border-width: 1px;
  border-color: #c2c2c2;
  color: #ddd;
}
.email_checked {
  color: #444;
}
/* Fix Hover / Focus */
.email_box:focus,
.email_box:hover {
  color: #ddd;
}
.email_checked:focus,
.email_checked:hover {
  color: #444;
}

The benefits here are total customization and it should work pretty well.


URL aliases is supported in Drupal by help of pathauto module; if you enable the Token module, you can use it efficiently by using tokens. Once these modules are enabled, you can visit admin/config/search/path/patterns to set the patterns for URLs.

But as I see in your question, you are looking to set this for menu; you can't do that here.

There is logic behind it for not supporting it. Suppose you have a node/18 for about-us and you have two menu 'About-Us" & "About-Company". Now you can add this same node/18 to both places as child.

How can you have two URL aliases for single node/18? So this is the reason why menu are not supported I think.

You can go for creating content type & use pattern for that. You can set pattern for taxonomy, users, etc.


page.tpl.php

for admin menu

    <?php print '
'.menu_tree($menu_name = 'navigation').'
';?>

//for primary menu
 <?php print  '
'.menu_tree($menu_name = 'primary-links').'
'; ?>
//for secondary menu
 <?php print  '
'.menu_tree($menu_name = 'secondry-links').'
'; ?>

template.php

  function menu_tree($tree}{return $tree;}


You can find DB Settings of Acquia DevDesktop locally at following location

  C:\Users\YOUR_USER_NAME\.acquia\DevDesktop\DrupalSettings\loc_mywebsite_local.inc

In above path Replace YOUR_USER_NAME with apropriate user name that you login on system. This path for Windows 7.


Different entity types for one field value

The "author" field would be a User Reference field.
You can use hook_form_alter to limit this fields allowed $options to be either the logged in user, or the list of users of Developers.

Something similar too ...

function MYMODULE_hook_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == 'node_add_application') {
    if (in_array('Developer', $user->roles)) {
      // Set the default value of the author field to the logged in users uid.
      $form['field_AUTHOR_FIELDNAME']['options']['#default_value'] = $user->uid;
    }
    if (in_array('Site Administrator', $user->roles)) {
      // Overwrite the general users list with UIDs only of a specific role.

      // Get uids of a specific role.
      $query = 'SELECT DISTINCT(ur.uid)
          FROM {users_roles} AS ur
          LEFT JOIN roles r on ur.rid = r.rid
          WHERE r.name = :role';
      $result = db_query($query, array(':role' => 'Developer'));
      foreach ($result as $row) {
        $developer_uids[] = $row->uid;
      }
      foreach ($form['field_AUTHOR_FIELDNAME']['options'] as $uid => $label) {
        if (!in_array($uid, $developer_uids)) {
          unset($form['field_AUTHOR_FIELDNAME']['options'][$uid];
        }
      }
    }
  }
}

This is a rough example of the logic and code it would take to alter the select list of user names for the author field to either default to the logged in developer, or show "site admins" only developers.

I have written such code before, this exact code is only an example based upon the details given in your question. It is un-tested.


Show "Add more items" for fields of limited cardinality?

You can do this in a form alter:

     YOURMODULE_form_alter(&$form, &$form_state, $form_id) {

        if ($form_id == 'YOURFORM') {
           if (isset($form['YOURFILED']['und']['#max_delta']) && $form['YOURFIELD']['und']['#max_delta'] == 4) {
                $form['YOURFIELD']['und']['add_more']['#prefix'] = '
';
                $form['YOURFIELD']['und']['add_more']['#suffix'] = '
';
            }
}

The max delta should be one less than you want as the maximum. When the delta is 4, then after five addmore fields, the add more button will be hidden.


You can do it like this. It uses exactly the same principles as your existing if statement.

// Change the type to the one you want to match on
$desired_type = 'booking';
if (arg(0) == 'node' && is_numeric(arg(1))) {
  $node = node_load(arg(1));
  return $node->type == $desired_type;
}
elseif (arg(0) == 'node' && arg(1) == 'add' && arg(2) == $desired_type) {
  return TRUE;
}
return FALSE;


Ajax Search Field with labels for node types

Can Inline Ajax Search cover your needs?


how to hide text format tips for text field in a module, not theme?

Here is the simple code you can write your role base logic in hidetips_test_node_form_after_build() fuction.

function hidetips_form_node_form_alter(&$form, &$form_state) {
  $form['#after_build'][] = 'hidetips_test_node_form_after_build';
}

function hidetips_test_node_form_after_build($form) {
  // Here you can write your logic for role based hide and display.
  $form['body']['und']['0']['format']['#access'] = FALSE;
    return $form;
}


The best way to do this is to write your own webform handler and attach it to the webform's postSave() method. You can also experiment and try another method if needed from WebformHandlerBase.

Webform handlers are not documented well, but they should be because they are quite useful.

modules/custom/mymodule/src/Plugin/WebformHandler/MyModuleWebformHandler.php

<?php

namespace Drupal\mymodule\Plugin\WebformHandler;

use Drupal\webform\Plugin\WebformHandlerBase;
use Drupal\webform\WebformSubmissionInterface;

/**
 * Webform example handler.
 *
 * @WebformHandler(
 *   id = "mymodule_webform_handler",
 *   label = @Translation("My Module Webform Handler"),
 *   category = @Translation("My Module"),
 *   description = @Translation("Block users after submission"),
 *   cardinality = \Drupal\webform\Plugin\WebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = \Drupal\webform\Plugin\WebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = \Drupal\webform\Plugin\WebformHandlerInterface::SUBMISSION_OPTIONAL,
 * )
 */

class MyModuleWebformHandler extends WebformHandlerBase
{

  /**
   * {@inheritdoc}
   */
  public function postSave(WebformSubmissionInterface $webformSubmission, $update = TRUE)
  {
    if (!$webformSubmission->isDraft()) {
      $webformSubmission->getOwner()->block();
    }
  }

}

After getting that setup, enable your new module (don't forget an info.yml file) and then edit your webform settings > handlers to add this to that particular form.


Use single create content flow to create many nodes

Bulk File Nodes is the solution for you to upload many files/pictures and create a node of it. Rest depends on your Logic how you implement it.


How to disable AVS check in commerce cybersource SASOP

It is possible to add parameters to the data using hook_commerce_cybersource_sasop_transaction_data_alter($data)

<?php
my_module_commerce_cybersource_sasop_transaction_data_alter($data) {
  // Ignore AVS check
  $data['ignore_avs'] = 'true';
}

Issue in Drupal.org


Disable (Close) webform form dynamically

Webforms are config entities and you can use hook_webform_load() to close the webform before it is rendered and then altered. Instead of closing and resaving the webform, you can call $webform->setPropertyOverride('status', FALSE); which will safely close the webform and prevent it from being permanently closed.


Accessing custom taxonomy term fields in a rules loop

Have a look at the question about "How to access commerce_product field of line-items using Rules to flag the Commerce Product?". The accepted answer to it (disclosure: it's mine ...) explains how that question can be solved (also) by creating a Rules Component, and which looks like so:

{ "rules_perform_an_action_on_a_selected_line_item" : {
    "LABEL" : "Perform an action on a selected line item",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "selected_line_item" : { "label" : "Selected Line Item", "type" : "commerce_line_item" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "selected-line-item" ], "field" : "commerce_product" } }
    ],
    "DO" : [
      { "entity_fetch" : {
          "USING" : {
            "type" : "commerce_product",
            "id" : [ "selected-line-item:commerce-product:product-id" ]
          },
          "PROVIDE" : { "entity_fetched" : { "product_fetched" : "Fetched Product" } }
        }
      },
      { "drupal_message" : { "message" : "Some details about this product: Product ID = [product-fetched:product-id], Product SKU = [product-fetched:sku], Product Title = [product-fetched:title], Product Creator = [product-fetched:creator]" } }
    ]
  }
}

Note the parameters used in this Rules Component, i.e. selected_line_item ( = the line item being processed). And also note the type of that parameter (a Commerce line item).

The main rule just executes this Rules Component, as part of a Rules Loop in it, whereas in each iteration of that loop the actual line item being processed is passed as the value for that parameter. So with this example in mind, it seems that this might be a solution to your questions:

  How can I let rules know what kind of entity I'm looping through

The type of the parameter you pass to the Rules Component.

  ... so it will give me access to the custom fields on that entity

I think your Rules Component would not need any extra Rules Conditions, though if needed (as shown in my Rules Component example with the Rules Condition related to "Commerce Product"), you could add relevant other Rules Conditions if needed.

For the sake of completeness, some more details about that Rules Component:

By adding the Rules Condition, I got access to the value of the id (key) of the Commerce Product that the line item was about.
Since I had made the value of that id (key) of the Commerce Product avaiable, I could use the Rules Action to fetch an entity by id (entity being the Commerce Product). And by doing that, from then on I had ALL the data (fields) of the Commerce Product available.


How to do "has term (with depth)" filter on field of a related field

You would not require a Relationship, just two Contextual Filters.

Based on your requirements Company would be one Contextual Filter - Content: Has taxonomy term ID and Country would be a second Contextual Filter - Content: Has taxonomy term ID (with depth).


How to implement the two categories of the same content type to automatically generate a new aggregation page?

Create a new view, go to admin/structure/views/add

Show: Content of type: All

✅ Create a page

Display Format: Unformatted List of: Fields

Save and Edit

Now in your view, Click on Advanced (located in the right side).

RELATIONSHIPS click add

Select ✅ Taxonomy terms on node

For Vocabularies checkmark your vocabs and then checkmark ✅ require relationship.

Then in FILTER CRITERIA add Has taxonomy term

✅ Autocomplete, then type regional, attribute.


How to create a workflow state field programmatically?

You should do it with entity_reference and target_type to be workflow, it should work like that. And with handler_settings you can set your type of workflow.


Remove tasks and index when creating a menu tab from views

You can achieve this using hook_menu_local_tasks_alter hook.

  Alter tabs and actions displayed on the page before they are rendered.

function hide_tabs_menu_local_tasks_alter(&$data) {
    foreach ($data['tabs'][0]['output'] as $key => $value) {
        if ($value['#link']['path'] == "check your path") {
          unset($data['tabs'][0]['output'][$key]);
        }
    }
}

You can also take a look on Tab Tamer module.

  Tab Tamer is an administration utility that provides easy re-ordering,
  hiding, and deactivation of tabs and subtabs. You can also rename tab
  labels.

  Tab Tamer makes use of Drupal's drag ordering, but degrades gracefully
  when javascript is disabled.

  Tab Tamer utilizes Drupal's cache system to help conserve server
  resources.


Theres is a module to add rules to voting api: http://drupal.org/project/voting_rules

Userpoints comes with native rules support.

I just set the whole thing up on my test environment, added a new Rule with

Event: User votes on a Node

Condition: User has role(s)
Parameter: User: [vote:user], Roles: authenticated user

Condition: Check the value of the vote
Parameter: Vote: [vote], Operator: is greather than, Data value: 0

Action
Grant points to a user
Parameter: User: [vote:user], Points: 5, Points category: General, Operation: Insert, Moderate: Use the site defaul

additional info:
you must enable userpoints and userpoints_rules as well as voting_rules

Here's the export of the rule

{ "rules_reward_voter" : {
    "LABEL" : "reward voter",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "rules", "voting_rules", "userpoints_rules" ],
    "ON" : [ "voting_rules_insert_node" ],
    "IF" : [
      { "user_has_role" : { "account" : [ "vote:user" ], "roles" : { "value" : { "2" : "2" } } } },
      { "voting_rules_condition_check_vote_value" : { "vote" : [ "vote" ], "operator" : "\u003E", "value" : "0" } }
    ],
    "DO" : [
      { "userpoints_action_grant_points" : {
          "user" : [ "vote:user" ],
          "points" : "5",
          "tid" : "0",
          "entity" : [ "" ],
          "operation" : "Insert",
          "display" : 1,
          "moderate" : "default"
        }
      }
    ]
  }
}


Go to Home » Administration » Configuration » System and set Error pages to some not used yet value, like http://localhost/403 and http://localhost/404, or http://localhost/forbidden and http://localhost/not-found. Then create a custom module. Implement hook_menu() to provide these pages. Use all logic you need in page callback function.


Add multiple user-roles in install profile

This should work:

// Make the first role
$role = new stdClass;
$role->name = 'Eindredacteur 1';
$role->weight = 3;
user_role_save($role);
$roleid_1 = $role->rid;

// Make the second role
$role = new stdClass;
$role->name = 'Eindredacteur 2';
$role->weight = 3;
user_role_save($role);
$roleid_2 = $role->rid;

// Permissions to assign to the role.
$perms = array(
'access content',
);

// Grant the permissions. This function takes care of all necessary cache resets
user_role_grant_permissions($roleid_1, $perms);
user_role_grant_permissions($roleid_2, $perms);


You have to set setTrackLastImported to TRUE.

What I've done is create a new source plugin that extends the source plugin that I was using and set to true the last imported property.

/**
 * Source plugin that extends "url" source plugin and saves the last imported
 * date.
 *
 * @MigrateSource(
 *   id = "url_last_import"
 * )
 */
class UrlLastImport extends Url {

public function __construct(array $configuration, $plugin_id, $plugin_definition, MigrationInterface $migration) {
    $migration->setTrackLastImported(TRUE);
    parent::__construct($configuration, $plugin_id, $plugin_definition, $migration);
  }
}

I don't know if it's the best solution, but it works.


How can I translate months of date field?

You're not supposed to do this yourself.

What you need to do, is to enable the core Language and Interface translations, select French as the site's language, and update the site's tranlations (this will take some time if its the first time you do this).  After doing all that, all long date fields should display the month names in French.

This is how it looks at my siste:


How to delete Panel variant programmatically

I just had to do this recently. If the variant is exported to code (like in a Feature) this will revert it. Otherwise it will just delete it.

   function MY_MODULE_update_N() {
     ctools_include('export');
     $page = ctools_export_crud_load('page_manager_handlers', 'node_view__test123');
     ctools_export_crud_delete('page_manager_handlers', $page);
   }


Theme Views exposed filters, how to add count?

What you are asking for is what is called faceted search.

If you want to have this feature you should think about using a search database that supports this, like Apache Solr. The problem is that it otherwise is going to be very heavy and complex to make, especially with views making the query for you. If you were to make this feature yourself with MySQL, it would probably be easier to code the entire page yourself, and add the facets for the terms in your custom form.

In Drupal 7 the search api module comes with support for Apache Solr and can do facets on both MySQL and Solr. It also have views integration.

For Drupal 6, you can use the Apache Solr Search integration module, which creates an API integration with Solr, making it easier to create facets with Solr. Use this would probably require that you custom made the entire form.


Why ajax form submit stop working after set form submit #id?

JS recognizes things by ID. But Drupal's AJAX only knows Drupal-generated ID. That's why when you change ID manually, it tries to attach click listeners to DOM nodes with IDs that are not there.

If you change ID to some custom value, you must also provide custom JS to attach all .on to the objects with new ID.


The solution I came up with is this:

At the top of the first JS file I include in my custom theme, I simply put the following line:

$ = jQuery;

Done :)


Difference between Content: Updated date and Content revision: Updated date in Views

I can see that the descriptions provided for both these filters can make things a little confusing. The below description and the image should help you out.

Content: Updated Date maps to node.changed and tells you the latest time when the node was changed.
Content revision: Updated data maps to node_revision.timestamp when a particular revision of the node (not necessarily the latest revision) was created.

You can check this in the query put together by Views, as shown in the image below. Hope this helps.


From your comments, I came to know that you have added a new menu and used it as Menu Block in second sidebar region.

But Menu position module doesn't support new menus.

See the following points from Menu Position module page

  This includes affecting:

  The main links of the theme
  The secondary links of the theme
  The breadcrumb trail
  Menu blocks provided by core's Menu module
  Menu blocks provided by the Menu Block module

So inorder to work with your new menu, you need to install Menu Block Module.

Menu Position module works well with Menu Block module.

So if you install Menu Block module you can use your custom menus also.

  So… have you ever used the Main and Secondary menu links feature on your theme and wondered “how the hell do I display any menu items deeper than that?”

  Well, that’s what this module does. It provides configurable blocks of menu trees starting with any level of any menu. And more!

I've tested this scenario and it works perfect.


How do I override an exposed filter input type?

Try in this way:
function seven_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if (in_array($form_id, ['node_page_form', 'node_page_edit_form'])) {
    $form['field_number']['widget'][0]['value']['#type'] = 'range';
  }
}

I think this post will help you, check once - https://www.drupal.org/project/drupal/issues/2958499#comment-12558959


How to send mail for every X months using rules?

Requirements:

Rules, Rules UI and Rules Scheduler must be installed and enabled.

Step 1) Create a new component, I named it send mail every 2 months

Step 2) Add an action of Send Mail, fill out the form, see picture below.

Step 3) Add an action (again)

This time select Schedule Component Evaluation and select your component (send mail every 2 months)

  Note: this will re-schedule your e-mail to be sent 2 months after its
  sent for the 1st time

Step 4) For SCHEDULED VALIDATION DATE, erase everything and put +2 Months

For Identifier, put something like I did (see picture) so you know who the schedule is for.

For ACCOUNT, put account

Step 5) Create a new rule, for React on Event, select After saving a user account.

Step 6) Add an action, select Schedule Component Evaluation and select your component (send mail every 2 months)

Step 7) Click on the switch to data selection button

Step 8) Put your field in Scheduled Evaluation Date. My user date field is called From Date with a machine name of field_from_date Therefore, it's account:field-from-date

Click on Add Offset, put 2 and select Months. (This means it will send the e-mail 2 months from the from date.

For Identifier, put something like I did (see picture) so you know who the schedule is for.

ACCOUNT, put account


project/configuration sync from shell (not from ./admin)

drush csyn does the job.

we're putting the config files in a non-default location, so need to specify the path:
  drush csyn --source=/path/to/config


Can emails be sent asynchronously via rules? (Using Queue?)

Oh the joys of email. Email is sent via the servers underlying or configured MTA. PHP merely passes-off the email content to be delivered. Depending on your email configuration PHP may wait for bounce notifications for example ... or simply spool the emails to disk and wait for the MTA to flush the outgoing mail folder.

Emails from Drupal though do not need to occur on page-load or form submission. If you want you could use Rules to slowly fill a Queue (a "list") of emails to send out from the "website" periodically.

Depending on how you want to process that Queue, whether in realtime using a Process or Job/Worker library is up to you. Or you could batch up the sending of the emails using Drupal (and/or Drush) and it's built in Cron support.

Or, for instance you could use one of the many email campaign modules for Drupal such as:

Emma https://github.com/myemma/integration-emma-drupal
Mailchimp https://www.drupal.org/project/mailchimp

to completely offload the work from your server. How you wish to approach this problem, it's feasibility and cost are up to you.

EDIT:

This module works to provide Rules to fill Queues using Drupal Entities, Rules Queue. Google is your friend! :D

For some example code that uses hook_cron to send Queue'd emails:
http://www.jide.fr/english/using-rules-and-the-queue-api-to-batch-send-mass-mails


Remove white spaces from inline form-inputs

Set form font size 0 and increase font size of input

form {
    font-size: 0;
}

form input {
    font-size: 12px;


Drupal is build and designed around the idea that the markup produced by a module is themable (ie. it can be changed by a theme independently of the module). Which mean that markup for a page is usually build using Drupal theming system. Basically, you define templates then use them in your render arrays. In your render arrays, #theme define the used templates, almost ever other entries are specific to the templates and used to inject variables into the template or its preprocess functions.

To add CSS and JavaScript you need to attach them to your render arrays with #attached as assets libraries, see the Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module documentation for details. This is used to allow Drupal core and other module to optimize inclusion of the CSS and JS files into your page.


If you want to integrate SOLR with Organic groups,  you can use the Apache Solr Organic Groups Integration module but it is in dev mode.

Also, while searching, you can filter data, and alter queries as required.


How many web pages can the Panels module handle?  What's the performance impact?

There is no reason to believe that "Panels is slow". This is a misconception created by the fact that Page manager and Panels modules are complicated, and not easily understood.

Panels is actually sometimes faster than core is on it's own.
And that's without utilizing caching, something Panels can do much better than core, because it allows you to do it from on a page by page basis, down to on a block by block basis.

At NodeOne, we build all our sites using Page manager, Panels, and Panels Everywhere. I have yet to see a performance problem caused by the use of Panels itself. That said, you should consider using Caching, as a website utilizing Panels well is most likely a complex one. (I'm no longer with that business, but this remained true for as long as I was)


Creating a view to show nodes with multiple aliases generated by Path Module

As this is a one-off requirement, there's not a lot of point creating a view for this purpose, as it would mean writing code to add extra entries for path in views tables.

You will be better off writing SQL. Here's a query that'll give you what you are after:

SELECT src, COUNT(*) AS alias_count FROM url_alias WHERE src LIKE 'node/%' GROUP BY src HAVING alias_count > 1

The result will be every source path like 'node/nnn' which has more than one alias.


views exposed filter does not redirect to itself

Look at the "Advanced" pane on the View config page: There is "Link display" where you can define custom URL for the view - it's something like a "base path" for the view and the exposed filter values will be added to it, e.g.: if you define my-view-path than the filtered view has the path my-view-path-?filter_1=true&filter_2=false&filter_3=&filter_4=0.

Hint: If you have created a panel pane you have to set "Link to view" to yes in "Pane settings" to make use of path/URL defined in "Link display".


You can simply create a node, and put this node (eg. node/15) in the admin/config/system/site-information default frontpage field.

Otherwise you can also create a custom  page with hook_menu() like this:

$items[path] = array(
    'title callback' => 'page title',
    'page callback' => 'page_callback',
    'access callback' => 'access_callback',
    'type' => MENU_SUGGESTED_ITEM,
);

and in page_callback() you can return your  custom theme template/function.

Or simply use some contributed modules like "Empty Page", "Front Page", "Empty Front Page" and others..


How to rediret to specific page depends upon user roles

This is possible with rules
You can try the following

Create a rule with event as "User has logged in".
Add condition "User has role(s)" and configure it as in screenshot
Then save the condition.
Now add action to you rule and select "page redirect" under system in the select the action to add dropdown.
This will open a form which will allow you to set the redirection path, simply in the value field give the internal page path you want the user to be redirected to and then save it.Check the screenshot for better understanding

This way you can set redirect for one role and similarly you can create one more rule in a similar way for the other user role, if you want the other role to redirect to some other page.


How to figure which function(s) are triggered upon file download to check permissions

If the Drupal log shows you that the access has been denied, then you have a simple way to debug this: if you have a debugger, simply set a breakpoint in drupal_set_message. Skip calls to that function (there shouldn't be too many) until you get the one with the access denied message - and then look at the backtrace. This should show you which function denied the access.

If you don't have a debugger, you can simply (temporarily) add some extra code in that function to test for the relevant error message, and then output a backtrace using debug_backtrace. You can output the data on the screen, to a log file using drupal_debug (if you have the devel module enabled), add it to the generated error message, etc.


You need to get an XML parser module that interacts with node inserts, similar to feeds xml I would assume. This should allow you to insert the data into your db.


programmatically get default value from translated body field per language

eventually, I fixed it myself by using the hook form alter and custom db_query to load the locales tables and then match the LID to get the source and target language and then manually overwrite the default language for every new translated language.

so my problem is solved, thank you guys for helping out.


RewriteRule causing internal redirect limit error

Start by getting the base site working at your Drupal domain then slowly add Rewrite rules. First remove everything you've added to the .htaccess files and elsewhere, upload the site to the directory you want and see if you can access it.

http://www.example.com/sites/default/files/staticsite

If that doesn't works then the problem is probably the current .htaccess configuration (docroot or files directory).  If it does work, move on to the next stage.

The next step is to get your custom hostname working. This seems pretty straight forward from the Acquia docs:

RewriteCond %{HTTP_HOST} ^subdomain\.example.com\.com$
# Don't loop anything targeting the actual mask directory, to allow
# for linked scripts, stylesheets etc in the static HTML
RewriteCond %{REQUEST_URI} !^/sites/default/files/staticsite/
# pass-through the matching file from beneath /sites/default/files/ and stop processing
RewriteRule ^(.*)$ /sites/default/files/staticsite/$1 [PT,L]

Important: The above needs to be inserted before the following. If it's not, non-file requests (such as directory index / ) may redirect to index.php instead.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^ index.php [L]

If that works, start adding the other domains one by one and testing.


How to set a specific date (fixed value) as default value on a date field?

Since, it isn't clarify about if the datefield is asking you for a PHP code or not; you can just use this:

2016-08-20

In that way the field will change that date into what you want.


I have muliple webforms in my site, but want to disable all webforms after user makes a submission

make a user role user has submitted survey. use hook_webform_submission_insert or hook_webform_submission_update (what you use depends on if you allow Drafts) -- and change whatever role they have by default in your site, to user has submitted survey. Dont allow this new role to access any forms.


Can I allow a user to create a Node using only an embeded rich text editor

I have done this using:

Automatic Node Titles Module

  "auto_nodetitle" is a small and efficient module that allows hiding of
  the content title field in the form. To prevent empty content title
  fields one can configure it to generate the title by a given pattern.

Advanced Form Block Module

  Welcome to Advanced Form Block Module. With this module you can do the
  following:

  1) Create any number of blocks with a particular node edit form.

  2) create any number of blocks with a particular node add form of a
  content type.

  3) Create as many blocks as you like of each kind.

  4) From the content type choose which fields to display on a per block
  basis.However required fields will be automatically displayed.

  5) All forms will be saved through ajax. So multiple node forms can be
  independently placed on a single page and worked with simultaneously.

With configuration and some css, you can get it looking really nice, and as a block it can go anywhere you want. You can also use hook_form_alter() on the appropriate form:

$form['actions']['submit']['#value'] = 'BUTTON TEXT';

to change the text of the submit button


Switch to admin theme based on path using hook_init() or template.php in Drupal 7

The Administration theme module will do it, but given you'd like to do it yourself, it does cast some light on that path by suggesting the hook_admin_theme_check() and hook_admin_theme_info() hooks.


How do I find and alter the Views field markup in Drupal 8?

First, enable twig debugging in sites/default/services.yml.

Then that should print a wrapper around each template that tells you which template it is exactly using for that piece of marking. In this case, it is probably views-field.html.twig or so.

Twig also reports what kind of suggestions you can use (e.g. a node type specific template for node.html.twig), but that doesn't work for views because views uses a different approach for that, and twig debug doesn't understand that yet.


In order to delete the field in a form   you have to  print the form  either using dpm($form) or print_r($form) and there you will get the field of username use that field to unset in form_alter .

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

  if (form_id=="Your_form_id"){

      unset($form['the_field_you_dont_want']);

        }
   }


For Drupal 8 Add your custom submit handler in form alter:

$form['actions']['submit']['#submit'][] = '_custom_node_form_submit';

And add custom submit handler:

function _custom_node_form_submit($form, \Drupal\Core\Form\FormStateInterface $form_state) {
  echo $form_state->getValue('nid');
}


unable to get custom service to return result using services module

Finally figured it out and boy was it bad. The endpoint I was supposed to hit was http://mysite.com/myawesomeendpoint/awesomeregistrant but instead I hit http://mysite.com/myawesomeendpoint. Hope this helps some one.


"Expand all menu links" Menu Block selection shows all menu items in block not just active trail items

Found a patch that does the trick:
https://www.drupal.org/project/menu_block/issues/2811337


How to include cck field image in Forward module template (forward.tpl.php)

Posted my solution on Drupal's site, the forward module issue queue:

https://drupal.org/node/2107769


How to solve "This version is not compatible with Drupal 7.x and should be replaced" error?

As per Writing theme .info files, core is a required key. You just need to add

core = 7.x

to make your theme compatible with Drupal 7.


Simpletest fails to create the field_config table

The issue is definitely related to cache backends.

Disable cache backends if you are testing using Simpletest classes.


Theming html output of privatemsg 6.x-2.x module

Ok, here is some information.

That list shows threads, not single messages. You can't change that, at least not with theming. The only thing you easily can do is enable the privatemsg_limits module and set the number of messages per thread to 1. That basically disables threading and each message will be sent as a new thread. Then they will be shown separetly on the list, but they will also be shown separately on the thread view page. Privatemsg views is currently only compatible with 6.x-1.x and looks rather unmaintained at this point.
You can configure the displayed columns and their order in the Privatemsg settings.
The theming functions are used to customize the content of single columns. For example, to show a different date format, you can override phptemplate_privatemsg_list_field__last_updated():

function phptemplate_privatemsg_list_field__thread_started($thread) {
  $field = array();
  $field['data'] = format_date($thread['thread_started'], 'custom', 'd.m.Y H:i');
  $field['class'] = 'privatemsg-list-date-started';
  return $field;
}

In 7.x, Privatemsg shows a different date format depending on the age of the message, that is done in privatemsg_format_date() if you want to backport that.
To change how the table looks, you should be able to that with just CSS. Privatemsg adds tons of classes to that table, including a seperate class for every column and classes for rows with new messages and soon for unreplied messages too.


Some things you should check:

Check if the owner of the sites/default/files is the proper user and groups. The user and group usually is www-data, but it depends on your webserver.
Since you mention temporary folder, you should check if the temporary directory at admin/config/media/file-system section of administrator interface is configured properly.

  What risks are there to set permissions 777?

It is a very very bad practice. There are tons of materials on the net you can look at, but long story short: Setting the permission to 777 means that anyone can write and execute anything in that folder, including malicious codes.


It seems you are looking for Hierarchical Select module.


Programically update node when visited by 'editor' role

I have replaced these 3 lines

            $node_data = node_load($node->nid);
            $node_data->promote = '1';
            node_save($node_data);

with

            db_update('node')
                    ->fields(array(
                        'promote' => '1',
                    ))
                    ->condition('nid', $node->nid)
                    ->execute();
            db_update('node_revision')
                    ->fields(array(
                        'promote' => '1',
                    ))
                    ->condition('nid', $node->nid)
                    ->execute();
            db_query('DELETE FROM cache_entity_node WHERE cache_entity_node.cid = :nid', array ( ':nid' => $node->nid));

and it seems working :)


You can use hook_form_alter and views_embed_view to alter the form and add the markup for a view.


StackExchange-style "related tags" block using drupal views?

There's a module that I believe does what you want: Similar by Terms

  This Drupal module attempts to provide context for content items by
  displaying a block with links to other similar content. Similarity is
  based on the taxonomy terms assigned to content. Blocks are available
  based on similarity within each of the defined vocabularies for a site
  as well as a block for similarity within all vocabularies.


Ok, I've got it. I'm using:

Menu Node API -- to manage relationships between node ids and menu items;
and Menu Node Views -- to make View of type 'Menu tree'

I then made a new view with these settings (called primary_link_in_admin):

Filter - Menu: Menu name = primary-links (or whatever you need)
Sort criteria - Menu: Weight asc
Fields -

Menu: Link path  - Exclude from display
Menu: Link title  - with overridden values - Output this field as a link → Link path: [link_path]/edit

So I have my Primary Menu in the admin section of the site and a site administrator is able to click on any menu link and goes directly to node/edit on that node. In that way I have very clean Admin section of my Drupal site....(perfect for small - brochure type sites)

That's why I love Drupal and it's community :)


How to attach a JS library to page or block with #attached?

This might be a simple case of misunderstanding. The difference between libraries_load and library #attached keys can be confusing.

['#attached']['libraries_load'] is for libraries defined through hook_libraries_info which is in turn a part of the Libraries API module. If a module has defined a hook hook_libraries_info but your installation doesn't have the Libraries API module installed, then that library will never load. The libraries_load key of #attached will not fire for the same reason. Ideally though, this module with the hook_libraries_info should have a dependency on the Libraries API module if it was written correctly.

['#attached']['library'] is for libraries defined through drupal core library api hook_library. This should always work without any additional modules, provided you've defined a hook_library in your module (and not hook_libraries_info)

Hope this helps you get a clearer idea of what's exactly wrong. You can't have these interchanging, and just trying libraries_load or library randomly to see if they work. Both require a certain prerequisite (see above) to function correctly.


Pass the value in a field into a colorbox popup

Using the Drupal Colorbox module you should be able to accomplish this.

You just need to add the class colorbox-load to your link and then to modify the colorbox settings per link append something like ?width=500&height=500 to the end of the path.

Colorbox Documentation

  Check the "Enable Colorbox load" option in Colorbox settings.

  This enables custom links that can open content in a Colorbox. Add the
  class "colorbox-load" to the link and build the url like this
  "[path]?width=500&height=500&iframe=true" or
  "[path]?width=500&height=500" if you don't want an iframe.

  If you want to pass the width and height of the Colorbox as a
  percentage (useful for responsive designs), you can format the link
  like this "[path]?width=90%25&height=90%25&iframe=true" or
  "[path]?width=90%25&height=90%25", where the "%25" is the HTML entity
  for "%".

  Other modules may activate this for easy Colorbox integration.

  Load inline content in a Colorbox

  Check the "Enable Colorbox inline" option in Colorbox settings.

  This enables custom links that can open inline content in a Colorbox.
  Inline in this context means some part/tag of the current page, e.g. a
  div. Replace "id-of-content" with the id of the tag you want to open.

  Add the class "colorbox-inline" to the link and build the url like
  this "?width=500&height=500&inline=true#id-of-content".

  It could e.g. look like this.

  Link to
  click  What
  ever content you want to display in a Colorbox.
  Alternatively instead of style="display: none;" you could use
  class="element-hidden".

  Other modules may activate this for easy Colorbox integration.


Display a particular field in a view by a comma separated values using custom code

You could create a template for the field you want to modify.

Click on link Advanced -> Themes -> Information, while editing the view, and select the right template and file name.
Then, in the template you can modify the output of the field.


How to set a field value from parent template in Twig?

There should be no reason to change any code for this, as you are using the default image formatter. You should be able to remove the link by going to /admin/structure/types/manage/article/display/teaser and change your field's formatter settings using the cogwheel-button and then select "None" for "Link image to".

Should the teaser view mode configuration page not be available, got to /admin/structure/types/manage/article/display and activate its checkbox on the far bottom of the page, then save and try again.


It's possible to stuff more values into a custom insert (or merge) by using the values method. This isn't comparable to the persist functionality, and can only be used in limited scenarios such as a single table. A more complex storage scenario, such as with entities, would not be possible as a single entity save operation could be writing to multiple tables (unless someone rewrote a custom entity storage layer).

Also, I am not sure what the loadObjectProduct exactly does in your code, but this seems to be loading node entities. It would probably be best to use an Entity Query::condition and fetch back multiple entities.

Finally you need to use an array map/reduce to map the values.

Something like the following pseudo-code:

// Using Database static method from \Drupal\Core\Database\Database.
$database = Database::getConnection();
// Assumes loadObjectProduct is refactored.
$nodes = $this->loadObjectProducts($itemCode);
// I tend to think backwards about this sort of thing. :-)
$values = array_reduce($nodes, function (&$result, $productNode) use ($cardCode) {
  $result[] = [
    'card_code' => $cardCode,
    'item_code' => $productNode->id(),
  ];
  return $result;
}, []);

try {
  $database->insert('customer_product')
    ->fields(['card_code', 'item_code'])
    ->values($values)
    ->execute();
}
catch (DatabaseWrapperException $e) {
  // Catch errors
}


As you can read in README.txt file:

*** About Google Site Search module
---------------------------------------
This requires "Site Search Edition" (paid version of Google's Custom Search).

You need to have a paid Google Site Search engine, so you can receive results in custom format (e.g. XML).

If you've free version, check the alternatives modules such as: Google Search Appliance or Google Custom Search Engine. Or use alternative services such as Yahoo YQL (e.g. YQL Views).