Show link only to user with permission to edit

Assuming that you are talking of the blog content type, you should need to use code that checks:

If the user who is currently viewing the blog node is the author of the node and has the "edit own blog content" permission
If the user who is currently viewing the blog node is not the author of the node and has the "edit any blog content" permission

<?php
  if ('[node:author:nid]' == $GLOBALS['user']->uid) {
    $permission = user_access('edit own blog content');
  }
  else {
    $permission = user_access('edit any blog content');
  }
?>
<?php if ($permission): ?>
  <a href="<?php print '[node:edit-url]';?>">Edit
<?php endif; ?>

A more generic code would be the following one.

<?php $item = menu_get_item('[node:edit-url]'); ?>
<?php if (!empty($item['access'])): ?>
  <a href="<?php print '[node:edit-url]';?>">Edit
<?php endif; ?>

This code is more generic because it shows the link whenever the current user has access to the edit link, whatever permissions are required to see that link. It could be a module alters which users can see the node edit page, and this code would take that in consideration.
The code is assuming [node:edit-url] is a URL like node/10/edit; if the URL is /node/10/edit or http://example.com/node/10/edit, then the code needs to be changed to extract the node/10/edit part, since that is the string menu_get_item() is expecting. See for example the code used by blog_menu_local_tasks_alter().

  // Add action link to 'node/add/blog' on 'blog' page.
  if ($root_path == 'blog') {
    $item = menu_get_item('node/add/blog');
    if ($item['access']) {
      $item['title'] = t('Create new blog entry');
      $data['actions']['output'][] = array(
        '#theme' => 'menu_local_action',
        '#link' => $item,
      );
    }
  }

That code is part of the Blog module, and it uses menu_get_item() to check if the currently logged-in user has access to the page to create a new blog. It doesn't merely verify the user has the permission to create a blog node, since that would not be enough if a module changes when a user can access the node create form.
Also note that the argument passed to menu_get_item() doesn't have a / at the beginning.

Notice that the Token module defines a URL token type, for which it makes available the following sub-tokens:

path, the path component of the URL
relative, the relative URL
absolute, the absolute URL
brief, the URL without the protocol and trailing backslash
unaliased, the unaliased URL
arg, the specific argument of the current page (e.g. 'arg:1' on the page 'node/1' returns '1')

Unfortunately, at the moment the type for node:edit-url is not set to url; when it is, the following code will work.

<?php $item = menu_get_item('[node:edit-url:path]'); ?>
<?php if (!empty($item['access'])): ?>
  <a href="<?php print '[node:edit-url]';?>">Edit
<?php endif; ?>


$data['activity_teamie']['table']['join'] = array(
  'activity_teamie_map' => array(
    'left_field' => 'aid',
    'field' => 'aid'
  )
);

You actually want to join the other way round.kk

A general tip, try to think of some kind of similar join relation in Drupal core and look it up in views/modules/$module.views.inc

$data['activity_teamie']['entity_id'] = array(

Isn't entity_id part of activity_teamie_map?


What is the proper RewriteBase setting for my staged server?

Unless you are running in a subcdirectory (eg, http://www.whatever.com/sub/directory/that/has/drupal/), you should use

RewriteBase /

RewriteBase is really used when you are doing rewrites from a directory that doesn't match your DocumentRoot.


How to determine taxonomy vocabularies related to a specific content type in Drupal 8?

In Drupal 6, this was configured per vocabulary, which had settings for which node type they should be displayed.

Since Drupal 7 already, this is handled through fields, a term reference field from a node type to a given vocabulary. The UI doesn't allow it, but a term reference field can also allow terms of multiple vocabularies.

So, if you want to know, you need to load term reference fields of that node type and then filter them by their allowed values setting. That said, the concept of "vocabulary of a given node type" simply doesn't really exist anymore, as there are other ways too, you can for example use an generic entity reference field too for term relationships. (In fact, there was an attempt to replace the term reference field completely in 8.x, but that was not successful so far).

Untested, but you need something like this:

$vids = array();
foreach (\Drupal::entityManager()->getFieldDefinitions('node', $node_type) as $field_definition) {
  if ($field_definition->getType() == 'taxonomy_term_reference') {
    foreach ($field_definition->getSetting('allowed_values') as $allowed_values) {
      $vids[] = $allowed_values['vocabulary'];
    }
  }
}

You can figure out most of this if you look at TaxonomyTermReferenceItem and how it is defining and using it's own settings, for example in getSettableOptions().


Set multiple items for an argument in embeded view

The argument itself needs to be configured to take multiple items. There is a checkbox which says "Allow multiple terms per argument".

After that you should be able to have a string with commas separating them

$view_args = array($node->field_page_cck[0]['value'] . ',' . $node->field_page_cck[1]['value']);

Note that you are still passing an array, but the first item is a comma separated string.


Drupal Crumbs can't get first "level" to show breadcrumb?

As Clive said, this ended up being a configuration issue on my part.

Shortest visible breadcrumb under /admin/structure/crumbs/display was set to 3 levels.


How to set the file status of files uploaded through theme settings to permanent?

You need set status FILE_STATUS_PERMANENT file when form submit

function mymodule_custom_form_submit($form, &$form_state) {
  if (isset($form_state['values']['images'])) {
    $file = file_load($form_state['values']['images']);

    $file->status = FILE_STATUS_PERMANENT;

    file_save($file);
  }
}


You can also use Maillog to test emails locally.

  Maillog provides an easy possibility to log all Mails for debugging
  purposes. It's possible to prevent the mails to being sent, so there
  is no need for an extra mail server to test the mail functionality of
  other modules or the drupal core. Additionally you can immediately
  display the mail through the devel dpm() facility.


Content referencing the referenced content

I don't see any problem here. or any difficulties to do this.. You only need a block with services of certain company, so you can create a views block , pass company id as argument (by contexual filter), and exclude current service from it.. But, I don't think that simply assigning it to region can help you, because you will need to fetch company id from service page and pass it to view block. I think the solution will be to implement hook_block_info and hook_block_view hooks to create another block and fetch company id from service page and display it..

example:

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

  switch ($delta) {
    case 'company_service':
        // there is multiple ways to get field value from entity. In this example I am it getting with entity_metadata_wrapper function from Entity API:

        $service_node = menu_get_object();
        $service_wrapper = entity_metadata_wrapper('node', $service_node);

        $company_id = $service_wrapper->field_company->value(); // I don't know the structure of your entity fields, that's why we assume that $service_wrapper->field_company->value() will get company_id..

        $block['subject'] = t('Company services');
        $block['content'] = views_embed_view(VIEW_NAME, DISPLAY, $company_id);
      break;
  }
  return $block;
}


If your are using drupal 7, then my favorite option is openlayers with address field and geofield.

The advantage of openlayers is that you are not tight to one particular map provider, but you can switch just by changing your options.

You can set geofield to take the value of the address field, geocode it and store the lon/lat value of the address. You can then draw the locations on the map.
The geofield works with google or yahoo for geocoding.


Did not find the answer (I did try hook_page_alter) - but I realised I was not focusing.  I want to hide those cookies from anonymous users, but those users will never access the admin section, so the two cookies I am trying to delete, will never be set.


Contextual Filter Problem in Drupal Commerce Using Indexed Textfield

I think it's because the value that you put into the Views preview will just be a value to pass to the PHP code. So if you enter return "Breitling", your code is going to try and find a brand named 'return "Breitling"'.

If you just need to return all results from the brand Breitling for testing purposes, in your PHP code in the contextual filter, set the value to look for as "Breitling".

Let me know how you get on.


I want to redirect the user to profile page after they log in

Hope this will help  you,

In Drupal 7 you can use RULES instead of using any modules only if you looking for redirection.

Go to admin/config/workflow/rules/reaction/add to add new rule

Now enter the RULE name and select the event on which you want to trigger this RULE

Now its time to give some condition(if required) and to trigger the action.

In Action select Page redirect

Give the redirect URL and and check Force redirect

If the rule is not working means, there may be a other same event with higher weight. Therefore you need to increase you rules weight.


How to get custom indexed field to show up in view?

It took a while, but I figured the issue out.

You have to set your solr server configuration within Drupal to return fields at /admin/config/search/search-api/server/

Here's the text on that settings page:

"Retrieve result data from Solr:
When checked, result data will be retrieved directly from the Solr server. This might make item loads unnecessary. Only indexed fields can be retrieved. Note also that the returned field data might not always be correct, due to preprocessing and caching issues."

Basically, if you want to pull data directly out of solr, you have to have this checked.  I don't think you can do this at the view level.


How do I create a merge request for a project?

As said in Issue forks & merge requests drupal.org only implements (so far) issue forks and merge requests related to those issue forks. Issue forks are still in development and enabled only on those projects that opted-in, a list of which is available in Opt-in core issues into the Drupal.org Issue Forks and Merge Requests Beta: The list doesn't include the projects maintained from the Drupal Association, for which issue forks have been directly enabled from a Drupal Association employee.
The plan is making them available on all projects on November 10, 2020.
When issue forks are enabled, an issue opened for that project contains a button as in the following screenshot, taken from Show commit activity for issue fork branches without merge requests.

When an issue fork has been created, there will be a different button, as in the following screenshot.

I didn't watch at the code used on drupal.org, but I expect the code checks users have the Git user role on drupal.org, which is given to the users who accepts the Git access agreement, or a Git account on Drupal.org, before allowing them to create an issue fork or obtain push access on an issue fork.

Merge requests aren't tested on DrupalCI, until Test merge requests made in GitLab with DrupalCI is marked as fixed. That could happen before, or after, issue forks are enabled on every project.
As for today, December 24, 2020, issue forks and merge requests have been enabled on every project hosted on drupal.org. Merge requests are tested by the DrupalCI instance running for drupal.org.


Difficulties install Drush using composer

Changing the .bash_profile to the following worked:

export PATH="~/.composer/vendor/bin:$PATH"

Now drush status gives good feedback on the Drush version etc. Thanks to Clive for suggesting this.


Update: As mentioned in the comments below, the actual answer here is that the git deploy module is required for --package-handler=git_drupalorg to work correctly.

If you just want to track the latest HEAD from some branch of some module, then you can use drush dl with --package-handler=git_drupalorg to download the file, and use git pull when you want to update your code.

drush pm-updatecode is best used in instances where you wish to track the latest stable release of the module.


Use field_info_instance()
  $entity_type = 'node';
  $field_name = 'body';
  $bundle_name = 'article';
  $body = field_info_instance($entity_type, $field_name, $bundle_name);

Which gives you access to numerous config/settings

  $body_weight = $body['display']['default']['weight'];


Taxonomy Term Block View Show Nodes For All Terms in Node?

I am not sure for d6, but in d7 you can do it like this(i believe it can be done same way in d6)

In Contextual filters(your Arguments) you need to add Nid like you did, after add new argument has taxonomy term ID and in WHEN THE FILTER VALUE IS NOT AVAILABLE -> provide default value chose not content from URL but PHP code and do this:

You need to load node and get your taxonomy terms from field.

 $node = node_load(arg(1));
  if($node) {
  $field = field_get_items('node', $node, 'field_YOURFIELDNAME');
  if($field) {
      foreach($node->field_YOURFIELDNAME[LANGUAGE_NONE] as $term) { $terms[] =  $term['tid'];          }
    return implode('+',$terms);
  }
}
  else { return; }

it will return tids of selected taxonomy terms. But its a d7 way with Views 3.


Limit Entity Reference to Only Display Content Created By User

You can create a view to return only the content by the current user and then use that as the entity field reference.

You can select this form ENTITY SELECTION


How to specify the correct private file path in a block

drupal will not let you specify a direct link to a private file

If you upload the file using file field (core) then you can use views to display the file in a block using block display and use https://www.drupal.org/project/private_files_download_permission for fine grained permissions on who can download the file

if you want to program this behaviour then you have to look at using file_create_url in a custom module

$fid = 1; //set fid to your file's fid.
$downloadlink = file_create_url(file_load($fid)->uri);

and this link will hide the actual path where you private file is

for more details you can look at

How can I get the URL to the public files directory?

https://api.drupal.org/api/drupal/core%21includes%21file.inc/function/file_create_url/8.2.x


I Can't add node of a custom content type

After following clues mentioned in the above comments (by CodeNext), I was able to solve my problem. The issues and the solution I have compiled as below.

There were two problems.

For some needed reason, I displaced the "add content" menu from "Navigation" to "Redaction" (a new menu). This caused the new content type not appear in the "Add content" page. By displacing the new content type in the "add content" menu, I could see my new content type in the right place.
I had a underscore in the content type machine name. Because of this, i couldn't navigate to the node/add/newcontenttype page (I reached the node/add page). By removing it (the underscore), everything goes now the right way.


domain access display content to ANONYMOUS USER

Under admin/structure/domain/roles you have to checkbox guest -> all domains.


Is it possible to rate a page generated with Views using the fivestar module?

I normally use a "hidden" node to accomplish this.  Typically, I will make a content type called something like  "internal use".  Then, I will make a panel page that contains an "inernal use node and my view.  The node-ish actions then get associate with this node.


How can I print a field from a referenced entity in my theme?

You could do this using either of these:

hook_node_view() in your own custom module
hook_preprocess_node() in your theme template.php

Here's an example of both of these methods. The idea is the same as what rooby suggested earlier but you need to modify the content of the node, not the fields.

Example 1: hook_node_view(), can be used in a custom module.

    // Implements hook_preprocess_node();
    function mycustommodule_node_view($node, $view_mode, $langcode) {

      $field_name = 'field_main_image';

      // Check that the field exists in our node and that it has no content.
      // Alternatively we could check $node->type.
      if (
        isset($node->$field_name) &&
        empty($node->$field_name)
      ) {

        // Use entity metadata wrapper to gain easy access to referenced entities.
        // This method is more reliable than digging the field array.
        $node_wrapper = entity_metadata_wrapper('node', $node);
        if ($node_wrapper->field_master_reference->raw()) {

          // Get the referenced node object.
          $master = $node_wrapper->field_master_reference->value();

          // Use field_view_field to get the renderable content of the field.
          // Save this data in $node->content so that node template can output it.
          $node->content[$field_name] = field_view_field('node', $master, $field_name);
        }
      }
    }

Example 2: hook_preprocess_node(), can be used in theme template.php.

    // Implements hook_preprocess_node();
    function mycustomtheme_preprocess_node(&$vars) {

      $node = $vars['node'];
      $field_name = 'field_main_image';
      if (
        isset($node->$field_name) &&
        empty($node->$field_name)
      ) {
        $node_wrapper = entity_metadata_wrapper('node', $node);
        if ($node_wrapper->field_master_reference->raw()) {
          $project = $node_wrapper->field_master_reference->value();
          $vars['content'][$field_name] = field_view_field('node', $project, $field_name, array(
          'type' => 'image',
          'settings' => array(
            'image_style' => 'thumbnail',
            'image_link' => 'content',
          ),
        ));
        }
      }
    }


You're right, the image_style_* functions only work with files in the managed file system. You can get round it by using the imagecache_external module, though, which takes remote images and stores them where we need them.

It might seem a little strange to be requesting local images as if they were remote, but this ensures the integrity of the image_style system without further hackery.

$image_uri = drupal_get_path('theme', 'mytheme') . '/images/banners/projects-banner.jpg';

$absolute_image_url = url($image_uri, array('absolute' => TRUE));
$banner_file = imagecache_external_generate_path($absolute_image_url);

$banner_url = image_style_url('my_image_style', $banner_file);


Ensure that all Cron jobs work correctly

Maybe.

Considering there are 20 cron jobs and they all run 15 times a day and you’re using advanced queue, I would make sure to test in your production environment timeouts and memory issues.

Personally I would use cron + drush making sure the php.ini for command line PHP has more than enough resources to accommodate whatever it is you’re doing.

drush cron-run

https://cgit.drupalcode.org/ultimate_cron/tree/ultimate_cron.drush.inc?h=8.x-2.x#n77


Need to ignore empty variable values for Computed Field when multiplying

Both @Neo's answer and @danielesus's question shows PHP code that will throw errors. @Neo, empty() only works with variables before PHP 5.5. Both: array_pop requires a variable or something returned by a reference-returning-function which field_get_items is not.

Now let's consider what field_get_items($entity_type, $entity, 'field_how_many') returns: it returns an array indexed by delta where the values are field_column  => value. You can do

if ($all_items = field_get_items($entity_type, $entity, 'field_how_many')) {
  $item = reset($all_items);
  $value = reset($item);
}

as there's no need to actually modify the array with array_pop but also you can use your knowledge about Field API and know the actual column name which I suspect will be value here (would be tid for a taxonomy reference field for example) and that $delta is, if you have a field with cardinality 1 is actually 0:

$value = NULL;
if ($all_items = field_get_items($entity_type, $entity, 'field_how_many')) {
  $value = $all_items[0]['value'];
}

Fast and simple.


In which file is the list of the installed modules saved?

You are looking for core.extension.yml. Directory for configuration synchronization is set up in settings.php with variable $config_directories.

Here is the documentation, but it's not full.


You can use Date picker Module for popup date on exposed filter.

It includes the date popup. You can use this module to easily add an exposed filter with the date popup.


create a custom form based on user fields

Is it possible you missed the comment (below)? It's on the post you linked to.

  "module_load_include('inc', 'user', 'user.pages'); should be added to hook_init() otherwise all profile form functionalities that require AJAX calls will return the error 'Call to undefined function user_profile_form_validate().'"


How do I create a Rule "When role is removed, send email to the user"?

It has to be triggered when a particular role ("subscriber") has been removed. So we can use 2 conditions User has role(s), to check if he had the role before the edit, and that he doesn't have it after the edit :

1st condition : selector "account_unchanged", check the role "subscriber" (here test)

2nd condition : selector "account", check the same role, and negate.


How can I have default field values for the node add form as arguments in the URL?

I figured it out.
in .module, hook_form_after()
$value = \Drupal::request()->query->get('q');
$value = Html::escape($value);
$form['student']['widget']['#default_value'] = [0 => $value];

with url /node/add/trip?q=6, where 6 is id of student Oleg


Permission base on the administration menu?

I found the solution here is how is done....

function my_custom_module_page_build(&$page) {

    // Check if user have access to the administration menu
    if (!user_access('access administration menu')) return false;

    // Check if user have access to navbar.
    if (!user_access('access navbar')) return false;

     drupal_add_css(drupal_get_path('module', 'my_custom_module') . '/css/mobile.css');

}


How can I get header part from my drupal 7 site?

Usually header part is included in drupal in page.tpl.php.

Still you can do it by creating a function in your template.php

e.g. myheader() and calling it in page.tpl.php.

function myheader(){
$html = "<div class='header'>
 Insert header html
</div>";
return $html;

}

Other way you create a template using hook_theme in your custom module and call it in page.tpl.php.

e.g. it will be called in page.tpl.php by below code

print theme('myheader');

//It will defined in custom module

function mymodule_theme($existing, $type, $theme, $path)
{
  if($type == 'module')
  {
    return array(
      'myheader' => array(
        'variables' => array('var_name'=>NULL),
        'template' => 'myheader'
      ),
    );
  }
  return array(); //will raise fatal error if void
}

and put a template in theme directory with name myheader.tpl.php

Hope it will help!


How can I create a content type in a custom module?

That hook is only run when the module is installed, maybe you added the hook during development of your module and when it was enabled?

The hook should be placed in a file called srl_dash.install.

Then disable your module and uninstall it, then enable it again. Now the hook will run.


Views-How do i redirect to the same page after saving the comment?

i think i fix the problem, i just use the page management and change the setting of the node view,give a content type variant and then user http response.

Problem fixed ~ if you have the same question, take a try!


Why my taxonomy term list in content is not using node languages prefererence

Check the "translation mode" that you've specified within admin/structure/taxonomy/colors/edit (whereas "colors" is the name of your specific category): by default that is set to "Localize", though it should be set to "translate".

After changing this value, be aware that you then also have to:

enter a translated value for each of the tags and
revisit any of the existing nodes that are already using the specific taxonomy, so that they use the (translated) term that corresponds to the language of the node.


Download spyc from http://code.google.com/p/spyc/. Inside the spyc folder find the file called spyc.php and copy it to the Services Module 'servers/rest_server/lib/' directory.


Split Delivery : Drupal Commerce future : 2 qty in differnt Address : Single Order in Multiple Address

There is no module offering split shipping like this out of the box. The Commerce Shipment module does support making multiple shipments out of the products on an order, but it requires custom code to tell it on what basis the order ought to be split. To date, this has only included support for line item based splits for pre-orders, so you'd need to develop a user interface for selecting products / entering their addresses and the ability to split up individual line items based on quantity.


referencing a field in a node in hook_node_api

If memory serves it should be something like this:

if (!empty($node->field_alert[0]['value'])) {
  //do something
  drupal_set_message('Your update will be emailed out.');
}


Selectively applying image style to a class

Image styles and HTML classes on images are completely unrelated, so you would have to do some sort of manual hack to achieve this. A very basic effort might be to use hook_preprocess_image_style like so:

function MYTHEME_preprocess_image_style(&$vars) {
  if (array_search('some-class', $vars['attributes']['class']) !== FALSE) {
    $vars['style_name'] = 'some_style';
  }
  elseif ($another_condition) {
    $vars['style_name'] = 'some_other_style';
  }
}


Services Entity REST Application - Update (via put) Field Collection Data

It appears that something to do with revisions is causing the problem as if I provide specific (required?) data in my PUT request it works. Working PUT request JSON:

{
    "field_primary_aircraft": {
        "und": [
            {
                "value": "1"
            }
        ]
    },
    "field_name": "field_aircraft",
    "item_id": "5929",
    "revision_id": "5929",
    "default_revision": true,
    "field_aircraft_registration": {
        "und": [
            {
                "value": "testing12355"
            }
        ]
    }
}

That JSON plus a working CSRF token allowed me to save data back to a field collection that  is part of a users Profile2 profile.

The revision_id and default_revision were the trickiest parts to track down and supply, I don't have revisions enabled as far as I can tell also, so why this problem started suddenly I have no idea...at least it is solved and hopefully this info helps someone else.


Anonymous checkout doesn't properly work

Happy end, and stupid lost time : the lone problem was the Anonymous user was accidentally deleted (don't know how) ! I thank all the gentlemen who tried to help me to debug.

The uid 0 must absolutely be there. If you encounter such case, simply insert an empty row in users table via phpmyadmin or run these 2 queries (for D7) :

insert into users (name, pass, mail, theme, signature, language, init, timezone) values ('', '', '', '', '', '', '', '');
update users set uid = 0 where name = '';

Meanwhile, I've read many things about Commerce checkout to make sure I was doing right. I share some clues below in case it could help somebody else.

A common issue for empty cart page (and other Commerce Views issues where user can't see products) is due to Referenced Product Relationship: 2 solutions may work depending on your config :

In the View's advanced settings fieldset, disable SQL rewriting.
Enable the not-totally-secure View any product of any type permission. This is discussed & patched here. If you have Commons distribution, you’ll have to disable paranoia (disable with Drush only, it's not visible in the module list).

Important permissions to grant (admin/people/permissions) :

Anonymous :

Checkout => Access checkout
Order => Create orders of any type  / Create orders

Authenticated : same ones, plus

Order => View own orders of any type / View own orders

Default behavior in Drupal Commerce :

Anonymous users can add a product to cart, checkout (filling email, name and address), review and complete order. Some documentation to read : Checkout: Anonymous vs. Authenticated  and Anonymous Carts and Logged In Users

An a few useful tips and links to enhance default checkout

How to auto login anonymous user that has completed checkout ? As per duckx answer, you can get this in 3 short steps : checking above rules, enabling Commerce Checkout Complete Registration or Commerce Immediate Login, adding the Login action to the default Commerce "Create new account for anonymous order" Rule.
Use Commerce Checkout Login to provide e-mail validation and an inline login form via AJAX.

  If the e-mail address an anonymous user enters is already associated
  with a user account, the checkout form will expand with an optional
  password textfield and login button for immediate login.

Use the popular Commerce Checkout Redirect  to redirect anonymous users to a page where they can login or create a new account when they try to checkout. Many settings available…
Use Commerce Address book to allow authenticated customers to reuse
previously entered addresses during checkout.
How to set up an Express checkout  (a single page checkout process that any user - including an anonymous user - can complete in a snap)
How to set Different payment methods for different product types  adding a condition to the payment method rule.
How to create an order through Drupal Commerce API
Use Commerce add to cart confirmation to provide an "add to cart" confirmation dialog, shown after the customer has added a product to his cart.
Last, Commerce Extra offers a bundle of features, from which cloning Address information from user's account (instead from previously made orders as Commerce Address book does), and adding an extra step to checkout so that users may log in optionally.


Is it correct to make queries to DB in preprocess functions?

No, it's not incorrect to query the database in a preprocess function. If the information is required to render the page, putting a query in a preprocess function is an acceptable choice. Plus, in this particular case taxonomy_get_tree() caches results, so there is very little cost associated with repeated fetches.

Regarding Views, yes there is some overhead associated with it, but it employs a sophisticated caching strategy, and is ultimately just so powerful and useful that most sites use it. You could probably solve this current problem with no custom code by using a Viewfield.

These questions provide a lot of interesting background on Drupal performance.


Find a node/page in admin by looking at the code

I'd recommend installing the Devel module and enabling Webprofiler. It gives you a lot of useful meta information about the current request, including the controller and route used:


Is it possible to use mixed LDAP and local Drupal authenticated users on the same site

Any accounts created through LDAP will have access to the site. Alternatively you can create local Drupal users that also have access when using mixed mode.

For instance I work with sites where I have LDAP credentials that allow me access to all the sites. I also had a local Drupal user for one or two that have different credentials and I can log in with either (same email).

Depending on what modules you are using to facilitate this process they may even create a local user for each LDAP user (not sure if they all do this or not). This comes in handy when experiencing LDAP issues as you still have access to your site/s.


Stop send email attempt when cron is run

It's likely defined as a hook_cron implementation in a custom module. Trying searching through your codebase for "_cron" to see what you can find. If you install Elysia Cron you should be able to get a full list of all cron jobs and could disable any jobs you don't way run.


How to define the right dependencies in .info, so drush can understand it?

You can declare the project name of the dependency using the following syntax:

dependencies[] = project:module

However, this this is a new feature that was added in Drupal 7.40, and as far as I can tell, Drush doesn't seem to understand it yet.


How to declare class that extends Drupal d2d Migrate class

Change your code like and try

 $migrations['CadeFields'] = array(
  'class_name' => 'CadeMigrateFields',
  'description' => t('Give your description abt this migration'),
  'source_type' => 'GIVE THE DRUPAL 6 NODE TYPE YOU ARE MIGRATING',
  'destination_type' => 'GIVE THE DRUPAL 7 NODE TYPE',
 );


There are a couple of other options you can explore, apart from the ones you have already mentioned:

drupal sync
The present module allows synchronizing content among multiple websites.
Supported entity types: node and taxomony, menu items.

deploy
The Deploy module is designed to allow users to easily stage and preview content for a Drupal site. Deploy automatically manages dependencies between entities (like node references). It is designed to have a rich API which can be easily extended to be used in a variety of content staging situations.


Display a Views slideshow only if more than one image

I think you'd have to do some custom coding to get that result. To simplify, you'd have to make a separate field for the single image option.


how to identify first element in array of node objects?

$nodes is keyed by the node ID, which you probably won't know in advance. Instead of directly trying to access the first node in the array, iterate over them with a foreach loop.

function mymodule_node_load($nodes, $types) {
  foreach ($nodes as $nid => $node) {
    if ($node->type == 'basic_page') {
      ...
    }
  }
}


looking at the details from https://stackoverflow.com/questions/5186047/drupal-gmap-views-popups-are-too-big I would suggest to wrap everything in the custom text field in a div with a specific class then do .myclass { width: DESIRED_WIDTH; } in your stylesheet.

or try to div.gmnoprint .views-field-nothing { width: DESIRED_WIDTH; } where div.gmnoprint is the wrapper div for the gmap popup and .views-field-nothing is the default wrapper for a custom text field in views.

Without a live example, it is harder to give an exact answer. I suspect you may have to add overflow:hidden; to your wrapper div if you have any floating going on there.


I managed to do that with the following code:

/**
  * Implements hook_views_pre_view().
  */
 function hook_views_pre_view(&$view, &$display_id, &$args) {
   /* Search page view */
   if ($display_id == 'search_page' && !empty($args[0])) {
     $args[0] = strtr($args[0], '-', ' ');
   }
}

You should also adjust the search form ofcourse..


How to display visitor's country flag depending on the visitor's IP address?

The Smart IP module can give you the user's IP address. The following code should give you a block, assuming you have flag images whose file names match the country code, e.g. "ie.png" for Ireland and those file are in "/sites/default/images".

function mymodule_block_info() {
  $blocks = array();
  $blocks['flag'] = array(
    'info' => t('Country flag')
  return $blocks;
}
function mymodule_block_view($delta='') {
  $block = array();
  switch($delta) {
    case 'flag' :
      $block['content'] = _flag_block_view();
      break;
  }
  return $block;
}
function _flag_block_view() {

  // Get the IP address
  $smart_ip_session = smart_ip_session_get('smart_ip');
  if ($smart_ip_session['location']['country_code']) {
     $code =  $smart_ip_session['location']['country_code'];
     $output = '<img src="/sites/default/files/images/' . strtolower($code) . '.png />';

  else {
    $output = "Nothing";
  }
  return $output;
}

The above is a simplistic solution. In practice you might want to make better provision for country codes and/or flag images not being available,  add alt and/or title attributes to your  tag, etc.

Also bear in mind you will need to choose a source of IP geolocation data. See this answer for info on that. And, remember geolocation data is not guaranteed to be 100% accurate.


Site Down for few minutes after clearing cache

Have you installed "Memcache" module ? If no then :

First of all, check mysql slow query log. Also install "Memcache" module which will help you to reduce mysql server load.

Please refer this link for Drupal Memcache installation.


Why does Drupal (8) not discover my custom taxonomy term template?

You need to use underscores in your suggestion (but continue to use dashes in your template file name):

/**
 * Implements hook_theme_suggestions_HOOK_alter() for taxonomies.
 *
 * {@inheritdoc}
 */
function HOOK_theme_suggestions_taxonomy_term_alter(&$suggestions, $vars, $hook) {
  if($vars['elements']['#view_mode'] == 'teaser') {
    $suggestions[] = 'taxonomy_term__teaser'; // note underscores
  }
}

you could also leave out your condition and do:

/**
 * Implements hook_theme_suggestions_HOOK_alter() for taxonomies.
 *
 * {@inheritdoc}
 */
function HOOK_theme_suggestions_taxonomy_term_alter(&$suggestions, $vars, $hook) {
  $suggestions[] = 'taxonomy_term__' . $vars['elements']['#view_mode'];
}


Output of entity_metadata_wrapper does not dump to dsm()/dpm()

Never mind, I found it. Leaving the answer here for anyone who follows

Basically, dpm($wrapper->getPropertyInfo());

https://drupal.stackexchange.com/a/42542


How to set default form fields value from controller

Add the default values to getForm():

return $this->formBuilder()->getForm('Drupal\mymodule\Form\MyForm', $default1, $default2);

And set the default values in the form class:

class MyForm extends FormBase {

  public function buildForm(array $form, FormStateInterface $form_state, $default1 = NULL, $default2 = NULL) {

    $form['field1'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Field 1'),
      '#default_value' => $default1,
    ];

    // ...

  }
}


How to execute javascript within drupal for a specific field on a specific page?

Your jQuery:

//Making a focus over the element
(function ($) {
    $('#fullname').blur(function() {
        $(this).removeClass("color");
      })
      .focus(function() {
        $(this).addClass("color");
      });
})(jQuery);

Your HTML:

<input type="text" id="fullname"><br>

Your CSS:

.color {
  background-color : yellow;
}

EDIT:
To attach the js code to your page you can use #attached in a renderable array (this is the recommended way). I think that you should read: How to add jQuery UI libraries to a page.


user relationship status as a visibility rule per panel pane

From: http://drupal.org/node/1185210

User Relationships provides individual panel pane visibility checks based on relationship status.
In order to use this functionality:
Make sure that the User context has been enabled for the current variant (most likely current user)
Add a new visibility rule for the pane you would like to control
Select 'User Relationship' and configure for your use case.

That being said, I wrote those instructions for Drupal 6 while porting this feature to 7 and there may be bugs with the 7.x implementation. If you find anything make sure to post what you find on the issue queue.
If you want to customize your implementation further that code would be a good starting point, and please post any additional visibility rules back to the queue.


Whats causing this garbled text below my pages?

You could try searching for part of the string in your codebase.  If you have SSH access then you could run something like:

cd /path/to/document/root
grep -r "W!b\EU6" .

Otherwise if the file is on you local computer then you could use any search tool to look for "W!b\EU6" (those particular characters are from the last line of your screenshot.

Note that it may not be in the codebase.  It could be in the database or could be the output of some function such as an encoding function.  You could check if it's in the database by dumping the database to a .sql file (not compressed) and searching in that.

If you find it and are not sure what to do with the results then paste them here for further advice.


Also worth mentioning, there is a new drupal 7 API called hook_module_implements_alter() which lets you alter the execution order for a given hook WIHOUT altering the module weights table.

Sample code from the API docs showing how easy this is to do:

<?php
function hook_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'rdf_mapping') {
    // Move my_module_rdf_mapping() to the end of the list. module_implements()
    // iterates through $implementations with a foreach loop which PHP iterates
    // in the order that the items were added, so to move an item to the end of
    // the array, we remove it and then add it.
    $group = $implementations['my_module'];
    unset($implementations['my_module']);
    $implementations['my_module'] = $group;
  }
}
?>


It turned out to be a caching issue which i resolved by suing the block_flush_caches
method.


Prevent drupal from adding a favicon from default directory in custom theme

I found a solution. in Appearance>Mytheme>Settings, there is an option to uncheck shortcut settings.

After unchecking that option the link provided in mytheme_preprocess_html was able to display the favicon unopposed.


How to post xml data in drupal_http_request? I have curl code of it

Seeing how drupal_http_request() is used in _xmlrpc(), something like this should do it.

// The path to send the request
$url = "http://example.com/API_PATH_HERE";
// Example of valid xml code;
$xmlrequest = "<showId>0</showId><tag>123</tag>";

$response = drupal_http_request($url, array(
  'headers' => array('Content-Type' => 'text/xml'),
  'data' => $xmlrequest,
  'method' => 'POST',
  'timeout' => 10
));
// If there is no error return data
if (empty($response->error)) {
  $result['xml'] = $response->data;
}


Missing Main Page Content Block in Blocks List

Recently had this issue. When I enabled my custom theme some files were missing and Drupal threw some errors and warnings. After adding the files everything worked fine except the Main page content block was missing.

To fix, I did the following:

Set Bartik as the default theme
Navigated to the block interface and configured the Main page content block (which was showing now that Bartik was the default theme)
My custom theme was still enabled so it showed up in Region settings and I was able to select a region

Set my custom theme as the default again and all was good. Main page block was showing again.


How to redirect by adding something after pathauto url?

What's what Splash module does. See Thickbox option. More about the module:

  Display any internal path, external URL or text as a splash page before going to the actual frontpage.


Update packages conflicting with core update

Update:
Thanks to the comment below from @mpdonadio below, it seems better to follow the official documentation right here: https://www.drupal.org/node/2700999#s-special-considerations-for-upgrading-to-drupal-880-and-later

composer update
git add composer.lock; git commit # Save the updates as a separate commit.
composer remove webflo/drupal-core-strict --no-update
composer remove drupal/core --no-update
composer require 'composer/installers:^1.7' --no-update
rm composer.lock
rm -rf vendor # Also helps avoid conflicts.
composer require drupal/core-recommended:^8.8 --update-with-dependencies
git add composer.json composer.lock; git commit -m "Update Drupal to 8.8.0 and use drupal/core-recommended instead of webflo/drupal-core-strict"

Old answer

First, make sure your composer version is not fixed (e.g. drupal/core:8.7.10):

composer require drupal/core:^8.7.10

This will update to its latest version (e.g. 8.7.11) but also makes sure you can progress later. To see which projects would cause problems, run:

composer prohibits drupal/core:8.8.0

This will result in a list:

typo3/phar-stream-wrapper (^3.1.3)
typo3/phar-stream-wrapper (but v2.1.4 is installed)

Then you can make sure you update the package:

composer require typo3/phar-stream-wrapper:^3.1.3

Then update like this:

 composer update drupal/core typo3/phar-stream-wrapper pear/archive_tar


How to obtain Drupal session cookie via an XMLRPC request?

The Services module does this. See its user.login service. Core Drupal does not offer this service via XML-RPC.


How to prevent that import with Feeds and Elysia cron gets stuck

I have discovered that temporarily switching off the modules PathAuto and SubPathAuto improved the speed x10, making all these problems dissapear forever. No more feeds stuck or hanged. Later, I enable the modules again, and everything is ready.


The Special Menu Items module will do exactly that for you:

Special menu items is a Drupal module that provides placeholder and separator menu items.
A placeholder is a menu item which is not a link. It is useful with dynamic drop down menus where we want to have a parent menu item which is not linking to a page but just acting as a parent grouping some menu items below it.


Find Menu Link Title given URL alias, to replace node Title in breadcrumbs

The sandbox module "wb_breadcrumbs' did the trick for me: https://www.drupal.org/sandbox/oles89/2367919


Migrate source id's and map them to already existing Drupal entity id's

This happens to me all the time, I post a question after fiddling around for hours and shortly after, I manage to find the answer myself. It appears that the first attempt was almost right. Though bundle_key should be vid, I'm not sure why though.

The config, for completeness sake.

  field_season:
    # Map the seasons to our already existing taxonomy terms
    -
      plugin: static_map
      source: season
      map:
        '1': 26 # Lente
        '2': 29 # Zomer
        '3': 24 # Herfst
        '4': 28 # Winter
    -
      plugin: entity_lookup
      value_key: tid
      entity_type: taxonomy_term
      bundle_key: vid
      bundle: seasons


Passing Arguments between an EntityReference field and an EntityReference View

Add a contextual filter of Has Taxonomy Term ID

Select Provide Fixed Value and type Fixed Value. For fixed value type the ID's of your terms separated by a comma. (You can find the ID of your taxonomy terms inside the edit url when you edit your terms)

Scroll all the way down to the MORE section.

Click on MORE and check mark allow multiple values.

For your other view, use Author Uid and follow the picture below.


I would expect this is more related to the backup and migrate module.

The addition of the webform module's data may have pushed your setup over its limit when doing large amounts of processing like backup and migrate would be doing.

I would suggest checking your MySQL configuration's max_allowed_packet setting, it may be too low.

I would usually recommend setting it to 64M for Drupal 7 and then restarting the MySQL service and see if that resolves the issue.


Are you sure that image style still exists?  Views doesn't like when you delete/change image styles that it is already using.  A remedy might be to delete that field from your view, and reset it (with the confirmed good image style?)

Maybe your image style was formed improperly?

(Are your view blocks restricted to not show on the home page (block admin?)


How do I insert the title of the block between two Views fields?

You could try Views block area

  This module exposes all available blocks as a views area. This way you
  can add any block inside a footer or header from your view.

Also there is Views Hacks

Or i would do it with Views PHP by adding a field and print the block there with https://drupal.stackexchange.com/a/14354/4471


Hide one form element until another is selected

As @leymannx stated you can achieve this using #states. Here is a simple example:

 $form['show_textbox'] = array(
  '#type' => 'checkbox',
  '#title' => t('Show text Box 1'),
        '#attributes' => [
        'id' => 'show_textbox',
        'name' => 'field_show_textbox',
      ],
);

    $form['text_box1'] = [
      '#type' => 'textfield',
      '#size' => '60',
      '#placeholder' => 'Enter Name',
      '#attributes' => [
        'id' => 'text_box1',
        'autocorrect' => 'none',
        'class' => 'text_box1',
        'autocapitalize' => 'none',
        'spellcheck' => 'false',
      ],
      '#states' => [
        //show this textfield only if the radio button 'show_textbox1' is selected
        'visible' => [
                ':input[name="field_show_textbox"]' => array('checked' => TRUE),
        ],
      ],
    ];

You can always change the condition.


Can't render node view mode pro-grammatically

Your problem is here:

use Drupal\node\Entity\Node;
use Drupal\taxonomy\Entity\Term;
use Drupal\views\ViewExecutable;
use Drupal\views\Views;
use Drupal\Core\Render;
$nid = 1;
$entity_type = 'node';
$view_mode = 'teaser';
$builder = \Drupal::service('entity_type.manager')->getViewBuilder($entity_type);
$storage = \Drupal::service('entity.manager')->getStorage($entity_type);
$node = $storage->load($nid);
$build = $builder->view($node, $view_mode);
$output = \Drupal::service('renderer')->render($node);
var_dump($node);

You have dumped your code raw into a file. You cannot do that - your code is being called before Drupal has bootstrapped. You need to put your code into a function some hook that is called after Drupal has bootstrapped. I don't know what you're trying to accomplish, so I can't give any more info than that.


I would still use blocks for this, because I always prefer to use the most appropriate and lightweight solution for the data storage, and then tweak the admin interface to enhance usability.

You could solve this with a special content type, combined with views or display suite. However, experience has taught me that if you're creating a content type for a small, fixed number of nodes, it usually means that there are better solutions out there.

You are right that the blocks page is too complex for many users. To solve that problem, I would:

Create the 3 blocks;
Enable the Contextual Links module (part of Drupal 7 core) to provide edit links on the blocks, right there in the front end;
Install and configure Block Access to make only those 3 blocks editable by the site maintainer;
Implement hook_form_alter to hide specific form fields from the site maintainer on the block edit form.


If I understood your question correctly, and given the directory structure, you'll want to modify the .htaccess (the one in the root directory) so that requests are rewritten.

To do so, find and modify (or add) the following line:

RewriteBase /mydrupalsite.com


You could use menu_get_menus, or use a modified version of its code:

https://api.drupal.org/api/drupal/modules!menu!menu.module/function/menu_get_menus/7

It returns an associative array of the menus names, either the custom one, or also including the system menus.


I suppose you should be loading the libraries through the libraries API:

It is in the Libraries API documentation

libraries_load($name);

// Usually, you'll want to do something after the library has been loaded.
// Because you cannot always depend on the library being installed you have
// to check first if the loading was actually successful:
// Try to load the library and check if that worked.
if (($library = libraries_load($name)) && !empty($library['loaded'])) {
  // Do something with the library here.
}

Since you say you don't understand this. The above check makes sure the library is loaded correct. So you will not run into weird errors or exceptions. Just put all the code that depends on the libraries inside that if-statement. (As a matter of fact is it much important for PHP than it if for JS, but nevertheless it prevents errors.)

UPDATE:

Oh wait. The problem is that jQuery.on() the function that throws the error was added in jQuery 1.7. Stock Drupal runs on 1.4, so in order to get this to work, have a look at jQuery update and make sure Drupal runs at leat 1.7.


One-time link without valid email address Spam Registrations

I can only think of a few ways this is possible:

There's a vulnerability in the one-time-login link system for new users (I'm not aware of one)
There's a vulnerability in some other module (in which case please give some more details of what modules you are running)
Your server does actually resolve the domain hotmailit or has a default place it sends mail and thus the mail is being delivered to somewhere which is then getting the login link and spamming.
Something about your configuration is different than you've described it (e.g. Users do not have to be verified before posting)


Ajax error and weird white space when connected

Finally found a solution so I'm going to post in case anyone has a similar problem.

First, I made sure I had no unnecessary PHP closing tag, just like Drupal recommands.
I also checked for the character in the database, just in case.

I started commented the page_top, page and page_bottom of my html.tpl.php to see where the problem was.

Turns out, with nothing in the html.tpl.php, (and I mean NOTHING), I still had the character.

I created a random "test.php" with simply an empty  and still had the problem. A similar "test.html" (HTML is the key here), it worked.

Someone had activated a "mod_deflate" in the .htaccess and it seemed to have issues with my version of PHP.

So there it is, hopefully it can help someone.

Thanks !


Correct way to add language switcher to a menu

It's not strange it's a question of order.
You use theme_preprocess_page and module_preprocess_page.
theme_preprocess_page runs first, this mean you save your menu before you change it.
Easy option would be, to add your theme_preprocess_page part to your module_preprocess_page.
(Set it outside of the if(drupal_multilingual()) {} and it run even if the if return false)
Better option would be to create a module for your mobile menu,
and set it's weight so it run after your other module.

EDIT: Ignore the Part about the order this https://www.drupal.org/node/223430  confussed me so i thought about template_preprocess_hook not the theme_preprocess_hook.
The Problem is your call, you think you add the switcher to the menu. But you just add temp items. On your call for mobile you get the original  Menu (so no lang switch).
You could fix it by adding the lang fix to the menu and not temp.
You could extend your module so you would get the new Menu for your vars.


How to send notification when node similar to flagged one is posted

You need to user RULES module to achieve this functionality. Drupal flag module has full integration with rules modules.

By creating a rule saying condition is "Node is flagged" add an action saying "Send email to author of node."


This is not an option at the moment in Drupal 8.
This option was removed in this issue
There is an issue for it.
They are trying to get it into ctools right now. ( 20-10-2016 )


How to exclude non-physical products from shipping calculations?

Do you have separate product types? Commerce Physical has a function that determines whether a line item is shippable: commerce_physical_line_item_shippable().

This function looks at the weight of an item. If the weight of the item is 0, then it considers it to be not-shippable.

You can also implement hook_commerce_physical_line_item_shippable_alter() and define your own logic to determine if something is shippable.

It looks like Commerce USPS implements this functionality and so you should be able to depend on this. Ideally, you'd have different product types for your physical and virtual products and your virtual products would have no weight causing them to not be factored into the shipping calculations.


Query arguments are available in $_GET. Drupal doesn't handle those query arguments for your menu callback; the only query argument Drupal automatically handles is $_GET['q'], which is the path for the requested page.

By default, $_REQUEST contains the contents of $_GET, $_POST and $_COOKIE. Drupal uses $_GET for the requested page path, and I would rather use $_GET also in this case, just to avoid possible conflicts.

In your case, those query arguments are accessible with $_GET['nid'], and $_GET['sid'].

If you define the menu handler with code similar to the following one, then your menu callback gets those values as arguments.

function event_menu() {
  $items["event/registration/failed/%/%"] = array(
    // …
    'page callback' => '_event_registration_failed',
    'page arguments' => array(3, 4),
  );

  return $items;
}

function _event_registration_failed($nid, $sid) {
  // …
}

You could get the node object, instead of the node ID, if you use the following code.

function event_menu() {
  $items["event/registration/failed/%node/%"] = array(
    // …
    'page callback' => '_event_registration_failed',
    'page arguments' => array(3, 4),
  );

  return $items;
}

function _event_registration_failed($node, $sid) {
  // …
}


What do I need to install to run Drush make?

Did you have a look at the INSTALL.txt file. The easiest is to put it inside .drush folder


Why is the View import option not shown in the views UI?

If the user you are logged in has the Administer Views
permission, if not then give this permission.
Also enable the 'PHP filter' core module.
Give the relevant user role the Use PHP for settings permission.
Paste the below url after your current url and you will see the
import views page.

admin/structure/views/import


Your URL is expecting an argument so your URL would have to be  http://mywebsite.com/example_callback/something. I wouldn't bother with the extra % in the path though.

So you should be doing something like and it will still pick up the arguments:

function example_module_menu() {
  $items = array();

  $items['example_callback'] = array(
    'title' => 'My Custom Callback',
    'page callback' => 'my_custom_php_function',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
 );

 return $items;
}

/**
* Function that gets called from JQuery asynchronously.
*/
function my_custom_php_function() {
  if (arg(1)) {
    // this means there is an argument
    // Do something with $argument...
  }
  return '';
}


Add javascript to multiple specific urls

The drupal_match_path() function should do the trick:

$path = drupal_get_path_alias();
$pattern = 'blog/*';

if (drupal_match_path($path, $pattern)) {
  drupal_add_js($theme_path . '/js/example.js');
}


qTips do not appear on content type create form

I found no solution why this was happening, so I had to switch to Form Tips which worked flawlessly along with some custom CSS theming.


You should be able to expose webforms results/submissions activating a complex (but effective) combination of Webform Mysql Views module, Data and Schema modules ...
as stated here for instance: https://www.drupal.org/node/1658784.
It works .. and you can just print your views results.

However, next time if I were you, would have assessed possibile alternatives to webforms.
Have you ever heard about Entity Forms Module?
It rocks, because it overcomes the above mentioned limitations, and also for other very good reasons, as mentioned here under:

Why Entityforms? The case for a Field and Entity based Survey System in Drupal
WHY ENTITY FORMS?


Display number of times content is referenced in content

This video series helped me an infinite amount: http://vimeo.com/33251051, http://vimeo.com/33252553.

Make sure Child has an entity reference to Parent.
Create a new view
In Filter Criteria, add a new Type (= Parent)
In Advanced>Other, set Aggregation to YES
In Advanced>Relationships, add a new relationship for "A bridge to the Content entity that is referencing Content via field_parent" where field_parent is your entity reference. Call this "Parents"
In Fields, add Content: Title and when prompted set its Aggregation type to Group results together
In Fields, add Field: Parents and when prompted set its Aggregation type to COUNT (Distinct)
Ta-da


There is no built-in way to do two-way encryption in Drupal, but there are two modules that will extend Drupal to support encryption:

Encrypt
AES

Encrypt:

Includes multiple encryption methods from simple to complex depending on libraries available on the server.
Focused on being a simple API that doesn't do much on its own.
Sub-module Field Encrypt let you use it to encrypt fields without coding (but beta only, no stable release of this one).
Uses CTools plugins for encryption methods and key providers.
Contains unit tests for all the features.
Stable Drupal 7 release, about 1400 installed sites.

AES:

Includes support for one encryption method (AES).
Built in functionality focused on two-way password encryption. Other uses requires coding by means of the API.
Requires use of the PHP extension mcrypt or the phpseclib (PHP Secure Communications Library) external library.
Has no built-in testing.
Stable Drupal 7 release, about 3000 installed sites.

You should be able to encrypt the entire site by using either of these modules and create a simple custom module that uses the hook system to encrypt content before it is stored in the datebase and decrypt as part of rendering content.

You may even do it without creating a custom module by means of Encrypt with sub-module Field Encrypt - if you find the beta-realese of the latter stable enough for your uses.

(PS: I can tell you how to restrict access as well, but that need to be a separate question).


How to change slider widget price range text and "Go" label in KickStart Commerce?

Below is a work around. See if it works :

Create a file custom_string_overrides.inc  inside your custom module folder and add the below code:

$conf['locale_custom_strings_en'][''] = array(
  'Go' => 'Add replacement here',
  'range from' => 'Add replacement here',
);

Add the below code to settings.php

include DRUPAL_ROOT . '/path-to-module/custom_string_overrides.inc';

The above trick does the string replacement and texts will be replaced where ever they appear. As I mentioned, this is just a workaround.


Custom editable, translatable email templates

Using Mail Editor you can add custom emails by going to admin/config/system/mail-edit

Did you try doing that?

Regarding translation at - /admin/config/regional/language/configure there is a 'Follow the user's language preference.' option.


Where do I make a feature request to drupal.org?

Generally speaking, the correct place to post feature requests for Drupal.org is the Drupal.org customization project issue queue.

However, you also wrote:

  FYI - I'd simply like to suggest that project owners have a tab for "roadmap" or "project Future".

If you just want to suggest that project owners publish a "roadmap", you can add that suggestion to the community documentation. It is a wiki so you don't request anything - you just do it (like I just did).

If you want to actually modify the project page layout by having a feature where project owner's may add an addtional tab for "Roadmap" to the page summary, you request this in the Project module's issue queue

Finally, I shall not suggest you use the Webmasters issue queue for any type of feature requests.  The Drupal.org webmasters issue queue is for reporting spam, broken links, or user account problems at Drupal.org - and that is about it.  My experience is that nothing much happens to feature requests posted there, even if the request just involves flipping a trivial setting in a module already installed. The webmasters obviously have the power to do this, but they do not make decisions about such things.  They usually move feature requests to the Drupal.org customization project, and bug reports to the Infrastructure project.


How do I update the body of a node using a query?

Load the node using node_load().
Set the body property of the node; examine the node object to determine which one the body property is. If you have the Devel module installed, kpr() will help you there.
Save the node using node_save().

This ensures that the hooks associated with updating a node get executed, and that the cache is properly cleared.


Approval required for all comments apart from on the forum

I know this is the reason advance forum modules recommends installing nodecomment.   You can select which content type's comments to be nodes.  Select Form topics.   In nodecomment content type select uncheck publish from the publish options.   Now every comment publish will be unpublish by default


field collection items are not in panels

I think the method depends on what you are trying to achieve by doing this.

You could write a plugin for panels to make it recognise field collections.
It looks like Fieldable Panels Panes might help.
You could use mini-panels to wrap the fields (part of panels)
You could just put the fields up individually

Hope this helps, without your intended use-case in your question it is difficult to provide a meaningful answer.


How to change property 'string' in object with class Drupal\Core\StringTranslation\TranslatableMarkup in my hook?

The object TranslatableMarkup is the result of t(). It's not possible to modify the content of this object. You overwrite the object with a new instance:

form['color']['#options']['All'] = t('All terms');


What's the class or id of the autocomplete suggestions pane?

The element's id attribute is autocomplete.


How to add a custom block on Print module?

You can do this by using Display Suite module. It allows you to add the block as a field in the "Manage display" tab of your content type. You can then place it wherever you want on your node page.

  Display Suite allows you to take full control over how your content is
  displayed using a drag and drop interface. Arrange your nodes, views,
  comments, user data etc. the way you want without having to work your
  way through dozens of template files. A predefined list of layouts (D7
  only) is available for even more drag and drop fun!


How can I display the time passed since a comment was created instead of the creation date?

Twig's date extension does exactly what you ask:

{{ created | time_diff }}

However, this extension isn't in Drupal by default, assuming you're using Composer you need to add this extension to your project by running:

composer require twig/extensions


how to develop multiple pages registration form

Try the Multi-Step Registration module

  With Multi-Step Registration you can create multi-step (wizard) user account registration forms. Each step of the wizard can be configured to, optionally, expose one ore more Profile2 types.

You can also achieve that by creating a custom module. Checkout this post and

Altering User Registration Form to Multi-Step Drupal 7


I just used drush to install on localhost and it solved all my problems.
At present my PHP Version 5.6.4-1, it works fine.


You can load all those nodes by nid with

node_load_multiple(array $nids = NULL, $reset = FALSE);

Loop over all nodes and then find and replace by using

str_replace('original link', 'new link', $node->field_you_want_to_change);

And then saving the node using

$node->save()


What worked for me was enabling and configuring the $cookie_domain variable in settings.php (because I have a site that can be accessed by 2 different domains).

Pay attention to the comment before this variable! The domain name must start with a period. EX:

$cookie_domain = '.example.com';

Good luck!


Nodes they have reference to the nodes of current user

I assume you already have the view. In it under 'Advanced' add a contextual filter on Content:Author:UID. When you configure the filter select 'Provide default value' under 'When the filter value is NOT available' and set the Type to 'User ID from currently logged in user'. This will limit the display to nodes the current user created.

EDIT:

Misunderstood. If you are trying to create a list if nodes which reference the current node (eg, view displayed as a block when the page is displayed) the method is the same. Create a view of the nodes, and a Contextual filter on the Node Reference field. The default value type should then be set to 'Content ID from URL'. This will limit the list to those nodes which refer to the current node.


How do I use message stack (or other) to send new blog post (nodes) to "email-only subscribers" like Wordpress?

There are three modules that support this type of subscription and notification workflow without requiring subscribers to actually be registered users on the Drupal site:

Simple Subscription https://www.drupal.org/project/simple_subscription
Total Subscription https://www.drupal.org/project/total_subscription
Simple News https://www.drupal.org/project/simplenews

Below are some notes and caveats to each module/approach:

Simple Subscription: the 7.x-1.x branch provides the basics, but hasn't seen much maintenance/activity since the move toward the 7.x-2.x alpha in 2016.  The alpha has some nice features and intent, but is also just an alpha release.  This module has token support and can work nicely with out of the box rules based messaging.
Total Subscription: This module does not offer to site managers any administrative functionality to unsubscribe email addresses or toggle on/off notifications for testing purposes. You'd have to enable/disable the module to toggle notifications (all or nothing) for any content types or taxonomies setup to publish subscription notifications.  Custom html email templates can be generated with the HTML Mail module, but templating only supports the default body/summary field and not any custom fields applied to the content type.  Messages are queued and sent via Drupalcron.
SimpleNews: This module is probably the most stable of the options and offers a D8 version; but it requires the extra step for content managers having to switch to the Newsletter tab and manually send the notifications after node creation.


Display the content of particular content type in side a block?

Install and enable the Views module.
Create a view with 'Block' display.
Filter by content type 'contact'. You can also choose sort options, etc.
Go to the Blocks administration page at Administration > Structure > Blocks.
Enable the Views block.


How to programmatically delete all values in custom CCK field for a given node?

Try to unset item

if (isset($node->field_received_email[0]['value'])) {
  foreach($node->field_received_email as $key => $value) {
    unset($node->field_received_email[$key]);
  }
}


EntityReferenceItem is more complicated than just the "entity" DataReferenceDefinition.

It has a DataReferenceDefinition for "target_id" as well.

I solved a similar issue by extending EntityReferenceItem.

Then you can get the entity from the parent definition, which is a bit long and complex and then just add your custom fields on top:

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);

    $properties['street'] = DataDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Title'));

    $properties['city'] = DataDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Title'));

    return $properties;
  }

Here's the code I used to add one text field to an EntityReferenceItem:

namespace Drupal\mymodule\Plugin\Field\FieldType;

use Drupal\Core\TypedData\DataDefinition;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Validation\Plugin\Validation\Constraint\AllowedValuesConstraint;
use Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem;
use Drupal\Component\Utility\Random;

/**
 * Defines the 'entity_reference' entity field type.
 *
 * Supported settings (below the definition's 'settings' key) are:
 * - target_type: The entity type to reference. Required.
 *
 * @FieldType(
 *   id = "entity_reference_with_title",
 *   label = @Translation("Entity reference with title"),
 *   description = @Translation("An entity field containing an entity reference and a text field."),
 *   category = @Translation("Custom"),
 *   default_widget = "entity_reference_with_title_autocomplete",
 *   default_formatter = "entity_reference_with_title_entity_view",
 *   list_class = "\Drupal\Core\Field\EntityReferenceFieldItemList",
 * )
 */
class EntityReferenceWithTitle extends EntityReferenceItem {

  /**
   * {@inheritdoc}
   */
  public static function defaultStorageSettings() {
    return array(
      'target_type' => \Drupal::moduleHandler()->moduleExists('node') ? 'node' : 'user',
      'title' => '',
    ) + parent::defaultStorageSettings();
  }

  /**
   * {@inheritdoc}
   */
  public static function defaultFieldSettings() {
    return array(
      'handler' => 'default',
      'handler_settings' => array(),
    ) + parent::defaultFieldSettings();
  }

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties = parent::propertyDefinitions($field_definition);

    $properties['title'] = DataDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Title'));

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public static function mainPropertyName() {
    return 'target_id';
  }

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {

    $schema = parent::schema($field_definition);

    $schema['columns'] = array(
      'title' => array(
        'type' => 'varchar',
        'length' => 255,
      ),
      'target_id' => $schema['columns']['target_id'],
    );

    return $schema;
  }

  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
    $constraints = FieldItemBase::getConstraints();
    // Remove the 'AllowedValuesConstraint' validation constraint because entity
    // reference fields already use the 'ValidReference' constraint.
    foreach ($constraints as $key => $constraint) {
      if ($constraint instanceof AllowedValuesConstraint) {
        unset($constraints[$key]);
      }
    }
    return $constraints;
  }

  /**
   * {@inheritdoc}
   */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $manager = \Drupal::service('plugin.manager.entity_reference_selection');
    if ($referenceable = $manager->getSelectionHandler($field_definition)->getReferenceableEntities()) {
      $random = new Random();
      $group = array_rand($referenceable);
      $values['target_id'] = array_rand($referenceable[$group]);
      $values['title'] = $random->sentences(2);
      return $values;
    }
  }

}


I started using Grunt.js by reading their easy to follow tutorial. Then, I created a Gruntfile.js inside of my theme’s js directory “sites/all/themes/mytheme/js/Gruntfile.js”:

  module.exports = function(grunt) {
    grunt.initConfig({
       pkg: grunt.file.readJSON('package.json'),
       concat: {
          main: {
             src: [
                'src/*.js',
             ],
             dest: 'production.js'
          }
       },
       uglify: {
          build: {
             files: {
                'production.min.js': 'production.js',
             }
          }
       },
       jshint: {
          files: ['Gruntfile.js', 'src/*.js'],
          options: {
             globals: {
                jQuery: true,
                console: true,
                module: true,
                document: true
             }
          }
       },
       watch: {
          files: ['src/*.js'],
          tasks: ['concat', 'jshint', 'uglify']
       }
    });

    grunt.loadNpmTasks('grunt-contrib-watch');
    grunt.loadNpmTasks('grunt-contrib-uglify');
    grunt.loadNpmTasks('grunt-contrib-concat');
    grunt.loadNpmTasks('grunt-contrib-jshint');
    grunt.loadNpmTasks('grunt-contrib-qunit');

    grunt.registerTask('test', ['concat', 'jshint']);
    grunt.registerTask('default', ['concat', 'jshint', 'uglify']);
  };

My Gruntfile does 3 things for me (right now):

Combines smaller, more manageable files inside src/ into one file.
Checks for errors in my compiled file.
Compresses my file when I’m ready for production.

All I have to do is run grunt watch from the terminal and whenever one of the files inside src/ is changed my production.js file is updated and compressed. When I’m all done debugging I just change the following in my .info file:

scripts[] = js/production[.min].js

This results in faster page loads because only one (smaller) request is being performed as opposed to many uncompressed file requests.


How to hide or remove field set on user profile page

You can hide, change weight of any form element by help of form_alter().

You will have to create a small module for it with any name like - myModule.

Put .info file in there & a .module file. Declare the information of the module. Enable the module.

Use my given hook & see what is available in form by DPM(You will need devel module to use this).

Write some thing like this

function myModule_form_alter(&$form, &$form_state, $form_id){
  dpm($form);
}

When you will visit the form you will get output of $form variable, where you can find $form_id to use to put in condition & the element which you are looking to remove or change properties.

Then you will have to put your logic in the function to have this working according to your need. Like see, how you can remove description from name/password field at login form --

function myModule_form_alter(&$form, &$form_state, $form_id){
  if($form['#id'] == 'user-login'){
    $form['name']['#description'] = t('');
    $form['pass']['#description'] = t('');
  }
}

This is not the exact solution you are looking for, but this is the way you can do it from yourself. I hope this help..


Try the Context module.

  Context allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.

  Think of conditions as a set of rules that are checked during page load to see what context is active. Any reactions that are associated with active contexts are then fired.


Retrieve / call facet blocks from non search page

The problem is, apachesolr_do_query checks if a query has already been made:

apachesolr.module line 1470 :

  // Verify if this query was already executed in the same page load
  if ($response = apachesolr_static_response_cache($searcher)) {
    // Return cached query object
    return array($query, $response);
  }

So, all you have to do to process multiple ApacheSolr queries is to reset the Drupal static variable like so:

drupal_static_reset('apachesolr_static_response_cache');


Date display differences in node templates

The proper thing to do here is to configure your field output to use the proper formatter.  On the Manage Display for your content type, eg admin/structure/types/manage/page/display, change the formatter for your field_event_start_date field to Custom, then click on the gear and change the format to 'g:ia'.  You should then be able to use {{ content.field_event_start_date }} in your template.

The standard Twig date() filter doesn't use the date.formatter service, so timezones and localization settings will not be honored.

TwigExtension defines a custom filter for Drupal that will call out to DateFormatter::format() called format_date().  This should work

{{ node.field_event_start_date.value|format_date("custom", "g:ia") }}

This apparently only works for Timestamp fields and not datetime or daterange fields.


How do you do a redirect after a batch job?

Apparently I needed to ask to see the answer: return a RedirectResponse from the finish callback:

public static function finished($success, $results, $operations) {
  if ($success) {
    // Here we do something meaningful with the results.
    $message = t("@count tasks were done.", array(
      '@count' => count($results),
    ));
    drupal_set_message($message);
  }

  return new RedirectResponse('/job/results');
}

As far as I can tell this is an undocumented behavior.

From the helpful comment below, you can also add batch_redirect on the batch array that's either a string or Url object:

$batch = [
  'title'    => $this->t('job running'),
  'init_message' => $this->t('starting job'),
  'operations'  => $ops,
  'finished' => '\Drupal\my_module\MyClass::finished',
  'batch_redirect' => '/job/results',
];


Uninstall module for which an update is pending?

Slight correction to Clive's comment above: as soon as you disable the module, it is inactive in the system tables. When you uninstall it, all of its data is erased from the database. The fact that a module has pending updates won't affect the operation of disabling or uninstalling it, but beware of re-enabling a module that has been disabled for a period of time.  For way too much information on this subject, see: https://drupal.org/node/1199946


Getting a specific value from form api in theme-settings.php

The way to really do this was to create variables in template.php using a preprocess function and take some of the logic out of page.tpl.php and to instead use the actual variables created. Based on this, my updated code that's working is:

template.php

function my_theme_preprocess_page(&$variables) {
 // create variables for each slideshow
  $variables['slideshow_alpha'] = (theme_get_setting('choose_slideshow') == 'alpha');
  $variables['slideshow_beta'] = (theme_get_setting('choose_slideshow') == 'beta');
}

... and then in page.tpl.php

 <?php if ($slideshow_alpha): ?>
    <?php require_once dirname(__FILE__) . '/slideshow_alpha.inc'; ?>
  <?php else: ?>
    <?php require_once dirname(__FILE__) . '/slideshow_beta.inc'; ?>
  <?php endif; ?>

It's important to note that what helped me figure much of the code updates out were running it through PAReview.sh. However, I did not want to set up the module and there is an online version which works great but your code needs to be in a git repo on drupal.org so you would have to set up a simple sandbox project to test your code. The online version is on ventral.org and it's what drupal.org uses to review projects. The new updated code also does not throw any errors with the code sniffer an the old code did.


First of all, blocks are stored in the Database, not in your web directory. Therefore, FTP is useless here.

If the custom block was created using a custom module, simply disable the module.

If the custom block was created using the Drupal User Interface, you can disable your custom block by changing the status from 1 to 0 or edit the block body by login in into your Database using PHPMyAdmin and finding the correct block table.


You could change the block title in your theme or module using the theme function or theme preprocess function.

For example:

/**
 * Implements hook_preprocess_facetapi_title
 */
function HOOK_preprocess_facetapi_title(&$variables) {
  $some_condition = TRUE;
  // If some condition
  if ($some_condition) {
    // Some title..
    $title = t('Custom title');
    // Set theme/template variable for title
    $variables['title'] = $title;
  }
}

See also: theme_facetapi_title


The correct way to override the theme function is:

/**
 * Implements hook_theme_registry_alter().
 */
function mymodule_theme_registry_alter(&$theme_registry) {
  $theme_registry['file_widget']['function'] = 'mymodule_file_widget';
}

function mymodule_file_widget($variables) {
 //your code
}


How to disable access to file page (view display mode = full)?

I have finally used the RABBIT HOLE module, it contains a sub-module for managing file_entity! :)


The best answer I could come up with was simply have a different node type that is automatically sticky / treated differently by views, which can then be set as a different price using either of the two modules I mentioned in my question.


FedEx Address Validation module setup help

Unless you desperately need those vars to be administered through the UI (in which case a small custom module would be the way to go), you can just add the variables through settings.php, using the following format:

$conf['fedex_address_validation_environment'] = 'test';
$conf['fedex_address_validation_live_key'] = 'foo';
$conf['fedex_address_validation_live_password'] = 'bar';
// etc...


What do I need to create a custom form widget?

You need to implement the "view hook":

/**
* Implements hook_field_formatter_view().
*/
function mymodule_field_widget_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
    $element = array();

    switch ($display['type']) {
    case 'custom_user_widget':
    $element[] = 'add here what you want to show';
    break;
    }
    return $element;
}


how can i add a subterm of taxonomy in code

Yeh~

i found out,this code can fix all the problem

$term->parent = $parent_tid;


Can I add a page without clearing cache?

It's not clearing the cache you should do, it's menu_rebuild(); if you change router items.


Add a 'Buy-it-Now' button to an ApacheSolr View

You can use one of the hooks provided by apache solr to alter your search results : hook_apachesolr_process_results

and you could append 'Buy it Now' button as well by using hook_theme()

Apache solr hooks


Are there any alternatives to drupal_add_js()?

drupal_add_js() allows inline code:

drupal_add_js($your_js, 'inline'):

You should however not rely on it too much. JS can be better cached by the browser (and aggregated with other JS) if delivered in a separate file.


It is pretty simple mate, here is an example:

field_url:
  plugin: iterator
  source: field_url
  process:
    uri: url
    title: title
    options: attributes

Because in D8 the field_url_url database field changed to field_url_uri and the attributes to options, you can not use direct mapping on this field.


Why does my D7 User view only display 6 results in Block View, but all results in Page view?

A good way to start understanding what happens is to turn on the Show the SQL query option  in the basic view settings under admin/structure/views/settings. You can then copy-paste the generated query into your database application and check if the query catches all expected results. If yes, then the problem most probably happens during the rendering of the results, maybe a custom views block template (check the theme overrides for the views display)? If no, then there is probably something wrong with the query itself, which could be either some kind of filtering, or maybe a contrib module that alters the query from code.


Drupal site that points to a non-drupal .html page

The issue is the path in question here must be a valid Drupal path, not a Unix path/filename.  I'd suggest investigating hook_menu() as a first step of learning about Drupal paths, callbacks and so forth.


How do I convert a render array to plain HTML?

ajax_prepare_response() contains the following code.

$html = is_string($page_callback_result) ? $page_callback_result : drupal_render($page_callback_result);
$commands[] = ajax_command_insert(NULL, $html);
// Add the status messages inside the new content's wrapper element, so that
// on subsequent Ajax requests, it is treated as old content.
$commands[] = ajax_command_prepend(NULL, theme('status_messages'));

So, to achieve the same (i.e. convert a render array into a HTML string), you can call drupal_render() passing the render array to the function.

 $render_array = array(
    '#items' => $items,
    '#theme' => 'item_list'
 );

 return ajax_command_html($elector, drupal_render($render_array));

Also theme() would return a HTML string, and you could as well use the following code.

 return ajax_command_html($elector, theme('item_list', array('items' => $items)));

Since Drupal 8 doesn't have the theme() function anymore, I would use drupal_render() just to make easier to convert Drupal 7 code to Drupal 8.

Keep in mind that drupal_render() is expecting an array; in the case you are calling it from a function that could receive a string as argument, you need to verify you are passing an array to drupal_render(), as the code I shown does.


How do I add a custom validation handler to an existing form/field?

Berdir gave the correct answer, that a constraint is the correct way to go about adding validation to a field in Drupal 8. Here is an example.

In the example below, I will be working with a node of type podcast, that has the single value field field_podcast_duration. The value for this field needs to be formatted as HH:MM:SS (hours, minutes and seconds).

To create a constraint, two classes need to be added. The first is the constraint definition, and the second is the constraint validator. Both of these are plugins, in the namespace of Drupal\[MODULENAME]\Plugin\Validation\Constraint.

First, the constraint definition. Note that the plugin ID is given as 'PodcastDuration', in the annotation (comment) of the class. This will be used further down.

namespace Drupal\[MODULENAME]\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;

/**
 * Checks that the submitted duration is of the format HH:MM:SS
 *
 * @Constraint(
 *   id = "PodcastDuration",
 *   label = @Translation("Podcast Duration", context = "Validation"),
 * )
 */
class PodcastDurationConstraint extends Constraint {

  // The message that will be shown if the format is incorrect.
  public $incorrectDurationFormat = 'The duration must be in the format HH:MM:SS or HHH:MM:SS. You provided %duration';
}

Next, we need to provide the constraint validator. This name of this class will be the class name from above, with Validator appended to it:

namespace Drupal\[MODULENAME]\Plugin\Validation\Constraint;

use Symfony\Component\Validator\Constraint;
use Symfony\Component\Validator\ConstraintValidator;

/**
 * Validates the PodcastDuration constraint.
 */
class PodcastDurationConstraintValidator extends ConstraintValidator {

  /**
   * {@inheritdoc}
   */
  public function validate($items, Constraint $constraint) {
    // This is a single-item field so we only need to
    // validate the first item
    $item = $items->first();

    // Check that the value is in the format HH:MM:SS
    if ($item && !preg_match('/^[0-9]{1,2}:[0-5]{1}[0-9]{1}:[0-5]{1}[0-9]{1}$/', $item->value)) {
      // The value is an incorrect format, so we set a 'violation'
      // aka error. The key we use for the constraint is the key
      // we set in the constraint, in this case $incorrectDurationFormat.
      $this->context->addViolation($constraint->incorrectDurationFormat, ['%duration' => $item->value]);
    }
  }
}

Finally, we need to tell Drupal to use our constraint on field_podcast_duration on the podcast node type. We do this in hook_entity_bundle_field_info_alter():

use Drupal\Core\Entity\EntityTypeInterface;

function HOOK_entity_bundle_field_info_alter(&$fields, EntityTypeInterface $entity_type, $bundle) {
  if (!empty($fields['field_podcast_duration'])) {
    $fields['field_podcast_duration']->addConstraint('PodcastDuration');
  }
}


When you load a node, you should always check if it exists (is not null) before calling a method:

$node = node_revision_load(59);
if ($node) {
  $node->set('publish_on', null);
  $node->save();
}

But this is not the cause for the memory error. This is more likely a recursive thing. For example you are saving again and again until the memory is filled up.


If you want somewhere to host modules you could use distributed version control such as Git or Mercurial to store them in a repository.

You can then use drush make to build the site with modules hosted on drupal.org and from your repository.


Content tab takes a very long time to load

I am not exactly sure if it is the best solution but it works for me.
I changed default nodes view to use GROUP BY (without any aggregation function) instead of DISTINCT and it works 40 times faster in my case.


This is kind of a crappy answer, but the fix was to switch to using ImageMagick. I still don't know what was wrong with GD.


How to auto purge old unapproved comments?

I'm not sure if there is a module which does that. However, you could do that with the help of some custom coding inside hook_cron:

function MODULE_cron() {
  // Find out the comment ids of the comments that are unpublished
  // and are older than 30 days.
  $comments = db_query('SELECT cid FROM {comment} WHERE status = :status AND created < :created', array(':status' => 1, ':created' => strtotime('today - 30days')))->fetchAll();
  $cids = array();
  foreach($comments as $comment) {
    $cids[] = $comment->cid;
  }
  comment_delete_multiple($cids);
}

You can change the time to fit your requirements. This will ensure that on cron run the comments which are older than 30 days and are still unpublished get deleted.


URL variable not respected when ajax call happens in user registration form

The AJAX callback shouldn't alter the form (that should be handled by the form constructor or a form alter). This tends to be a good thing, because it forces you to put all your form logic in form functions, and that means they can degrade gracefully if JS isn't available. When dealing with AJAX forms, the callback typically just decides what part of the form to return. Take a look at the example from the examples module:

/**
 * Basic AJAX callback example.
 *
 * Simple form whose ajax-enabled 'changethis' member causes a text change
 * in the description of the 'replace_textfield' member.
 *
 * See @link http://drupal.org/node/262422 Form API Tutorial @endlink
 */
function ajax_example_simplest($form, &$form_state) {
  $form = array();
  $form['changethis'] = array(
    '#title' => t("Choose something and explain why"),
    '#type' => 'select',
    '#options' => array(
      'one' => 'one',
      'two' => 'two',
      'three' => 'three',
    ),
    '#ajax' => array(
      // #ajax has two required keys: callback and wrapper.
      // 'callback' is a function that will be called when this element changes.
      'callback' => 'ajax_example_simplest_callback',
      // 'wrapper' is the HTML id of the page element that will be replaced.
      'wrapper' => 'replace_textfield_div',
      // There are also several optional keys - see ajax_example_autocheckboxes
      // below for details on 'method', 'effect' and 'speed' and
      // ajax_example_dependent_dropdown for 'event'.
    ),
  );

  // This entire form element will be replaced whenever 'changethis' is updated.
  $form['replace_textfield'] = array(
    '#type' => 'textfield',
    '#title' => t("Why"),
    // The prefix/suffix provide the div that we're replacing, named by
    // #ajax['wrapper'] above.
    '#prefix' => '
',
    '#suffix' => '
',
  );

  // An AJAX request calls the form builder function for every change.
  // We can change how we build the form based on $form_state.
  if (!empty($form_state['values']['changethis'])) {
    $form['replace_textfield']['#description'] = t("Say why you chose '@value'", array('@value' => $form_state['values']['changethis']));
  }
  return $form;
}

/**
 * Callback for ajax_example_simplest.
 *
 * On an ajax submit, the form builder function is called again, then the $form
 * and $form_state are passed to this callback function so it can select which
 * portion of the form to send on to the client.
 *
 * @return array
 *   Renderable array (the textfield element)
 */
function ajax_example_simplest_callback($form, $form_state) {
  // The form has already been submitted and updated. We can return the replaced
  // item as it is.
  return $form['replace_textfield'];
}

Note how the dynamic change of the form happens in the form constructor while the callback is minimal.


Best way for including javascript/jQuery OnLoad in EVERY page on my site

Please read Managing JavaScript in Drupal, specifically the section on Behaviors. You'll need to do something like this:

(function ($) {

  Drupal.behaviors.exampleModule = {
    attach: function(context, settings) {
      var bgs=["bg1.jpg", "bg2.jpg"];
      var bgr=Math.floor(bgs.length * Math.random());
      $.backstretch(bgs[bgr], { speed: 1000 });
    }
  };

})(jQuery);


Render array only working with numeric keys

The return value of FormatterInterface::viewElements is defined as:

  Return value

  array A renderable array for $items, as an array of child elements keyed by consecutive numeric indexes starting from 0.

The theming layer can't handle other arrays for field values, see  How to print all values of a multi-value field, except the first?


How to restrict access to view a block for a certain role?

Visibility Block base on the Role is built-in Drupal 8 feature.

go to admin/structure/block and click on your desire block configure button

then in Visibility section, there is Role that you can define for which role your module  show , or not to show.


Is there potential performance loss by using multiple nodeapi calls instead of one?

There is a performance loss with additional modules. Mostly due to more opening parsing and function_exists() and memory use.

Node api in 6 will be called for every node action and called for each node. (in 7 multiple nodes can be used at once and there is a separate hook for each action)

So if you are careful:

Put all your code inside a switch($op);
Check the content types to work on what you need
Keep DB queries to a minimum

there will be little overhead (some but not overwhelming).

If on the other hand your nodapi call, share DB queries (or can share DB queries), have a lot of setup / code which is common, then you may start to be hurting yourself performance wize.

One way round this is to be a bit more selective with the code you include:

mymodule_nodeapi($op, ...) {
 switch($op) {
  case 'load':
    // Insert common code here.
    if ($node->type == 'my_complex_node_type') {
      module_load_include('inc', 'mymodule', 'complex_type');
      mymodule_complex_load($node);
    elseif ($node->type == 'some_other_node_type') {
      module_load_include('inc', 'mymodule', 'other_type');
      mymodule_other_load($node);
    }
  break;
 }
}

Rough pseudo code

You can keep your code in seperate files to aid maintainability and keep load time down as files are only included/parsed when needed.

The downside is you need to manage the include and callback yourself rather than relying on module_invoke_all.