How to append currency symbol as prefix to total sum in views calc?

You can achieve that in two ways CSS or jQuery

1)CSS (Note: It requires CSS2 capable browsers. )

td.your-views-class-name:before { content: "$"; }

2)jQuery

$('.your-views-class.name').each(function() {
  $(this).before($('<td>').text("$"));
});


Elegant way to retrieve nodes by content type?

You can just use the Views module and add a filter on the content type.


How do I print a value from a custom user field on page.tpl?

First I want to thank @mototribe and @Kimi for helping me figure this out.  I was able to get access to my field by putting

<?php
global $user;
$user_fields = user_load($user->uid);
$MYVARIABLE = $user_fields->field_MYFIELD;
?>

at the start of my page.tpl.  Then I had to print it out by adding this to my page  <?php print $MYVARIABLE['und'][0]['value'];?>


How can I add a progress bar to Managed File upload?

managed_file fapi elements are already progress bar capable by default.

managed_file

  Description: Provides a complete ajax/progress aware widget for
  uploading a file and saving it to the {file_managed} table.

  By default a simple upload button is provided for choosing the file to
  upload. Once a file has been chosen it can be explicitly uploaded via
  the "Upload" button. The upload is via AJAX and a progress meter is
  displayed.
  ....

  Non-standard form element properties:

  #progress_indicator: options are 'none', 'bar', and 'throbber', default is 'throbber'.
  #progress_message: (string) Progress message to display along with progress meter while a file is being uploaded. Defaults to NULL.

It may be possible that your server doesn't support file progress, in which case you should check and verify if the server settings are correct.

More info:

https://drupal.org/node/793262
https://drupal.org/node/793264
https://drupal.org/node/654732


How do I build a form with embedded view results

Sign Up Form

<?php
    function formfun_menu() {
    $items = array();
    $items['formfun'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'FORM FUN',
    'description' => 'A form to mess around with.',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('formfun_form'), //put the name of the form here
    'type' => MENU_NORMAL_ITEM,

    'access callback' => TRUE
  );
  return $items;
}

function formfun_upload_form($form, &$form_state) {

$form['add'] = array(
 '#type' => 'fieldset',
'#title' => t('Add company details'),
);
  $form['add']['companyname'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#title' => 'Company Name',
  );

  $form['add']['contactname'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#title' => 'Contact Name',
  );

    $form['add']['companyaddress'] = array(
    '#type' => 'textarea',
    '#required' => TRUE,
    '#title' => 'Contact Address',
  );

    $form['add']['postalcode'] = array(
    '#type' => 'textfield',
    '#title' => 'Postal Code',
  );

    $form['add']['city'] = array(
    '#type' => 'textfield',
    '#title' => 'City',
  );

    $form['add']['country'] = array(
    '#type' => 'textfield',
    '#title' => 'Country',
  );

    $form['add']['file'] = array(
        '#type'     => 'file',
        '#title'    => t('Choose a file'),
);

  $form['add']['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Click Here!'),

  );
   return $form;
}

function formfun_submit($form, &$form_state) {

    echo '<pre>';
var_dump($form_state['values']);
echo '</pre>';

    db_insert('details')
    ->fields(array(
    'companyname' => $form_state['values']['companyname'],
        'contactname' => $form_state['values']['contactname'],
        'companyaddress' => $form_state['values']['companyaddress'],
         'postalcode' => $form_state['values']['postalcode'],
        'city' => $form_state['values']['city'],
         'country' => $form_state['values']['country'],
         'image' => $form_state['values']['file'],
   ))
   ->execute();
    drupal_set_message("successfully saved Security Settings");
    exit();
}

function formfun_validate($form,&$form_state)

{
  }


Check Textimage 7.x-3.x

It provides a field formatter for long text. Be aware that very large text may create memory issues.

From README.TXT:

via Content Type field display formatters

Access 'Content type' administration features via Administration->   Structure->Content Types
Select the content type for which you want to manage a Textimage field   (e.g. Article, Basic page, etc.)
If you need to create a new field, in the 'Manage Fields' tab, add a new   field of type 'Text' (or 'Long text', or 'Long text and summary') or   'Image'
In the 'Manage Display' tab, select a 'Textimage' format for the field   created above (or any existing one)
Click on the gear icon
Select from the dropdown displayed the image style you want to use to   represent the content as a Textimage


Views relationship not been added by code

Have you considered using the module Commerce Notification?


I've solved a similar problem with drupal_get_path_alias() and hook_form_alter(). In my case I link from my content-type to the taxonomy page with the following:

<?php
// have a field with tags - in my content-type template I do
$terms = array();
foreach ($node->field_blog_post_tags['und'] as $key => $value) {
    $terms[] = '' . $value['taxonomy_term']->name . '';
}
print implode(', ', $terms);
?>

And to set the exposed filter I use hook_form_alter() in a custom module:

/**
 * Implements hook_form_alter().
 */
function YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ('views_exposed_form' == $form_id) {
    // term-id and vocabulary are part of arguments
    $args = func_get_args();
    // select your filter
    if (isset($args[0]->vocabulary_machine_name) && 'YOUR_VOCABULARY' == $args[0]->vocabulary_machine_name) {
      // set the exposed filter with name 'YOUR_FILTER'
      $form_state['input']['YOUR_FILTER'] = $args[0]->tid;
    }
  }
}

Maybe it's helpful for you.


Basically you would have to do:

$path = current_path();
$path_array = explode('/', $path); // Doing this you would get the array of all the elements that there in the url.

Once you have the array of items in the array, you would have to do

$term_name = $path_array[1];

So in $term_name you would have lakename, which is your term name.

Once you have the name, simply do

$term_object = taxonomy_get_term_by_name($term_name);

$term_object would have the object of the term.

For more detail: https://api.drupal.org/api/drupal/modules!taxonomy!taxonomy.module/function/taxonomy_get_term_by_name


Migrate d2d – Problem with duplication of thumbnails

Finally found a workaorund… by deliberately giving the destination field an empty value instead of not doing anything when $fid2 is FALSE, I got rid of all the duplications :-)

if($fid2 === FALSE){
    $filepath = array();
    $this->addFieldMapping('field_thumbnail_newsite')->defaultValue($filepath);
} else {
    $filepath = Database::getConnection('default', 'legacy')->query('SELECT f.filepath FROM {files} f WHERE f.fid = :fid',array(':fid' => $fid2))->fetchAssoc();
    $this->addFieldMapping('field_thumbnail_newsite')->defaultValue($filepath);
}


Add custom field in exposed form in view

You can define the field as a widget by messing with the #info part of the form in hook_form_alter - it's not very elegant but hey.

$form['text_search'] = array(
  '#type' => 'textfield',
  '#description' => t('Or start typing here to find your competition.'),
  '#default_value' => '',
);
// Create widget from new form item.
$new_form_info = array(
  'filter-text_search' => array('value' => 'text_search'),
);
// Put new widget definition at top, so widget will appear
// first (change order to change to desired position).
$form['#info'] = $new_form_info += $form['#info'];


How to remove stylesheets only for anonymous users?

Having tried to do this myself before, this is probably not a route you want to go down.  This approach becomes harder to maintain as you install more modules (different modules can inject CSS on different paths), and often can turn into a maintenance nightmare.
Drupal can aggregate CSS files out of the box; this is often all you need to improve performance dramatically.
To turn on the basic aggregation, you can check Aggregate CSS files at /admin/config/development/performance.
To do something more complicated, try using the Advagg module. Configuring this module can be complex but it allows you to do more specific aggregation, CSS minification, and so on.


Add default image to image file programmatically

Add ->save(TRUE); as in $field_bluescope_header_bg_image_config->set('settings.default_image', $default_image)->save(TRUE);


This seems to be related to this issue and there is available patch file for Drupal 7 and UTF-8 file encoding.

So your options are:

Disable the notice in site settings or in PHP configuration.
Wait until patch is committed and upgrade your Drupal core.
Disable faulty module.
Apply the patch your-self.
Apply patch manually by opening it and check the changes:

--- a/includes/common.inc
+++ b/includes/common.inc
@@ -7369,7 +7369,8 @@ function drupal_parse_info_format($data) {
   $constants = get_defined_constants();

   if (preg_match_all('
-    @^\s*                           # Start at the beginning of a line, ignoring leading whitespace
+    @^(?:\xEF\xBB\xBF)?             # Check for UTF-8 byte order mark and remove it
+    \s*                             # Start at the beginning of a line, ignoring leading whitespace

where on the top is the file to edit which is includes/common.inc (ignore a/b), 3rd line is the line number, then remove the lines which starts with minus and replace them these with pluses (without plus signs). If you got the error, then double check your syntax or revert your file to the previous version.


How can I scrape data from the web into drupal?

Not to put a damper on things (I've written more scrapers than I care to remember and it's always fun), but such an act is specifically against Google's Terms of Service:

  Do not misuse our Services, for example, do not interfere with our Services or try to access them using a method other than the interface and the instructions that we provide.

I'm sure you'll be ok if you're doing this for fun/educational purposes (don't take my word for it though, I'm not a lawyer!), but if you make something commercial out of this you could find yourself in a tricky position.


Drupal 7 add calendar module. Doubleclick on a day to add calender item for that day

The Calendar module does not provide such a feature per se. There is also another calendar module, FullCalendar. This uses the FullCalendar jQuery plugin. By default the Drupal module does not provide this functionality, but from the demo pages it seems that it is a relatively easy one to implement by yourself. You would have to study the demo a bit.


Log into Drupal using drush uli via CURL on the command line

Is your site redirecting from http to https when you access admin pages?  If so, try to set the --uri parameter you provide to Drush to an https instead of http protocol, and see if that works better.


Best way to make an EntityFieldQuery query be case sensitive?

MySQL documentation shows you can simply define collation at a query level:

SELECT k COLLATE latin1_german2_ci AS k1;

 SELECT *
 FROM t1
 WHERE _latin1 'Müller' COLLATE latin1_german2_ci = k;

 SELECT *
 FROM t1
 WHERE k LIKE _latin1 'Müller' COLLATE latin1_german2_ci;

If collation is only thing that affects case sensitivity for you, that's the way to go, no need to cast anything.

Based on this, you can set the operator in the EntityFieldQuery to be 'COLLATE utf8_general_cs ='. For instance the following will work:

$r = (new EntityFieldQuery())
  ->fieldCondition('field_my_field', 'value', 'eXample', 'COLLATE utf8_general_cs =')
  ->execute();

This remains limited to MySQL field storage backend however.


Hide a div on webform submission using ajax

The most effort-free way to hide something i can think to goes trough some CSS.

Inspect the div you want to hide for its id, then just add a rule in your theme CSS

#id { display: none; }


How can an author mark the update date of a node to be visible or hidden for visitors?

You could add new field as a checkbox author check if he needs the update date visible to visitors.

Use panels and page manager to build a custom page view for that node type

Add visibility rule to display the update date if the checkbox field is checked


Getting current node ID for use in VBO operation

You can patch VBO module - to get optional disable batch.
https://drupal.org/node/1902104

It is working - i get normal token current page url, not batch url.

I need to get current NID - where VBO function runs.

when you will get result - please write it, maybe here.


I suggest  split your text to some part  with jquery and by scrolling you append(may with some effect like fadeIn .... ) another part to main part.
I suggest you achieve this job by jquery (client side solution)


How to output custom field of Content type in page.tpl.php?

To output content types fields within a template you'll need to create a specific node.tpl.php for that content type for example node--article.tpl.php and then using the code you already have above should work.


There is some dependency changes with the new drupal version and drush but this should fix it.

composer update --with-dependencies drupal/core:~8.5 symfony/class-loader:~3.2.13 drush/drush:~9.@dev


Views one to many relationship, display many records in columns

How about using the viewsfield module? You can try solving your problem by creating two views A and B, such that -

View A excepts an argument 'ID' and lists all the marks associated with it, by having only the 'marks' field included for display/output.
View B has an ID field, a session field, and a viewsfield. In this third field the view A is embedded.

I hope this helps. I have not tried this, but I am reasonably sure it should help if the module is doing what it promises to do.


Taxonomy path to a view instead to the taxonomy page?

The TVI module should help you with this:

  The TVI (Taxonomy Views Integrator) module allows selective overriding
  of taxonomy terms and/or vocabulary with the view of your choice.
  Using TVI you can easily create custom views to output all terms in X
  vocabuarly.


The most direct way would probably be to do something along the lines of...

function YOURTHEME_preprocess_views_view(&$vars) {

  $name=$vars['name'];
  $display_id=$vars['display_id'];

  if ($name=='THE_VIEW_YOU_ARE_LOOKING_FOR' && $display=='THE_DISPLAY_YOU_ARE_LOOKING_FOR') {

     $vars['more']= // the exact html you want to have in your more link

  }

}

If you would rather work with just templates, you can copy views-view.tpl.php to your theme and name it appropriately, eg, views-view--VIEW_NAME.tpl.php, and then modify the following in it:

<?php if ($more): ?>
  <?php print $more; ?>
<?php endif; ?>

to whatever you want $more to be.

Clear theme registry/caches and you should be all set in both cases.

ADDITION DUE TO COMMENTARY:

Gotcha.  However, the more link is generated from inside the view display plugin via render_more_link() and it eventually creates it by calling up a theme template via...

return theme($theme, $path, check_plain($this->use_more_text())); // D6

or

return theme($theme, array('more_url' => $path, 'link_text' => check_plain($this->use_more_text()), 'view' => $this->view)); // D7

...both implementations of which check_plain() the text entered via the UI.

So, in order for this to work via the UI, you will most probably need to craft up a new views display plugin without that check_plain() in there.

It also goes without saying that you will need to have implicit trust in the folks working with the UI to not enter any errant HTML in there.


In a custom Drupal module do something like:

function sfusd_scheduler_form_alter(&$form, $form_state, $form_id)
{
    // Let's change sticky at top of lists to client preferred verbiage
    $form['sticky']['widget']['value']['#title'] = 'Pinned to top of announcement list';
}


Migrating input formats for taxonomies with empty description

The field is empty so it'll get a format set from the configured default when someone enters a description. If there's no value it doesn't need a format, because the format is purely there to say how the value should be displayed.

In theory a value of an empty string with a format attached might give a different result to a null value (the empty string might be wrapped in <p> tags for example) but this will not usually matter in practice.

So the migration is doing what is expected, by not creating an entry for an empty field value.


how to create file programmatically only login users download it

Create a private file field as you would if they were regular private files.

Hook in to the file download function: https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_file_download/7

Let Drupal handle permissions,  create your file dynamically.


You can set the value of the Exposed form style to "input required". This shouldn't display the items when the first view the page.

Is that what you were after?


Performance issues with Migrate Cron update

Updating all nodes every couple of minutes is bound to kill your performance. It's write-heavy and invalidates caches and there is no way around it in any possible CMS, not only Drupal.

If you cannot decide which nodes needs to be updated on XML read, try to decide on export, and export only nodes that changed since last time. Perform full export-import once a day, deep at night.

Other way around it is to write a custom module that would perofrm following steps:

Download XML file to local variable
Compare checksums of current and previous XML

If checksums was equal, exit.
If checksums was different, perform import.

If changed update XML checksum.

That way you will only write anything if XML was changed - couple of times a day instead of every other minute.


How can I execute jQuery within a *Basic page* content type node?

I am not sure, but You can try to change filter to Full HTML, or the second method, create template file for that content type like node--NAMEOFNODETYPE.tpl.php and clear cache and put your javascript code inside it.

example:

<div>
     // Here YOUR JAVASCRIPT CODE
     <?php print render($content['body']); ?>
</div>

Or another method, in template_preprocces_page you can check: for all nodes by one type - just check:

$node = menu_get_object();
if($node->type == "your type") {
  drupal_add_js('YOUR CODE', 'inline');
}

for only one node by nid:

$node = menu_get_object();
if($node->nid == YOUR NID) {
  drupal_add_js('YOUR CODE', 'inline');
}


How to display a variable in callback hook_menu?

Based on your code, it should be written as

$output =  array(
  'first_para' => array(
    '#type' => 'markup',
    '#markup' => '
Test
 ' . $user_agent,
  ),
);

rather than

$output =  array(
  'first_para' => array(
    '#type' => 'markup',
    '#markup' => '
Test
 ' $user_agent,
  ),
);

You need the period to concatenate the your string and variable.

Edited - Full working module

/**
 * Implements hook_menu().
 */
function testing_menu() {
  $items = array();
  $items['custom_module'] = array(
    'title' => 'My Custom Module',
    'description' => t('Best Custom Module'),
    'page callback' => 'testing_back',
    'access arguments' => array('administer site configuration'),
  );
  return $items;
}

function testing_back(){
  $user_agent = $_SERVER['HTTP_USER_AGENT'];
  $output =  array(
    'first_para' => array(
      '#type' => 'markup',
      '#markup' => '
Test
 ' . $user_agent,
    ),
  );
  return $output;
}


How to execute rules action programatically

rules_invoke_component is used to invoke a Rules Component.

In your case, it seems like you should invoke a Rules Event, using rules_invoke_event.


Image gallery with original image proportions

You most probably want the functionality provided by Masonry API and its sub-modules: Masonry Views and Masonry Fields.

  Masonry is a dynamic grid layout plugin for jQuery. Think of it as the
  flip-side of CSS floats. Whereas floating arranges elements
  horizontally then vertically, Masonry arranges elements vertically,
  positioning each element in the next open spot in the grid. The result
  minimizes vertical gaps between elements of varying height, just like
  a mason fitting stones in a wall.

In the view you will specify a image formatter that only sizes on the width so that the height remains proportional.


How to create an alternate title for a node when in a nodequeue?

I've used this css quite often in these cases:

width: // short width;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;

Which turns something like

A great new article about something so important that we have highlighted it for you

into

A great new article about som...

Obviously, this works best when the jist of the title is in the beginning of it :)


How do I name a mimemail-message.tpl.php template to be used with a specific webform?

As you can see in line 264 of webform.submissions.inc Webform uses submission as the key.
Thus it needs to be named
mimemail-message--webform--submission.tpl.php

There is no way to target a specific webform without some extra custom code work.
mymodule.module
function mymodule_mail_alter(&$message) {
  if ($message['module'] == 'webform') {
    $nid = $message['params']['node']->nid;
    $message['key'] = $nid; // set key to nid
  }
}

Now you can do
mimemail-message--webform--250.tpl.php


Views exposed filters - how to show "You searched for [exposed filters]" above results?

Use the Exposed Filter Data module. With it you can print the filters used in the view header.


Howdo I display all the images from a field in a view?

You see the limited number of values (as a drop-down) in Views instead of a text field where you can type in all or some number because you have limited the number of values this field can take in its settings.

Check your Content type field settings for "Imagenes" and see if it's limited:

Since this is in your field settings it's enough to set your Views field multi-settings to 5 because there are never more than five values in this particular case.


LDAP authentication module not working in xampp

Yes i have sorted out this issue.
In the \xampp\php folder you will find this file:libsasl.dll
Copy it into the \xampp\apache\bin folder.
Now try and start Apache again.It should now start.Now it is working.


Since you have Product Referenced field hanged on your content type you can access your Product ID in content 's $product_id = $vars['node']['field_product'] then you can get commerce product item with commerce_product_load($product_id) and then access field_price.


Where do I set the HTML that wraps a module's config $form inputs?

Did you look at form templates? The steps change a little if you are using a starter theme, but the basics are the same.

http://themery.com/dgd7/advanced-theming/forms/with-templates


How to use Rules to email users when any field(s) is changed in a node (and include the unchanged/changed values for that field)?

Some of the ingredients you'll need for a possible solution to make this work:

The Conditional Rules module.
Rules Actions "Add a variable" and "Set a data value".

Read on for more details ...

Here is a rule, in Rules export format, which is a prototype of what you're trying to get to work:

{ "rules_notify_admin_of_selected_field_updates" : {
    "LABEL" : "Notify admin of selected field updates",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_conditional" ],
    "ON" : { "node_update" : [] },
    "IF" : [
      { "OR" : [
          { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_optionlist" } },
          { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_free_format_text" } }
        ]
      }
    ],
    "DO" : [
      { "variable_add" : {
          "USING" : { "type" : "text", "value" : "Field changes applied to a node:" },
          "PROVIDE" : { "variable_added" : { "field_changes" : "Added variable" } }
        }
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : {
                "data" : [ "node:field-optionlist" ],
                "value" : [ "node-unchanged:field-optionlist" ]
              }
            },
            "DO" : [
              { "data_set" : {
                  "data" : [ "field-changes" ],
                  "value" : "[field-changes:value] - Field Optionlist changed from \u0022[node-unchanged:field-optionlist]\u0022 to \u0022[node:field-optionlist]\u0022"
                }
              }
            ]
          }
        ]
      },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : {
                "data" : [ "node:field-free-format-text" ],
                "value" : [ "node-unchanged:field-free-format-text" ]
              }
            },
            "DO" : [
              { "data_set" : {
                  "data" : [ "field-changes" ],
                  "value" : "[field-changes:value] - Field Free Format Text changed from \u0022[node-unchanged:field-free-format-text]\u0022 to \u0022[node:field-free-format-text]\u0022"
                }
              }
            ]
          }
        ]
      },
      { "mail" : {
          "to" : [ "site:mail" ],
          "subject" : "Field changes in node with nid=[node:nid]",
          "message" : [ "field-changes" ],
          "language" : [ "" ]
        }
      }
    ]
  }
}

Some more details about the above rule:

It showcases updates to (only) 2 fields, i.e.:

a selection list field with machine name  field_optionlist, and a few possible values.
a free format text field with machine name field_free_format_text.

The Rules Actions "Add a variable" is to create an appropriate variable.
The Conditional Rules module allows for including like "Rules Conditions" within the Rules Actions.
Using "Set a data value" we append what's appropriate to that variable.
In the end (last Rules Action), we make Rules send an eMail with an extremely basic eMail body: the content of the variable we populated in the previous Rules Actions.

Assuming that you enabled the Conditional Rules module, you should be able to import the rules example above in your own environment (provided you first defined 2 similar fields with identical machine names to make the import work, or after you first edit the field names to match your field names).

Homework:

Extend the prototype from 2 to 20 fields (= sames as except ...).
You may want to improve the formatting of the eMail body, eg add some relevant HTML tags in it to make it more readable. Maybe also its subject, etc.

Voilà, happy (Conditional) Rules-ing!

PS: Would be nice if you could use a Rules "loop" to iterate over all 20 fields in a single loop, similar to what is shown in the answer to "How to create a rule to send an email to a list of selected email addresses?". However I'm not aware of anything in Rules to do so.


data selector not working in custom Module

Have you tried with the options as 'getter callback' & 'setter callback'? It seems that these data selectors that you are creating needs to pass the values to the already implemented hook_rules_condition_info as parameters.


The idea of creating a menu entry to redirect in the case of a 403 is fine, except that you need to configure the core handler to point to it, which is the element missing from your question (it's mentioned in the comment you linked to).

Once you have defined your menu entry go to Administer > Site Configuration > Error Reporting and set the value of the 403 page to the corresponding path.

Now the page callback for your menu entry will be invoked whenever there is access denied, so you can supply the appropriate logic for your needs.


Alternative ways to group results of a view by CCK field?

You can do almost anything you want within a views template.  If you look at the Theme Information in the View UI, you can see what you can modify, or just cd into modules/views/theme and take a peek at them.  But, given that the $view variable is available to almost if not all of the templates (whether or not the comments say it is), and $view->result is an array of row values of the view, you can certainly foreach() through it and do whatever you want.  Otherwise, you have the whole gamut of preprocess() hooks, views_pre_render() of which is probably most of interest here.


Independent arguments for View Page and Attachment

Personally, if you just want some content from the node at the top of a view, I'd override the Views template.

Then, in that template just use the following code to get the content:

<?php if (is_numeric(arg(2)) : ?>
  <?php $node = node_load(arg(2)); ?>
  <?php print $node->content; ?>
<?php endif; ?>

I'm pretty sure you can get attachments to inherit arguments, but they can't be used independently; all arguments will always affect the parent view.

If you have to use a view, you can always do as above, create a template, then create a 'new' view; then, embed that view inside the other using:

<?php print views_embed_view('viewname', 'displayname', arg(2); ?>

This will manually pass the third argument into the embedded view.


If writing code is not an issue you could probably handle this in your custom module's hook_init() implementation by using sessions (to check if the user has been redirected already) and PHP-s $_SERVER['HTTP_ACCEPT_LANGUAGE'] variable. Assuming that your site is using path prefixes to determine the language the code could be something like this:

function mymodule_init() {
  // If the user landed on the front page and hasn't been redireced during their session.
  if (!isset($_SESSION['mymodule_redirected']) && drupal_is_front_page()) {
    global $language, $base_url;
    $current_lang = $language->language;
    // Available languages besides the sites main one that is using $base_url as it's path.
    $available_langs = array('en', 'de');
    $langcode = explode(";", $_SERVER['HTTP_ACCEPT_LANGUAGE']);
    $langcode = explode(",", $langcode['0']);
    $langcode = explode("-", $langcode['0']);
    $lang = $langcode[0];
    $_SESSION['mymodule_redirected'] = TRUE;
    if (in_array($lang, $available_langs)) {
      if ($lang == 'en' && $current_lang != 'en') drupal_goto($base_url . '/en');
      if ($lang == 'de' && $current_lang != 'de') drupal_goto($base_url . '/de');
    }
  }
}


How to create a new role with authenticated user permissions

Got it. following code will achieve the this functionality,

$role = new stdClass();
$role->name = 'New role';
// load the authenticated user role
$auth_role = user_role_load(DRUPAL_AUTHENTICATED_RID);
// Give the weight more than authenticate user, so that
// New role will have all the authenticated user permissions
// by default.
$role->weight = $auth_role->weight + 1;
user_role_save($role);
$auth_permissions = user_role_permissions(array(DRUPAL_AUTHENTICATED_RID => 'authenticated users'));
$auth_permissions += array('other permissions');
// Grant permissions to our 'New role' role
user_role_grant_permissions($role->rid, array_keys($auth_permissions[DRUPAL_AUTHENTICATED_RID]));


There's no point doing that, use node_load() or node_load_multiple() instead (or entity_load()). EFQ exists to return you the IDs of entities, essentially so you can use them in an entity load function. If you already know the ID beforehand, then using EFQ is a waste of a database query.

To illustrate, if you were to add a nid condition to your query, then these:

->entityCondition('bundle', 'article') // ex. article
->propertyCondition('uid', $uid) // node written by a specific user
->propertyCondition('status', 1);

are all redundant, your query will just be:

$query->entityCondition('entity_type', 'node')->propertyCondition('nid', $nid);

and the only useful data you'll get is the node ID, which you already have.


How can I add multiple field collections based on a reference on a new node

I ended up using the same approach as How to create (& pre-populate) multiple “field collection” fields on an ajax call.

Use hook_form_FORM_ID_alter() to the node you need the functionality at.

// Add ajax callback when a node reference is entered or changed.
$form['field_node_reference'][LANGUAGE_NONE][0]['target_id']['#ajax'] = array(
  'callback' => 'your_module_ajax_rebuild_form',
  'wrapper' => 'field-collection-values',
);

Create ajax callback.

/**
 * Ajax callback, rebuilds and returns the field_collection_colorizer
 * element.
 */
function your_module_ajax_rebuild_form() {
  // Get Field collections and children.
  $field_collection_colorizer = &$form_state['field']['field_collection'][LANGUAGE_NONE];
  $field_childs = &$form_state['field']['field_collection'][LANGUAGE_NONE]['entity'];

  // Found that I had to set item and items count in order for this to work.
  $field_collection_colorizer['item_count'] = $options_count;
  $field_collection_colorizer['items_count'] = $options_count;

  // Create any new field collection instances if needed.
  for ($i = 0; $i < $field_collection_colorizer['item_count']; $i++) {
    if (!isset($field_collection_colorizer['entity'][$i])) {
      $field_collection_colorizer['entity'][$i] = entity_create('field_collection_item', array('field_name' => 'field_collection_colorizer'));
    }
  }

  // Reset the input to make sure cached version of the form insn't returned.
  $form_state['input'] = array();

  // Rebuild the form.
  $form = drupal_rebuild_form($form_state['build_info']['form_id'], $form_state, $form);

  // Return the field you want to replace.
  return $form['field_collection_colorizer'];
}


8 autocomplete pass current value to function

The form value is automagically added as a query parameter so it is not necessary to pass the current value. This is accessible in the Request object. The controller class method should be:

public function autocomplete(\Symfony\Component\HttpFoundation\Request $request) {
  $value = $request->query->get('q');
}


Remove VAT based on company field and country

I got the right settings now, but I have one problem. I want to show my product prices always with VAT. But with my current settings in rules the price is showing without VAT until I make a country selection on the checkoutpage.

In the view I selected: Display the calculated sell price for the current user.

Is there a way to fix this? Thanks!


How to test if current page is an admin page?

* Updated *

When I first answered this question, node edit and taxonomy edit pages weren't set as admin routes.  So I added separate checks for those.  Such separate checks aren't necessary any more.  The following seems to cover it pretty well:

if (\Drupal::service('router.admin_context')->isAdminRoute()) {
 // do stuff
}

If you want to check a route other than the current route, you can pass it into isAdminRoute().

Note, the above way won't work for node edit pages or taxonomy term edit pages if you uncheck "Use the administration theme when editing or creating content" on the theme admin page at /admin/appearance.  Then you'd need a separate check.

* Original Answer: *

To test if a page is an admin page, you can use a two step process.  Since regex for the node edit may not be using the admin theme.

First I use the isAdminRoute method:

  $route = \Drupal::routeMatch()->getRouteObject();

  $is_admin = \Drupal::service('router.admin_context')->isAdminRoute($route);

Then you can use an additional check for the path to see if it's a node edit page:

  $current_path = \Drupal::service('path.current')->getPath();
  if(preg_match('/node\/(\d+)\/edit/', $current_path, $matches)) {
    $is_admin = TRUE;
  }

Here's a pretty elaborate, but pretty complete way to test for node and taxonomy term edit pages as well as other admin routes:

  $route = \Drupal::routeMatch()->getRouteObject();

  $is_admin = FALSE;
  if (!empty($route)) {
    $is_admin_route = \Drupal::service('router.admin_context')->isAdminRoute($route);
    $has_node_operation_option = $route->getOption('_node_operation_route');
    $is_admin = ($is_admin_route || $has_node_operation_option);
  }
  else {
    $current_path = \Drupal::service('path.current')->getPath();
    if(preg_match('/node\/(\d+)\/edit/', $current_path, $matches)) {
      $is_admin = TRUE;
    }
    elseif(preg_match('/taxonomy\/term\/(\d+)\/edit/', $current_path, $matches)) {
      $is_admin = TRUE;
    }
  }


Link existing social media accounts to drupal account

May be you are looking for this module. It supports many providers for register and login integration.

Basic version is free. More details check below link!

http://janrain.com/products/engage/engage-pricing/


Use drupal.settings variables on javascript

It gets its value from your PHP code. Here is an example of using drupal_add_js:

//Your module.php
$settings = array(
  'helloWorld' => array(
    'display' => 'alert',
    'message' => 'Hello World!',
  ),
);
drupal_add_js($settings, 'setting');

You can access the message in your JavaScript with Drupal.settings.helloWorld.message.


I think you are mis-using #header and #rows properties of the Form API and getting them confused for variables passed to the theme_table function that is being called with the form['#theme'] => 'table'.

This question is similar and might be what you're looking for: How to insert a theme table form inside an existing form?

Perhaps you want to use the tableselect element?


Multisite Installation (Attempt) Goes To My Main Site

Indeed this is not a DNS issue, the problem here is your sites directory is located in the wrong directory. It shouldn't be under all but in the root of sites. In your case it should be:

sites/jackstahlco.com/settings.php
sites/jackstahlco.com/files
sites/meadowlarknm.com/settings.php
sites/meadowlarknm.com/files

If you want the Drupal installation process popping up, you need to put an empty array connection info in the settings.php of the desired website.

$databases = array ();

The sites.php should be like this:

$sites = array(
    'jackstahlco.com' => 'default',
    'meadowlarknm.com' => 'meadowlarknm.com',
);

You don't need to specify the www prefix.


Update button for each line item in cart (drupal 7 commerce)

This is pretty simple to explain but building this will probably give you some headaches.

create a views handler (for the update button)
add the button in the cart view
done

Now the tricky part is building the form handler, you should take a look at commerce_line_item_handler_field_edit_delete which almost does what you need (only it deletes an item instead of saving it).

Since you only need to update the quantity you need to find out line item id and the new quantity. Load the line item and then update it. You don't need to update the order itself, commerce should handle everything when the order is updated.


Are you using the live() function in jQuery to bind your behaviors? Drupal behaviors are triggered on page load and after every ajax request. If your behavior only needs to be called once then you can use the add class processed trick. It is explained here.


Is it possible to hook_form_alter by path?

I think you should use  $_SERVER['HTTP_HOST'] . request_uri();

This will give you the complete path.

So your code should be

function MYMODULE_form_alter(&$form, &$form_state, $form_id, $host) {
  $host = $_SERVER['HTTP_HOST'] . request_uri();
  if ($host == "m.local.dev/donate" or  $host == "m.live.com/donate") {
  $form['submitted']['donation']['amount']['#title'] = t('My new title');
   }
}


It depends on what exactly you want to do. Maybe you just make one contenttype for your product and let users comment this product with nodecomments. This way you can make an extra contentype for your comments with extra fields (e.g. price.). There is no need in displaying these comments afterwards. But why does the webform-module not work for you?


How to retrieve all nodes for a taxonomy term using Services?

I found out how to do it, so I am posting it here in case it is helpful to somebody.
Feel free to post if you know a better way.

I assume you have created some content with fields corresponding to taxonomy vocabularies.

Create a Services View

Install the Services View module, as suggested in my previous comment.
Go to Structure / Views / Add new view
Give your view a name and uncheck 'create a page' because we just want a service.
Click 'Continue & Edit', you should then be in the 'Displays' screen.
Click on the '+Add' displays button, select 'Services'.
Under 'Service Settings' click on the path and change it. e.g my_view_path.

Create criteria for your view

Under 'Filter Criteria' click 'Add'. Do not use Advanced/Contextual Filters.
Search for your field, and click Apply'
'Autocomplete' in the Selection Type, 'Apply and Continue'. It should not matter because we are going to call this from a URL, not a web page.
The 'Configure filter criterion' popover is shown.
Check 'Expose this filter to visitors'. If you don't do this, you will not be able to pass as an argument.
Scroll down to the bottom and click on 'More'.
Take note of the 'filter identifier'. This is the name of the argument you need to pass in the URL, e.g: field_myterm_tid
Click on Apply filter
Repeat for other filter criteria as needed.
Click on Save View

Enable the Service Resource

One last step, go to Structure > Services
You should see a list of endpoints, click 'Edit resources'
Check to enable the resource you just created.

Finally, retrieve your info with HTTP GET

    http: //myserver/my_endpoint_path/my_view_path?field_myterm_tid=XX&field_myterm2_tid=YY

XX and YY are the textual names of the terms


How can I speed up drupal's node_save() function?

You will never get 30 000 inserts a minute using node_save.
No way.

An INSERT is fast because that's all it does.
Node save does multiple inserts (main table, revision table, a table for each field), clears any entity caches, and fires hooks.
The hooks are the tricky part. If you have many contrib modules (or even one that misbehaves) that can really kill performance, especially if the author didn't account for the "I am saving a ton of nodes at once" use case.
For instance, I had to add this to my Migrate class:

  public function processImport(array $options = array()) {
    parent::processImport($options = array());
    // Do not force menu rebuilding. Otherwise pathauto will try to rebuild
    // in each node_save() invocation.
    variable_set('menu_rebuild_needed', FALSE);
  }

On the other hand, if you write a custom save function that invokes no hooks, you are in clear danger of getting inconsistent data, in a state that is unexpected by the system. I would never recommend doing that.
Fire up xhprof and see what's happening.


How can I have a multilingual URL for a views result page depending on the language?

You should enable "Translation sets" and "Path translation" modules, both part of i18n module.

Then in admin/config/regional/i18n_translation/path, you have to add the translated paths and then add a "translation set" which will map all these pages together.

Doing this, you'll be able to switch language on your view page and retrieve the corresponding alias (same view with different current language)

See also this page on drupal.org documentation.


I found the solution

        $join = new views_join();
        $join->table = 'users_roles';
        $join->field = 'uid';
        $join->left_table = 'node';
        $join->left_field = 'uid';
        $join->type = 'left';

        $query->add_relationship('users_roles', $join, 'node');
        $query->add_where(1,'users_roles.rid','4' ,'=');

This works


Workflow and Organic Groups. How can you email the next state changer when content is posted?

Solved this by writing a module to create a custom token from a field added to the group_node_form.  I followed this tutorial, making adaptations for organic groups:  http://rbayliss.net/story/creating-tokens-drupal-6


is it possible to populate subclass of FieldItemList from code?

So I found out what I was trying to do in a complicated way could be done by simply setting the field values on the node, like this:

            $node->set($field_name, $field_values);
            $node->save();


How to make the comment author name required for anonymous users?

I found the answer:

Implementing the hook_form_FORM_ID_alter() hook you can use the comment form id (comment_comment_form) to alter the form.

The problem was that the field name is inside the author, so you need to use $form['author']['name']['#required'] = TRUE;

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_comment_comment_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
  $form['author']['name']['#required'] = TRUE;
}


Change Menu Item's links Dynamically, per page basis

It depends on how exactly you want to change the links, but views can handle most links if you configure the contextual filters correctly.  Basically, just display a link to the content as the field and then set your filters and contextual filters (getting the argument from the node/user) as you need.

If you just want to change around links for user profiles, there's also the me module.


How to add custom badges depending on the amount of User Points earned?

Why not simply use the user_badges module which explicitly integrates with userpoints?

userpoints_badges
Integrates Userpoints with the User Badges module.

Check out the userpoints contrib modules list, there may be more tools in there you can use..


Publishing events on a calendar to an individual/a specific group/ or all

Events are nothing but nodes so you finding for a solution to have node access for a user, user role, or to all will give you the answer

Might the following modules can do this for you

https://drupal.org/project/nodeaccess_userreference

https://drupal.org/project/content_access


To translate action labels install the core module Actions and go to /admin/config/regional/config-translation/action.

Actions are config entities, which you can translate in an exported config as well, if you don't want to install the UI option.


Can't really comment on the no results problem.

However, the Taxonomy View renders as a page, so no you can't have both the original view and the cloned view enabled at the same time and expect them both to override taxonomy pages.

The only way to have both enabled is to set a different path for each view, which means one or both views would not override taxonomy pages at all.

If what you want to achieve is overriding taxonomy pages for terms of specific vocabularies, what I did was use the Disable Taxonomy Term Listing module to completely hide results of the normal taxonomy page, then replaced that content with taxonomy block views.  If this isn't what you are looking for then feel free to disregard this all ;-)


How to know the format when programmatically setting a field value

You will need to pass price object to it and not just a number. Do like this -

$price = new Price('2000', 'USD');
$entity->set('price', $price);
$entity->save();

You can always look at tests to know how things are working for the module. :)


Conditionally aggregate (count) views field

I have a feeling there may be a solution using a separate view with aggregation and then using the Views Field View module to embed the aggregated view as a field.

Another option (which feels like a bit of a cop-out and cheating) would be to create a content type called "articles count".

Then each time you do a sync with the external publisher you update the "articles count" node title to be "New [count] articles", and set the body to be a list of links to each of the new articles. This is neat as you always have an index to your new articles.

Then simply include this as one of your content types in the original view. To be honest this is probably the easiest way.


You can do it in a custom module (MYMODULE.module):

use Drupal\Core\Render\Markup;

function MYMODULE_page_attachments(array &$page) {
  $fallback = '<link href="fallback.css" rel="stylesheet" />';
  $noscript = array(
    '#tag' => 'noscript',
    '#value' => Markup::create($fallback),
  );
  $page['#attached']['html_head'][] = [$noscript, 'mymodule'];
}


I never found a solution for that. I did it always the following way:

Install the rules module (if you did not work with Drupal's hooks yet - otherwise you could use these hooks for that)
Then give an user a role like "unconfirmed" as soon as a new user account is created by one rule
Then define another rule: triggering event is "user logged in", check, if the user has the role "unconfirmed" and if so -> action "Take role away" (do not know now what the action is called in English).


View should show related articles from shared reference field - relation from a relation

In order to fetch resources under specific Megazine, you need to have the Magazine ID on your contextual filter instead of the Article ID. Here is my suggestion:

Play with your URL pattern to add the magazine ID to it (You can do this using Pathauto and Token Module). Once you install those two modules define a URL Pattern for your articles (/[node: field_related_magazines:entity]/[node:title])

Now you each article page will have a URL with Magazine ID to it so, you can change your contextual filter to get Magazin ID from the URL using "Raw Value From URL". This will give you the result you are looking for.


How to bring the REMOTE ID of a commerce payment into the checkout completion page?

Unfortunately, because each order may have any number of payment transactions (meaning there is no strict 1:1 relationship), we cannot provide a simple token to make this available. You could create a custom Order token for the logic you know works on your site (e.g. [commerce-order:payment-id] that prints the remote ID of the first successful payment associated with the order). Otherwise you could customize the checkout completion page through a custom checkout pane, message text, etc.


What is the benefit of Node Blocks module versus adding content to blocks in body field?

Nodeblock

  This module allows you to specify content type(s) as being a block. This > allows > the content managers of the site to edit the block text
  and title without having to access the block administration page.
  Users only need edit access to that node in order to edit it.

Also, based on above I imagine that you don't need to assign the block a region and a "display only on url". (I could be wrong, never used this module).


How can I trace module dependencies in Features?

Look through the info file of Feature B and look for anything known to be added or modified with Feature A.

My guess (with little information) would be that Feature A defines a field/cck field and Feature B either uses that in a content type or view.


How do I load taxonomy terms basing on the current language?

Use EntityRepositoryInterface::getTranslationFromContext:

$terms_translated = [];
foreach ($terms as $key => $term) {
  $terms_translated[$key] = \Drupal::service('entity.repository')
    ->getTranslationFromContext($term, $language);
}

BTW, you don't need to provide a language code, because the current content language is the default value for the second parameter in getTranslationFromContext() and in a standard multilanguage site this is equal to the current language.


404 when using named placeholders for variable parts of Panels path

For others who find this question and have similar scenario make sure for your arguments you set your context up properly, for mine I had context set to Taxonomy term ID, instead of the Name and as soon as I changed it to name and saved it. Cleared Cache, everything worked again.


Configure Menu Access Visibility and permission

If you edit the content type's menu settings, you can see the menus allowed, you can also set the default parent item.  You could set up multiple content types with each one representing one parent, then remove the permission to change menu settings.  That way each content type will pick the appropriate parent automatically.


Drupal core patches with Commerce Kickstart 2.0

Basing on the content of the drupal-org-core.make file that comes with the distribution, I can say the patches are not part of Drupal 7.34. In fact the make files requires Drupal 7.34, and then lists the patches to apply.

projects[drupal][version] = 7.34

; Patches for Core
projects[drupal][patch][] = "http://drupal.org/files/issues/install-redirect-on-empty-database-728702-36.patch"
projects[drupal][patch][] = "http://drupal.org/files/drupal-1470656-14.patch"
projects[drupal][patch][] = "http://drupal.org/files/drupal-865536-204.patch"
projects[drupal][patch][] = "http://drupal.org/files/issues/drupal-7.x-allow_profile_change_sys_req-1772316-28.patch"
projects[drupal][patch][] = "http://drupal.org/files/1275902-15-entity_uri_callback-D7.patch"

You could apply those patch manually, but you would still be missing all the patches the distribution is applying to third-party modules. See all the lines containing [patch][] in the drupal-org.make file. The following lines are the ones for the Features module, but you can find more lines for other modules.

projects[features][version] = 1.0
projects[features][patch][] = "http://drupal.org/files/1572578-part-one.patch"
projects[features][patch][] = "http://drupal.org/files/1597186-1-features-do-not-cache-includes.patch"
projects[features][patch][] = "http://drupal.org/files/927566-multiple-link_path.patch"
projects[features][patch][] = "http://drupal.org/files/1669720-fix-features-flush-cache.patch"


Show the latest post titles for posts using a specific category

Drupal shows those nodes in http://example.com/taxonomy/term/$tid. If all you want is getting a page listing the nodes using a taxonomy term, that is the page to look at.

If you want to obtain the list of nodes using a taxonomy term with code, you can use the following one, based on taxonomy_select_nodes().

function mymodule_get_node_titles($tid, $order = 'n.sticky DESC, n.created DESC', $limit = 10) {
  $term = taxonomy_get_term($tid);
  $tree = taxonomy_get_tree($term->vid, $tid, -1);
  $descendant_tids[] = array_merge(array($tid), array_map('_taxonomy_get_tid_from_term', $tree));

  $args = call_user_func_array('array_merge', $descendant_tids);
  $placeholders = db_placeholders($args, 'int');
  $sql = 'SELECT DISTINCT(n.nid), n.title, n.created FROM {node} n INNER JOIN {term_node} tn ON n.vid = tn.vid WHERE tn.tid IN (' . $placeholders . ') AND n.status = 1 ORDER BY ' . $order;

  $sql = db_rewrite_sql($sql);

  return db_query_range($sql, $args, 0, $limit);
}

The code to call that function is similar to the following one.

$result = mymodule_get_node_titles($tid);
$items = array();
while ($row = db_fetch_object($result)) {
  $items[$row->nid] = $row->title;
}

$tid is the taxonomy term ID.


Can you duplicate a Drupal 7 site and database when a new user registers?

Yes, using hook_user_insert() to start the process off.  From a custom module that implements hook_user_insert() you can run any code you want.  However to pull it off you're going to have to write quite a bit of custom code.

Your hook_user_insert() function would need to do quite a lot of steps:

Fetch the database connection information defined in settings.php
Run mysqldump to make a .SQL dump of the database
Run a tar command to make a .tar.gz file of the Drupal codebase (PHP files) and files directory.
Zip or tar or something the sql file, the .tar.gz file, and probably some kind of instructions
Present the file for download.  This is made trickier because you don't want to have the file inside your codebase.. or each time you clone the database you'll pick up all the .zip files from previous users in the next user's .zip file.  You either need to serve the file directly, exclude the zip files from future codebase archives, or serve the zip files out of a directory that won't get zipped into the zip file.
(optional) Clear the user out of the master site so that it doesn't exist for future signups.

You ask about Multi-Sites, that's only relevant if you plan to immediately start hosting the cloned site yourself.  If your plan is to have the user download their files and .SQL database, you don't need to worry about that. (The user will have to worry about loading the SQL dump and setting up a database username and password though, which you'll need to babysit them through or it will never end up working out).

If your plan is to clone the site on your server, then you could do it with a multi site.  Your steps would then be:

Fetch the database connection information defined in settings.php
Run mysqldump to make a .SQL dump of the database
Create a new MySQL database to hold the new cloned site 4. There are security implications here.. if your webserver is allowed to create mysql databases, is it really secure from hackers?
Create a new sites/new.example.com folder for the new site (if it were named new.example.com)
Create a new settings.php file for the new site's database in sites/new.example.com
Load the SQL dump from step 2 into the new database (using the command line mysql command)
Redirect user to the new site.  You will need to use Wildcard DNS (ie. *.example.com woudl match site1.example.com, site2.example.com, etc. and you wouldn't need to add DNS entries for each new site).

While this plan is not impossible, it will be quite hard to get working well.  Your biggest challenge will be helping the users get through the complicated task of creating a new database, setting up username and password for it, loading the SQL dump, configuring their webserver etc etc etc.


The issue with updating jQuery manually in Drupal is that the potential arises for parts of Drupal core (and contrib modules) to break because of the change in jQuery version. The main benefit of the jQuery Update module is that it corrects the things that break in Drupal core when jQuery is updated.

Thus, your best option is to utilize the 7.x-2.x-dev version of jQuery Update, which includes rudimentary support for jQuery 1.7.x. Keep an eye on the issue queue related to this version so that you can report and/or investigate any issues that may arise in utilizing jQuery 1.7.x in Drupal 7.


Node update date changes when saving without changing anything

If you save a node then it has changed according to Drupal...regardless of whether or not any specific property/CCK field values have actually been changed.

You can find the evidence for this in the node_save() function which contains this line of code which runs for every single call to the function:

// The changed timestamp is always updated for bookkeeping purposes (revisions, searching, ...)
$node->changed = $time;

Drupal does not do any sort of diff against the current and new revisions of a node when saving, so if you've pressed "Save" it makes the assumption that you wanted to add a new revision of the node.


Pages are cached for anonymous users. Views obtains random image every time it has it's chance to work, but for anonymous your cache time is probably significantly longer.

All you have to do is to disable cache on the page you have this view on. How depends on the cache system you are using.


REST request through Actions and Triggers

I think the Rules HTTP Client module will suit you:

  This module adds an action wrapping of drupal_http_request to use
  Rules for making http requests. It has many general uses, because the
  Hypertext Transfer Protocol is the foundation of web data
  communication.


How to see the results of my first module

hook_views_query_alter() is supposed to alter the query passed as second parameter, or the view object passed as first argument, not to output anything. If you want to debug the hook, you should use code similar to the following one.

watchdog('my_module', 'View: @view', array('@view' => print_r($view, TRUE)), WATCHDOG_DEBUG);

The name you gave to your hook is wrong: You just need to replace hook with the short name of your module. For a hook like hook_views_query_alter(), the function name is not my_module_hook_views_query_alter(), but my_module_views_query_alter().


error 500: Premature end of script headers: index.php

@mcaleaa answer helped me on an acquia based site. To fix it I commented out the following lines in development.services.yml:

parameters:
  http.response.debug_cacheability_headers: true


Find the drupal facebook module listing on this link

So far I find fb module will be worth starting with.

  This set of modules turns Drupal into a platform for developing
  Facebook Applications. This allows you to embed your content and
  features within facebook, or allow facebook users onto your site via
  Facebook Connect.

A quick glance for module description is here.


When you create a node they will always use the url node/[nid].

You can use the path auto module to create an url alias for the standard node. Path auto uses the token module to create the url alias for the nodes.

What you can do, is to create a token for the value of the field, and then setup path auto to use the contents of the field when creating the url alias.

Another thing you could do is to use the ShURLy module, to actual create short urls. You could make a custom module where you created or update the short url for the node when saved, and let ShURLy handle the redirects.


Views module: How to limit access by user

Try the Views Access Callback module.

  Provides callback-based access control for Views.

  Available callback functions are defined by modules using hook_views_access_callbacks() function (in the same way as in hook_perm()), then could be set in the view's "Access restrictions" configuration.


Is there a way to Embed Facebook Videos?

I was able to embed facebook, youtube and vimeo videos in a view using just the following:

Drupal version:  7.54
Media Module version:  7.x-2.0-rc5
Media: oEmbed Module version:  7.x-2.7
Entity view modes module: 7.x-1.0-rc1 // optional

Facebook URL:  https://www.facebook.com/video.php?v=10153231379946729

Try the above URL format.  If the video still won't embed, then it's probably the configuration.

My media field in the content type is setup as follows:

Field Type:  File
Widget:  Media Browser
Enabled browser plugins:  Upload and Web
Allowed file types: Image and Video
Allowed URI schemes: oEmbed resources and Public files
Allowed file extensions for uploaded files:  png, gif, jpg, jpeg

Note this field supports both images and videos.

Then you need to setup your file display for videos here:

/admin/structure/file-types/manage/video/file-display

I used the Entity view modes module to create a a new view mode for this field.  Then I selected the oEmbed formatter for my view mode.

Then in the view, select the Rendered file formatter and the view mode you created.

Then when creating the node, try the above url.


Error Passing Extra Parameter to Custom Form

The problem is that your FormSettings class is not the controller in this case. It's the controller method which is where the routing system expects $arg_1.

I think you need to define your own controller which accepts the request and passes the argument to the form. Extending the core Drupal\Core\Controller\FormController class is probably the simplest way forward.


Check out the example on Batch operations. And remove batch_process() from your code. Since you are starting the batch in a form submit handler batch_process() is interrupting that. Just batch_set() and Form API takes care of the rest.

// Only needed if not inside a form _submit handler.
// Setting redirect in batch_process.
batch_process('node/1');


You can alter a webform by modifying the YAML content of the config field elements:
use Drupal\webform\Entity\Webform;
use Drupal\Core\Serialization\Yaml;

  $webform = Webform::load('contact');
  $elements = Yaml::decode($webform->get('elements'));

  // add a field
  $elements['additional_field'] = [
    '#type' => 'textfield',
    '#title' => 'Additional field',
  ];

  $webform->set('elements', Yaml::encode($elements));
  $webform->save();


Getting pages defined by taxonomy to display in a view

Hope this will help you,

In Drupal 7,  you can use Context module.

Context : It allows you to easily organize your site into manageable sections .
Create a new context using the path - videos/%category and arrange the items like Overall View.

Note : Context


preg_replace() not working on node title in hook_preprocess_page()

Just did dpm($node->title) and noticed extra white-space here:

building  Sell, Alatau r-n // City - mon, 03/03/2014 - 22:29

Though, when i was just printing it $node->title it didn't showed any extra white-spaces.


Taxonomy vocabulary not showing up as existing field in new content type

To use taxonomy with your content nodes, you have to add fields to your content types that allow you to assign taxonomy terms.
To add a field for your taxonomy to a content type:

Go to Structure > Content types.
Find the listing for the content type you want to modify, and then
click its manage fields link.
In the Add new field section, enter text for the Label and Name
columns.
In the Field type column, select Term reference from the drop-down
menu.
In the Widget column, use the drop-down menu to select from the
following widgets:

  Check boxes/radio buttons - The taxonomy terms are listed in a check box on the content creation page for this content type.
  Select list - A list of the taxonomy terms are displayed on the creation page for this content type.
  Autocomplete term widget (tagging) - A text box is added to the content creation page for this content creation page.

Selected or entered taxonomy terms are assigned to the content node when the node is saved or published.
Click Save.
In the Vocabulary drop-down menu, select the vocabulary you want to
use with this content type.
Click Save settings.

A taxonomy term field is added to your content type, using the label you chose. When you create content of this type, you will now find a field on the creation and edit forms that allows you to assign taxonomy terms to the content node.

Thank you.


Like PHP documentation says:
In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>

http://php.net/manual/en/control-structures.foreach.php


Rather than filtering on a certain field (and then exposing the filter), try adding a filter of the type 'Search terms'. That uses drupal's search module to search, which has much smarter ways of searching.


The SMTP module configuration page is at admin/config/system/smtp.

Make sure that you have the permission change the SMTP configuration.


How do I treat the phrase as individual words in Search?

When adding text fields to your search index, you need to indicate it's usage by specifying if you want it to be a Fulltext field or a String field.

You can add the field twice, once a String and once as a Fulltext field.

If you are using views, you'll want to make sure your full text search exposed filter includes the Fulltext version of this field, and is set to "Contains any of these words"


How to get nodes with term programmatically

You want to specify that you searching for nodes first (and optionally by your content type), and then filter by term:

$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'YOUR_CONTENT_TYPE_HERE')
->fieldCondition('field_game', 'tid', 5);

$result = $query->execute();
$nids = array_keys($result['node']);
$nodes = entity_load('node', $nids);

Here's a good example of an entity query like this (and more field conditions)


Boost – Cache expiration does not clear cache in views pages

Finally the solution was simple. Apparently you cannot use aliases in the Custom pages settings in the Cache expiration module. By adding taxonomy/terms|wildcard in the custom pages box, and also setting the cache to None in each concerned View (in the Advanced section), the cache expiration worked as wanted.

Hope this helps, if anyone else has this problem.


you can use visibility:hidden; (and height and/or width 0px). I use visibility:hidden; when display:none is not useful (issues of inheritances of CSS, or maybe still you can need the values of the hidden elements).

Other suggestion. I have several forms that use lots of checkboxes, so I use Vertical Tabs http://drupal.org/project/vertical_tabs to divide the forms in several tabs, to show only one group of checkboxes per tab. So here is not necessary to remove labels of checkboxes.


Each content type will have a form associated with the content type. Using hook_form_alter, you can change these items and set them in batch.

Here is a great video that teaches how to do what you are asking, but using the author check box.  Using a technique like this you could set everything to 'on' (1).

http://mustardseedmedia.com/podcast/episode53

How many is 'Tonnes' - do you have 50 content types or 500? Remember you would have to write custom code to do this, so you would need to be familiar with PHP and how modules are written.  If that is not your forte and there is not a module, it may be best just to dedicate a few hours and a beer to it :)


You can create your custom code in a hook_cron, and you can handle your verifications following the date of publication.


For a strictly hierarchical organization (i.e. an inverted tree) I would use the core Books module.  With a book, you get some "extras" to help you with maintenance and navigation. E.g. you get a drag and drop UI to help you re-organize the entire book (or parts of it), you get up/down/sideways navigation links automatically created and inserted, and you get meaningful breadcrumbs.  You also get a "Create child node" link at the bottom of any node that is part of the book.

Also note that in Drupal 7, any node content type may be included in the book (i.e. you're not restricted to the "Book page" content type. However, you can't include non-node entities such as taxonomy terms, files and users.

I would not use the References as it is more restricted than the Entity reference module.

And I would only use the Entity reference if I wanted to create a linked structure that is not hierarchical but some sort of directed graph, or I wanted to include non-node entities in this structure.

A typical use case for the Entity reference module would be the "Related issue", "References", "Referenced by" (directed graph); and "Parent issue", "Child issue" (hierarchical) links that are maintained in the new issue tracker system at the D7 version of Drupal.org.

To sum up.  You get a lot of tools for maintaining the structure for free with the core Books module, but you're restricted to having a hierarchical structure made up if nodes.

With Entity reference, your structure can be made up from any entity type, and it can be a directed graph, but there is no tools to help you maintain the structure or to navigate it (beyond clicking on the links).


Editing field twig template for taxonomy term

The field type for taxonomy terms is entity-reference. You can use the field type for the naming of the field twig:

field--entity-reference.html.twig

Because there may be more than one reference field, it is more specific to use the field name, for example a twig for the preinstalled tags field:

field--field-tags.html.twig

If you want to use the target entity of a reference field as theme suggestion you would have implement this in a hook.

Edit acc. to the clarification:

If the field is inside of a taxonomy term, you have to add one more detail, either the field name or the name of the vocabulary:

field--taxonomy-term--field-body.html.twig
field--taxonomy-term--tags.html.twig


How can I identify if a database is D6 or D7?

In Drupal 6 the node revisions are in {node_revisions}, and in Drupal 7 the node revisions are in {node_revision}.  So, you can just check which table exists.  There are some structural differences with the tables, too.  For example there is a status column in D7, but not in D6.


Custom datepicker options are now supported (as of Date module version 7.x-2.6) by setting the necessary values with #datepicker_options. Alex's use case of a custom form element to display only future dates would look like this:

$form['date'] = array(
  '#prefix'=>t('When do you want to start the featured campaign?'),
  '#date_format' => 'Y-m-d',
  '#date_year_range' => '0:+1',
  '#type' => 'date_popup',
  '#weight'=>0,
  '#datepicker_options' => array('minDate' => 0),
);


Cache is not clearing, deleted template is still loading

Make sure you clear your browser cache as well as Drupals.  Also it's worth checking you're making the changes in the right template files.  You could do this by switching templates in > admin > appeRances .

I hope this helps .


How do I define multiple blocks in one module and include different javascript for each?

Use the following folder structure to create multiple custom blocks in drupal 8

-mymodule
--src
---Plugin
----Block
-----block1.php
-----block2.php
-----block3.php


How to add GitHub repositories in Profile Installation

The easiest way is to add the dependencies to your profile's composer.json file, and use Composer to install the profile into your project. The dependencies will be automatically downloaded with it.

Failing that, it'll be a custom script job which will take whatever shape makes sense for your workflow/config.


ob_start(), ob_get_contents()  do not work in preprocess functions?

I think nothing is left on buffer in Drupal. After evaluating each template the rendered output is preserved as value and passed to outer level template. In this scheme Drupal might be getting buffered content and clearing it across each template.

That is why you should look for variables in that scope.


Can't you use [node:field_calendar_date:custom:l, Fd, gia]? Custom being whatever date format you set up. (like the presets: short, medium, long)

Make sense?


Cannot change date input format in views exposed filter

Well, I am not proud of the clunky fix but it works!

function gmcvo_date_format_views_query_alter (&$view, &$query){
    $newDate = DateTime::createFromFormat('Y-d-m H:i:s', $query->where[1]['conditions'][0]['value']);
    $query->where[1]['conditions'][0]['value'] = $newDate->format('Y-m-d H:i:s');
}

If someone has a better way to do this it would be great to hear it...

edited to use the new datetime object instead of strtotime


Form Validation: Let the comma as separator to be valid in integer field input

If you have integer (or Big int) field you can't submit data with , in integer field and this means that you should strip all , before data passed to Drupal default form submit handler ( as you know before data passed to submit it must be  validated first ) So  the tiny and quick solution is  you set a custom  validate handler  that  called before Drupal node validation handler then in there try to strip all , ( manipulate data in your custom validation handler ) and then enjoy it.

 // in your custom module

function yourmodule_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == 'your_form_id' ) {
                array_unshift($form['#validate'], '_mycustom_validate_handler');
}
}

function _mycustom_validate_handler($form, &$form_state)
{
$form_state['values']['your_integer_field']['und'][0]['value'] =strtr($form_state['values']['your_integer_field']['und'][0]['value'] , ',' ,'');
}

And if you also  want save , in database(!!!) try text field instead using integer field  and then with client side validation  Regex  Rule validate what you want.


Creating some views fields for a taxonomy menu with the active trail CSS classes?

Silly me!! This is how you do it, without even thinking


A little googling and I found one solution, I'm not sure if it is the correct way to go.

I created a small module with one function, installed and enabled the module and it seems to work exactly as I need.

The mymodule.module file contains the following code:

function mymodule_views_query_alter(&$view, &$query) {
  // this is the name of our View and Display
  if ($view->name == 'upcoming' && $view->current_display == 'block') {
    // override the ordering
    // this is because the two different date fields are one or the other
    // but not both fields, so we coalesce.
    $query->orderby = array(
      array(
        'field' => 'COALESCE( field_data_field_repeatdate_field_repeatdate_value, field_data_field_startdate_field_startdate_value)',
        'direction' => 'ASC',
      )
    );
  }
}

This gets called in when needed and uses COALLESCE to on the sort order (


I've found out I also have to send the Accept header:

Accept: text/csv

I'm also sending some parameters on POST and PUT, in JSON format (the resource also accepts JSON for input), so I also send:

Content-Type: application/json

and, on the query string, as mentioned, _format=csv


Embed view and set filter from CCK field

You should use arguments instead of filters on your view. That way you can use views_embed_view.

Just add an argument to the view with the same field you would use as a filter. That adds a where condition to the views query in a similar way as a filter would do.

Then pass on the CCK field value as the third argument on your template file like this:

print views_embed_view('view_name', 'default', $node->field_name[0]['value']);


You need to run YourDomain/update.php and here you can find why.

If the problem is not resolved and (hjhkjhj) is a custom module, then you can't have the same function with the name twice. In your case views_views_plugins.


Custom Views Filter - won't display as checkboxes

I've the same issue, debugging the code I've seen that the exposed_translate() method changes any checkboxes form types to select if $form['#no_convert'] and #multiple are not set.

So you need to change it to:

$form['value'] = array(
   '#type' => 'checkboxes',
   '#title' => t('State'),
   '#multiple' => TRUE,
   '#options' => $options,
   '#no_convert' => TRUE,
);

Here is the code:

/**
   * Make some translations to a form item to make it more suitable to
   * exposing.
   */
  function exposed_translate(&$form, $type) {
    if (!isset($form['#type'])) {
      return;
    }

    if ($form['#type'] == 'radios') {
      $form['#type'] = 'select';
    }
    // Checkboxes don't work so well in exposed forms due to GET conversions.
    if ($form['#type'] == 'checkboxes') {
      if (empty($form['#no_convert']) || empty($this->options['expose']['multiple'])) {
        $form['#type'] = 'select';
      }
      if (!empty($this->options['expose']['multiple'])) {
        $form['#multiple'] = TRUE;
      }
    }
    if (empty($this->options['expose']['multiple']) && isset($form['#multiple'])) {
      unset($form['#multiple']);
      $form['#size'] = NULL;
    }

    // Cleanup in case the translated element's (radios or checkboxes) display value contains html.
    if ($form['#type'] == 'select') {
      $this->prepare_filter_select_options($form['#options']);
    }

    if ($type == 'value' && empty($this->always_required) && empty($this->options['expose']['required']) && $form['#type'] == 'select' && empty($form['#multiple'])) {
      $any_label = variable_get('views_exposed_filter_any_label', 'new_any') == 'old_any' ? t('<Any>') : t('- Any -');
      $form['#options'] = array('All' => $any_label) + $form['#options'];
      $form['#default_value'] = 'All';
    }

    if (!empty($this->options['expose']['required'])) {
      $form['#required'] = TRUE;
    }
  }


You could use a hook that checks for this field (which you'd have to add to the content type that you're importing into) then delete the node if its set to 1.  In order for this to work you would need to specify a field as unique otherwise feeds wouldn't know what item that already exists is to be deleted.


Compute price based on order item fields

The short answer: No

Why:

In the Drupal Commerce Slack Channel, I asked whether it would be possible to add Order Item to the Context class. This was the response:

  price resolvers are also called by regular price formatters the whole
  point of the context is to provide known information when the order
  item is missing

  so changing that would be a big API change if you need order item
  data, for now use an order processor instead

How to solve the issue:

Replace YOURMODULE with the name of your custom module.  The Priority value is used to prioritize what order processors get called first.  You need to look at other order processors and figure out when yours should be called and set the priority value appropriately.

In YOURMODULE.services.yml

services:
    YOURMODULE.order_processor:
    class: Drupal\YOURMODULE\OrderProcessor
    arguments: []
    tags:
      - { name: commerce_order.order_processor, priority: 110 }

In YOURMODULE\src\OrderProcessor.php

<?php

namespace Drupal\YOURMODULE;

use Drupal\commerce_order\Entity\OrderInterface;
use Drupal\commerce_order\Entity\OrderItemInterface;
use Drupal\commerce_order\OrderProcessorInterface;

class OrderProcessor implements OrderProcessorInterface {

  /**
   * {@inheritdoc}
   */
  public function process(OrderInterface $order) {
    $order_items = $order->getItems();
    foreach ($order_items as $order_item) {
      if ($order_item->bundle() == 'YOURCUSTOMBUNDLE') {
        // YOUR LOGIC TO FIGURE OUT $calculated_price
        $price = new Price($calculated_price, $currency)
        // Set to TRUE if you want to override unit price.
        $order_item->setUnitPrice($price, FALSE);
      }
    }
  }

Hope this helps!


Since you've already linked my article on the topic, I'll just answer definitively here that there is no way to do this through the user interface. The code I show in that article is the only way to bypass customer profile duplication, but if you wanted to you could apply it to a user interface in a custom module. Just be careful you don't give administrators more control than is safe for your historical order data.


How do I customize an entity's canonical page?

There are modules you can find that help you do that. Search for "computed field" and similar.
You can then adjust your node form (Manage form display) not to show the computed fields, and on the Manage display page (default view mode is what you call canonical, you can create more of them though) adjust the fields so only the computed ones are shown.
One example: Computed Field


How to create custom menus with different path

If you want to give user view page then this :

1) You need to give path as user. That will take you to the currently logged-in user account.

Or if you want go to view edit page:

2) You can use menu token module to give path as user edit page.You can use the token replacements to get to the user edit page.Hope this helps you.

3) You can use user/[current-user:uid]/edit once you have the menu_token module installed.But i dont know why its not working.

You can try installing me aliases module and give path as user/me/edit. This will give option for editing user account.Hope this resolves your current issue.


Using ENTER key to submit default Drupal 7 Search doesn't not return results: Why?

Are you using the <form>'s submit event rather than the <input>'s click event to respond to the form submission? Check out this working example on jsFiddle.

$("#form").bind('submit', function(e) {
    var $div = $("
Transmitting
").appendTo('body');
    $.ajax({
        url: '/ajax_html_echo/',
        data: {html: $("#html").val() },
        type: 'POST',
        success: function(data) {
            $div.html("Received: "+data);
        }
    });
    return false;
});


How to display search results in admin theme?

At the code level you can use hook_admin_paths(), e.g.

function MYMODULE_admin_paths() {
  return array(
    'search/*',
  );
}

Or if you'd rather use a non-code solution, you could install a module like ThemeKey

  ThemeKey allows you to define simple or sophisticated theme-switching rules which allow automatic selection of a theme depending on current path, taxonomy terms, language, node-type, and many, many other properties.


The settings for the menu is on the same page as the menu block settings page. You'll find your menu block at /admin/structure/block where you click configure for your menu block, and you'll be able to change the settings.


Call to undefined function Drupal\Component\Utility\imagecreate()

The imagecreate function is part of php's gd library. If a server has been set up manually it's possible it doesn't have the gd library.

First, figure out which version of php you are using, for example with this command:

dpkg -l | grep '^ii' | grep php

Look for a line like:

ii  php7.2     7.2.19-0ubuntu0.18.04.2           all          server-side, HTML-embedded scripting language (metapackage)

That indicates the server is using php7.2. To install gd library for php7.2 on a system managed with apt you need a command something like:

sudo apt install php7.2-gd

And then the error will be gone.


You can add the webform using hook_page_alter().

/**
 * Implements hook_page_alter().
 */
function my_module_page_alter(&$page){

  // Get the webform's nid that you want to display on the current page.
  $webform_nid = my_module_webform_to_display();

  // Load the webform node.
  $webform = node_load($webform_nid);

  // Render the webform using my custom view mode.
  $markup = drupal_render(node_view($webform, 'my_custom_view_mode'));

  // Add the markup to the page element.
  $page['content']['system_main'][] = array(
    '#markup' => $markup,
  );
}


drupal_mail() and names with apostrophes

I assume a few things:

You have no exotic mail transport installed, having Drupal fallback to phps' mail()
You deliver the mail trough a unix system. Windows deals differently with mail.

Digging into RFC2822 you will find about escaping " and some other characters.

The solution then presents itself as

$to = "\"Another O'Neil\" <anotheroneil@example.com>";
drupal_mail('contact', 'page_mail', $to, language_default(), $values, $from);

print $to; #=> "Another O'Neil" <anotheroneil@example.com>


Whether this is the best, I don't know, but it is pretty easy:

Create a new field called handicap.  It doesn't need to have any value as you will be computing it.
Create a views template for that field.  It would be something like views-view-field--field-handicap-value.tpl.php. If you want it specific to the view, you will need to include its name in there as well, but just look in the Views Styles/Themes to find it.
In that template, do your custom aggregation function, and then output that result instead of the default $output.

Now, if all is good in the world, you will have your handicap output in the view and you can aggregate on that value as well later on in the view, too.


This function can help you

/**
 * Remove a role from a user.
 *
 * @param $user
 *   User object or user ID.
 * @param $role_name
 *   String value of role to be removed.
 */
function custom_remove_role_from_user($user, $role_name) {
  // For convenience, we'll allow user ids as well as full user objects.
  if (is_numeric($user)) {
    $user = user_load($user);
  }
  // Only remove the role if the user already has it.
  $key = array_search($role_name, $user->roles);
  if ($key == TRUE) {
    // Get the rid from the roles table.
    $roles = user_roles(TRUE);
    $rid = array_search($role_name, $roles);
    if ($rid != FALSE) {
      // Make a copy of the roles array, without the deleted one.
      $new_roles = array();
      foreach($user->roles as $id => $name) {
        if ($id != $rid) {
          $new_roles[$id] = $name;
        }
      }
      user_save($user, array('roles' => $new_roles));
    }
  }
}

first load user's roles, then call this function  something like

$user=user_load($uid);
foreach($user->roles as $role){
custom_remove_role_from_user($user, $role)
}


Why does external js only appear in header? D7, in a block, via custom module

Content isn't a valid region for scope, it can only be header or footer. See this documentation: https://api.drupal.org/api/drupal/includes%21common.inc/function/drupal_add_js/7

The render process runs drupal_add_js/css based on items inside of #attached.


While creating node, Check on Provide a menu link. Add Menu link title and select Parent item where you want to add the current node.

That's it


Access restriction modules block nodes, but not teasers?

Uh, okay this is a little embarrassing ... I had my Drupal site update itself and its modules, and lo: it suddenly worked as intended. Whee.


How to prohibit a view for specific languages?

Applying filter while creating views. Add a new filter & select "Node translation" from the "Groups" listed and check "Node translation: Language" and click "Add". Then you can choose languages which you want to show.

OR

  Create Block
  Under Visibility settings change to PHP (If PHP is not an option, go into modules and enable the PHP input method)
  Use below code & save :

 global $language;
    $lang_name = $language->language;
    if ( $lang_name == "en" ) { return TRUE; } else { return FALSE; }

NOTE:  Replace the "en" with the two letter name of what ever language you want the block to be visible for. For Example if you want your block only visible when the language is French, change "en" to "fr" .


You need to change the type for submenu.

 $items['custom tab'] = array(
    'type' => MENU_NORMAL_ITEM,,
);
 $items['custom tab/sub-item'] = array(
    'type' => MENU_DEFAULT_LOCAL_TASK,
);


added to Views header (global unfiltered text) disappears with inspect element

Add your header (for quick testing purposes, so you don't need to add it to a css file)

<style>
 .some-class { border: solid red; }
</style>

To double check that indeed it's not there.

If it's not there (you don't see anything red), then try using Global: Text area instead and use Full HTML as your text format.


Is there anything wrong w giving a node a status other than 0 or 1?

I would keep $node->status to 0 or 1 doing a grep in a couple of installs there are some explicit checks for it. (not in core but in contrib). While there is nothing to stop you, you won't guarantee that things will work with it.

You can create your own field which represents another status and use that for your own needs.


How to pass additional arguments in $form['#after_build']

Most of callbacks like #after_build will received automatically 2 arguments: $elements and $form_state, like this :

my_callback_after_build($element, &$form_state){
//...
}

So you simply have to push your var in the form_state var from where you add your callback :

function custom_third_level_auto_suggest_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
   $form['#after_build'] = 'custom_third_level_auto_suggest_widget_selection_afterbuild';
   $form_state['foo'] = 'bar';
}

And you'll get it in the form_state var of your callback like this:

function custom_third_level_auto_suggest_widget_selection_afterbuild($form, &$form_state){
   var_dump($form_state['foo']); //will print "bar"
}


How to insert fields into a link field in twig?

I don't see anything for the insert tag in Twig or Drupal, but you can preprocess the url variable in mytheme.theme and pass it to the template, giving you what you want:

{{ content.body }}

{{ content.field_subtitle }}

{{ content.field_category }}

The url variable would be created in the preprocess function.

If its a standard link field, you could try:

$link = $node->get('field_link')->getValue();

if (!$external) {
  $variables['url'] = Url::fromUri($link['uri'])->toString();
}
else {
  $variables['url'] = $link['uri'];
}

Edit: totally forgot the line that checks if it is external.


Passing arguments to a URL with view blocks and contextual filters

Views comes with a (initially disabled) page that will display your taxonomy terms for you. If you look for "Taxonomy Term" in your views overview you should find it. It will display all of your taxonomy terms through a view.

It is recommended that you enable the view, clone it, disable the original and work with the clone, to begin with. However, be careful as it will turn all your taxonomy terms into a views page.


Drupal 8: Webform - how to programmatically prevent or call a form submission?

Sitepoint has a nice example of Ajax form validation in Drupal 8:

https://www.sitepoint.com/using-ajax-forms-drupal-8/


Create defaults for panels to be deployed on install only

To start, I created my mini panel as I wanted it to be and did an export. I saved the export code to a file in a custom module I created. I used install file in the module and this hook_install function:

function custom_footer_install() {
  if (!ctools_export_crud_load('panels_mini', 'fat_footer')) {
    $filename = drupal_get_path('module', 'custom_footer') . '/panel_exports/profile.txt';
    $handle = fopen($filename, "r");
    $contents = fread($handle, filesize($filename));
    fclose($handle);
    $panel = ctools_export_crud_import('panels_mini', $contents);
    ctools_export_crud_save('panels_mini', $panel);
  }
}


$(...).find(...).once is not a function Drupal 8.2.5

As suspected and confirmed this is an issue with the bootstrap theme. My advice would be to roll back to the previous working version and open a bug report in their issue queue on drupal.org.


load custom CSS/JS for each CKEditor instance on page

use hook_page_build to add or remove css or js files to the page based on the url. See the examples module for developers on how to add/remove js or css and to examples of render arrays.

your question is not so much about the CKeditor module or WYSIWYG module -- just how to customize css and js on specific criteria such as the page url.


The Devel module can also help here.

It makes a "Reinstall modules" page available at /devel/reinstall, which lets you re-install modules in bulk.

It's also worth mentioning Drush; dis (obviously) doesn't work any more, but pm-uninstall and en still do. And if you have Devel installed, you can invoke a reinstall with

drush dre module1 module2


Multiple copies of the same content shown due to voting

Hmm.. On the right side, go to Advanced, Other, then Query Settings.

Select the checkbox for "Distinct", and click Apply.

According to the help note:

  This will make the view display only distinct items. If there are
  multiple identical items, each will be displayed only once. You can
  use this to try and remove duplicates from a view, though it does not
  always work. Note that this can slow queries down, so use it with
  caution.

There are more options past that if it doesn't work.. making it more strict, for example.  But as the help note mentions.. this doesn't always work.


How can I update webform_submission uid in the table, after which the anonymous user has registered?

It sounds like your webform has already been submitted by the time they reach checkout. So essentially, you may need to "Update" the submission with the new user ID.

Check out webform_submission_update:
http://drupalcontrib.org/api/drupal/contributions!webform!includes!webform.submissions.inc/function/webform_submission_update/7


A question about Drupal Books and assigning classes to the body based on last viewed book

Thanks to No Sssweat's comment my solution for this was to use Jquery to look for the body class that controls the sidebar color then use jQuery.cookie (already packaged in Drupal just need to make sure it loads on every page) to set a cookie with that value. Then if a page visited that doesn't have the body class that indicates it was a book and therefore also doesn't have the color class then I had jQuery .addClass to add the cookie value to the body element.


I figured it out that i used multi-field selector which has its own set of min-max fields limits, which were by default set to display all. There was no conflicts between the CCK pager and the view pager nor with the pager id.


If your real question is more along the lines of:

  Should I make the CSS conform to the markup, or make the markup conform to the CSS?

Then that's just a judgment call, there's no right or wrong answer. Go with what you feel comfortable doing. Some people love the plethora of classes Drupal adds by default, some people hate it. Some people prefer the Bootstrap approach (class, class, class), some people prefer the Susy approach (as few classes as possible, ostensibly). Neither is right or wrong, just different.

Read on for answers to the specific posed questions...

  When to use a tpl.php file instead of a .css file?

The literal answer to that is simply "never".

A CSS file and a template file are for different things, and contain different things. You wouldn't put markup in a CSS file, and you wouldn't put CSS in a template file (except perhaps in rare circumstances like if you were inlining the above-the-fold content or something).

  What are the problems and/or disadvantages of using a single .css file to make styling adjustments on my drupal site?

There are no problems or disadvantages per se. It's arguably better to split your CSS into multiple files, simply for modularity's sake, but those are all going to be aggregated back into one when the site goes into production mode anyway (assuming the CSS you're talking about is "every page" CSS; you haven't mentioned otherwise).

Basically go with what feels comfortable, by your organisation's standards, or whatever general advice you find and like about organising CSS files. Drupal doesn't mind how you do it.