Try the SMTP module to send mails via SMTP:

  This module allows Drupal to bypass the PHP mail() function and send email directly to an SMTP server. The module supports SMTP authentication and can even connect to servers using SSL if supported by PHP.


I mount the remote drive locally using 'Transmit' so I can use my local dev stack (sublime, livereload, sass, compass etc...). This does not always play nicely with file permissions and kinda urks some of the devs who are used to working locally then to git and staging servers for testing. I just backup alot and like to fly by the seat of my pants on the live server... although I feel i should be working git in there more!


How to provide pagename.tpl.php to specific page?

copy this code to template.php (donot forget to change the yourtheme name)

function yourtheme_preprocess_page(&$vars) {
  // Do we have a node?
  if (isset($vars['node'])) {

    // Ref suggestions cuz it's stupid long.
    $suggests = &$vars['theme_hook_suggestions'];

    // Get path arguments.
    $args = arg();
    // Remove first argument of "node".
    unset($args[0]);

    // Set type.
    $type = "page__type_{$vars['node']->type}";

    // Bring it all together.
    $suggests = array_merge(
      $suggests,
      array($type),
      theme_get_suggestions($args, $type)
    );

    // if the url is: 'http://domain.com/node/123/edit'
    // and node type is 'blog'..
    //
    // This will be the suggestions:
    //
    // - page__node
    // - page__node__%
    // - page__node__123
    // - page__node__edit
    // - page__type_blog
    // - page__type_blog__%
    // - page__type_blog__123
    // - page__type_blog__edit
    //
    // Which connects to these templates:
    //
    // - page--node.tpl.php
    // - page--node--%.tpl.php
    // - page--node--123.tpl.php
    // - page--node--edit.tpl.php
    // - page--type-blog.tpl.php          << this is what you want.
    // - page--type-blog--%.tpl.php
    // - page--type-blog--123.tpl.php
    // - page--type-blog--edit.tpl.php
    //
    // Latter items take precedence.
  }
}

all examples are inside the comment which format you should follow in side the template folder for creating tpl.php '%' is use for all, best of luck,
note : don't forget to clear the cache
you can use devel_themer module for specific suggestions of tpl's.


Different Status Message templates for different pages

Here is an example adding routename to status messages' templates suggestions (you may also add some parameters or whatever you need)

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function HOOK_theme_suggestions_status_messages_alter(array &$suggestions, array $variables) {
  $route = \Drupal::routeMatch();
  $suggestions[] = 'status_messages__'.str_replace('.','_', $route->getRouteName());
}

This way you can have status-messages--[routename].html.twig as a template, and if this file not exists, have a fallback to status-messages.html.twig


When adding Content: has taxonomy term id contextual filter to view and check specify validation criteria box, why don't I see validation options?

Duh, in case anyone else runs in to this problem:

This really boiled down to after adding a contextual filter, if I clicked any of the checkboxes under the heading "When the filter value IS in the URL or a default is provided":

Override title
Override breadcrumb
Specify validation criteria

I did not see any of the options for any of those checkboxes appear after checking it.

Turns out I didn't have the most up to date version of the chaos tools module.

When I updated to chaos tools 7.x-1.3 (sometimes referred to as ctools) problem fixed.


This should already be happening. Which version of Views?

If, as you said, the headlines ARE the values of the select list, then they should be showing up above each group automatically.

In Views 3:
Under Fields, add the select_list_field and check "Exclude from display"
Under Style settings (unformatted), choose Grouping Field: select_list_field

It will group by the select list item, and display that select list item's name (ie, the headline) above the group.


CCK nodereference is returning empty nid when no node is selected

You are looking at a node in CCK's post build_content() phase.  When you add a node reference field to a node, CCK adds the 'nid' portion to the database, and when you build or display the content, it creates the 'safe' and 'view' portions.  If you were doing this manually, you could do something like:

$foo=node_load(27);

and if $foo had a nodereference, $foo would contain

[field_my_node_reference] => Array
(
    [0] => Array
        (
           [nid] =>
        )
)

eg, you could print 'my nid is ' . $foo->field_my_node_reference[0]['nid'];'

and it would print out my nid is [blank] if unset, or my nid is 593 if set.  Now,
when CCK comes in and gets all fancy, it creates the safe and view pieces, and these are set up by those widgets you select in the display fields portion of CCK before getting to node.tpl.  (You can do this yourself by calling $foo=build_content($foo); in a module and looking at $foo again.)  Anyways, CCK works all of that up into the $content variable it aggregates things together into for your node.tpl as well as in the $node variable it has in there if you yourself want to get fancier, eg, print 'this is a link to my node: ' . $node->field_my_node_reference[0]['view'] would normally print out 'this is a link to my node:' followed by the title of the node linked to it.  All changeable via those display options/widgets.

But as to why it has empty keys, they are just part of the data structure created to ensure everything up and down the workflow works together as well as it does, eg, the safe and view portions are blanks where a link would probably go if the field was set, so that makes sense.  And a NULL is in nid since it hasn't been set.

But...just plop in some content and you will see everything fill up all nice :)


What is the alternative to file_unmanaged_save_data()?

Drupal always documents all the methods using ::, so you need to look closer as to whether the method is static or not.
So if you look at FileSystem::saveData

Its public and not a static. Therefore using ::saveData() is incorrect, needs to be called with the arrow ->saveData()
Also, as pointed out, you need to call it with a class that implements the FileSystemInterface.


Is it possible to restore a deleted node?

If you have a database backup (which you should ;) you can restore an old copy of the site and retrieve it that way.

Drupal does give users quite a clear warning that deleting a node is final, and there is a confirmation dialog.


Submitting a form with only a text field

Yes, for basic forms you need to include a submit button for the submit function to be called.

Read more about the Form API for Drupal 7


Is there a way to run a shell script on a custom cron?

I believe you can edit the crontab or by talking to hosting provider you will be able to edit the crontab file.

In case, if you have to do it in custom module using Elysia Cron API, I assume you can do it following way :

function example_cronapi($op, $job = NULL) {
  $items['example_shell_cron'] = array(
    'description' => 'Send mail with news',
    'rule' => '0 */4 * * *', // Every 4 hours
  );
  return $items;
}

function example_shell_cron() {
  shell_exec ('wget --quiet http://www.example.com/custom-sitemap.xml --output-document - |
egrep -o "http://www.example.com/[^<]+" | wget --delete-after -i -');
}


For D7, you will need to use a contrib module.

https://www.drupal.org/project/wfm
https://www.drupal.org/project/webform_addmore

For D8, you can use a 'Custom composite' element.


Show contact form in a pop-up window with Bootstrap classes

Bootstrap and Ajax are two different methods for modal dialogs.

If you want to open a popup with Bootstrap this would be client side. This means you deliver the form embedded in the page as a block and hide it by wrapping it in a Bootstrap modal container:

https://v4-alpha.getbootstrap.com/components/modal/

If you want to load a modal with Drupal Ajax, then use the link you've provided in the question, but target the url of the form, not that of the frontpage:

Open form

For this to work you have to attach a js library:

$build['#attached']['library'][] = 'core/drupal.dialog.ajax';

  And why is the modal window not working for anonyms?

It works for logged in users without attaching the library, because core code is doing this already for the admin dialogs.


How to create a view displaying fields only from block it was created in (Custom Blocks Types + Paragraphs)

To start, I cannot think of any benefits for creating a block type to act as a container element for slideshows. Especially since you will be using views to create the slideshow. If you like, please write in a comment why you felt it was a good idea. IMO content types make more sense.

The main cause of your problem is probably a misunderstanding of what is happening. A paragraph field on a drupal entity (block, node, whatever) is a one to many relationship. Every paragraph you add to the field will be a separate entity with its own id. If you have a contextual filter on the paragraph id, it does make sense that Drupal only loads one slide. You instruct it to load one id. (In fact I am surprised that you somehow managed to show more).

Normally you would add the reverse relationship (from paragraph item to container entity) and then use a contextual filter on the container entity: I would create a slideshow of paragraph items, add a relationship to the node and then use a contextual filter on node id. Then if I filter on node id 1, I would see all paragraph items linked to node 1.

Since you are now dealing with a block, I think you might be able to build a similar construction (relationship to the block and contextual filter on block id?) But I encourage you to reconsider.


Replacing an existing image via the admin interface

If the image is referenced via a template, there is no (easy) way to replace it via the CMS.  You will need access to the file system, like FTP access.

Otherwise, you could look at finding or writing a module that gave you full access to the filesystem via the Drupal CMS.  This would be.. difficult and dangerous.


I recommend trying to use Ctools Automodal module. It's really easy to use just look at the project page:

  Provides automatic modal support for any hook_menu() paths that have
  'modal' => TRUE defined. This makes it easy to add optional modal
  support in any contrib module and helps reduce the burden on module
  developers to support modals.

  Example Usage

<?php
function mymodule_menu() {
  $items['mymodule/form'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_form'),
    'access arguments' => array('administer mymodule'),
    'modal' => TRUE, // This line is where the magic happens.
  );
}
?>


Drupal 7.14 - grouping site links on search engines

These are generated by google, not by any module inside of drupal.  googling 'sitelinks' will show you more information about how google creates them for popular sites.

http://support.google.com/webmasters/bin/answer.py?hl=en&answer=47334 from google is a good start.


Inorder to remove Simple newsletter completely. You need to disable and uninstall the module.

Follow the steps

Go to Modules list (admin/modules) and uncheck simplenews letter to disable and click 'Save Configuration' to disable the module
Then Go to admin/modules/uninstall page and select/check the simplenews letter module and click 'Uninstall' to remove all data related to Simplenews letter module from your instance.


From your question, I'm assuming that you've already created view and set everything.

You just need to do some Format settings for Views Accordion in your View.

Here are the steps to make your grouping field as the "header" or "trigger" of the accordion action.

Go to  Format: Views Accordion Settings and select Grouping field.
Check "Use the group header as the Accordion header"

I've tested it myself. It works as you expected.


Module development - Layout of dynamic content

Some pointers:

Try getting the data in your database somehow. You could import the data into nodes or you could use the Entity API. That way, you could expose your data to modules such as Views. The only thing you'll need to do left is to synchronize the data in your database with the XML data that you're receiving.


Directly adding data in MYSQL tables made through drupal

Not sure but could you design your view fields [name, address, country] the way you want to use them. Then enter unique data.

Then look in the DB for the unique data to be sure you have the right fields.

After backup and site shut down you could import your csv right into mysql. With the db interface. Make sure you backup The tables before starting.

A bigger question perhaps is how will you work with the data.


Custom form with multiple textarea fields

There is no property in Drupal's Form API to create multi value fields. You have to create that functionality manually. Check this tutorial.

[Edit] the tutorial seems to have a couple errors (e.g. the values entered in names are not inherited as default_value when the form is rebuilt when adding a field). But it can give you a general idea on how do this.


views exposed filter: Prevent a user from searching default Paceholder Text

@Bala You actually pointed me in the right direction by mentioning "placeholder", I have also added that word to the question, Thanks for the help, so i did more research since i wanted to avoid enabling 2 modules because of only one exposed filter (i have many modules enabled already), so adding this code to my theme's template.php file as per this comment worked perfectly for me:

<?php
function yourtheme_form_alter(&$form, &$form_state, $form_id){
  if($form_id == "views_exposed_form"){
    if (isset($form['combine'])) {
            $form['combine']['#attributes'] = array('placeholder' => array(t('Find Professionals')));
    }
  }
}
?>

For benefit of novices, "yourtheme" in the function should be replaced with the name of your theme, 'combine' is the name of my exposed filter (You Can find yours by right-clicking the form on firefox or google chrome and clicking "inspect element").

This solution works for drupal 7


Implementing hook_field_group_pre_render_alter() seems the way to go, it's called just after field_group_field_group_pre_render() which calls field_group_pre_render_accordion_item() and receives the correct info.

It should be like this:

function mymodule_field_group_pre_render_alter(&$element, $group, &$form) {
  if ($group->format_type == 'accordion_item') {
    $element['#prefix'] = '
format_type . ($group->collapsed ? '' : ' field-group-accordion-active') . '">' . check_plain(t($group->label)) . '

classes . '">';
    if (!empty($group->description)) {
      $element['#prefix'] .= '
' . $group->description . '
';
    }
  }
}

Remember to implement it in a module, as a hook_*_alter() implemented in a front-end theme may not be discovered while flushing cache via drush or in the back-end theme.


Arguments in url break other view on same page

Turns out. If you have a view page with a pager and another view block with a pager on the same page, they conflict.


As long as you're not skipping major Drupal versions (i.e. going from Drupal 5.x to Drupal 7.x), just jump to the new version(s).


Selling art with Drupal Commerce - how to approach?

Products you sell are not nodes in Drupal commerce, but are their own entity where you can define product related stuff, like SKU, price etc.

You probably will need two product types, one for originals and one for reproductions.

You will need to create a product reference field on a node or something else in order to display the add to cart form along with product details, this can be done on your work of art content type.

In order to select size, the easiest solution will be to create on product per size, then reference all of them and commerce will do the rest.


Entity Reference. Hide not user referenced terms in node form?

I solved this task with my module:
This code limit radiobuttons of field_firm on the node addition page with only those terms that have entity reference to current user. Admin have access to all. If user has no one term access field Firms hides.

/* BASE_FORM_ID : node_form */
/* Displays only terms that have Entity Reference field with current user reference */
//$form['field_firm']['und'][1551]= array('#access' => FALSE); //hides taxonomy term 1551

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

  global $user;
  //if current user has roles administrator or editor return
  foreach ($user->roles as $role) {
      if (($role == 'administrator') || ($role == 'editor')) return;
  }
  if (isset($form['field_firm'])) {
    $query = new EntityFieldQuery();
    $term_entities = $query
      ->entityCondition('bundle', 'firms')
      ->entityCondition('entity_type', 'taxonomy_term', '=')
      ->fieldCondition('field_seller','target_id',$user->uid) // if user has access
      ->execute();
    if ($term_entities) {
        //forming array of firms using $term_entities array
         $items = array_keys($term_entities['taxonomy_term']);
         foreach ($form['field_firm']['und']['#options'] as $key=>$value) {
             if ($key == '_none') continue;
             $delete=true;
             for ($i=0;$i<count($items);$i++) {
                 if ($key == $items[$i])  $delete = FALSE;
             }
             if ($delete) $form['field_firm']['und'][$key]= array('#access' => FALSE);
         }
    }else {
        //hide field firm if user has no access to any term
        $form['field_firm']['#access'] = FALSE;
    }
  }
}


Retrieve the list of posts for a particular forum

To get all posts (forum topics) for a particular forum with id=4:

curl -i -X POST \
  -H Cookie:SESSe6a3baadbeef=ovQpO6aYeehaw_3W4onya22i9bonusQW \
  -H X-CSRF-Token:v6j7r9RactujA872hSHSKW-mYYWAA \
  -H Accept:application/json \
  -H Content-Type:application/json \
  http://myserver/rest/taxonomy_term/selectNodes \
  -d '{"tid":4}'

To find the mapping between forums and tids, refer to this answer.

I don't know how to do a parameterized query (GET) to retrieve forum topics. As far as I can tell you need to use POST, as described here.


drupal_add_js causes blocks to be executed twice

I finally discovered two circumstances when blocks are executed twice:

First is adding a missing javascript file, either in theme.info file or in theme_preprocess_page() function using drupal_add_js.

Second is by adding a broken url(..) image reference in a css file which is actually used on the page.

Here are the steps to recreate the problem with css, for javascript it's analogously:

install Drupal (it has Bartik theme as default) and log in, to see
the search box
in a debugger, set a breakpoint inside function search_block_view()
refresh the page and check that the breakpoint is reached once
go to /themes/bartik/css/styles.css line 1467 and change the line containing:

background: url(../images/search-button.png)

into something that does not exist:

background: url(../images/search-button1.png)

refresh the page with shift and check that the breakpoint is reached
twice

Maybe such behavior is obvious for someone more advanced and has rational explanation, but for me it is not obvious and took me a while to discover. Anyway the conclusion is just to make sure that all loaded css and javascript resources are available and nothing is missing, otherwise blocks will be silently executed twice and depending what they contain, the page may load longer.


Make search block appear for anonymous user

There is one more permission need to set at admin/people/permissions. Under Search give  'Use search ' permission for anonymous user


Associating Multiple Date/Location Pairs to Node

I was able to solve this by adding a relationship in the Views setup.  Now, I have access to all the fields of the host entity.


I had this issue when I was testing out this module as well.

Solution: Create an Alias for each piece of content.

Each node/page you want to include on the single page, visit and add the alias. As admin, visit say, your default page you wish to have at the top, click Edit, and create the alias. In MY experience, once I did this for the pages for the Single Page using the single_page module, it worked.


What is the purpose of the "Links" field in the "Manage Display" UI?

The Links section is used normally in Teaser section/display to display links like add comment, read more, etc.

On Node Full Display, it is depending on configurations we do. Such as "Add new comment" link will only be visible when we disable "Show reply form on the same page as comments" check-box in comment field settings. You can also give a try to Flag Module or other contributed modules which adds links on Node display.

Please check screenshot below (Teaser Display):

The above screenshot is of default Teaser Display of node type article, which is being displayed on site home page. When we hide Links from teaser display, these links are no more visible in node teaser.

Following screenshot shows links working in Node Full Display:
Depending on configuration we do in comment field (check screenshot below), comment link will be visible on Full Display.

Comment link visible, when checkbox is disabled.

Comment link is not visible, when checkbox is enabled.


What to do about an 'illegal Choice' error in views?

'An illegal choice has been detected. Please contact the site
  administrator. '

This type of issue generally arises when, for example, you have 2-3 select list, select list 'second' is dependent on 'first' select list. Now if you get empty result (say) in your first select list, second select list will not get populated correctly and throw this type of exceptions.

This is just an example so that you might get an idea, the sequence of selecting values is not right.

Try the whole procedure again, and this message will get disappeared.


Modifying login/user panel position in a theme

The user login form is a core block you can position. The other bit you'll have to write in a custom module as a custom block. The menu links part should be a menu block.


configuring drupal to use unicode characters

After further investigation: "" and other characters beyond the Basic Multilingual Plane need to be stored in a database set up with the "utf8mb4" charset.  The general configuration steps are very nicely described here:

http://mathiasbynens.be/notes/mysql-utf8mb4

In addition to updating MySQL to 5.5.28, and doing the basic tweaks outlined in that link, in order to get this working with Drupal, I needed to take some further steps:

Replace SET NAMES utf8 with SET NAMES utf8mb4 in includes/database/mysql/database.inc
Modify settings.php to include the following

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'DB',
      'username' => 'UN',
      'password' => 'PW',
      'collation' => 'utf8mb4_general_ci',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
      'pdo' => array(
                     PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8mb4",
                     )
    ),
  ),
);

And modify the table and column (per the page linked to above) where the fancy UTF8 characters are to be stored:

ALTER TABLE tn CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
ALTER TABLE tn CHANGE cn cn longtext CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;


How display node author roles at node.html.twig

You can get roles in twig using:

{%  for role in node.Owner.roles %}
    {{ role.entity.label }}
{% endfor %}

Update :
If you want to use roles in classes i recommended you to use clean_class filter to get the clean css class from roles instead of the code you post in comment use this:

   {% set custom_classes = [] %}
    {% for role in node.Owner.roles %}
      {% set class_role = role.entity.label | clean_class %}
      {% set custom_classes = custom_classes | merge([class_role]) %}
    {% endfor %}
    <div {{ attributes.addClass(custom_classes) }}>
      {{ content }}
    </div>


Need help Converting a jQuery event to a Drupal Behavior

Alter don't show because in your code:

jQuery('.tab-pane').bind('fadeIn', function() {
             alert('fadeIn Done.');
        });

this function mean that when selecter .tab-pane fadeIn done, alert will show. But You don't call fadeIn => don't have event fadeIn. You need call that same:

jQuery('.tab-pane').fadeIn(2000);

And better function jQuery.fn.fadeIn need outside Drupal.behaviors.fadeInEvent

(function ($) {
    var _old = $.fn.fadeIn;
    $.fn.fadeIn = function(){
        var self = this;
        _old.apply(this,arguments).promise().done(function(){
            self.trigger("fadeIn");
        });
    };

    Drupal.behaviors.fadeInEvent= {
        attach: function (context, settings) {

            $('.tab-pane').bind('fadeIn', function() {
                alert('fadeIn Done.');
            });
            $('.tab-pane').hide();
            $('.tab-pane').fadeIn(2000);
        }
    };
})(jQuery);

then you call fadeIn() every where and have event fadeIn.


So, though a bit of experimentation I found that the language

  "Allows control over where within the page's DOM structure the
  minipanel will be inserted. This defaults to $(document.body), i.e. at
  the end of the page's content."

Was what confused me - it turns out that just by adding a standard css selector to that field moved the menu.


How to print a view in node.tpl.php only if it's not empty

You can check it using the below code

<?php
$viewName = 'myview';
$displayid = 'block_1';

$view = views_get_view($viewName,$displayid);
$view->execute();
$reviewCount = count($view->result); //It will return number of results
if($reviewCount>0){
print views_embed_view($viewName,$displayid);
}
?>

Hope it will help.


Custom PHP code as a Panels selection rule

I think the calling function which executes your PHP code would expect the RETURN true/false statement. Thus, you would need return to the calling function as returned by the called function.

return mymodule_selection_rule_is_location_set();

If you don't have return, the calling function would expect NULL and it would execute as FALSE always regardless of what is returned by the called function.


Why is there a  tag where I didn't add it?

For not getting the paragraph tags, you need to use an input format that does not include the Lines and paragraphs break automatically setting.

Check to see if Convert line breaks into HTML input format is enabled in admin/config/content/formats/full_html, and disable it. You can still add <p> and <br>, but Drupal will not add them automatically for every line break present in the text.


Prices are always going to be rounded when saved unless you've updated the definition of the currency itself to support storage to the 5th decimal place. It sounds like that module is simply offering part of the solution, while the whole solution will involve hooking into the currency info array and then updating whatever prices you've already entered to be saved with the new precision.


The HTML in the title is escaped because template_preprocess_page() gets the title using the following code:

// Construct page title
  if (drupal_get_title()) {
    $head_title = array(strip_tags(drupal_get_title()), variable_get('site_name', 'Drupal'));
  }

drupal_get_title() then contains the following code:

function drupal_get_title() {
  $title = drupal_set_title();

  // during a bootstrap, menu.inc is not included and thus we cannot provide a title
  if (!isset($title) && function_exists('menu_get_active_title')) {
    $title = check_plain(menu_get_active_title());
  }

  return $title;
}

The title is escaped from that function.

As far as I know, the content of <title> should not contain HTML tags; that is the reason it is escaped.

In the W3C specifications for HTML 4 is reported the following text:

  Titles may contain character entities (for accented characters, special characters, etc.), but may not contain other markup (including comments). Here is a sample document title:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">
<HTML>
<HEAD>
<TITLE>A study of population dynamics</TITLE>
<!-- other head elements -->
</HEAD>
<BODY>
<!-- document body -->
</BODY>
</HTML>

In Changed Elements it's not reported any changes between HTML 5 and HTML 4 about the <title> tag.

In Drupal 7, you could set the title with drupal_set_title($title, PASS_THROUGH), but the documentation says:

  Only set to PASS_THROUGH if you have already removed any possibly dangerous code from $title using a function like check_plain() or filter_xss(). With this flag the string will be passed through unchanged.

PASS_THROUGH is used to avoid the title is filtered twice, not to filter the title at all.

Then, using drupal_set_title() is not possible from the title callback; you should set it in a different place. I would not suggest doing so, though.


webform add more module does not show add more button

It seems the module has no good support and does not work properly with latest versions of webform I think both 3 and 4 versions

Here is the issue that describes the problem you are having and I am posting this as a solution as there is numerous workarounds there that might give you a solution and some patches to try but none were tested by me.

If admins say this is not fit for an answer I will erase.


You seem to be having two issues: this module (i.e. PHP Fatal Errors resulting from something that's broken in the module) and Drush.

Let's start by the easiest fix, Drush.

Make sure you have Drush 8 (or 9-dev), which is the only version compatible with Drupal 8. Run $ drush --version to know for sure. If you're not running Drush 8, then, read the documentation and install it via Composer.

As to your module issue, my best bet at this point would be to put the module back in place where it was so that Drupal can see it, else, it'll never be in a position to trigger the uninstall process if the module isn't there. Once it's back (under the /modules directory at the root of your Drupal install), run the $ drush pm-uninstall -y command which will not disable the module (this has been removed completely from D8) but uninstall it completely. If it doesn't fail during the process, then, chances are that everything will be fine. If you do have issues during the uninstall phase, try to visit the /admin/modules/uninstall page to uninstall the module from the UI (assuming something didn't work well with Drush).

If nothing works, try to rebuild the cache (/admin/config/development/performance or $ drush cr) and repeat the above operation. Finally, if you're still stuck, I'd advise you report your bug (at the very least the PHP error message) in the module's issue queue. Note that it should not be the error you mentioned earlier since you got it after you removed the module from its original location.


Try with print render($node_author->field_custom);

Or you can try as well:

insert at the top of you node.tpl.php

<?php
global $user;
$node_author = user_load($user->uid);
$yourvariable = $node_author->field_custom;
?>

Where you want print the field insert:

<?php print $yourvariable['und'][0]['value'];?>


Why would a view be displayed differently in different software?

Ironically, the PDF document format was designed to display the same everywhere ... but that's an overly ambitious goal.

First note that "in the browser" isn't especially meaningful - different browsers, with different configurations, will use different engines to display the pdf.

Your different experiences are due to those different engine(s) in your browsers vs. the acrobat reader engine, which is perhaps also used for your ipad and outlook.

My best guess is that your browsers have access to some non-standard fonts that you're using in the output, but the other engines don't. Getting the views pdf to embed those fonts, or using standard fonts instead, will probably fix it.


You can restrict by placing file extensions which you want to display in the permitted file extensions field. It will appear in the configuration of IMCE profiles. See below image for your reference.


I would suggest adding a custom text field then add the language value as a field. this way you will have the language as a replacement pattern that you can use with any custom link field which would be  something like {{ language }}

You need to checkout the style settings of to use the custom link option.


You need to enable multisite.

The documentation inside the settings.php file is also very helpful, read that too by viewing the source of the file here https://api.drupal.org/api/drupal/sites!default!default.settings.php/8.

Briefly, the steps are,

Multi-site requires the existence of the sites/sites.php file in your Drupal 8 installation. You will need to create this file manually.

Example content would be:

<?php
$sites['mysite.com'] = 'site1';
$sites['8000.localhost'] = 'site2';

Create a site directory inside sites/, the path should be sites/site1.
Put a settings.php file in this directory in order for Drupal 8 to recognize it.
Visit the URL of site1, like mysite.com to install it.


Is there a way to add managed_file field to theme-settings.php?

The theme-settings.php is included from system_theme_settings(), which executes the following code.

// Call engine-specific settings.
$function = $themes[$key]->prefix . '_engine_settings';
if (function_exists($function)) {
  $form['engine_specific'] = array(
    '#type' => 'fieldset',
    '#title' => t('Theme-engine-specific settings'),
    '#description' => t('These settings only exist for the themes based on the %engine theme engine.', array('%engine' => $themes[$key]->prefix)),
  );
  $function($form, $form_state);
}

foreach ($theme_keys as $theme) {
  // Include the theme-settings.php file.
  $filename = DRUPAL_ROOT . '/' . str_replace("/$theme.info", '', $themes[$theme]->filename) . '/theme-settings.php';
  if (file_exists($filename)) {
    require_once $filename;
  }

  // Call theme-specific settings.
  $function = $theme . '_form_system_theme_settings_alter';
  if (function_exists($function)) {
    $function($form, $form_state);
  }
}

Unfortunately, the file is not loaded from Drupal before any validation/submission handlers for that form are invoked.

When form_cache_get() is called, the following code is executed.

    foreach ($form_state['build_info']['files'] as $file) {
      if (is_array($file)) {
        $file += array('type' => 'inc', 'name' => $file['module']);
        module_load_include($file['type'], $file['module'], $file['name']);
      }
      elseif (file_exists($file)) {
        require_once DRUPAL_ROOT . '/' . $file;
      }
    }

As form_get_cache() seems called before a form is validated/submitted, you could use the following code. (Replace mytheme with the short name of your theme.)

function mytheme_form_system_theme_settings_alter(&$form, &$form_state) {
  $theme = $GLOBALS['theme_key'];
  $themes = list_themes();

  $form_state['build_info']['files'][] = str_replace("/$theme.info", '', $themes[$theme]->filename) . '/theme-settings.php';
}


Remove items in taxonomy entity relation on node edit form

You're deep in the field definitions there, that's the wrong place, you can't change anything there and you don't need to.

In case of a select, the available options are already part of the form; they should be in $form[$field_name]['widget'] somewhere.
You could also try to use hook_options_list_alter().


does node_save wait until end of php session to create db record?

Is it possible/expected that node_save() does not create a new record until the current php session is complete?

I'm not sure 'session' is the right word there, I'm assuming you mean 'current request' (queuing actions to be run when the session has expired would be an odd thing, and not something PHP/Drupal would do without you telling it to).

Either way, before node_save() completes it commits the database transaction and flushes relevant caches. So no, it doesn't wait for the current request to complete.

So to address

  the ones i am creating in my script will not yet be included in the full list?

No, once you've saved the node, and assuming it completed without error, it will be in the database and available immediately via node_load().

Of course you don't actually need to load it, as your $node object will be in an identical state to the loaded node when node_save() has completed anyway.

Ignoring all that, if you actually mean "does running node_save() automatically update an array of nodes I've previously loaded into a variable earlier in the script", then also no. That would be magic :)


You can change it back with drush:

drush vset admin_theme seven

Or PHP:

variable_set('admin_theme', 'seven');

Or if you're in a real bind, via the settings.php file temporarily:

$conf['admin_theme'] = 'seven';

Replace "seven" with the machine name of the theme you want to use for the admin pages.


Adding fields, account registrations and editing profile

This is part of Profile2's interface design; different profile types (created in admin/structure/profiles) are presented as separate submenus on the user edit page.

If you want to work with the constraints of its interface, you can create profile type for each group of fields that you feel should be edited separately. If you feel like a field should be part of the main user edit page, you can add it to the core user entity (admin/config/people/accounts/fields).

As far as combining profile2 forms into the user edit form, Profile2 does allow you to embed profiles into the registration form (via its Show on all user account registration forms. option) but not the edit form. For that, there is the Account Profile module.

  Profile2 by default creates an additional tab for each new profile
  assigned to a user. Alternatively the submodule "Profile2 pages"
  provides a separated pages for viewing and editing profiles.


How do I use a referenced entity in a Views contextual filter?

For the curious, with Huelfe's help I solved it with a custom PHP code, in order to obtain the applicable NID for that contextual filter.  Seems like something that should be built in to Views already...!   I've successfully reused the string or several other projects as well.


What you want is to find the content of the variable site_frontpage.

You could:

drush vget site_frontpage
Use devel and it's variable listing
SELECT * FROM variable WHERE name = 'site_frontpage';

This will tell you where the frontpage is controlled from. Often it will simply be a node that you can edit.


Setting Panels category for blocks and other pre-existing Content Types?

A kinda hacky way of doing it is to hook into hook_ctools_block_info() like so:

/**
 * Implements hook_ctools_block_info().
 *
 * @see ctools_block_content_type_content_types().
 */
function menu_block_ctools_block_info($module, $delta, &$info) {
  if ($info['title'] == 'Sub Menu Menu Block') {
      $info['icon'] = 'icon_core_block_menu.png';
      $info['category'] = t('Page Content');
  }
}

I just dropped this code in a separate module and I'm off to the races. The only problem is if Menu Block decides to implement its own hook_ctools_block_info function (Indeed, I got the above code from a patch that does exactly that), in which case redeclaration errors will show up. I'll leave this question marked as unanswered for the moment; if anyone can think of a better way of accomplishing the above, I'd be happy to accept that answer instead.


Retrieve field value using PHP + Search API + Views?

Run $data though dmp to inspect the array and see what values are available.

Search Krumo may be useful as I expect that array will be huge!


Use Drupal to communicate a translated string to Javascript:

drupal_add_js(array('my_string' => t('Default Text')), 'setting');

Then, have your jQuery read the value:

var str = Drupal.settings.my_string;


(solved) send mail with Rules when a term in multi value vocabulary is selected

I see 2 possible reasons that may cause your problem:

Maybe it's a data type conversion issue. You may be more lucky to get that 2nd condition to work if you'd use a text comparison (= "text_matches")  instead of a data comparison (= "data_is").
Maybe your zichtbaarheids-field is a multi value field?

To further investigate this, just add a "Display a message" (within System) as your very first Rules Action, to display the actual value (using an appropriate token for your field), after you temporary remove that 2nd rules condition (to ensure the Rules Actions are performed). If that doesn't help either, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".


Editor being able to create tabs (quicktabs style) inside CKeditor

A bit late to the party, but this module will do it for you. I've been using it for a while now.

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


Be sure:

your migrate_rcmd_migrate_api function is in the file migrate_rcmd.migrate.inc.
your Classes are included in .inc files defined in your modules .info file. See this documentation page on Migrate: https://drupal.org/node/1006982
Lastly in Migrate > 2.5 (i think thats the right version) migration auto discovery is now gone. You can use drush migrate-register to register your migrations and classes. See drush help migrate-register as needed.
when in doubt clear your caches: drush cc all to be sure the .inc files are registered in drupals code registry.


How to create a new entity that is fieldable

I am assuming that there must be a function that creates the form for you

Not quite - you need to create the form yourself with the API as normal, but you can use field_attach_form() to have the field elements added automatically. You'll also need the complementary field_attach_validate() and field_attach_submit() in your form's validate and submit handlers respectively.

Elements for your entity type's properties need to be added manually.

The best place to look for code examples is the entity example module in the Examples project, it has all of this in it and is pretty well commented.


D7: file_create_url() usable in node.tpl.php?

file_create_url takes a uri, such as public://science-of-rock_background.png

The revised:

$img_src = $content['field_image'];
$bgimage = file_create_url($img_src);

Would work if your field is only returning the URI.

And, for best practices, should set that up in preprocess_node, otherwise will work in node.tpl.php


You need the Path module for URL aliases. (It is a Drupal core module.)

Once the module is enabled, you can edit a node, and set a path alias for the node. Now, you can access your node through the path alias you just created.
Drupal will use the path alias you set as URL for the node, except for sub-paths (e.g. node/1/edit).


It looks like there is a token [current-page:query:?] you just need to replace the ? with your query parameter, so [current-page:query:source] should do the trick.


How can we divide the price if the customer select certain attributes?

Why dont you try the Rules module? It is great for that kind of automation.


(Disclaimer: This is not tested, it's been a while since I did a D6 site...)

First, I would implement hook_menu_alter and clone the node/%node/edit item into topic/%node/edit and arts/%node/edit. (If you want to use custom page callbacks for the forms, that's fine. You can make all changes you need to the menu items.) At least, you must change the access callback property and set it to the function name of your custom access callback (see below). Now you have three similar menu items with three different URL's. All of these should be visible as tabs on all nodes, so we're not done yet.

Second, I would create a custom access callback to hide the tabs with the incorrect URL's. This is described in HowTo: Add / Remove a menu_local_task for specific node types. In your case, the access callback should check the type of node on the current page and use it to decide if the tab must be shown or not. Don't forget to also call node_access(), because if the user is not allowed to edit that node, the tab must be hidden too.

Sorry I don't have actual code to share, I hope this helps.


Is there a way with drush or console to delete all active config with a certain prefix?

This isn't the greatest solution, but it does work, and also allows you to not have to execute a dozen steps/commands to register your migrations.

In my custom module where I'm creating migration sources/plugins, I added a .install file and implemented hook_uninstall().  In there I delete the configurations remaining manually.

<?php

/**
 * @file
 * Contains my_module_migrate.install.
 */

/**
 * Implements hook_uninstall().
 *
 * Removes stale migration configs during uninstall.
 */
function my_module_migrate_uninstall() {
  $query = db_select('config', 'c')
    ->fields('c', array('name'))
    ->condition('name', db_like('migrate_plus.') . '%', 'LIKE')
    ->execute();

  $config_names = $query->fetchAll();

  // Delete each config using configFactory.
  foreach ($config_names as $config_name) {
    \Drupal::configFactory()->getEditable($config_name->name)->delete();
  }
}

Note: You may need to clear cache after uninstalling for the changes to show before re-enabling the module.

If you want to remove them before you uninstall you can either run each line from hook_uninstall() implementation in devel/php, or you can run them via drush:
drush ev "\Drupal:;configFactory()->getEditable('migrate_plus.migration.xxxxxx')->delete();"
You will probably have to clear cache after removing all of them manually via drush as well.

If you'd like to just run a couple of drush commands to re-register your migrations, you can add this drush plugin file my_module.drush.inc to your modules' root directory, clear cache, and run drush mpc -y && drush mcr my_module.  You may need to also run drush cache-clear drush for the commands to be come available.

Here's the code for the my_module.drush.inc file:

<?php
/**
 * @file
 * Contains my_module_migrate.drush.inc
 */

/**
 * Implements hook_drush_command().
 *
 * Defines drush commands.
 */
function my_module_migrate_drush_command() {
  // Company update Dynamically
  $items['migrate-prune-configs'] = array(
    'description' => dt('Prune migrate configs.'),
    'aliases' => array('mpc'),
    'examples' => array(
      'drush migrate-prune-configs' => 'Removes migrate configuations.',
    ),
    'callback' => 'my_module_migrate_migrate_prune_configs',
  );

  $items['module-config-reset'] = array(
    'description' => dt('Resets default config for a given module.'),
    'arguments' => [
      'module_name' => dt('Module name'),
    ],
    'aliases' => ['mcr'],
    'required-arguments' => 1,
    'callback' => 'my_module_migrate_config_reset',
  );

  return $items;
}

/**
 * Callback for drush command migrate-prune-configs to prune migratin configs.
 */
function my_module_migrate_migrate_prune_configs() {
  //Confirmation will be Y/N when use type “y” the condition will be executed if not it will not
  if (drush_confirm(dt("Are you sure you want to remove migrate configs?"))) {
    drush_print("Removing.....");
    // Get all of the migration config names.
    $query = db_select('config', 'c')
      ->fields('c', array('name'))
      ->condition('name', db_like('migrate_plus.') . '%', 'LIKE')
      ->execute();

    $config_names = $query->fetchAll();

    // Delete each config using configFactory.
    foreach ($config_names as $config_name) {
      drush_print("..." . $config_name->name);
      \Drupal::configFactory()->getEditable($config_name->name)->delete();
    }

    drush_print("Removed succesfully");

    return TRUE;
  }
}

/**
 * Reinstall default module's config files
 */
function my_module_migrate_config_reset($module_name) {
  if (!in_array($module_name, array_keys(\Drupal::moduleHandler()->getModuleList()))) {
    return drush_set_error(dt('Module @module_name not found.', ['@module_name' => $module_name]));
  }
  // Initiate config installer for given module.
  \Drupal::service('config.installer')->installDefaultConfig('module', $module_name);

  drush_print('Configuration was successfully reset.');

  return TRUE;
}

The code for resetting the module's configs was found in this issue on d.o.  I found that it doesn't work unless the configs are already removed, hence the first command to remove them.


Use body field for views nivo slider instead of title field

When you set up the view, you can click on the Row Style options (the little gear thingy :) and then it will give you three options, Image Field, Title Field, and Link Field.  The Title Field is the Caption and you can put any field that you've selected in your view (in Fields) you want for it. So, if you've selected Node Body as a field, you should be able to select it there.  But, just as using the Node Title, it will put in the whole body (or at least what part will fit I'd imagine) in the caption.  If you want something else, you may want to consider yet another field in your content type, or some sort of views rewriting of the field.


THEME_preprocess_field() not recognised in template.php

Try with THEME_preprocess_field(&$variables, $hook), replace the &$vars with &$variables


Displaying a taxonomy term (token) in a block

I will answer my own question here:

Create a block view (taxonomy term)
Add relationship: "Taxonomy term: Content using your vocabulary)
Add contextual filter "Taxonomy term: Term ID" (no depth)

Configure the filter to "Provide Default Value: Taxonomy term ID from URL"
   below,

Check "Override title" and type "%1" in the input box

Specify validation criteria: "Taxonomy Term"

check box that has your vocabulary,

Select the Filter value type: Term ID

That's it. No need to add fields or filters. You can remove all sorting criteria.

This works even if you have several levels of children. All it does is take the term of the vocabulary that is in your URL and displays it as the page title. Also works if the page or view, or whatever is there, is empty or returns no results.

Hope that helps. :)


Paragraph how to get content level wise?

You can use this template file:

/themes/mytheme/templates/field--paragraph--field-category--faq.html.twig:

    <div{{ attributes }}>
        {% for item in items %}
            <div{{ item.attributes }}>{{ item.content }}</div>
        {% endfor %}
    </div>


If you mean controlling which database Drupal uses for its own database tables (e.g. the table containing all the registered users, the active sessions, the nodes created), then it is not possible. There is no way to tell Drupal which database use basing on the user's roles.

If you are asking about your own module, then it is possible, but your module needs to handle this on its own because Drupal doesn't have my specific functions to handle your use case, except the following ones:

user_has_role() checks the user account passed as argument (or the currently logged-in user) has the role passed as argument
db_set_active() set the database used from the successive database API calls using one of the keys set in the settings.php file

Rather than using db_set_active(), I would use $options['target'] which can be used from any Drupal function necessary to query the database.


Apparently you have somehow broken your Cygwin installation. In the Cygwin setup.exe, go through the setup sequence until you get to the "Select Packages" screen, then type "intl" in the Search box. Open the Libs section, and click the third column on the "libintl2" line until it says Reinstall. Proceed.

That should fix this one particular problem, but chances are good that if you've lost that one library, you've broken other things, too. A complete Cygwin reinstallation might be in order.

You too can follow this steps for install drush properly:

Installing Drush on Windows

or

Installing Drush on Windows using Cygwin


How to hide default "N/A" option for checkboxes?

You can use jQuery to accomplish this

$("#edit-field-gender-und-none").remove();


I Changed how to build my form,

public function buildForm(array $form, FormStateInterface $form_state) {
  $terms = \Drupal::service('entity_type.manager')
      ->getStorage("taxonomy_term")
      ->loadTree('faq', $parent = 0, $max_depth = 1, $load_entities = TRUE);
  $terms_select = array();
  foreach ($terms as $term){

      $question = $term->get('field_question_faq')->getValue();

      $terms_select[] =  $question[0]['value']);

  }

and then everything was fine!!

Thx to Vikram8888


Save xml file produced by views data export module to a different location

You will not be able to save anything automatically expecially to a particular path

Some browsers allow you to remember the action (Save/ Open) for each file type. If the user had chosen to "Remember my Answer", then the browser saves the file automatically. You can not force a similar it on all users using your site.

Regarding the path, it again depends on the browser config. If the user had configured a download directory, some browsers save the file in the download folder by default. Else will ask the user to select the path showing the last saved path.

If browsers allowed websites to save files directly to d:\ on your machine without your consent at the click of a button, your machine would have been full of stuff that you never intended to download!!!!


Is it possible to have a single date exposed filter with date range?

yes, there is a module for that, views_between_dates_filter, from module:

This Views filter provides the between date functionality you've been looking for by answering the question: "What events are on this date?" It displays all content (comparing start and end dates) occurring on a specified date.
It compares two date fields with one supplied date. Effectively it is the opposite of the standard Date Views "between" operator, which compares one date field with two supplied dates.


Import CSV, row by row, into custom table

I used the code below;

public function submitForm(array &$form, FormStateInterface $form_state)
{

    $file = $form_state->getValue('csv_upload_file');

    $destination = $file[0]->toArray()['uri'][0]['value'];

    $file = fopen($destination, "r");

    while (!feof($file)) {
        $customer = fgetcsv($file);
        \Drupal::database()->insert('your_db_table')
            ->fields(array(
                'column1' => $customer[0],
                'column2' => $customer[1]
            ))
            ->execute();
    }

    fclose($file);

    drupal_set_message('CSV data added to the database');
}


How to export only content, strictly core content like articles, pages, users, taxonomy ect?

There are several ways to achieve this

Use migrate module
Use Node Export Module
Use Feed Module
Or you can use web services to achieve this. For example expose data in services and import those data back in the other drupal site. (Very easy approach)
You need to check the database structure a bit and write a custom php script to take data from one table and insert it into another.


How to reduce HTML output on Drupal forms

With Display Suite and sub module Display Suite Extras you can remove unnecessary wrappers.


I've resolved my problem finaly, I think there was a conflict with a Disabled module (Rules Forms).
I can set the displayed variables under "parameters" in my rule config.


How to get the node ids of answers for a question in Drupal Services (REST)?

I didn't know what are question and answers modules that you used. My assumption is your answer and your question has a content type and they linked together. So if my assumption is correct here is the way that you can use for solving your problems:

Create a views will list all the answers of specific question(your question nid).
using Views Services to get the views that you created before and use your question (question nid) for the views parameter.

In case my assumption is wrong. Your have to create custom resource by your own to get the list of answers. In this way you must create your SQL sentences too. The reference for creating custom resource here


Paid node checkout plus membership plans for a Drupal site

Being a great fan of Drupal Commerce, I will suggest you to use it in your instance for this need.

You can use Commerce Node Checkout module for your pay to publish requirement.

For membership requirement, you can set product for each membership type & set rules for it. Create rules on event completing checkout process & put some condition like - product SKU match to membership product SKU, current user type etc. & then add usertype to the user.

You will get many payment related modules with Commerce, so you don't have to worry about any ecommerce feature.


POST parameters not received in drupal module

You cannot use an empty string with those super global variables. You need to use a string that is the parameter you request, such as in $_GET['q'], or $_REQUEST['q'].


.js extension for javascript file is missing

What version you are using? And are you sure the my_module.js is exist?

I think the best way is using hook_library to add js and css for your module:

function my_module_library() {
  $libraries['my-module'] = array(
    'title' => 'My custom module library',
    'version' => '1.0',
    'js' => array(
      drupal_get_path('module', 'my_module') . '/my_module.js' => array(),
    ),
  );
  return $libraries;
}

function my_module_init() {
  drupal_add_library('my_module', 'my-module');
}


Font Awesome not working when using HTTP

Not exactly sure if this is the issue, but when I've had CORS errors with web fonts the following Apache directive in .htaccess has worked for allowing any Origin for those files:

<IfModule mod_headers.c>
  <FilesMatch "\.(eot|otf|tt[cf]|woff)$">
    Header set Access-Control-Allow-Origin "*"
  </FilesMatch>
</IfModule>


Convert theme from ASP.net-based site to Drupal

I don't think there's any tool doing something automatic for you. Just take the ASP.net as as a prototype and start again with a solid base theme like zen.


Calculate percentage between two entity fields in Drupal using Computed Field Module

First print_r($data) in your Output code text area so you can see what you can work with. Depending on what you have, your Output code is going to look something like this:

$percent = 100 * $data->field_accounts_payable_bs['0']['raw']['value'] / $data->field_customer_deposits_bs['0']['raw']['value'];

print(number_format($percent, 1, '.', ','));


I've found inspecting the routes availble and then working back to the controller to be a super helpful way to understand how to override things.

You will need Drupal console installed.

For example run

drupal router:debug | grep node | grep delete

This will list all routes, and then filter only ones with node in and then filter only ones with delete in.

You should then see the route you are interested in (/node/{node}/delete) is called entity.node.delete_form

Now you can debug just that specific route:

drupal router:debug entity.node.delete_form

This will show you that the form for this route is called node.delete. If however there was a method and a controller for the route is would show you exactly what the callback is.

To change the entity.node.delete_form route to use your own callback you can use the new method of doing menu_alter.

However if you want to keep the same node delete form and just change the submit handler then you can still use hook_form_alter to change this.


How to get taxonomy tree with path auto token?

Found it. Token should look like:

[node:field_structural_category:entity:parents]

It appeared (I think) after I changed reference field from multiple to accept only one value.

While it was accepting multiple values I could access first 3 elements, but not their parents. So this option is available only for single value fields. I see that lot of tokens are missing when tag reference field is set to accept multiple values. Bug or feature - can't say.


What is the difference between {{ |t}} and {% trans %}?

Both the {{ |t }} filter and {% trans %} ... {% endtrans %} blocks, when used in the context of Twig template file in Drupal, are part of the Drupal localization system. And translation for strings processed with either one are handled in the same way, and via localize.drupal.org. For simple strings of text they can be used interchangeably, however the %trans block has some additional useful features for complex strings.

The difference is that the t filter only allows for simple strings, while using a %trans block allows the use of dynamic placeholders in the string. Much like using the php t() function.

Here's a few examples:

Simple string translation via t filter:

{{ 'Hello Stack Exchange!'|t }}

String translation with placeholder:

{% trans %}Hello {{ user.name }}, today's date is {{ date|placeholder }}.{% endtrans %}

Placeholders are escaped by default, but can also be left-unescaped {{ var|passthrough }} or formatted as a placeholder {{ var|placeholder }}. This is equivalent to using @string, !string, and %string in the t() function respectively.

You can also use %trans blocks in order to format plural strings.

{% trans %}
  There is 1 comment.
{% plural count %}
  There are {{ count }} comments.
{% endtrans %}

For simple strings there are really no rules about when you should use |t vs. %trans. So I would recommend using whatever is easiest to read in your template. In my experience using the |t filter works well for short strings, while the %trans block is easier for longer strings of text.

More information about usage can be found here: https://www.drupal.org/node/2357633 and here https://www.drupal.org/developing/api/8/localization


I want to add a prefix to my database Drupal8 how?

Changing the $databases['default']['default']['prefix'] setting does not change your database. You'll have to either manually prefix your existing DB tables or run the installer again while placing the d8_ prefix in the Advanced Options > Table name prefix field of the D8 installer.


full html isn't always enough to provide the necessary access.  go to /admin/config/content/formats and create a new format (I call mine 'Unaltered') with the following setup (make sure to restrict it to admin ONLY):

This will allow you to perform inline js, etc within a block, without requiring a new module. Also, make sure the style listed in the js you include matches the size of the block (or more accurately, that the block matches the size of ad you want to show), or you will have strange layouts where the ad doesn't fit the container.


CPU spikes enabling / disabling modules when site is under load

If you look at the source for module_enable() you can see what is going on.  In particular, several cache tables get cleared, as does the registry.  It also does filesystem scanning to rebuild module data.  All of these are expensive operations.

If you look at the source for system_modules() (this is the callback for the modules page), you will  see that system_rebuild_module_data() is called.  This is also an expensive operation.

My guess is that something on your server isn't optimized.  Even though you have gobs of CPU and RAM, Apache and MySQL may need tuning.  I have seen similar instances to yours, where MySQL hangs due to heavy loads and then incoming HTTP requests stack up.  Eventually, connections to the database will block, and slow things down more.  When this happens, the system will very often hit swap due to the number of httpd processes.  A live webserver hitting swap is a catastrophe; load/memory will swell exponentially.

In this case, you need do a few things.

First, run mysqltuner on your database, and make sure buffer sizes are OK, and that your max memory usage is sane.

Then, tune Apache to make sure you won't ever hit swap under normal conditions by limiting the number of concurrent servers.  Enabling keepalives, and setting up some aggressive HTTP cache rules can also help reduce the number of active httpd processes.  Using the CDN module can also help reduce Apache load by offloading most CSS, JS, and image requests to the CDN instead of your server.

It is also possible that your memcache doesn't have enough memory, and you are thrashing.  You may need to check these settings, and also check which tables you are offloading.

I would also avoid enabling/disabling modules outside of maintenance mode.  Schedule windows where you can do work.  Assuming you stage/test everything properly, and work from a checklist, you shouldn't have more than 5-10 min downtime to do this.


adding block region inside of menu section

Part of the problem is that regions aren't really what you're looking for here. Drupal regions are just areas of the page, and you set content to appear in a given region. One way of utilizing regions for this would be to have a menu region defined in your theme's .info file, and then putting the menu and the search block in that region. I'm betting that's not really what you're after, though, because it doesn't result in very clean code.

There are two other options that I can see. One is to create your own theme callback for menus so that instead of calling theme('links', array(...)), you're calling theme('your_new_theme_callback', array(...)). You can define different variables for this theme, and one of them could be for the search block.

Of course, because this is Drupal, there's already someone who's gone "Man, I really want blocks in my menu and there's no nice way to do that in Drupal" and created a module. The Menu Attach Block module lets you attach a block to your menu. I've not used it before so I'm not 100% sure how to implement it in the way you're looking for. It doesn't look like you'd have to change your code at all, I don't think, because it looks like the module overrides theme_link() for you.

Does that make sense? If you want more details, let me know!


Is it possible to change the layout of the registration form using display suite?

Sorry, I don't think it is possible with display suite on its own but you may find this link helpful Changing the layout of user profile edit page. Display suite appears to only get you some of the way there.


Is there way to rearrange node on front page?

You can create views with weight sorting nodes and set it as front page


What is a one line mysql query that can update all body fields of matched nodes?

In drupal 7 it is a bit simpler.
You don't need the join.

UPDATE field_data_body
   SET body_value = 'This is my string.'
 WHERE entity_type = 'node'
   AND bundle = 'basic_page';

You must clear the drupal cache after updating content directly in the database.

Also, if you are using revisions, note that you have just changed the latest revision without creating a new revision.
This may not matter to you but it's worth noting.


How to make a taxonomy vocabulary overview page with Drupal 7

If you refered that taxonomy term in a content type then a listing page is created by default.

For example if you created a taxonomy named Category  and terms inside it are

Knowledge
courage

If you created a content type and refered category taxonomy then listing page will be at category/knowledge , category/courage and so on

To display all the contents of the vocabulary then

  Create a view of type Node

  Add a display of type block or page according to your need

  Add your desired fields(CCK) along with a field Taxonomy: Term

  Add a filter Taxonomy: Vocabulary and select is one of operator and choose the
    particular vocabulary name.

This solution will include taxonomy terms associated with content node but filter according to the defined vocabulary in filter.


Git making code changes in local branch 'develop' and push to Acquia Cloud Dev

This simply means you need your develop branch to be pushed to the remote Acquia Cloud repository.

$ git push origin develop

Once you do so, just select develop in your Acquia Cloud dev environment. You'll now by in synch between your local and remote branch and will be able to push code as you expect.

UPDATE:

Using the develop branch can be permanent or not, it's up to you.
You can, say, have develop always checked out in dev, master in
stage, and a git tag in prod. develop would then be your
cutting-edge branch while master would be safer and primarily for
QA. Sometimes, you'd have to delete develop and create it again
from master to clean things up. It's part of a normal workflow.
Don't be mistaken between a feature branch and a regular branch. develop isn't a feature branch, it's an integration branch. This means that you could have a feature branch locally called, say, twig-fixes that you would merge with develop when you're happy with the changes. You would then test your feature one last time in the develop branch locally and/or on Acquia Cloud, and then would take it from there.

NOTE: always create feature branches from master as it's your stable branch.

Example workflow:

$ git checkout master
$ git pull
$ git checkout -b twig-fixes

Do your work and commit changes to the feature branch, and, when you're ready to test your changes on the Acquia dev environment, merge your branch into the develop branch and push it to origin:

$ git checkout develop
$ git pull origin develop
$ git merge twig-fixes
$ git push origin develop

If all looks good, merge the feature branch into master using the squash option, to compact all commits into one commit only.

$ git checkout master
$ git merge --squash twig-fixes
$ git commit -m "Squashing twig-fixes"
$ git push origin master

If all looks good again in master, then you're free to delete your feature branch.


Can't clear cache as drupal_test.cache_filter doesn't exist

Did you try to run drush rr in advance? It would clean up your registry of modules an quite often fixes those issues.

Maybe some module got moved or if removed try to figure out what has been removed, re-install it and try again.


How to create a table during the module installation

You're missing the length property for the varchar column ('list'). length is required so the CREATE TABLE query will fail.

From the Schema API docs:

  All parameters apart from 'type' are optional except that type 'numeric' columns must specify 'precision' and 'scale', and 'varchar' columns must specify 'length'.


Domain Name language negotiation and mobile prefix m

Take a look at the Language Negotiation API, specifically hook_language_negotiation_info_alter.  With this hook, you can replace the default URL based language negotiation callback function with one that respects the m. prefix.

Something like this should get you started.

function mymodule_language_negotiation_info_alter(&$negotiation_info) {
  // Replace the core function with our own function.
  module_load_include('language', 'inc', 'language.negotiation');
  $negotiation_info[LANGUAGE_NEGOTIATION_URL]['callbacks']['language'] = 'mymodule_from_url';
  $negotiation_info[LANGUAGE_NEGOTIATION_URL]['file'] = drupal_get_path('module', 'mymodule') . '/mymodule.module';
}

function mymodule_from_url($languages) {
    // Your version of locale_language_from_url() that ignores the m. prefix.
}

For reference, the core function that handles language negotiation based on URL is locale_language_from_url.


EPSG is fixed in Geofile 7.x-2.x
Geofile provides a map formatter for the file field. more instructions

If you don't want to use the new version of Geofile, then go to the module(sites/all/modules/geofile) folder, open geofile.openlayers.inc in a text editor. if 'projection' and 'displayprojection' are assigned just numbers '4326' or '900913' change it to 'EPSG:4326' or 'EPSG:900913'


Unable to change the widget for a webform coponent

Disabling module Hide Submit Button (7.x-2.4) restored the webform functionality.


Maybe  reason can be if you use Search API module, in this case hook_search_api_views_query_alter will work instead

link 1
link 2

I have the same problem now and after some search find that when search API module enabled  hook_views_query_alter not worked.


It should be because the way you're generating the form is wrong, form element should be as below:

<?php
function mymodule_form($form, &$form_state, $i) {
  $form['value_' . $i->fid] = array(
    '#type' => 'value',
    '#value' => $i->fid,
  );
  $form['view_' . $i->fid] = array (
    '#type' => 'submit',
    '#value' => t('view'),
    '#name' => 'view_' . $i->fid,
  );
  $form['delete_' . $i->fid] = array (
    '#type' => 'submit',
    '#value' => t('delete'),
    '#name' => 'delete_' . $i->fid,
  );

  return $form;
}
?>

Each element name in $form array should be unique. Check Drupal Form API reference guide for more details. The value, view and delete doesn't contain any form element data like #type, etc. Please check the value of $form_state['values']['op'] in your form submit handler to understand which one is called.


Drupal View of CiviMember troubleshooting

Is there nothing to give you a clue in the actual table of results? Eg are the duplicates ones that have multiple websites (since that field has not filtering in field for ' website type' afaik but you should be able to apply a Views Filter)
That seems the most likely reason.
If not, have you tried setting the Query Settings (under Advanced) to Disinct or Pure Distinct.
If none of that helps, can you attach the view?


Drupal Commons 3 and Original Drupal Core Updates

The Commons team has committed to having a new release of commons within a short period after a core or contrib security release so you should just be able to upgrade by following the Commons upgrade procedure.

It's a bit risky to update core or contrib modules inside of a distribution. If you can do it on a test site first, confirm that it's working, and report your problems with the test site to the issue queue then you'll help getting the fully packaged Commons out.


HELP! Can't make glossary using taxonomy term name

This appears to be a bug in D8 core. Here is a link to the issue:

https://www.drupal.org/node/2630692


Get into your Superfish menu block (find from the block admin page: /admin/structure/block usually the specific address is: /admin/structure/block/manage/superfish/1/configure.

There under "Superfish plugins" -> "sf-smallscreen" -> "window width settings" and change the breakpoint value; make it smaller (default is 768 pixels).


Node blog dislpay all content type blog in theme

if I understand correctly you'll need this query:

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'blog')
  ->propertyCondition('status', 1);

$result = $query->execute();

then do you foreach($result);


Data coming from entityTypeManager->getStorage is cached data?

load() and loadMultiple() are cached, loadByProperties() is a shortcut for an entity query + load, the entity query is not cached.

Do not use loadByProperties() if you know the entity ID.


Unable to transfer php logic from node--post-esl-material.tpl.php to template.php

I think that the problem is that $content is not defined there. You have it only inside the template file but not in the preprocess hook.


How to perform a redirect after completing a Quiz?

If using Quiz 7.x-5.x
Assuming you're using the 7.x-5.x-rc3 version of the Quiz module, you can take advantage of integration with the Rules module that this new release comes with.
To do so, have a look at the delivered rule, which looks like so:
{ "rules_send_results_at_the_end_of_a_quiz" : {
    "LABEL" : "Send quiz results at the end of a quiz",
    "PLUGIN" : "reaction rule",
    "ACTIVE" : false,
    "OWNER" : "rules",
    "TAGS" : [ "quiz" ],
    "REQUIRES" : [ "rules", "entity" ],
    "ON" : { "quiz_result_update" : [] },
    "IF" : [
      { "data_is" : { "data" : [ "quiz-result-unchanged:is-evaluated" ], "value" : "0" } },
      { "data_is" : { "data" : [ "quiz-result:is-evaluated" ], "value" : "1" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : [ "quiz-result:uid:mail" ],
          "subject" : "[site:name]: Your results for [quiz-result:nid:title]",
          "message" : "[quiz-result:uid:name],\r\n\r\nYou finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nYour score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz-results\/[quiz-result:result-id]",
          "language" : [ "" ]
        }
      },
      { "mail" : {
          "to" : [ "quiz-result:nid:author:mail" ],
          "subject" : "[site:name]: [quiz-result:uid:name]\u0027s results for [quiz-result:nid:title]",
          "message" : "[quiz-result:nid:author:name],\r\n\r\n[quiz-result:uid:name] finished the quiz [quiz-result:nid:title] on [quiz-result:time-start]\r\n\r\nTheir score: [quiz-result:score]%\r\n\r\nYou can access the result here: [site:url]node\/[quiz-result:nid:nid]\/quiz\/results\/[quiz-result:result-id]\/view",
          "language" : [ "" ]
        }
      }
    ]
  }
}

After you enable Rules (and Rules UI, a submodule of it), just clone the above rule (using the Rules UI) and replace both Rules Actions with a basic "redirect" (a typical Rules Action) that fits your needs.
If using Quiz 7.x-4.x
For the 7.x-4.x version of the Quiz module, you may want to try the patch from fago (aka the Rules maestro ...), attached to issue # 1300420, which has a description like so (note the last phrase in it ...):

... adds basic rules integration to quiz. It includes an event when users have finished taking a quiz, a condition to check whether a user has passed a certain quiz and an action to clear quiz results for a user.
Patch works for me.


Change the height of the ckeditor text window

You should give this a go...

/**
 * Set a class on the iframe body element for WYSIWYG editors.
 * This only works for the WYSIWYG module: http://drupal.org/project/wysiwyg
 */
function adaptivetheme_wysiwyg_editor_settings_alter(&$settings, &$context) {
  $settings['bodyClass'] = 'wysiwygeditor';
}


Does hook_drush_exit() get called for disabled modules?

Using Drush 7, I get different results -- which is to say, hook_drush_exit() is usually not called unless the module it is implemented in is enabled.

Two things to note about this:

Earlier versions of Drush may have behaved differently; I did not test older versions, and I do not remember.
In some instances, it may be possible for some hook_drush_exit() to fire, even if the module it is not enabled.  One example where this happens is the drush help command.

hook_drush_exit() will be called for all commandfiles (module.drush.inc) that are loaded.  If Drush bootstraps the Drupal site all the way to the configuration level, then it will only load commandfiles for enabled modules.  If Drush is going to bootstrap the Drupal site at least to the "BOOTSTRAP_DRUPAL_ROOT" level, but not all the way to the configuration level, then it is not possible for Drush to determine which modules are enabled, and which are disabled.  In these somewhat rare cases, Drush will go ahead and load all of the commandfiles it can find anywhere inside the Drupal root, even for modules that are not enabled.

In any event, the workaround you used is the right solution, but now you know why your hook is being called.


How can I recreate a previously deleted Content Type?

You should delete the actual content first before deleting the content type. And nodes are going to be orphaned too and provably they will not display same as the content type news. can you try to search the existing news node in admin/content and check if you can still see the existing node type news that you created before. and try to delete them all before deleting the news content type and try to re-create the news content type.


I don't know if it really stores them anywhere by default, but I think that this module wouldn't exist if it does store them. Check it out.


How to delete a node or a list of nodes with Drush?

Finally I create my own module named drush_delete

Inside the drush_delete.drush.inc file put this code:

<?php
/**
 * @file
 * The Drush Delete drush commands.
 */

/**
* Implements hook_drush_command().
*/
function drush_delete_drush_command() {
  $items['node-delete'] = array(
    'description' => dt("Delete nodes."),
    'aliases' => array('nd'),
    'arguments' => array(
      'nids' => dt('The nids of the nodes to delete'),
    ),
    'examples' => array(
      'drush node-delete 1' => dt('Delete the node with nid = 1.'),
      'drush node-delete 1 2 3' => dt('Delete the nodes with nid = 1, 2 and 3.'),

    ),
  );
  return $items;
}

/**
 * Callback for the node-delete command
 */
function drush_drush_delete_node_delete() {
  $nids = func_get_args();
  $nids = array_filter($nids, 'is_numeric');
  $nids = array_map('intval', $nids);
  $nids = array_unique($nids);
  $nids = array_values($nids);
  $cant = count($nids);

  if ($cant > 0) {
    node_delete_multiple($nids);

    drush_print(dt("Deleted nodes:"));
    drush_print(implode(' ', $nids));
  }
  else {
    drush_set_error('DRUSH_ERROR_CODE', dt("You must enter at least one nid"));
  }
}

Install the module, run drush cc drush to clear the drush cache and use the command like this:

To delete a node use:

drush node-delete 1
drush nd 1

To delete multiple nodes use:

drush node-delete 1 2 3
drush nd 1 2 3

You can found the command in this module:

https://github.com/adrian-cid/drush_commands


How to access block fields programmatically?

I found the value by first grabbing the assignment value from the URL, then looking up the path to find the node id, then loading that node and using a wrapper to find the value of that specific field.

        $url = $_SERVER['REQUEST_URI'];
        $pos = strpos($url, '?') + 1;
        $assignment = substr($url, $pos, strlen($url)); //get the assignment from the URL

        $nodeID = drupal_lookup_path('source', "student-assignments-new/" . $assignment);//get the path from the assignment - e.g. node/145
        $pos = strpos($nodeID, '/') + 1;
        $nid = substr($nodeID, $pos, strlen($nodeID));//get the node id

        $node = node_load($nid);

        $wrapper = entity_metadata_wrapper('node', $node);
        $fieldValue = $wrapper->field_file_type_text->value();

        $output = $node->field_file_type_text[LANGUAGE_NONE][0]['value']; //field_file_type_text is my own field name
        return $output;


Colorbox links not working on Ajax loaded content

You need to attach your js using Drupal behaviors.

Drupal.behaviors.yourmodulename = {
  attach: function (context, settings) {
    // This code is run on page load and after every ajax request
    // attach colorbox functionality here...
    // the following line should do the job but I've not tested it
    // we are using context so it only applies to the newly added objects
    $('.colorbox', context).colorbox();
  }
};

I found this blog post on the subject really useful.


Content Statistics: Total View not showing up in Services

As I understood, this is a permission problem and it is possible that only admin is allowed to see that view.

You can set the permissions in the view itself so that it is available to all users otherwise just log-in as Admin to see the 'view'.


I'm guessing you have caching enabled for this view.  You can disable caching for this view or, better, you can apply this patch: https://www.drupal.org/node/1819538


Another option is the recently released Google Store Locator module on drupal.org. Some cool features: you can customize the map marker pins to be your own custom icon, and you can make the map 'location aware' which allows the user to share their location with the browser, and the map will re-center and zoom based on their location.


Ubercart override default flat rate quote

What I discovered is that in order for the default shipping flat rate quote to be overridden by product flat rate quote:

In Configuration->shipping quotes:
Base price must be set to 0.00
Default product shipping rate set to whatever the flat rate is.  In my example, it was $7.00.

In product ->shipping settings->flat shipping rates:
Flat rate quotes should be set to the overriding amount.  In my example, it was $3.00.

So, in the test product example, the flat quote shipping rate would be $3.00.  If no rate is set in the product, then the rate will be the default shipping quote of $7.00.

A bit confusing at first, but logical, I guess.


Best way to place hard coded link in template in multi lingual drupal 8

For translated links you can use the path function

 {{ 'DIENSTEN ON SITE'|t }}


Fully display only most recent post on front page, furl the others

You can render a views block within another views page. E.g. you want to show 10 nodes in total, and 1 of them in full mode:

Duplicate the existing view display as a new display of type "block". (Do not duplicate the entire view, only the sub-display by using "Duplicate as block").
In the original page display, in the Pager section, limit the number of items to 1.
In the original page display, in the Format section, set the view mode to full.
In the new block display, in the Pager section, limit the number of nodes to 9 and set the offset to 1.
In the new block display, in the Formatw section, set the view mode to Teaser. While changing the Format make sure to change the settings only "for: this block (override)" and not "for: All displays".
In the orignal page display, in the Footer section, add a "View area" and place the newly created block display. Here also change those settings only "for: this page (override)".


How can I limit the number of email sent per hour in a rule?

Below is a summary of how you can get this to work:

Use the Flag module and introduce a flag to allow "flagging" all those "users of a role" (as in your question). Let's assume you label that flag as "eMail notification outstanding" (to indicate that something still needs to happen to send that eMail later on).
Adapt the rule you already have, like so:

Remove the Rules Action "Send HTML mail to all users of a role".
Flag those "users of a role", using the new flag (from step 1) for each of the users. To actually do so create a view of those users (using Views), and use that view in combination with Views Rules to flag each of these users. Refer to my answer to "How to use Rules to send an E-mail after saving a new comment, to users who checked a boolean in their profile?" (the option 2-part of it) for an example (with screenprints) about how to use the Views Rules module.

Use the Views and the Views bulk operations (VBO) modules to create a VBO list of all flagged users (flagged by the new flag in step 1), sorted by flagging date (oldest first), and limit the results to the first 50 users only (50 is the value that seems to fit your needs).
Create a new Rules Component that "loads the VBO list" (from step 3) and add a loop to that rule to perform these Rules Actions:

Send HTML mail to each of the users in that VBO list.
Unflag (using flag from step 1) the user for which you just produced an eMail. This to indicate that the eMail notification was completed (no longer outstanding).

In that same rule, as the very last Rules Action, add an action to reschedule the execution of the same rule within 1 hour (1 hour is the value that seems to fit your needs).
Use the Rules UI to manually trigger the very first execution of that self-rescheduling Rules Component (from step 4.).

Using the above approach, every hour, Rules will notify 50 users "as requested".


Is different checkout-flow per product possible?

You need to implement a checkout flow resolver.

Look at the default resolver for an example: https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/checkout/src/Resolver/DefaultCheckoutFlowResolver.php
And don't forget the matching services.yml entry:
https://github.com/drupalcommerce/commerce/blob/8.x-2.x/modules/checkout/commerce_checkout.services.yml#L7
(You don't need to set the priority on yours though, it's -100 here so that DefaultCheckoutFlowResolver runs last)


How to get row weights from a form before saving?

You don't need to do anything special to get the row weights for the images.

The "weight" or list order of the images is stored in the delta value.

e.g:

$node->field_images[LANGUAGE_NONE][0]['fid'];
$node->field_images[LANGUAGE_NONE][1]['fid'];
$node->field_images[LANGUAGE_NONE][2]['fid'];

The delta value is 0, 1 & 2 representing the first, second and third images respectively.

Also, if you're using one of the node API hooks, e.g hook_node_insert, you won't need to load the node, it should already be passed as a parameter there.


Fraud detection on hotmail from Simplenews Newsletter

There are a few steps you can also carry out by looking here How can I prevent my mail from being classified as spam?. It includes setting up Domain Keys, SPF etc.

You can also refer to some steps for Microsoft here How to prevent email sent from drupal from going into spam box.


I have rewrited my code from an example of a custom token:

$replacements = array();

if ($type == 'node' && !empty($data['node'])) {

    $node = $data['node'];

    foreach ($tokens as $name => $original) {

        switch ($name) {

            case 'team_url':

            $path = 'node/'.$node->nid;

            $mlid = db_select('menu_links' , 'ml')
            ->condition('ml.link_path' , $path)
            ->fields('ml' , array('mlid'))
            ->execute()
            ->fetchField();

            $menuParents = token_menu_link_load_all_parents($mlid);

            foreach ($menuParents as $itemParent_mlid => $itemParent_title) {
                $item = menu_link_load($itemParent_mlid);
                $item_path = $item['link_path'];
                $item_path_args = explode('/', $item_path);
                $item_id = $item_path_args[1];
                $item_entity = entity_load('node', array($item_id));
                $item_type = $item_entity[$item_id]->type;
                if ($item_type == 'team' or $item_type == 'page_team') {
                    $itemParent[]= pathauto_cleanstring($itemParent_title);
                }
            }

            $itemsParents = implode("/", $itemParent);
            $replacements[$original] = $itemsParents;

        }
    }

}

return $replacements;

It's functionnal. Perhaps we can simplify this code and get a cleanly syntax.


I think you're desire to use Oauth is justified. However, if you have no other options, you can use Cookie authentication. I have used it before and have heard of people using it as well. Here are some things to keep in mind and you'd be good to go with Cookie auth with your mobile application:

You will have to increase the session timeout time to a long period, say, 1 year or more. This means that after the period, the user would have to be asked to login again. Alternatively, you can refresh the Cookie with each request. You will need to:

Change session settings in PHP settings
Change session settings in Drupal settings

You will have to authenticate the user and then have a mechanism to persist the user's Session ID using a Set-Cookie header.
You will need to have a mechanism to handle sign-in failure when the session cookie has expired. When the session expires, you can send the user to the sign-in page again (maybe with the username field pre-populated) and ask then to sign-in again.
Since leaving a session long open poses to be a security threat, you might consider using other mechanisms like CSRF tokens.

Note: If you are in the mood for experimentation, you can also look into JWT authentication. Also, if you expect to have a huge user-base, you might consider a service like Firebase for storage.

Hope it helps. Happy coding!


By default Drupal has forget password functionality which will send the one time password link to the user. may be you can use this  https://www.drupal.org/project/simple_pass_reset module if it matches your requirement

https://stackoverflow.com/questions/24051390/change-admin-password-in-drupal-7


one view for each term or one view for all terms

You just need to define the views path like taxonomy/term/%. It will override all the terms path automatically.


Entity reference fields store the ID of the referenced entity. They don't store anything else about the referenced entity.

You have an Entity reference towards nodes and the data that the ER field stores is the node ID. That is why when you add a filter for that ER field you get the "number" options, because the ID is a number/integer.

But there is a way to add a filter that filters results based on other properties of the referenced entity. When you need extra information you add the Relationship based on the ER field. This introduces all other available info about that entity into your Views.

In your case, you want to add the Relationship for your ER field (Content referenced from fiscal_certificates). Require it if you only want results that don't have that field empty.

After you add the Relationship you can add the Title filter, but make it use the Relationship for the ER field. Title is a text field so you'll get the text options (Contains...).

If you don't use a Relationship on that filter it will search through Titles of your "original" items, but if you use the ER Relationship it will search through the referenced node titles.


How do you clear menu caches programmatically?

Menu's are displayed via blocks.  You will probably have to clear the block render cache as well.

\Drupal::cache('block')->invalidateAll();


This didn't work for me either. I worked around this one by creating a panel page and using two different variants, placing each view block in the appropriate page and restricting the access based on user roles.


Attaching Callbacks to Standard Drush Commands

Take a look at the sync_enable.drush.inc example file.  If you configure this example as it describes, then your alias file can be configured to disable any modules that you do not want to have enabled on staging or dev sites.  This is presuming that you are copying your database from @prod down to @stage or @dev.  Disabling as sql-sync time is probably best, as this will protect you if, for example, someone clears the caches through the admin interface on a dev machine.

If you do need to run code prior to the cache-clear command, you can easily do so, as Drush does provide a general callback mechanism that can be used to hook any Drush command.  sync_enable is just one example of this; a policy file is another example of the same thing.

To get started, first you will need a Drush commandfile.  We'll call it mycf.drush.inc in this example.  Drush will tell you what hooks are available for a command if you specify the --show-invoke global option.  There are many many possible hook functions, so you'll probably want to pipe the output through grep, and filter on your commandfile name.

$ drush cc all --show-invoke 2>&1 | grep mycf

drush_mycf_cache_clear_pre_validate
drush_mycf_cache_clear_validate
drush_mycf_pre_cache_clear
drush_mycf_cache_clear
drush_mycf_post_cache_clear

In your case, you would want to implement the function drush_mycf_pre_cache_clear(), and put whatever guard function you wanted in there.

I'm not sure what you are asking vis-a-vis patch files and bash scripts & c.; perhaps ask this part in another question with more specific details, if the Drush pre-and-post command hooks do not solve the problem for you.


Get Field Collection Array From Field Collection ID

this is how you can get values from field collection

if(isset($node->field_field_collection['und'])) {
  foreach($node->field_field_collection['und'] as $field){
    $colection_node = entity_load('field_collection_item', array($field['value']));
    $name_from_collection = $colection_node[$field['value']]->field_field_name['und'][0]['value'];
  }
}

now you can understand how to get value from field collection try to fix this in your code

THANKS


drupal 7.14,where to install a new module,it is different than 7.13

It's at http://mysite.com/admin/modules/install.

You can also get to it from the main modules page ( http://mysite.com/admin/modules ):


how to default value to select list CCK with form_alter

CCK requires a little voodoo to alter values with a hook_form_alter(). You need to implement a special type: after_build, so put this code in a custom.module:

//Declare the callback for after_build for page node form
function custom_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'page_node_form) {
    $form['#after_build'][] = 'custom_after_build';
  }
}

function custom_after_build($form, &$form_state) {
  //For a select list you have to modify this to set default to black
  $form['field_select']['value']['#value'][0] = 'black';
  //if your field is multivalued you can put more
  $form['field_select']['value']['#value'][2] = 'red';

  //for a single text it's a little different:
  $form['field_text'][0]['value']['#value'] = 'black';
  //have a look at the form after after_build
  dsm($form);
  return $form;
}

Here are some (a little confusing/complicated but useful) articles regarding this:

hook_form_alter() and CCK fields
FAPI/CCK Confusion: 'value' vs '#value'


Thanks everyone for your answer. Finally, I've achived to solve the problem. At first, this bug comes from last versions.

If you create in this module a Long Question which max score is 0, it creates an inconsistency because you cannot divide by 0.

Some months ago, I found a patch to solve it:

https://www.drupal.org/node/2394759

But it's incomplete, because the module save the scores of each question in database and then it updates the total score adding the score of each one.

So, the way to solve that is changing the next lines in the same file that the patch file (../question_types/long_answer/long_answer.module):

db_update('quiz_node_results_answer')
  ->fields(array(
     'points_awarded' => $points_awarded,
     'is_correct' => $is_correct,
))

to

db_update('quiz_node_results_answer')
  ->fields(array(
     'points_awarded' => $calculated_score,
     'is_correct' => $is_correct,
))

To note the change is the variable $points_awarded for the variable calculated in the patch: $calculated_score.

With these changes, the patch is complete and everything is working.