You can use this module elysia_cron  Elysia Cron extends Drupal standard cron, allowing a fine grain control over each task and several ways to add custom cron jobs to your site.

Elysia cron is usually used in large sites that needs performance optimization.


How can I inject a taxonomy menu as the sub-menu of a standard menu item?

Option a) Unless I am mistaken, can you not just pick where your Taxonomy Menu will be parented (Menu Location) when you create it? The only problem I think you might get with this is I think it requires you to rebuild the menu every time the taxonomy is updated

Option b) I have done something reasonably similar to this on my site, I used Menu Views module, to allow me to put a view into my primary menu.

If you create a new view which lists all of your taxonomy terms, as a block display, apply any additional filtering/modification in the view if necessary (you may not but in my example I wanted to). Then when you add a new link to your main menu, you can select to use a view rather than a link. From there you pick which view you want to use, select the 'Category' menu item as its parent and save (after saving you then have to enable it in the menu, which appears to be a bug with the module itself)

I can't guarantee that this is the best solution for you, but it worked when I just tested it


html5-respond.js not rendering CSS3 properties in IE7 and IE8

IE8 doesn't work on @import'ed stylesheets. but you can write query by this way

@ Media screen and (min-width: 980px)
{

  / * CSS Document * /

}

and also you must include css3-mediaqueries js

<! - Css3-mediaqueries.js for IE less than 9 ->
 <! - [If lt IE 9]>
 <script src="http://css3-mediaqueries-js.googlecode.com/svn/trunk/css3-mediaqueries.js"> </ script>
 <! [Endif] ->

see this http://westilian.com/ie7-and-ie8-support-for-css3-media-query/


I had exactly the same problem here and complete system cache clearing helped me out.

  Configuration -> Development -> Performance -> Clear all caches.

That solved the problem for me.

See: Undefined variable: hide_site_name in include() while change theme


How to create a horizontal views slideshow of content in views?

You can use Views Slideshow module for this.

  Views Slideshow can be used to create a slideshow of any content (not just images) that can appear in a View. Powered by jQuery, it is heavily customizable: you may choose slideshow settings for each View you create.

You can read tutorial here: http://drupal.org/node/755010

Demo: http://drupalmultimedia.org/slideshow


How can I conditionally show a field in the node/add page?

By default in Drupal 8 "Seven" is the admin theme.

(Assuming you're using Seven as your admin theme) In /core/themes/seven/js add/create custom.js file.

custom.js

(function ($) {

   $('#edit-body-wrapper').hide();

   (function Forever(){

     var title = $('#edit-title-0-value').val();

     if (title != '') {
       $('#edit-body-wrapper').slideDown(1500);
     }
     // slides down and shows the body field in 1.5 secs if the title field is not empty

     else if (title == '') {
       $('#edit-body-wrapper').slideUp(1500);
     }
     // slides up and hides the body field in 1.5 secs if title is empty

   setTimeout(Forever, 1);

   })();

})(jQuery);

Now edit seven.libraries.yml

In the node-form: section add

  js:
    js/custom.js: {}

So it should look like this:

node-form:
  version: VERSION
  css:
    layout:
      css/layout/node-add.css: {}
  dependencies:
    - node/form
  js:
    js/custom.js: {}

PS: Don't forget to clear the cache to see changes.


How to programmatically update a user role name

Information about user roles should never be loaded/saved directly from the database, but using the functions the User module provides, such as:

user_role_load($rid)
user_role_load_by_name($role_name)
user_role_save()

As for changing the role name, that is not as simple as editing the role object and saving it, since the role name is required to be unique. (The name field, in the database, is the unique key for the role table.)

Before saving the role object, the code should verify the name is not already used, as the following code does.

// Load the role object from the database into the $role variable, using user_role_load()
// or user_role_load_by_name().
// The $role_name variable is assumed to contain the new name you want to give to the role.

if (!(bool) user_role_load_by_name($role_name)) {
  // There isn't a role with that name, so it's possible
  // to change the role object and save it.
  $role->name = $role_name;
  user_role_save($role);
}
else {
  // There is already a role using that name.
  // Make the name unique, or abort the operation.
}

Using the functions made available from the User module is preferable, since it allows other modules to react to changes to roles. Those functions invoke at least one of the following hooks.

hook_user_role_insert()
hook_user_role_update()
hook_user_role_delete()
hook_user_role_presave()


D7: jQuery script for creating 'active' links in menu system. (partially works)

I'm pretty sure Drupal 7 does that for you out of the box. I can see, from my D7 site, I have first, last active-trail classes

Opportunities

Organisations

Events

As can be seen above the LI have the class you require. Do you have any custom code, modules or theme functions causing this not to happen on your site?


This question is over 6 months old.  The best solution now for adding custom fonts is to use the @fontyourface module.


url of custom theme not showing up with page.tpl

Thanks everyone for helping. I changed the contents of the callback function, print to return. It solved the problem.


How do I intercept a press on "Save" and get the nid?

If you read through node_form() you will see that the Submit button has its own submit handler:

$form['actions']['submit'] = array(
  '#type' => 'submit',
  '#access' => variable_get('node_preview_' . $node->type, DRUPAL_OPTIONAL) != DRUPAL_REQUIRED || (!form_get_errors() && isset($form_state['node_preview'])),
  '#value' => t('Save'),
  '#weight' => 5,
  '#submit' => array('node_form_submit'),
);

so you need to add your own submit handler to this

function MYMODULE_form_node_form_alter(&$form, &$form_state) {
  $form['actions']['submit']['#submit'][] = 'MYMODULE_node_form_submit';
}

Then inside that $form_state['nid'] or $form_state['node'] should have what you need.


You can rewrite the output of any field in a view by using "Rewrite results" and clicking on "Rewrite the output of this field" (see screenshot below). You can use a replacement pattern for the actual content of your field and then add the "€" symbol.


How can I render a birthday field to display only Day and month

Go to /admin/config/regional/date-time/formats and select Add format. You will be prompted to enter a format string. This is a php date() formatting string. If you enter "F j" (without the quotes" the date format will be the full month name and the date eg April 11. Refer to the manual for a full list of options.

Then go to /admin/config/regional/date-time and select Add date type. Call your new type 'Birthday' and select the date format you just created from the select list.

Under /admin/config/people/accounts/display select your field and configure the display to use the 'Birthday' format.


Separate page for payment methods selection in drupal commerce

Sure! You can use a module like Commerce Checkout Pages to create a new page via the UI or you could implement hook_commerce_checkout_page_info() in your module and create a new page. Then just move your Payment pane onto your new page and you'll be all set:

/**
 * Implements hook_commerce_checkout_page_info().
 */
function MYMODULE_commerce_checkout_page_info() {
  $checkout_pages = array();

  $checkout_pages['payment'] = array(
    'name' => t('Payment'),
    'title' => t('Payment'),
    'weight' => 3,
  );

  return $checkout_pages;
}

Then, implement hook_commerce_checkout_pane_info_alter() to add your payment pane to your new page:

/**
 * Implements hook_commerce_checkout_pane_info_alter().
 */
function MYMODULE_commerce_checkout_pane_info_alter(&$checkout_panes) {
  // Payment selection on the new 'payment' page.
  $checkout_panes['commerce_payment']['page'] = 'payment';
}


Is Sweaver module compatible with Domain Access module?

It doesn't work because it saves all the data files in the same place and all the sites will have your same changes. The admin settings maybe able to be changed based on the domain but code that controls your CSS changes doesn't change based on the current domain.

This is with Drupal 6.


How to add an id element to a field in Drupal 7

First of all are you using the Link module? Just so we know.

I would create a template to the field:

You can copy the /modules/field/theme/field.tpl.php to your theme, change the name to field--field-print-link.tpl.php and customize it in any way wanted.

Don't forget to flush your caches!

Or, of course, you could add the id with JS using a bit of jQuery (as Drupal already uses it):

$('element').attr('id', 'value');


You can do it by using Tax option under store-> configuration.

Just go and add a tax rate.

Now you can apply tax rate using rules easily on event something like "after saving new commerce order.

And then add action you want to perform.


how to pass variables from a views style-template to the row-template it invokes

You can't pass variables from one template file to another.  That is not how things work.

However, a general rule is that every template file has a corresponding preprocess function for creating the variables available in the template.

So, you need to figure out what preprocess functions are being called.  The Theme Developer module can help out with this.  The theme.inc file lists all of the preprocess functions that the Views module uses.

With those, the standard way of handling things is something like

function mymodule_preprocess_views_view(&$variables) {
  $view = $variables['view'];
}

Once you have the $view object, you have everything you need.  However, you often need to dpm($view) to figure out what is there and/or look at the default preprocess functions.


What you are looking for is the equivalent of SQL aggregation. I have done this successfully in a Drupal 6 install using the Views Group By module. The process is pretty simple as long as you are reasonably familiar with views. Your setup sounds like exactly what you should have for this case.

In Drupal 7, the equivalent functionality is built into the default views module. You will need to open the "Advanced" section to see it.

An alternative approach would be to write a custom module that creates the SQL aggregation itself. But it sounds like you are already familiar with views and should stick with this approach.


Get body summary in field's replacement pattern

You need to select Summary or trimmed as your formatter, then {{ body }} will print out your summary.


Pulling capacity and slots left from entity registration

I managed to solve this by pulling in the relationship of "Registration Settings: Node to Registration Settings" and putting the fields for total as well as used slots in.

In addition, when needing to calculate the amount of remaining slots, I calculated this with views php.


In the rules config UI I can't see any "Add Loop" button - is this to be expected in version D8 Alpha 3?

yes ... as per the issue about Implement Loop UI.

  What data selector should I use for accessing field_items on the Order node that has just been saved?

I doubt this is possible in the D8-alfa3 release of Rules. Though you may want to retry using the D8-dev release ...

  What data selector should I use in the rules component to access field_reservation_status on the current object from field_items?

Refer to my answer to "2." above ...

  How do I set up a loop over the variable that is created in the reacting rule?

Refer to my answer to "1." above ...

PS: No doubt you'll run into more-of-the-same issues using any of the currently available releases of Rules for D8. However, using the D8-dev release is currently your best bet/alternative.


Multilingual content and single language admin interface

On a fresh install, I could get it working that way:

In admin/config/regional/language/detection

put  Account administration pages on top of Interface text language detection an enable it of course.
enable URL method as second choice
enable Content language detection and put URL on top of detection methods.

In user/1/edit language settings :

set Administration pages language with your preferred language

There are various issues on D.O about that, maybe this is the most relevant  one : When content language detection is different from interface language detection, the detected language is not applied to the rendered content.

Apply these patches :

When content language detection is different ... (patch #24)
'Account administration pages' language negotiation causes 'access denied' in toolbar subtree caching (patch #10)
Admin toolbar should always be rendered in the admin language (if set) (patch #40)

Empty caches :

$ drush cache-rebuild

Language dropdown switcher and everything else seems now to be working fine !

An example of spanish content, strings passed through t() are translated, admin toolbar in english...

The same page edited: admin interface fully in english, but content shows  the correct translation....


Output the field as $_rendered in the node page

To load the data back to the node and render them, you first need to implement a hook_nodeapi load. Here some a short example:

function satya_module_nodeapi(&$node, $op, $teaser, $page) {
  switch ($op) {
    case 'load':
      // retrieve the p1 value from custom_table (it's better to use vid instead of nid to allow revisions.
      $p1 = db_result(db_query('SELECT p1 FROM {custom_table} WHERE vid = %d', $node->vid));
      return array('p1' => $p1);
      break;
  }
}

Then you will have a $p1 variable available in your node.tpl.php.

If you don't know yet the Examples modules, I'll definitely recommends it to have great examples and developer documentation for a lot of hooks.


How do I change date format in the submitted line using only template.php without node.tpl.php?

You can use template_preprocess_node to alter submitted variable. Here is the sample code.

function awesome_preprocess_node(&$variables) {
  $node = $variables['node'];
  $date = format_date($node->created, 'custom', 'm-d-Y - H:i');
  $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $date));
}

The most important line there is $date = format_date($node->created, 'custom', 'm-d-Y - H:i');. Change the format (m-d-Y - H:i) to any format you want.

See this page about PHP date format.


#ajax is never used by elements of markup type. You need to use it with one of the following elements:

button
checkbox
checkboxes
image button
password
radio
radios
select
submit
tableselect
textarea
text_format
textfield


Is it OK to remove field values or revisions by deleting individual lines from the field table in the database?

It is better to Use the Node Revision Delete module to delete and manage your revisions.

  The Node Revision Delete module allows you to manage the revisions of the Node according to your choice. It helps you to keep the specific number of revisions for the node. This module provides you the flexibility for applying the revision delete for the specific content type and run it on the specific time. You can manage your settings from the Node Revision Delete Administration Page.


Show first view result, but show next result when the view's cache is cleared

I would have used some scheduling mechanism for node publish and unpublish instead of using views chache.

Some thing as schedule a node A to publish today and unpublish tomorrow, node B is unpublished today and will be published tomorrow, meanwhile the view will always pick the published nodes.

Node scheduling can be handled by scheduler module.


How to trace down to find where a field has been removed/hidden of a particular node

some things to look at: make sure under display, that the type of display is set correctly (full content, teaser, default, etc). Check if field permissions or similar is installed and that the permissions for that field are set correctly. Check for any rules or actions that could be causing it to be removed.

another - is it in a field collection, display settings for those are shown under /admin/structures/field collections not under the content type


Table Pager Rendered in an Ajax Callback Shows White Page

This sounds like a known bug in core:

Pager, tablesort links in a form point to system/ajax when reloaded via AJAX
https://www.drupal.org/node/1181370

Someone has offered up a "quick fix" in comment #22:

  As a quick fix I overrode theme_pager_link() to set the url of my AJAX-loaded pager to the page url instead of $_GET['q'] (which was system/ajax).

[Edit...]

I haven't tested this, but give it a try:

In your callback function, save the current path in a session variable:

$_SESSION['page_path'] = current_path();

Copy and paste this function into your *.module file:

/**
 * Implements hook_theme_registry_alter().
 */
function YOUR_MODULE_NAME_theme_registry_alter(&$theme_registry) {
  $theme_registry['pager_link']['theme path'] = drupal_get_path('module', 'YOUR_MODULE_NAME');
  $theme_registry['pager_link']['function'] = 'YOUR_MODULE_NAME_pager_link';
}

Copy the theme_pager_link() function into your *.module file.
Rename the function YOUR_MODULE_NAME_pager_link.
In the function, replace the following line:

$attributes['href'] = url($_GET['q'], array('query' => $query));

with:

if (isset($_SESSION['page_path'])) {
  $attributes['href'] = url($_SESSION['page_path'], array('query' => $query));
}
else {
  $attributes['href'] = url($_GET['q'], array('query' => $query));
}

Clear the caches.


modules for building ajax application and friendly urls?

You shouldn't need an additional module, Drupal's AJAX framework should provide the needed features. For instance, it can easily be used to ajaxify links.

See the AJAX Example, AJAX Graceful Degradation and AJAX Commands example modules for API usages.


you shouldn't need to add the "q=" drupal will deal with that side of things, especially when you turn on clean urls.


How do you save data that is in fields inserted via hook_form_alter?

Other modules aren't generally programmed to be aware of your custom additions and don't know where/how you want to save the data. If you add fields via hook_form_alter() then you should also add your own submit and possibly validation handlers to the form similarly to this:

$form['#validate'][] = 'mymodule_someform_custom_validation';
$form['#submit'][] = 'mymodule_someform_custom_submission';

In the validation handler you can then validate your custom field data (if needed) and in the submit function you should save it. Small amounts of information can be stored in a variable, but if there's bigger amounts of data from different users you'll probably want to create a custom database table where to store all the information in.


Getting the value submitted from form with FAPI radios in template.php

I think the problem is that your #options array for the radios isn't keyed (which it should be). PHP will automatically assign the keys as 0,1,2 etc but 0 is not valid as Drupal ignores such a value which may be causing you a problem, and I guess you're expecting a value of 2011, 2012 or 2013 which currently you won't get.

Drupal does provide a handy function, drupal_map_assoc to create a keyed array from a flat one. This code:

$array = drupal_map_assoc(array(1, 2, 3));

will produce an array of

array (
  1 => 1,
  2 => 2,
  3 => 3
)

So if your form element looks like this:

$form['years'] = array(
  '#title' => t('Please, choose appropriate year'),
  '#type' => 'radios',
  '#options' => drupal_map_assoc(array(2011, 2012, 2013))
);

In your submit function you would grab the selected value with:

$form_state['values']['years'];

I think you might have a slight confusion in your logic, this bit of code:

$name = $form_state['values']['years'];

is fine to grab values from the $form_state array but years is not a name, it's a year. That might also be adding to the confusion.

EDIT

I've just noticed a few other problems in your code that may be causing unexpected results.

The first one is in mymodule_page(). drupal_get_form() returns an array in Drupal 7 so concatenating it to a string (the return from print_r()) will not produce the results you're expecting.

Secondly, you're calling drupal_get_form('mymodule_form'); and your form is actually named frontpage_form().

Lastly, you don't actually need the mymodule_page() function at all...you can change the page callback of your menu item to drupal_get_form() and the form will automatically be built for you on that page. Remember to clear Drupal's cache once you've made this change.

The last thing I'd say is that relying on print_r for debugging can be very tedious. Instead, I'd advise installing the Devel Module which has a wonderful function called dpm(). This will print a nicely formatted representation of any variable to the standard messages area when you call it. It's a must for Drupal development really.

You'd use it like this, for example in your form submit handler:

dpm($form_state['values']);

EDIT 2

Quick dirty way to get the submitted value into template.php:

In your module file

function frontpage_form_submit($form, &$form_state) {
  frontpage_submitted_value($form_state['values']['some_value']);
}

function frontpage_submitted_value($new_value = NULL) {
  $value = &drupal_static(__FUNCTION__, FALSE);

  if ($new_value) {
    $value = $new_value;
  }

  return $value;
}

And then in a function in template.php

if ($submitted_value = frontpage_submitted_value()) {
  $vars['some_val'] = $submitted_value;
}


I would suggest you to use drush and try rebuilding registry using Registry rebuild because there might be modules file path issues (conflicts) while migrating.

After you put all files in place and database imported. try this,

Download Registry rebuild module.
now run drush rr on your drupal installation directory. [ if it is multi-site then your working directory should be inside sites/example.com/ ]


how to Create some nodes of a content type when created a node of another content type?

Custom module is the best way to go. With rules it's really complex. You need to use below hook in your custom module to solve above problem.

hook_node_insert to hook into above node creation. Hook Responds to creation of a new node.
In above hook implementation you need to create new nodes using code. Please find article which explains same.


"Convert Media tags to markup" in CKEditor is not working

This is most often caused by the order of the filters. Try to set this filter as the last (or first) one.

Another alternative is CKeditor's ACF (advanced content filter). This should be fixed in the latest Wysiwyg module release.


Automated tests describes the different tests and makes clear which test should be used, in a Drupal environment. In particular, it says:

Unit tests: Test functionality of a class if the Drupal environment (database, settings, etc.) and web browser are not needed for the test, or if the Drupal environment can be replaced by a "mock" object.
Kernel tests: Test functionality of a class if the full Drupal environment and web browser are not needed for the test, but the functionality has significant Drupal dependencies that cannot easily be mocked. Kernel tests can access services, the database, and a minimal mocked file system, and they use an in-memory pseudo-installation. However, modules are only installed to the point of having services and hooks, unless you install them explicitly.

If you are testing a class that should insert data in the database, the test should be a Kernel test, which means:

The base class of the test should be \Drupal\KernelTests\KernelTestBase
The namespace of the test should start with (in your case) \Drupal\Tests\some_module\Kernel, and it should be placed in the some_module/tests/src/Kernel directory or a sub-directory

For example, the DatabaseBackendTagTest class implements a Kernel test that accesses the database.

  public function testTagInvalidations() {
    // Create cache entry in multiple bins.
    $tags = [
      'test_tag:1',
      'test_tag:2',
      'test_tag:3',
    ];
    $bins = [
      'data',
      'bootstrap',
      'render',
    ];
    foreach ($bins as $bin) {
      $bin = \Drupal::cache($bin);
      $bin->set('test', 'value', Cache::PERMANENT, $tags);
      $this->assertTrue($bin->get('test'), 'Cache item was set in bin.');
    }
    $connection = Database::getConnection();
    $invalidations_before = intval($connection->select('cachetags')->fields('cachetags', ['invalidations'])->condition('tag', 'test_tag:2')->execute()->fetchField());
    Cache::invalidateTags(['test_tag:2']);

    // Test that cache entry has been invalidated in multiple bins.
    foreach ($bins as $bin) {
      $bin = \Drupal::cache($bin);
      $this->assertFalse($bin->get('test'), 'Tag invalidation affected item in bin.');
    }

The code shown in the question just reads data from the database. (I don't see code writing the database.) Keep in mind that the database used from tests isn't automatically populated; if the purpose of the test is verifying the controller outputs the correct data, the database table needs to be filled with the data. That is normally done from the setUp() method, which could also initialize a property with the connection (for example with $this->connection = Database::getConnection();) if the data is the same for each test, or at the beginning of the test method, if each test needs different data. (For example, testCanFilterData() could test the controller filter the data in the database and testCanFilterWrongData() could test the controller doesn't output completely wrong data or out-of-the-set data.)


Is there a way to register on my Drupal site with mobile number and password instead of email?

Yes, it is possible, but you will have a lot of work to do it.

First thing first, you need a way to communicate with your users. Drupal sends quite a lot of data to users, like password restoration mails. If you want phone numbers to replace mail, you need to be able to send SMS messages. SMS Framework seems to be your friend here. There is no stable version for Drupal 7, but as far as I know it is most stable at the moment anyway.

When you have a way to communicate using their mobile numbers, you need to override mail sending, to convert mails into SMS messages. There are, generally, two ways to achieve this:

SMTP Authentication Support - It is possible to configure mailserver to send sms messages if address is in phone_number@sms.local or similar format. This does not even require any SMS framework in Drupal, really.
Use Mail System and create your own  MailSystemInterface implementation that will detect sms addresses and use SMS Framework instead of whatever mail system you are using.

If you don't want to mess with mail systems, you will need to effectively write user module from scratch and replace core one with your own - it relies on mails too much, writing alters would not be feasible.

Last thing: For all Drupal forms, you need to use form alter and detect required email, changing it into two fields, at least one required. And provide relevant storage. Actually, this seems to be an easy part.

Note pretty much every modern phone can receive emails, so I hardly see a point in this.


Establish relationship between two text fields

Both content types have to share a field, in the same way a both the database tables used in a INNER JOIN have to share a common field for the join to work.

In Drupal, this is easy as you can reuse fields between your content types and in this wway joining the content types will be super simple with Views.

Current setup:

  Recording: field_called_phone, field_caller_phone

  Twilio: field_phone_number

Suggested setup:

  Recording: field_called_phone, field_phone_number

  Twilio: field_phone_number


Ok, I found!

function fb_event_crawler_node_load($nodes, $types) {
    foreach ($nodes as $node) {
        if ($node->type=="event"){
            $fb_url = $node->field_event_url['und'][0]['value'];
            $url = parse_url($fb_url);
            if (!$url['host'] == 'www.facebook.com'){
                echo t('This is not a Facebook URL');
            }

            $path_exploded = explode("/", $url['path']);
            if (!$path_exploded[1] == 'events'){
                echo t("This is not a Facebook event page!");
            }

            $fb_event_id=$path_exploded[2];

                // dpm($path_exploded);

            $app_id = isset($app_id) ? $app_id : variable_get('fboauth_id', '');
            $app_secret = isset($app_secret) ? $app_secret : variable_get('fboauth_secret', '');
            $app_token_url = "https://graph.facebook.com/oauth/access_token?"
            . "client_id=" . $app_id
            . "&client_secret=" . $app_secret
            . "&grant_type=client_credentials";

            $response = file_get_contents($app_token_url);
            $params = null;
            parse_str($response, $params);
            $access_token=$params['access_token'];

                //echo($params['access_token']);

            $fbquery = fboauth_graph_query($fb_event_id."/", $access_token);

            dpm($fbquery);
        }
    }
}


Add a relationship to logged in user, not content author, on content view?

There is no way to accomplish this via UI. At least not if the User field may contain multiple values.

In the example below 'field_test' is a List(text) field w/ select widget (unlimited values allowed for user account). When the same field is added to Content type - I set it to allow for single values.

The code will take in consideration multiple values from User field and add WHERE  clause to the View that shows all nodes of a Content type.

WHERE clause filters out all nodes that have 'field_test' set to anything other than what currently logged in user has set in 'field_test' on their own account.

/**
* Implements hook_views_query_alter().
*/
function MYMODULE_views_query_alter(&$view, &$query) {
  // 'test_related_field' -> view's machine_name
  if ($view->name == 'test_related_field') {
    global $user;
    $user = user_load($user->uid);

    // 'field_test' -> field that is shared between user accounts ans content type
    $user_field = field_get_items('user', $user, 'field_test');
    if($user_field) {
        $query->ensure_table("field_data_field_test");
        // create query that processes multiple values of User 'field_test'
        $db_or = db_or();
        foreach ($user_field as $item){
            $db_or->condition('field_data_field_test.field_test_value', $item, 'IN');
        }
        $query->add_where('test_field_group', $db_or);
    }
    // use dpm() to see added WHERE clause
    //dpm($query);
  }
}

UPDATE:
If User field and Content Type field are allowed to have only single values then you can use UI for filtering view's results.

add shared field as Contextual Filter
Provide Default value for the field -> select PHP Code
enter the following code in the box

global $user;
$user_fields = user_load($user->uid);
$test_field = $user_fields->field_test['und'][0]['value'];
return $test_field;


install.php displayed instead of update.php

The script useful for tracking this down was:

<?php
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_CONFIGURATION);
print_r(getcwd()); echo '
';
print_r(conf_path()); echo '
';
$settings_path = DRUPAL_ROOT . '/' . conf_path() . '/settings.php';
echo "settings_path: $settings_path
";
$ret = realpath($settings_path);
echo "ret: $ret
";
?>

The clue was that $ret was empty. From the realpath documentation:

  Note:
  The running script must have executable permissions on all directories in the hierarchy, otherwise realpath() will return FALSE.

Changing

drwxr-x---  3 root  users  512 May 16 14:34 default

to have world executable permission worked around the problem.


Migrate part of a Drupal 6 installation to a new Drupal 7 installation

I might try the Migrate module.  It takes some coding but  but the documentation and example modules for it are very detailed and helpful. Basically you would create a migration class for the users (see BeerUserMigration) and a class for the forum nodes (see BeerNodeMigration).

One of the great things about this module is it creates a mapping between both data stores which allows you to rollback and re-run the migration until you get it right.


Allow all users with a certain role to set Groups Audience to any Organic Group

I was able to achieve the above requirement using OG Role Override module.
From Global Permissions for role "A" we would set:
"Act as role 'member' in OG Node Group Main Page groups"

Hope this helps!


How to limit the display of a field on the front end, based on a Form API state

For option #1 you would have to create a custom validation.

For option #2 which is the better solution you would have to load the fields via AJAX.


Remove "add to cart button" when event date has passed

If you're using Drupal Commerce, this question seems to provide a step-by-step of what you're looking for.

How do I use rules scheduler to disable and enable a commerce product entity based on certain date fields?

At the very least it should point you in the right direction and give you a better sense for how Rules integrates with Commerce.


find Menu Settings of node, given URL alias (or node ID)

Comments in my question getting URL from Route: breaks in localhost subdirectory have clarified that the solution of @4k4 is absolutely the right way to get the alias from the current path.  But the alias is not as useful as I thought in applying suggestion (@Ivan Jaros) to use entityQuery to take it the rest of the way, since the current path is able to match the link.uri field of menu_link_content, except for a leading slash in the pathname and the entity: protocol:

$current_path = \Drupal::service('path.current')->getPath();
$system_uri = 'entity:' . trim($current_path, '/');

$query = \Drupal::entityQuery('menu_link_content')
  ->condition('link.uri', $system_uri)
  ->condition('menu_name', 'main');

$result = $query->execute();
$menu_link_id = (!empty($result)) ? reset($result) : FALSE;

if ($menu_link_id) {
  $menu_link = MenuLinkContent::load($menu_link_id);
  $menu_link_title = $menu_link->getTitle();
} else {
  drupal_set_message(t('no Menu Link Content for ID that we found...'), 'error');
}


How do I programmatically use the S3FS module?

I used the following command to write the file. The system picks up the S3 connection (as I mentioned earlier that I'm able to store file as a field of a node):

file_put_contents('s3://Dir1/output.json', $jsonStr);


How to exclude Views results for custom entities for which a user has no permission to view them?

After reviewing the list of Views hooks, I think hook_views_pre_render() is the one you can use to filter results before they are rendered.

/**
 * Implements hook_views_pre_render().
 */
function MODULE_views_pre_render(ViewExecutable $view) {
  if (!empty($view->result)) {
    $entities = [
      'your_custom_entity_id',
      'another_entity_id',
    ];

    foreach ($view->result as $key => $result) {
      if (empty($result->_entity)) {
        continue;
      }

      if (!in_array($result->_entity->getEntityTypeId(), $entities)) {
        continue;
      }

      $access = \Drupal::entityTypeManager()
        ->getAccessControlHandler($result->_entity->getEntityTypeId())
        ->access($result->_entity, 'view', NULL, TRUE);

      if (!$access->isAllowed()) {
        unset($view->result[$key]);
      }
    }
  }
}


Update existing field collections with Migrate module

There's no current support in field_collection for this (a destination plugin must explicitly support Migration::DESTINATION, merging mapped fields with pre-existing values for the unmapped fields). I'd suggest submitting a feature request at https://www.drupal.org/project/issues/field_collection.


View of file entities, sorted by upload date, reorders when updating a file

A quick check with drupal_get_schema() confirms that file entities have only one associated time column called timestamp; there is no separate "upload" and "modified" date. So that timestamp, presumably, gets updated every time the file entity gets saved.

This makes sense from a certain standpoint because editing a file entity could involve updating the file itself.

I decided to take a crack at a custom module that would add a new "upload date" column to the file entity table. This may be completely wrong, and I haven't tested it, so do NOT try to use it on a production website until you're sure it works, but it might just give you what you're looking for.

In mymodule.install:

function mymodule_install() {
  // Add a column to the file table for your new creation date field.
  db_add_field('file_managed', 'upload_date', array(
    'type' => 'int',
    'unsigned' => TRUE,
    'not null' => TRUE,
    'default' => 0
  ));
  // Load all existing files and set their upload date to be equal to their current timestamp.
  $files = entity_load($file);
  foreach($files as $file) {
    $file->upload_date = $file->timestamp;
    file_save($file);
  }
}
// Drop the new field if the module is uninstalled.
function mymodule_uninstall() {
  db_drop_field('file_managed', 'upload_date');
}

In mymodule.module:

// Set the upload time field to the current time when the file is first saved
function mymodule_file_presave($file) {
  if(!isset($file->upload_date) || $file->upload_date == 0) {
    $file->created_date = time();
  }
}
// @TODO make the upload date field editable.

In mymodule.views.inc:

// Add a field handler for your new field.
function mymodule_views_data_alter(&$data) {
  $data['file']['upload_date'] = array(
    'title' => t("Upload date"),
    'help'  => t("The date the file was first uploaded."),
    'field' => array(
      'handler' => 'views_handler_field_date',
    ),
  );
}

Assuming that I didn't screw up, once the module is installed you'll need to add the upload date field to your view and use it for sorting.


How do I update the CKEditor text widget using CKEditor API

In the end I was able to solve this using a custom Ajax command:

In our custom module (called b47_custom_authors) we created a custom ajax command in src/Ajax/B47CustomAjax.php

/**
 * @file
 * Contains \Drupal\b47_custom_authors\Ajax\B47CustomAjax.
 */

namespace Drupal\b47_custom_authors\Ajax;

use Drupal\Core\Ajax\CommandInterface;

class B47CustomAjax implements CommandInterface
{

  /**
   * A CSS selector string.
   *
   * If the command is a response to a request from an #ajax form element then
   * this value can be NULL.
   *
   * @var string
   */
  protected $selector;

  /**
   * An optional list of arguments to pass to the method.
   *
   * @var array
   */
  protected $arguments;

  /**
   * Constructs an b47customajax object.
   *
   * @param string $selector
   *   A jQuery selector.
   * @param array $arguments
   *   An optional array of arguments to pass to the method.
   */
  public function __construct($selector, array $arguments = []) {
    $this->selector = $selector;
    $this->arguments = $arguments;
  }

  public function render(){
    return [
      'command' => 'b47customajax',
      'selector' => $this->selector,
      'args' => $this->arguments,
    ];
  }
}

The custom js (in js/b47customajax.js) is as follows:

Drupal.AjaxCommands.prototype.b47customajax = function (ajax, response) {

// response is an array with the keys
// response.command: the command called (b47customajax)
// response.selector: the selector to be used (NULL)
// response.args: the arguments to be passed as an array: 0: the ckeditor instance, 1: the text (data) to be passed

var ajaxckeditorinstance = response.args[0];
var ajaxckeditordata = response.args[1];
var editor;

var instance = CKEDITOR.instances[ajaxckeditorinstance];

if (instance) {
   // Trying to call setData method: https://ckeditor.com/docs/ckeditor4/latest/api/CKEDITOR_editor.html#method-setData
   editor = instance.setData( ajaxckeditordata , {
          callback: function() {
                      this.checkDirty(); // true
                  }
          });

};

};
In my ajax callback function I call my custom ajax via:

$response->addCommand(new \Drupal\b47_custom_authors\Ajax\B47CustomAjax('textarea'.$fieldid,[$fieldid, $texttobeinserted]));

The $fieldid is the id of the textarea, and @texttobeinserted is the full html of the text I want in ckeditor.

This now allows me to update the ckeditor based on the text dynamically via my AjaxResponse. The textfield is hidden by default and depending on the input in another field I fetch the text that needs to be placed in the textarea/ckeditor. The form field is then also displayed.

This now works.


What date format is required to import entityform submissions via feeds?

Checking the code is seems the validation is done by entity module entity_property_verify_data_type which checks for numeric values regarding a date field. So try

yyyymmdd
20170627

not working

valid date


How to include a field's suffix when using its Token?

AFAIK, field metadata isn't available in tokens. However, Rules to the rescue!

Create a rule set component which takes the field value as an integer parameter and two additional string parameters and provides a string value in return.
In your rule set, add a rule which checks to see if the value is one. If it is, set the provided string value with the integer value and the first string parameter.
Then, add another rule which does the same thing if the value is > 1.
Now you have a string which is pluralized!

Here is an export:

{ "rules_pluralize" : {
    "LABEL" : "Pluralize",
    "PLUGIN" : "rule set",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "integer" : { "label" : "Integer", "type" : "integer" },
      "string_one" : { "label" : "One", "type" : "text" },
      "string_many" : { "label" : "Many", "type" : "text" },
      "pluralized_version" : { "label" : "Pluralized version", "type" : "text", "parameter" : false }
    },
    "RULES" : [
      { "RULE" : {
          "IF" : [ { "data_is" : { "data" : [ "integer" ], "value" : "1" } } ],
          "DO" : [
            { "data_set" : {
                "data" : [ "pluralized-version" ],
                "value" : "[integer:value] [string-one:value]"
              }
            }
          ],
          "LABEL" : "Set string for one item."
        }
      },
      { "RULE" : {
          "IF" : [
            { "data_is" : { "data" : [ "integer" ], "op" : "\u003E", "value" : "1" } }
          ],
          "DO" : [
            { "data_set" : {
                "data" : [ "pluralized-version" ],
                "value" : "[integer:value] [string-many:value]"
              }
            }
          ],
          "LABEL" : "Set string for multiple items."
        }
      }
    ],
    "PROVIDES VARIABLES" : [ "pluralized_version" ]
  }
}


Fatal error: Call to undefined function ctools_include()  While implementing Drupal 6 Multistep Form Using Chaos Tools

As the Chaos tools suite module defines ctools_include() in ctools.module, the only reason I can think of what would explain the error is that you didn't install the module. The other reason could be that you are trying to access the function when the module is still not loaded; for example, if you call the function inside hook_boot(), then you would get that error.


Getting the node link in views-view-fields.html.twig

Add a "Path" field and include it in the view. It should be something like: {field.path.content} You can always format it :D


My solution was to modify the javascript directing traffic to the mobile video page so that it replaced the slashes with triple underscores.

urlNoProtocol = src.replace(/\//i, "___");

The validation in mobilevideo.routing.yml was updated to vguid: '^[-a-zA-Z0-9._?=]+'

Then in MobileVideoController.php the content() function was updated to reverse the replacement.

$url = preg_replace('/___/','/', $vguid);


How to embed Twitter  and E-mail links inside a webform?

There is a module for that, in fact there are many. Since a webform is a node, it makes the possibilities much greater. An example of a module that allows users to share your content in various ways is the Service links module.


How to show in a view the total number of paragraphs for a node?

I managed to achieve this doing the following:

Create a View to show Content of Type All. Add a page as well if you wish.
Format the style to be a Table.
Go to Advanced and turn on "Use aggregation".
Go to aggregation settings for the field "Content:Title" and set the aggregation type to "Count".
Change the label of this field to something like "Number of paragraphs in the node:".(*optional)
In Fields add field "Content:Title", aggregation type should be Group results together.
Add Filter Criteria "Hours (field_hours:target_id)", aggregation type should be Group results together, and set the operator to "is not empty(NOT NULL)".

This is how the Display settings should look at the end:

And here are the desired results in the preview:

I hope this helps.


Have you tried setting

$settings['file_public_base_url'] = 'http://sitename.local/sites/default/files';

In sites/default/settings.php?

I do this for all of my sites both in dev and production and haven't had any issues.

I realise that you may have solved the issue, but just so you know you can set the base url for your files through that setting :)


How do I add managed images to the Media Module browser stored locally through a remote URL?

First, a form is built. Then the elements in the form array are expanded during drupal_process_form(). The default value of each element is set during this stage. The file.module has a callback hook added during the set element value stage which other form elements do not have, '#file_value_callbacks`.

I simply added a textfield element to the upload form for the media browser and registered a callback. If there is an URL in the textfield, drupal_http_request() is used to pull the data / image and save it passing the file ID as the value of the upload widget element to finish processing the image.

It seems to work as expected. There are some gaping security holes which need to be cleaned up. Nonetheless, this implementation will greatly increase the efficiency of workflow for my next project.

Here is my solution:

/**
 * Implements hook_form_FORM_ID_alter()
 */

function helper_form_file_entity_add_upload_alter (&$form, &$form_state, $form_id) {
  // Keep the textfield clear if there is a file ID
  // We only have to upload the image once then who cares?
  if (!empty($form['upload'])){
    $form['upload']['#file_value_callbacks'][] = 'helper_file_value_callback';
    $form['url'] = array(
      '#type' => 'textfield',
      '#title' => 'Enter image URL',
    );
  }
}

function helper_file_value_callback (&$element, &$input, &$form_state) {
  global $user;

  // Make sure that there is a $url
  if (empty($input['fid']) && valid_url($url = $form_state['input']['url'])) {

    $upload_name = implode('_', $element['#parents']);
    $destination = $element['#upload_location'];
    $parsed_url = parse_url($url);
    $path = str_replace('///', '//', "$destination/") . drupal_basename($parsed_url['path']);

    // Make sure that there is a directory.
    if (isset($destination) && !file_prepare_directory($destination, FILE_CREATE_DIRECTORY)) {
      watchdog('file', 'The upload directory %directory for the file field !name could not be created or is not accessible. A newly uploaded file could not be saved in this directory as a consequence, and the upload was canceled.',
          array('%directory' => $destination, '!name' => $element['#field_name']));
      form_set_error($upload_name, t('The file could not be uploaded.'));
      return FALSE;
    }

    // Download file and make sure that return code is 200 or else abort!
    $result = drupal_http_request($url);
    if ($result->code != 200) {
      drupal_set_message(t('HTTP error @errorcode occurred when trying to fetch @remote.',
          array('@errorcode' => $result->code, '@remote' => $url)), 'error');
      return FALSE;
    }

    // Construct the $file object
    // file_save() adds the timestamp and filesize on save
    // file_unmanaged_save_data posts message on error
    if ($uri = file_unmanaged_save_data($result->data, $path, FILE_EXISTS_RENAME)){
      // Create a file object
      $file = new stdClass();
      $file->fid = NULL;
      $file->uri = $uri;
      $file->filename = trim(drupal_basename($parsed_url['path']));
      $file->filemime = file_get_mimetype($file->uri);
      $file->uid = $user->uid;
      $file->status = 0;

      if (file_save($file)){
        $input['fid'] = $file->fid;
      }
    }

  }
}


How do I highlight an element in a view result?

First check the thumbnail is passing your condition then simply just add a unique class to that field using the tpl file for that field.


Restrict menu item to certain roles in TB Mega Menu

A possible workaround solution would be to create another menu all together and give the block menu access to the role that you need and exclude this role from your original menu.


if i want to install Acquia DEV Desktop, do i need to un-install XAMPP first?

No, you can run them both at the same time by configuring different ports in Acquia Dev Desktop. Acquia Dev Desktop will also create its own hostname, so you'll access it differently. Eg, http://othersite:8080


serialize is better for small array, cuz unserialize will work faster. So if you work with huge data use json_encode &json_decode.
Comparison PHP Serialization vs JSON Encoding for an array  and your question already answered here on stackoverflow you can find more information about your question.


Yes, Drush 8 works with Drupal 6, 7 and -8.3. I just tested Drush 8.1.17 against a Drupal 7.58 site: worked a charm to clear cache, generate a login URL and download a module.

This is the compatibility table from their site for reference:

  I mean are there different commands to clear the cache for a Drupal 7.x site?

Yes, it was cache-clear, or cc for short in Drupal 7, e.g.

drush cc all


How do I get the path alias without the language code?

Since you just need the last part of the path, you can use the following code in a hook_preprocess_html() implementation.

$current_path = \Drupal::service('path.current')->getPath();
$alias = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);
if (basename($alias) == 'the-new-webpage.html') {
  // Your code here
}


Remove core and contrib. modules css files

I think the function should be named MYTHEME_preprocess_page.  Though a more common method is to add

stylesheets[all][] = nice_menus.css

to your theme's .info file.  nice_menus.css will be replaced by the one provided by your theme, or suppressed entirely if your theme doesn't contain this file.


As beebee said on comments :

$rows should be indexed like this :

foreach ($result as $res){

    $rows [$res -> entity_id] = array(

and the condition of the publishing function :

function publishing_submit($form, &$form_state){

    $check = array_filter($form_state['values']['table']);
    $sql = db_update('field_data_field_state');
    $sql->fields(array('field_state_value'=> 'Published'));
    $sql->condition('entity_id', $check, 'IN');
    $sql->execute();
}

Thanx beebee


You can achieve this using search_excerpt function.

for eg:

in your views tpl file add the following code

 <?php foreach ($rows as $id => $row):

      $keys = $_GET['body_value'];
      $row = search_excerpt($keys, $row);
 ?>

it will highlight the searched word, see the screenshot below


Views Search Returning Unexpected Results

Of course. Since I have 10 sub-categories and I'm ranking them by 'key' number 10 is displaying AFTER number 1 and then 2, 3, 4, 5, 6, 7, 8, 9. That's why it's returning the incorrect results. 10 should be named something else like 99 so it comes after 9.


hook_validate() returns errors, but the form has lost all the user's submitted values

There is nothing particular that needs to be done, to avoid to overwrite the value entered by the user, when a validation handler returns an error.

For example, the following form, is build from the code shown below (system_ip_blocking_form()):

function system_ip_blocking_form($form, $form_state, $default_ip) {
  $form['ip'] = array(
    '#title' => t('IP address'),
    '#type' => 'textfield',
    '#size' => 48,
    '#maxlength' => 40,
    '#default_value' => $default_ip,
    '#description' => t('Enter a valid IP address.'),
  );
  $form['actions'] = array('#type' => 'actions');
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Add'),
  );
  $form['#submit'][] = 'system_ip_blocking_form_submit';
  $form['#validate'][] = 'system_ip_blocking_form_validate';
  return $form;
}

Its validation handler is the following one (system_ip_blocking_form_validate()):

function system_ip_blocking_form_validate($form, &$form_state) {
  $ip = trim($form_state['values']['ip']);
  if (db_query("SELECT * FROM {blocked_ips} WHERE ip = :ip", array(':ip' => $ip))->fetchField()) {
    form_set_error('ip', t('This IP address is already blocked.'));
  }
  elseif ($ip == ip_address()) {
    form_set_error('ip', t('You may not block your own IP address.'));
  }
  elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_RES_RANGE) == FALSE) {
    form_set_error('ip', t('Enter a valid IP address.'));
  }
}

When I enter a value for which the validation handler returns an error, the value I enter is not modified, as you can see from the following screenshots.

This is what happens on Drupal 6 too. The only case where a field value is cleared is when the form validation handler reports an error for a password form field; in that case the password field doesn't contain the previously entered password, which would be difficult to edit as it is shown as "•••••."

There is nothing that needs to be set; by default Drupal will not change the content of a field when a validation handler reports an error for that field. As far as I know, the value of a field could be changed by its "#after_build" callback, that is invoked after the field is built, and that is described in form_builder() with the following sentence:

  The "#after_build" flag allows any piece of a form to be altered after normal input parsing has been completed.


Recursive Drush make, working with different git branches

This is a great question! I maintain both Aegir and Drush Make, but I'm not certain that I have a really good answer for you.

I think that you're suggestion in (1) is probably the best bet at
the moment. It has the virtue of already working, as you've
mentioned. The issue with accidentally merging these [branch]
attributes is still valid though. The solution though, lies not in
Drush Make, but in Git!

Check out this article. It describes using Git attributes,
along with a custom (null) Git merge driver. To summarize, each
developer would have to run the following:

git config --global merge.ours.driver true

This basically means that when an item is flagged to use the
'ours' merge driver, it'll just call /bin/true, hence my earlier
reference to it being a null operation.

But, how do you flag your makefiles to use this driver? That's where
Git attributes come into play. Create a .gitattributes file at the root of your repo (i.e., along side .gitignore). Then add the
following line:

build-SITENAME.make merge=ours

You'll probably want to do the same for your feature repos as well.
As for solutions leveraging Drush Make, I don't know that there's a
solid solution.

A few years back, I experimented with using overrides trying to do
something similar, as described in the Drush Make
documentation. The basic idea is that you can change (override)
attributes from included makefiles.

However, in the case of recursive makefiles, they are built
separately, instead of being merged into the parent makefile prior
to build. As a result, there's no opportunity to override their
attributes. This may have changed in the time since I tested it, but
I think the underlying mechanics remain largely the same, and so
it's unlikely to work.

Setting a default in a parent makefile would be a nice way to
accomplish something like this too. I haven't tested this, but
again, I'm pretty sure the default wouldn't apply to the recursively
built makefile.

Instead, an option would be to build your parent makefile without
recursion, but rather including the feature makefiles directly. You
can now include makefiles directly from within a Git repo
(using the new YAML syntax):

includes:
  # A file from a git repository.
  makefile: "example_dir/example.make"
  download:
    type: "git"
    url: "git@github.com:organisation/repository.git"
    branch: "master"

You'd either want to call drush make with the --no-recursion
option, or specify it in your makefiles:

--no-recursion                   Do not recurse into the makefiles of any
                                 downloaded projects; you can also set
                                 [do_recursion] = 0 on a
                                 per-project basis in the makefile.

I'm sure there are other options available, but those are the ones that I think would least impact your existing workflows. I'd be very curious to see other suggestions.

There is a feature request to allow the use of variables in .make files, which might address such a use-case more directly, if it were implemented. Perhaps we could look for such variables in options passed on the command line, or in environment variables.

That said, in the long run, I believe that Drush Make will be supplanted entirely by Composer, so it might be more fruitful to explore in that direction, if the suggestions above don't work out.


For a short tutorial about the "aggregation" features of the Views module, refer to Using aggregation in Views. As an alternative, have a look at the (free) set of 30 video tutorials about the Views module. Specific to "Aggregation", you may want to look at these episodes (quotes are from the linked pages):

The aggregation setting.

  ... makes Views return not one row per item in the database, but one row per aggregation group. Perhaps more importantly, it also makes it possible to count the number of items baked into each row, or sum them up, or calculate their average, or count the number of unique items, or…

Aggregation and relationships.

  ... shows how to use the aggregation setting in Views in combination with relationships.

Aggregation edge cases.

  ... shows some of the more rare use cases of aggregations in Views:

  Using aggregation on filtering
  Using aggregation on sorting
  Using aggregation on contextual filters (which is currently broken)
  NOT aggregation on relationships (since aggregation doesn't apply to this handler)
  Using aggregation on multiple-value fields


How to add month and year dropdown to calendar month view

The Date module has a subproject called Date Views. Once that
module is enabled, you can add exposed filters to your date fields. Setting the filter option Date selection form element to select will provide the dropdown selection widget for your date.

Finally, under the Advanced > Exposed form > Exposed form style > Settings link there's an Autosubmit option that will submit the filter form upon date change.


I would use Smart IP module.

  Smart IP identify visitor's geographical location (longitude/latitude), country, region, city and postal code based on the IP address of the user. These information will be stored in session variable ($_SESSION) with array key 'smart_ip', Drupal $user->data object with array key 'geoip_location' in Drupal 6 and 7 and user data service using the parameters 'smart_ip' as module and 'geoip_location' as name in Drupal 8 of the user but optionally it can be disabled (by role) at Smart IP settings page. Other modules can use the function smart_ip_get_location($ip_address) in Drupal 6 and 7 and \Drupal\smart_ip\SmartIp::query($ipAddress) in Drupal 8 that returns an array containing the visitor's ISO 3166 2-character country code, longitude, latitude, region (FIPS), city and postal code. It provides a feature for you to perform your own IP lookup and admin spoofing of an arbitrary IP for testing purposes.

You can get the user location in different ways using this module.

<?php
$smart_ip_session = smart_ip_session_get('smart_ip');
if ($smart_ip_session['location']['country_code'] == 'PH') {
  drupal_set_message(t('You are in the Philippines.'), 'status');
}
?>

Or

<?php
if ($_SESSION['smart_ip']['location']['country_code'] == 'PH') {
  drupal_set_message(t('You are in the Philippines.'), 'status');
}
?>

Now, in the Theme_preprocess_html function of your theme in the template.php file, use the above codes to check if the user is in a right place. Create template.php file in your theme and use this function:

function themeName_preprocess_html(&$variables){
{
      $code = $_SESSION['smart_ip']['location']['country_code'];
      $currentLocation = arg(1); //it returns the /de or any language
      if(strtolower($code) != strtolower($currentLocation))
           drupal_goto("www.example.com/".strtolower($code));

}

If the default provides the language code, it works well but if not, you need to handle that case. For example if the default language is English and the /en is not coming after example.com, then you need to check if arg(1) == 'en'. It is easy to do.

update

To get the user language use this code

global $language;
print $language->language;

So your code will be

function themeName_preprocess_html(&$variables){
{
      global $language;
      $code = $_SESSION['smart_ip']['location']['country_code'];
      $currentLocation = $language->language;;
      if(strtolower($code) != strtolower($currentLocation))
           drupal_goto("www.example.com/".strtolower($code));

}


How do I get clean output (without menus, header, footer, etc.) in Drupal?

Just print it from your page callback rather than return it. Drupal will only invoke the theme wrappers for the html/page when you return something from your callback.

function MYMODULE_some_page_callback() {
  print theme('my_theme', array('html' => $html);
}

The other method is to set an explicit delivery callback for your menu item, to be used in place of the standard drupal_deliver_html_page() method. See the hook_menu() docs for more details.


Content display based on user preferences

You can accomplish the first by enabling PHP in modules, and making a check in the block configuration / Pages - using php you can check each block for the appropriate $user field and whether or not its set for that particular language.  You could also create a module to build each block programmatically, and then show/hide depending on the field value.

The second can be done with something like this:

Content Type
  * create a hidden field called language

using Rules set an event (After Saving New Content - ), event - set data value - node->language equal to user->language. This will assign a language to each node created
create a view with the relevant fields/information you want presented, and filter on current user:language - in this way each user who sees this view will only see the entries that match their own language settings


How to access Drupal variables in a PHP included file?

You can access the $variables array in your included file like this:

 // assuming you are viewing a node
 $node = $variables['node'];
 // the node is an object, so to display the url do
 echo drupal_get_path_alias('node/'.$node->nid);

To see what kind of data the $variables array contains do something like:

 echo '<pre>';
 print_r($variables);
 echo '</pre>';


Why field tables are not getting removed when I remove the field?

I feel like having these many unused tables in database might impact the performance

That's very unlikely, unless the extra disk space used will somehow affect your server's performance.

Deleted fields and data are cleared up on cron runs (by field_purge_batch()), so running cron a few times will probably get rid of them. Exactly how many runs it takes will depend on the number of fields, amount of data in each, etc.

I'd advise against removing it manually unless you're quite familiar with the internals of the field API, and understand the implications.


CKEditor4: the image disappear when I switch from Rich text View to source view

You need to make it clear that images are allowed content.

You may safely declare that images, only certain image attributes, all image styles, and all image classes are allowed content. You do that with the following line of JavaScript:

config.extraAllowedContent = 'img[!src,alt,title,width,height,style](*){*}';

To set these variables, navigate to Configuration → Content authoring → CKEditor and then press edit for the profile you want to configure. Expand Advanced options, and type the JavaScript directly into the textfield Custom JavaScript configuration as shown in the screen shot below (disregard the first line unless you also want to set custom format_tags);

PS: If you Google this, you'll often see the following JavaScript suggested to "fix" the disappering image problem:

config.allowedContent = true;

Yes, it will fix the problem of images disappeearing when you toggle between rich text and source. But it will also make all sorts of content allowed - which is a gaping security hole in your site if you allow untrusted users to create and edit content.  Don't use this quick "fix". Use the solution that uses the extraAllowedContent directive to spell out what shall be allowed (and allow only safe content).


Search api solr create a custom search link

f[0] param doesn't work directly. To allow ApacheSolr to filter results based on custom fields you will need to define them as facet (checkout FacetAPI module) or you can implement hook_apachesolr_query_alter and add your own filters in it.


I think the easiest solution will be to use db_query, where you can write raw SQL, like this:

$query = db_query('SELECT publication_year FROM books etc.');


Is there configuration I'm not seeing to adjust the submission edit screen

No, there is no config screen to customize this "edit" screen.

  the client doesn't want to see all of the fields and
  submission-related information (UUID, URI, etc.)

You can use hook_form_alter() in a custom module and remove the submission information section.

  and wants to see all of the form submission fields filled out here as
  well.

They should be already be filled out, unless the user left them empty. Make these fields required if they should be filled out.

  I also see there's a Webform Views Integration module, but that
  looks more like what I'd want if I wanted to put a view within a form.

In correct, this allows you to display the webform results in a View. This is exactly what you need, well if you want to make an alternate page that has that "edit" info.

Also, you could alter the Webform's edit route so it uses your Webform View instead, but you would lose the edit ability tho. Since the View just displays what was entered and is not a form.


Performance implications of many user roles

I don't have any hard stats but based on several years of experience and knowing how Drupal works I would be extremely surprised if adding another user role made any appreciable difference at the page request level. The only difference will be when a user has multiple roles, but the amount of extra data required per role is tiny.

I have profiled page loads for all sorts of different site setups and never seen an issue relating to the number of user roles.

Having said that, adding extra roles can make administration more complicated, so you won't want to add new ones without a good reason. If you were to create a hundred user roles the main permissions panel would be unusable but I would be willing to bet that the effect on normal page loads would be negligible.


if you are using Entity API, you can take a look to this article http://www.trellon.com/content/blog/creating-own-entities-entity-api and to the example_task module:

The process works like this:

  // Your entity view path
  $task_uri = 'task/%example_task';
  $task_uri_argument_position = 1;

  $items[$task_uri] = array(
    'title callback' => 'entity_label',
    'title arguments' => array('example_task', $task_uri_argument_position),
    'page callback' => 'example_task_view',
    'page arguments' => array($task_uri_argument_position),
    'access callback' => 'entity_access',
    'access arguments' => array('view', 'example_task', $task_uri_argument_position),
    'file' => 'example_task.pages.inc',
  );

/**
 * Task view callback.
 */
function example_task_view($task) {
  drupal_set_title(entity_label('example_task', $task));
  return entity_view('example_task', array(entity_id('example_task', $task) => $task), 'full');
}

This will invoke to the function in entity/includes/entity.controller.inc folder of Entity API module:

  /**
   * Implements EntityAPIControllerInterface.
   */
  public function view($entities, $view_mode = 'full', $langcode = NULL, $page = NULL) {
    // For Field API and entity_prepare_view, the entities have to be keyed by
    // (numeric) id.
    $entities = entity_key_array_by_property($entities, $this->idKey);
    if (!empty($this->entityInfo['fieldable'])) {
      field_attach_prepare_view($this->entityType, $entities, $view_mode);
    }
    entity_prepare_view($this->entityType, $entities);
    $langcode = isset($langcode) ? $langcode : $GLOBALS['language_content']->language;

    $view = array();
    foreach ($entities as $entity) {
      $build = entity_build_content($this->entityType, $entity, $view_mode, $langcode);
      $build += array(
        // If the entity type provides an implementation, use this instead the
        // generic one.
        // @see template_preprocess_entity()
        '#theme' => 'entity',
        '#entity_type' => $this->entityType,
        '#entity' => $entity,
        '#view_mode' => $view_mode,
        '#language' => $langcode,
        '#page' => $page,
      );
      // Allow modules to modify the structured entity.
      drupal_alter(array($this->entityType . '_view', 'entity_view'), $build, $this->entityType);
      $key = isset($entity->{$this->idKey}) ? $entity->{$this->idKey} : NULL;
      $view[$this->entityType][$key] = $build;
    }
    return $view;
  }
}

As you can see the content is finally rendered through a render element using "Entity.tpl.php"

A way to add your customizations to the view in order to render elements which are not fields may be extending from "EntityAPIController" and writing builContent function:

class ExampleTaskController extends EntityAPIController {

      public function buildContent($entity, $view_mode = 'full', $langcode = NULL, $content = array()) {
        $wrapper = entity_metadata_wrapper('example_task', $entity);
        $content['author'] = array('#markup' => t('Created by: !author', array('!author' => $wrapper->uid->name->value(array('sanitize' => TRUE)))));

        // Make Description and Status themed like default fields.
        $content['description'] = array(
          '#theme' => 'field',
          '#weight' => 0,
          '#title' =>t('Description'),
          '#access' => TRUE,
          '#label_display' => 'above',
          '#view_mode' => 'full',
          '#language' => LANGUAGE_NONE,
          '#field_name' => 'field_fake_description',
          '#field_type' => 'text',
          '#entity_type' => 'example_task',
          '#bundle' => $entity->type,
          '#items' => array(array('value' => $entity->description)),
          '#formatter' => 'text_default',
          0 => array('#markup' => check_plain($entity->description))
        );

        return parent::buildContent($entity, $view_mode, $langcode, $content);
      }
    }


As far as I know the only way would be to disable permissions for viewing or editing the profiles for specific user roles. Those roles won't be able to see them.

There are a few "things" that can be disabled (without deleting them) in Drupal - Views and Panels are some of them.


Why ConfigFormBase does not goes through custom construct() when using managed_file?

The difference could be that managed_file is using Ajax which is caching the form object.
If you want to have this property cached you would need to declare it as protected property:
class CustomForm extends ConfigFormBase {

  protected $config;

Normally $this->config() is the method FormBase::config as the main entry point to the config API, not a property you populate when constructing the form object. Using the same name could be quite confusing and it's also recommended to use the mentioned method to retrieve the config and declare the config in ConfigFormBase::getEditableConfigNames() if you intend to save it.


Adding Fivestar rating each item in a view containing most recent stories?

Adding the Fivestar widget to your views is pretty simple:

Add the relationship Node: Vote Results
Add the field Vote Results: Value
Choose how you wish to display the widget by changing Appearance: to either Fivestar Stars (clickable, with text) or Fivestar Stars (clickable, no text)
Click "Update" and save your view


Why doesn't the function taxonomy_term_search exists?

Long story short, it does not exist because either no one wrote it, or maintainers found it not suited for inclusion in taxonomy.module for whatever reasons. For most purposes, taxonomy_get_term_by_name is enough. When it's not, there are various search solutions in separate, search oriented modules.

If you think you can write it, and make it good, please do so, and then post entry in issue queue with appropriate patch file.


When reimplementing Drupal.tableDrag.prototype.dropRow(), how do I access classes of would-be parent?

Get a reference to some parent DOM element ... the jquery parents() or parent function(s) comes to mind. Then use hasClass on those parents as needed.

some parent would be something like the following based on your example:

var parents = $(self.rowObject.element).parents(/* a selector to limit the type of parent, td, tr, whatever */);

EDIT:

dragged rows get a class of like .dragged-previous. The file tabledrag.js doesnt care about the current row, nor about IDs of anything during drag -- its just doing a DOM swap of rows and inserting the dragged row before another row; and assigning a Drupal weight to the hidden weight column. So cant you use like jquery prev() function to get the immediate previous element:

var parent = $('#menu-overview tr.drag-previous').prev();

I'm taking these values from a Main Menu tabledrag example of a vanilla D7 site:


Update existing content using migrate module

This post about Unknown column 'destid1' in 'field list' helped me when I had the same problem.

In particular, drop the migrate_map_* and migrate_message_* tables since they may have been created incorrectly beforehand.


How to get the id of a group when using the Group module?

I would just start with creating a view (using Views) of all "Group memberships", and include all available colums of that specific base table. It should include things like "user id" and "group id".

If you then add a contextual filter to limit it to some selected user id, you'll get 1 views result (row) for each group that the selected user is member of, or is invited for, revoked from, etc (membership status for each group is one of the available columns to include in your view). For each group you'll have its group id available also, so if needed you can add a relationship to the group itself to have access to additional data about the group itself (eg: the group title, or any of its custom fields you added).

After you have such view created, you have a prototype of anything else you want to do with that, e.g use whatever you want in your custom module to invoke the Group's API functions.

PS: refer to my answer to "How to add a column to the list of group members or create a Views equivalent of it?" for getting started with creating such view (even though it's for D7, for D8 you can use a similar one).


AJAX append content via link on existing page

you need to add the nojs uri part in your menu item like:

$items['buy-animal-licence/animal/%ctools_js']

also, to make all more clear - your type argument in the callback should default to NULL

function ajax_link_response($type = NULL) {


How can I programatically prevent users from saving the same entity twice in a row?

I find this to be a UX issue. 1 thing I would recommend is to allow certain high-traffic forms on your site to show a throbbing/progress/submit indicator upon click.

I believe you can do this using the Form API by overridding the default submit element on your site forms as needed. This is explained some in this related SO post with links to documentation:
https://stackoverflow.com/questions/6100970/how-do-you-remove-the-throbber-from-drupal-7-ajax-link


Try Menu Editor module

  Menu Editor enhances the menu editing form with inline text fields for
  title, path and description, and provides placeholders for new items.


Manage Form Display - not saving configuration

How many fields are we talking? Is it hundreds?

I don't believe there is a maximum within Drupal but your server might have a limit. Within the php.ini config file on your web server you should see "max_input_vars"

You could try increasing that and restarting your apache/nginx server to see if that resolves the issue


Delete nodes if URL is called via Wget Command

Services module is great for this job. Here are the steps how you can make it work:

Download Services, Chaos tools and Libraries. Enable the REST Server module (shipped with Services), it will make you enable all dependencies as well.
Go to Structure » Services, add a new endpoint.
Choose a machine-readable name, e.g.: node_remove.
Select REST as a server.
Define a path to your endpoint, e.g.: node-remove.
Enable debug mode, it's handy while you are experimenting, Services will write useful information to the log.
Enable session authentication, this will ensure security.
After saving your endpoint, edit its resources.
Enable the delete operation in the node group and the login operation in the user group.
Go to the Server tab, select the response formatters and request parsing options that you want.

Your endpoint is ready to use. First you need to post a username and password to http://example.com/node-remove/user/login. (It's recommended to create a user with a strong password and permissions for only deleting nodes.) You will get a session ID (among others) in the response. Then you need to perform a DELETE request to http://example.com/node-remove/node/{nid}. You can write a script for these actions and execute that as a cronjob.


How to allow OG admins to view private groups?

After spending some time in the debugger, I would say this is a flaw in OG.

Users allowed to administer OG permissions should be granted access to view any group.
Solution: patched og_node_access() in og.module:490

patch format:

--- og.module
+++ og.module
@@ -490,6 +490,11 @@ function og_og_default_roles() {
 function og_node_access($node, $op, $account) {
   $type = is_string($node) ? $node : (is_array($node) ? $node['type'] : $node->type);

+  //   Grant access to view any OG group content if the user is allowed to administer OG permissions
+  if ($op == 'view' && user_access('administer group', $account)) {
+    return NODE_ACCESS_ALLOW;
+  }
+
   if ($op == 'create' && og_is_group_content_type('node', $type)) {
     // Save some legwork if the user has the core permission and strict node
     // access is not set.

The interesting bit is just this:

  //   Grant access to view any OG group content if the user is allowed to administer OG permissions
  if ($op == 'view' && user_access('administer group', $account)) {
    return NODE_ACCESS_ALLOW;
  }

The above solved the issue with OG-Admins not being able to view private groups they did not belong to. There was another issue involving views. When for example creating a list of all groups with views, the same problem occurs. In this case, creating a separate view for admins and effectively disabling node access checks for it:

  In the Advanced tab of Views UI under Query settings, select the Disable SQL rewriting checkbox

Various approaches detailed here: https://drupal.org/node/677644


How to send uploaded file as a link in entityform submission

How are you sending the mail?

You can try using https://www.drupal.org/project/mimemail and just insert the image in your mail


Can't restore profile-installed site after D7.12 core upgrade

Did you remember to run update.php?

Also, Drupal 7.11 and 7.12 are both security updates. 7.12 includes bug fixes, while 7.11 only addresses the security problems. You might try 7.11 and see how it goes.

Also 2: Here's an issue thread about it.


Just create them as blocks and place them on a static page together in any region you wish. (Keep it simple)


I'm not aware of any module that would provide this particular functionality. First of all, I would reduce the risk for confusion. An example is: Store a CID in the users $_SESSION, and theme the comment form with "You have X comments awaiting moderation."

You could also add a custom validation function to the comment form with a hook_form_ID_alter, and simply deny comments that fall within your stated condition, "Same body text within 5 minutes from same session", or so.

I would definitely focus on the first one though. No matter what type of validation criteria you add, there will always be edge cases where there is a good reason for posting something that your will then reject. This will of-course be a tradeoff between how large a risk you are willing to take rejecting valid input, and the effor required to "un-confuse" users.


Why is Drupal with redis slower than mariadb?

This topic should probably be closed, as the Drupal Redis module maintainer, I am taking over the issue in the module official issue tracker, specific questions are pending there, and a few micro-optimizations have already been done since this question was opened.

For everyone that would help us or need support, please consider participating to https://www.drupal.org/node/2550275 - this would be great help.

Thanks in advance to everyone that will give us a few minutes to solve this and improve the module.


AFAIK the checkout page is dynamically generated by Ubercart, you cannot create a node for it. You can theme the dynamically generated page or alter it through custom modules if needed, see several very helpful Ubercart tutorials here: https://drupal.org/project/ubercart


Javascript works inline in webform but not as standalone

I think you can use default druypal behaviors

  Drupal.behaviors.mywebform = {
      attach: function (context, settings) {
    var ac_config = {
            source: "/example/sites/all/themes/skeletontheme/js/democities.php",
            select: function(event, ui){
                $("#edit-submitted-info-company").val(ui.item.company);
                            $("#edit-submitted-info-address").val(ui.item.address);
                            $("#edit-submitted-info-address2").val(ui.item.address2);
                            $("#edit-submitted-info-city").val(ui.item.city);
                $("#edit-submitted-info-state").val(ui.item.state);
                $("#edit-submitted-info-zip").val(ui.item.zip);
            },
            minLength:1
        };
        $("#edit-submitted-info-company").autocomplete(ac_config);
        }
    }

Hope it will help!


Is it possible to redirect anonymous users from /admin to /user?

Sure, you can install a module like Redirect 403 to User Login:

Redirect the HTTP 403 error page to the Drupal /user/login page with an optional message that reads:

"Access denied! You must login to view this page."

Also, the desired page is appended in the url query string so that, once login is successful, the user is taken directly where they were originally trying to go.


How to get changes in database done by someone else?

Unlike code Database changes cannot be synced easily.

Try using Features Module This module exports your database settings to code so that they can be added to Version Control took like Git.

Tip : Create one feature for every independent functionality, so that it will be easy to manage. There are other supporting module for Features, which can reduce your efforts.


Creating a content type that merges fields with its assigned area within the body

I think it sounds like you want to write a node template. http://api.drupal.org/api/drupal/modules%21node%21node.tpl.php/7

Basically you are going to create a template file called node--content-type-name.tpl.php and in that template you have access to the $node object which contains fields. Then write your html and use the values from $node.


Add contextual filter on term id
select Provide default value
select type content id from url
also change your path to [your_path]/%


How to show book information in search result page

Finally managed it using search-result.tpl.php file which copied in theme folder.

 $url = $variables['result']['fields']['url'];

this variable gives search result urls from which i extracted book name and based in book name i printed book id.
@Anil, thanks for the help which guide me at right direction and got to know many more.


How do I create a rule to run during every cron run?

Rules has a specific "React on event" under system -> "cron maintenance tasks performed". If your using the rules modules, that will trigger your rule on every cron run.

Also, if your building a custom module, and you need to call a function on every cron run, you can use hook_cron to add a function to the cron tasks as well.


You can't access Protected members directly.

you'll need to extend the class that represents that object to provide getter methods for the protected properties.


The Automatic Node Titles module does that.


How to track mailchimp signup form location

I'm sure there's a simple answer to the above question, but in the end I took a different approach described here: Create custom signup block with mailchimp module?

Because I'm using hook_form_submit to control processing once the form is submitted, I can add the form location (using request_path()) to the merge variables that are passed back to mailchimp. That way, the form is the same on ever page that it appears, but the location is passed back to mailchimp as part of the sign-up process.


I found the error in the second module: It was because the opening <?php tag had a tab before it.

I fixed the second module, too. I don't know which produced the empty space, but I created for every file I used a new file and pasted my code into, renamed the module and enabled it. Everything now works.


webform submitted by the user the email that is sent is wrapped after around 75 characters

DefaultMailSystem::format uses drupal_wrap_mail() to wrap the body text on sending. There is no option to send unwrapped text.


Multi Axes Voting using Fiverstar, Views, Reference

You can add as many vote fields (using Rate or Fivestar) as you want to your Reviews, one vote for each criteria you want to make available.
Your Reviews can be a new Content-Type (then you would use a Relationship in the Business View) or you can use Comments (of Business) for this propose. Both Content-Type and Comments are customizable: you can add fields to them.

My first choice would be to add n Fivestar rating fields to Business's Comments. You can do that in Business Content-Type Edition, in the "Comment Fields" tab.

But if you want each user to make only one review and have more control/customizations, then a new Content-Type for Reviews can make your life easier.


When using rules to set an entity reference, do I use node or node:nid?

When setting an entity reference with rules, there is no need to specify the nid field. setting the value to the node itself will work.


Problem with Facebook Feed: Warning: file_get_contents(): https:// wrapper is disabled

Put this in your settings.php:

ini_set('allow_url_fopen' , 1);

If that solves the issue you will want to hard code that into your php.ini.


hook_query_alter() is executed for every dynamic query run by Drupal. If you want to execute the hook for queries having a specific tag, you should implement hook_query_TAG_alter().

The code for getting the alias for the main table is similar to the following one.

function mymodule_get_main_table_alias($tables) {
  $alias = '';

  foreach ($tables as $id => $info) {
    // If 'join type' is not set, then it's the main table.a
    if (empty($info['join type'])) {
      $alias = $id;
    }
  }

  return $alias;
}

I would write then the hook code as follows.

function mymodule_query_term_access_alter(QueryAlterableInterface $query) {
  global $user;
  if ($user->uid > 1) {
    if (strstr(current_path(), 'admin/structure/taxonomy')) {
      if ($alias = mymodule_get_main_table_alias($query->getTables())) {
        $alias = $query->leftJoin('term_permissions_user', 'tpu', "$alias.tid = %alias.tid");
        $query->condition(db_or()
          ->isNullcondition("$alias.uid");
          ->condition("$alias.uid", $user->uid, '=')
        );
      }
    }
  }
}

Notice that:

In $query->leftJoin(), %alias is replaced with the alias the query is using for the table  being joined. As you are altering an existing query, you cannot know if the alias you chose is already used.
The result of $query->leftJoin() is the alias being used for the joined table. It is better not to hard core that alias, for the reason said in the previous point.
To check if a field is NULL, you should not use QueryConditionInterface::condition(); as the documentation says, you should use QueryConditionInterface::isNull().
There is not need to create a QueryCondition object with db_and(); the conditions used to a query with $query->condition() are ANDed with each other.


The marked answer is correct here, but I can't comment on it. There's a couple "bugs" in it. The following changes were made to make it work with the object/array that gets exported when using field_group_load_field_group()

Specifically, I changed this line:

'format' => array('type' => 'fieldset'),

To:

'format' => array('type' => $group['format_type']),

And:

foreach ($group['fields'] as $field_name) {

To:

foreach ($group['children'] as $field_name) {

The final code:

/**
 * Create a field group.
 *
 * The field_group module does not come with an API that can be used by other
 * modules. This method fakes a Drupal new group form submission to create the
 * new group.
 *
 * @param  array  $group
 */
function _field_group_create_group(array $group) {

  drupal_load('module', 'field_group');
  module_load_include('inc', 'field_group', 'field_group.field_ui');

  $defaults = array(
    'entity_type' => 'node',
    'mode' => 'form',
    'parent' => '',
    // TODO: default to heaviest weight
    'weight' => '',
    'format' => array('type' => $group['format_type']),
    'fields' => array()
  );

  $group = $group + $defaults;

  $form = array(
    '#entity_type' => $group['entity_type'],
    '#bundle' => $group['bundle'],
    '#view_mode' => $group['mode'],
    '#groups' => array()
  );

  $form_state = array(
    'values' =>  array(
      'fields' => array(
        '_add_new_group' => array(
          'group_name' => $group['group_name'],
          'label' => $group['label'],
          'parent' => $group['parent'],
          'parent_wrapper' => array('hidden_name' => '_add_new_group'),
          'weight' => $group['weight'],
          'format' => $group['format'],
        )
      )
    )
  );

  foreach ($group['children'] as $field_name) {
    $form_state['values']['fields'][$field_name] = array(
      'parent' => '_add_new_group',
    );
  }

  field_group_field_overview_submit($form, $form_state);
}


Allow the user to permit per role to view of any/all profile2 fields

Instead you can try Profile2 Privacy module, It will do your requirement exactly.

  This module extends Profile 2 by allowing administrators to create
  privacy levels as predefined groups or sets of profile fields on a per
  role basis. Users can then select from among the privacy levels to
  apply access control to their profile.

  For each role, select the profile fields that are visible to users in
  that role, when the profile owner has selected this role. For example,
  if you created an “authenticated users only” privacy level, you might
  set the anonymous role to view first and last name fields, the
  authenticated role to see first name, last name and contact fields
  and an admin role to see all fields.


I've added a title metatag to the default Content view. Then went to translation page where I found the string to translate under Displays-> Page Display Settings-> Display Extenders-> Test Metatags


Modules to set up audio podcast functionality

Take a look at FileField Podcaster

  Using Views2, this module delivers a way to podcast with nodes that
  have CCK FileFields included as RSS file enclosures. It provides a
  podcast-compatible (as determined by Apple) RSS feed, using node
  variables, getID3, filefield in cck, and filefield meta data to
  generate the RSS tags


How do I upgrade drush from 3 to the latest release?

The short answer is on the Drush project page under the heading Install/Update - Unix/OSX:

pear upgrade drush/drush

I first had to install PEAR, but that should not be an issue.


Add placeholder or default value to captcha text field

you can use this module too:

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

it worked for me very nice


Altering all urls to include extra information

So you're looking for a way to modify a link URL as it is being written? I looked into this recently and was surprised at how much hunting was required.

I went with hook_url_outbound_alter( &$path, &$options, $original_path ), which allows you to alter link URLs that are being written by the Drupal URL system.

There's also hook_url_inbound_alter( &$path, $original_path, $path_language ), which might be better as it includes the path's specific langauge - it depends on where you want the alteration to take place. I personally find hook_url_outbound_alter() reliable and simple to work with - it changes all appropriate URLs as they are written, and using $options you can reliably add and edit query strings (...?query=string&foo=bar) and hash frangments (...#someId).

Modify $path and it'll update the actual path that gets written into the URL href. Of course, this runs on all links, so you'll want to start by checking that it's a link you want to modify.

It's executed before aliasing, so it'll be based on the Drupal defaults. To give two very simplistic examples, if you want to modify only taxonomy paths:

function some_module_url_outbound_alter( &$path, &$options, $original_path ) {
  if(strpos($original_path, 'taxonomy/term') === 0) {
    // do stuff
  }
}

And/or if you only want it to run on particular pages, e.g. node edit pages:

function some_module_url_outbound_alter( &$path, &$options, $original_path ) {
  $current_path = explode("/", current_path() );
  if (count($current_path) >= 3 && $current_path[0] == "node" && $current_path[2] == "edit") {
    // do stuff
  }
}


How can I substitute field in hook_query_alter?

SelectQuery::getFields() returns by reference, so something like this should do it:

$fields =& $query->getFields();
$found_index = FALSE;
foreach ($fields as $key => $val) {
  // Check what's in the field, note the index if it matches the one to remove
}

if ($found_index !== FALSE) {
  unset($fields[$found_index];
}


Image field upload shows a broken preview until I reload the page

make sure the "image style" of your image field exists. for example to make sure about our "Article" content type, we check the path below:

  http://yoursite.com/admin/structure/types/manage/article/fields/field_image

find your "image style" name and then go the path below:

  http://yoursite.com/admin/config/media/image-styles

check the image styles name and make sure "Article" image style is here. if it's not, you have to change image style of your content type.


How can I set the energy settings for the Radioactivity module?

All those cool features are still there, you just need to set up a "Decay profile". You can do this at /admin/structure/radioactivity.

Once you've got the profile setup (with the "Advanced" method by the sounds of what you're looking for), you can edit the Radioactivity field on the entity, and choose that profile. When the entity is viewed, the tracking will kick in automatically.

To respond to events such as fivestar ratings, you need to use the Rules module as everything's been decoupled for flexbility.


With a standard HTML form in Drupal 8, how can I get the submit message to post in the "Status Message" block?

You should create this form through the Form API in a module, then in the form submit handler you can use Messenger to do this.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Messenger%21MessengerInterface.php/function/MessengerInterface%3A%3AaddMessage/8.6.x

You can see that drupal_set_message now routes through it:

function drupal_set_message($message = NULL, $type = 'status', $repeat = FALSE) {
  @trigger_error('drupal_set_message() is deprecated in Drupal 8.5.0 and will be removed before Drupal 9.0.0. Use \\Drupal\\Core\\Messenger\\MessengerInterface::addMessage() instead. See https://www.drupal.org/node/2774931', E_USER_DEPRECATED);
  $messenger = \Drupal::messenger();
  if (isset($message)) {
    $messenger
      ->addMessage($message, $type, $repeat);
  }
  return $messenger
    ->all();
}

This is how flash/status updates are created.


How to prevent actions using Flag (or similar) module?

I haven't done this, but if you want a library check in/check out system this is the approach I would try.  Create a flag (here I'll call it Check out) that allows users to "check out" files.  Make sure this is a global flag.  Name the unflag link "Check in" or something similar.  (You could also automatically have files checked back in after a certain interval with Rules Scheduler.)

Then, I would create views so that users cannot see the nodes that are checked out.  To actually enforce security, I would also add a rule that automatically redirects users away from the page of any node that they did not flag that has been flagged (this probably will cause a performance hit and may not be the most secure way but will probably work for general cases).