How to create a rule which after several updates in 5 minutes of a node sends 1 message?

Assuming your question is about D7, and that you can think of creating a view for such updated content for (say) "the last 5 mins", there is a solution to do what you're asking about. This solution uses the Rules, Views and Views Rules module, as further detailed below.

1. About the Views Rules module

The Views Rules module makes Views data available in Rules, enabling intuitive rule configuration for dynamic data. Some details from its project page:

  ... provides two types of elements in Rules, configured with a "Rules" view display:

  Views loop: A views loop is similar to a regular Rules loop, but allows looping over rows of view results.

  Collect view result rows (action): This action collects each variable in all view result rows into list variables for use in Rules.

  Tip: When selecting the data type for variables in the view, if the field is an entity identifier (e.g. Node ID), you can set the data type to the entity type (i.e. Node) to directly use the variable in Rules as an entity!

2. Create a view of display type 'Rules'

After you enable the Views Rules module, use Views to create a view of your "updated content for (say) the last 5 mins" (as in your question). Add of view of display type Rules (important, that's the key to make it work!). Here is how you can add such display:

Next configure the row variables, by using the link that says "edit field info", as shown here:

3. Create a Rule Component using the view of display type 'Rules'

Create a Rules Component, using these guidelines:

Add whatever Rules Conditions you might want (if any).
Some Rules Actions you'll need to create (add) for sure:

Create a variable, with no initial value, say you name it "eMail Summary" (machine name email_summary), which will be used in subsequent Rules Actions.
Add a Views loop (by using the link that says Add view loop), and select the "Rules" display created in the previous step. Configure the parameters and variable names. And for each views result contained in your Views loop (about some "flagged content / user", as in your question), perform a Rules Action like Set a data value, for the email_summary variable from the previous Rules Action. The actual value to be assigned, is the previous value of email_summary, to which you append the desired data about the Views result being processed. For this you can use the variables you configured at the end of the previous step (you may have to revisit the previous step to add more similar variables there if needed).
Add a Rules Action to Send an eMail to a selected role (as per your "periodic summary email that gets sent to a specific role"), whereas for the body of that eMail you simply use the value of the email_summary variable.

If you're not familiar enough with Rules to create and populate that email_summary variable, you may want to have a look at the Rules example included in my answer to "How to concatenate all token values of a list in a single field within a Rules loop?", in which a similar variable is used.

Try to execute your Rules Component "manually" (just to test), to unit-test if it works as desired. To do so, use the "execute" link to the right of the Rules Component (in the Rules UI).

4. Schedule the Rules Component for periodic execution

Make sure you have the "Rules scheduler" enabled (a sub-module of Rules).

Improve your Rules Component from the previous step, by adding a Rules Action (as the last action to be performed) to Schedule a Rules Component, whereas the actual Rules Component to be scheduled is the Rules Component itself. You want it to be scheduled in "5 mins from now" (to make it happen every 5 mins).

To execute this Rules Component the very first time, just execute your Rules Component "manually". To do so, use the "execute" link to the right of the Rules Component (in the Rules UI).

Assuming your QA-testing succeeded, and assuming your cron jobs are running also, the eMail should get created next time cron runs (after an amount of time, depending on the amount of time you configured in your Rules Component to get it rescheduled).


How to change the field type of existing fields?

A possible approach to avoid running into this commonly known challenge, is to perform a mini-migration for each of both of your fields, on your PROD website.

Here are the highlights of such approach:

For your eMail field:

Assume your existing field (with type text) has machine name field_email.
Create a new field with type eMail (instead of text), say with machine name field_email_new.

For your Link field:

Assume your existing field (with type text) has machine name field_link.
Create a new field with type eMail (instead of text), say with machine name field_link_new.

Deploy both fields field_email_new and field_link_new to your PROD site, using Features (similar to what you tried to use, but which failed). Since these are new fields, that should not cause similar problems. Obviously, at that point the values of these fields will be empty.
For each of both fields, use an approach similar to what I described in my answer to "How do I move content from one field to another?", which (only) uses modules Rules and Views Bulk Operations. You should be able to reuse the Rules Component included there, after adapting the machine names of the used fields.
To the extend that would be needed, don't forget to adapt custom Rules, Views, etc to reference the new (instead of old) machine names of both fields.
Delete the original (old) eMail field and Link field.
Double check your custom Rules, Views, etc that you (should have) modified in 'Step 5' above, to ensure you don't have any of the typically "integrity" error messages (because you forget or skipped some of them). If any such errors show up, adapt the machine names to the new ones to fix them.

Obviously, steps 5, 6 and 7 can be refined by creating a clone from your PROD site, and prepare that kind of work in some none-PROD equivalent. Possibly combined with using a Features based deployment procedure to migrate your changes from that clone to your PROD site afterwards.

Note: NO custom coding, only some (rather basic) admin stuff, using robust contributed modules (and which can be uninstalled again afterwards).


View in views header still displaying when no result

Looks like you have added the filter only for the Featured Judge View.

Try adding a filter in the View that lists the Judge Nodes. This will completely note render the whole view at all.


How can I configure CKEditor to show content in 'plain text editor'?

Assuming Drupal 7 - goto admin/config/content/formats and change the order of the text formats, placing Plain Text at the top of the list. This will default the edit format, however content that is already created would default to whatever format was used to create it in the first place.

This will however filter quite restrictively the output. If you mean to include a text format that does not perform any formatting at all, on the same page, you can 'Add Text format', label it unaltered or whatever title you prefer, set roles to administrator (very high security risk with giving this format to untrusted persons), and leave everything else blank. This will create an unaltered format which allows things like direct html, javacript and php writing in blocks, etc.


How to create add and edit pages for content types beside to Administration

If it's simply a matter of using the non-administration theme for node edit pages, there is a setting at admin/appearance, at the bottom of the page, for setting the administration theme. It also includes the following check box: "Use the administration theme when editing or creating content". Simply uncheck this to use your non-admin theme for node add/edit forms.


Change the ID used for the pager: The setting is under the advanced options for the view, in the administration area.


dblog not working, page shows a 500 Internal server error

This sounds like the incorrect watchdog data was saved to the database. Truncate the 'watchdog' table that contains your dblog messages in your database and you should be good.


Galera Replication for Drupal

Things you need to watch out for:

Caching
Sounds like you are using memcached, that good because drupal caching needs to be disabled because if one drupal node modifies the cache stored in the db and that change
replicates the other drupal nodes don't know about it creating conditions in which the drupal cache can serve stale content. Most people use memcached for caching to get around this.
Deadlocks
On websites that are high writes you can incur deadlocks when two drupal nodes try to update the same row at the same time. In this case you would want your app to retry the action but Drupal doesn't always do that. In the Galera settings you can set up some settings in my.cnf (wsrep_retry_autocommit=n) to enable retries at the Galera layer to prevent deadlocks being sent to drupal. Although for a website with low writes and mostly reads you may never encounter the issue.

Other than perf testing a realistic workload I don't know of a formula for performance expectation.

For Galera I've used both MariaDB and Percona. Percona does have additional information it can expose for performance and troubleshooting. Not a lot of difference in how they use Galera replication. I've moved innodb databases between percona and maria and had no issues.

I've found a Percona whitepaper on galera performance and best practices for drupal. It seems to cover all the issues I've encountered plus some additional info: http://www.percona.com/files/presentations/percona-live/nyc-2012/PLNY12-galera-cluster-best-practices.pdf

At this time I would use Percona Galera or Maria Galera. I don't touch mysql from Oracle anymore.

hope that helps


Can a javascript variable be made configurable?

Too vague of a question, bring some examples of code.

It might go in a custom module (thus doing differently) or just using JavaScript where you can surely alter values of a variable.


One of these contrib projects:

default_content - for install profiles
entity_pilot - paas content staging (disclaimer, my product)
deploy

Or build your own deployment with rest API


How to hide language selector dropdown on node add page for a role?

Don't use jQuery for this. Better use hook_form_alter.

Check if user has target role.
Print out your $form and find language select in printed array.
Than hide language select.

There are 2 options for hiding:

1st:

$form['language']['#access'] = FALSE;

2nd:

$form['language']['#prefix'] = '
';
$form['language']['#suffix'] = '
';


You would need to do 2 things. Create your own hook_init that runs after boost_init to modify the global $_boost['cache_this'] value & use hook_boost_cookie_handler_callback_alter to write your own boost_cookie_handler function that works with POST.

To check if the page exists in the cache the boost_block_view_status() function has the parts needed but it has not been abstracted out so you would need to create your own function to do this.

That will cache POSTs.

If you want to serve from the cache on a POST (ignore the post) in your htaccess file remove RewriteCond %{REQUEST_METHOD} !^(GET|HEAD)$ [OR].

A lot of things can go wrong if doing this. It's a bad idea 99% of the time.


How can I reset render cache on an entity for current user in hook_entity_view_alter()?

At first I disabled the cache for the link, but the entity was cached, preventing the link from being shown or hidden.  Therefore, I disabled the cache for the entity and that worked.
In the alter hook:
$build['#cache']['max-age'] = 0

The entity is now rendered with the proper state of the cart link.


How to limit the execution of a rule for sending an email to only run once in a day?

Have a look at the "Rules Once per Day" module. Here is how it works (as per the comment in issue 2495775, from the module owner):

You specify a trigger hour on the administration settings page for this module.
The Rule trigger will then run when cron tasks are first run after the start of that hour. The actual run time will depend on your cron task timings.

So this is another way to understand/Read this:

The "Event" will only be triggered when a cron job is run.
And that event will only be triggered 1 time / day, i.e. "next time cron runs after the trigger hour has passed".

With that, you should be able to adapt your "rule that sends an email" to run ... once a day, on any day, including the 28th of each month.


Set permanent status for managed_file in theme settings

I think you just need to adjust your submission handler; don't include the fieldset "options_settings". I use the getValue() method and pass it an array of values, the form key and the index of its value.

  if ($file_id = $form_state->getValue(['header_background', '0'])) {
    $file = \Drupal::entityTypeManager()->getStorage('file')->load($file_id);
    $file->setPermanent();
    $file->save();
  }


Some consider it a best practice to create RDF mappings per a given content type but to also include a unique vocabulary for the Homepage node.

I suggest creating it for the Homepage by giving it a unique content type (you could clone an existing one and change by need).

This solution saves overriding the already RDF-mapped previous content type of the homepage node; An overriding that can be tiresome to create and maintain.


Performance for file serving and storage

If you are storing them the public file system, Drupal does not really interact with them other than to provide the URL.  The .htaccess rules check if the request is for a real file.  If it is a real file, the web server service it up.

So for individual files, it is more about can your webserver handle the load.  You probably want to look at using a static file caching service in front of your site.  CloudFlare does a good job and its basically free. Some alternates are to have a varnish server or a caching Nginx server in front of your server.

Drupal has been used for a lot of sites with a lot of users, files and the like.  E.g. I know that Story Corps uses it internally to manage the thousands (millions) of interviews  they have.

Just be aware that if you need to have a large volume site, you will need to plan for a large volume system setup.  This is true of ANY web software you use.


Can't login: user/login redirects to live site

If the live site uses HTTPS, implements SSL, try to check if is using modules like secure_pages. This kind of modules sometimes causes that kind of redirections.

Another thing to check could be the settings.php to see if there are something related to this issue.


(2nd Attempt!)
It almost looks like the symbolic link they have you create in step 3.1.1, is not working correctly and may be causing this issue.

I don't know anything about the differences between Debian and RH 5.5, but maybe RE doesn't have a /etc/apache2/conf.d directory, in which case you would have to manually add an include line into httpd.conf

Cheers.


Where can I see the options accepted by the field API for the widget type?

There isn't a preset list of widget types; the widget types are the ones defined from modules that implement fields. Using the following code, you can get the list of all the widget types implemented by the enabled modules:

$array = module_invoke_all('field_info');

foreach ($array as $id => $info) {
  print $info['default_widget'];
}

The code essentially invokes all the implementations of hook_field_info(), and print what is defined as default widget.
If you have installed Devel, instead of print you can use dsm().

If you want to know the settings available for the field implementation, then you need to look for the implementation of hook_field_settings_form(), such as list_field_settings_form(), or text_field_settings_form().

function text_field_settings_form($field, $instance, $has_data) {
  $settings = $field['settings'];

  $form = array();

  if ($field['type'] == 'text') {
    $form['max_length'] = array(
      '#type' => 'textfield',
      '#title' => t('Maximum length'),
      '#default_value' => $settings['max_length'],
      '#required' => TRUE,
      '#description' => t('The maximum length of the field in characters.'),
      '#element_validate' => array('_element_validate_integer_positive'),
      // @todo: If $has_data, add a validate handler that only allows
      // max_length to increase.
      '#disabled' => $has_data,
    );
  }

  return $form;
}


How can I use the form control in a drupal form?

Forms can not be nested in HTML. Since Drupal generates HTML, this should not be possible.


Change de default status: Published to Not Published in Publishing Options

You can set the default status on /admin/structure/types/manage/YOURCONTENTTYPE in the publishing opitons. Just uncheck "Published".


(upon writing back and forth, the solution to this problem is listed underneath Edit 2)

not sure where exactly you are stuck. are you asking how to check which taxonomy term they have assigned in a field, or how to show/hide fields?

if you already have access to the taxonomy term id and you need to further check the content of the taxonomy term, you can assign that id to a variable like$tid, and then do something like this:

$myfield_term = entity_load('taxonomy_term',array($tid))[$tid];

I find myself doing this a bunch of times, because of the way I use taxonomy terms.
this gives you an object with all the content of the taxonomy term.
if you wanna fetch information out of it, keep in mind that php uses a different approach for objects than for arrays.
so if you need the title value, instead of doing $myfield_term['title'], you need to do $myfield_term->title

EDIT 1:

can you please show us what the structure of the array looks like?
this can be done in various ways. drupal has its own technique of printing arrays (I believe it's caled devel or something), but I still prefer the good old native php way via print_r.

how I'd do it:

assign the array to a value, e.g. $user_apartments
then in the next line add print_r($user_apartments);
switch back to your browser, right click > view page source (may vary depending on your browser, this would be Chrome)

somewhere at the beginning or further down the code (depending on the file that executed the print_r command) should be a printed list of an array, that may look something like this:

Array
(
[0] => 4
[2] => 11
[3] => 28
[4] => ...
)

but it may as well be more complicated than this, if for example it not only lists the term IDs but all the content of the terms as well.

now just grab it and past a part of it here please (if it is a huge list, no need to post the repetitive part)

the way the print_r command works is it takes the object that you feed into it and displays the content in a more human-readable manner, giving you an insight of its structure, whether something is an object, an array, what else it contains etc.

so depending on what this array looks like, we will need to use a different approach on checking the array for your specific ID, this is why I am asking for an insight of the array we want to check.

EDIT 2:

so upon looking at the structure of the array, this is how you check for your term ID:
the array that we need to look at is ...['field_affiliation']['und']. you can (optionally) assign it to a variable, e.g. $field_affiliation, and then do something like this:

$hasDepartment28 = false;
foreach( $field_affiliation as $thisTerm ) {
    if( $thisTerm['tid'] == 28 ) {
        $hasDepartment28 = true;
        break;
    }
}

then, where- and whenever needed, you can simply check by doing

if( $hasDepartment28 ) {
    // do..
}

and here is how it works:

$hasDepartment28: we declare a boolean, and we say by default the department with the term id 28 is not listed
using foreach, we loop through every entry that is listed in the taxonomy term array we named $field_affiliation and every time we assign current entry to the variable name $term
now, as we could see in the structure of the array, what we want to look for is the 'tid' key of every entry
we compare it with the ID you mentioned in the comment below, and if we have a match, we set $hasDepartment28 to TRUE
and via break; we stop the current foreach. since we found what we were looking for, there is no need to loop through any other entry in the array that may come after it
if we found no entry at all where the tid equals 28, the boolean we set earlier will still equal FALSE

let me know if it worked!

keep in mind all the variable names are arbitrary and you should use whatever describes the variable best.

one last thing I'd add is if you were delete and re-create that term entry, you'd have to update this code and check for a different Term ID. perhaps a more readable and future-proof approach would be to check inside the foreach loop for something like:

if( $thisTerm['taxonomy_term']->name == 'Apartment A' ) { ... }

but this in return only works if the [taxonomy_term] gets loaded into your array for every entry. chances are only the first entry has all the term content, but based on the array you submitted I cannot tell you if this is the case. if you wanna stick to this approach though, this is exactly where drupal's entity_load function becomes super useful!


Retrofitting CSS media queries into an existing project

Got it. Basically we're moving ['all'] to ['(min-width: 720px)'] in the array structure. When it's loaded back in all of the stylesheets are effectively now wrapped into a media query.

function hook_preprocess_page(&$vars) {
  // get style sheet array
  $css = $vars['css'];

  // copy over the [all] to a media query key
  $css['(min-width: 720px)'] = $css['all'];

  // Remove the all
  unset($css['all']);

  $vars['styles'] = drupal_get_css($css);
 }

This leaves us the ability to define other style sheets in theme.info for other breakpoints.

stylesheets['(max-width: 480px)'][] = phone.css

Update, I turned this into a larger structure to let my content maintainers pick where the breakpoint should be.

A small idea for an add-on. I had an issue with a recent Drupal 6 site that I was trying to make responsive. I got tired of trying to override CSS from various areas so I wrote the following hook_preprocess_page to move stylesheets from [all] and move them to a logical break point. By doing this I can retro fit a mobile stylesheet into

A small idea for an add-on. I had an issue with a recent Drupal 6 site that I was trying to make responsive. I got tired of trying to override CSS from various areas so I wrote the following hook_preprocess_page to move stylesheets from [all] and move them to a logical break point. By doing this I can retro fit a mobile stylesheet into

/*
 * Implemntation of hook_preprocess_page
 *
 * Takes CSS files from the $vars['css']['all'] and moves them to $vars['css'][$breakpoint]. In effect, this moves all
 * existing stylesheets into a media query that you can specifiy. By default it's 480px.
 */
function wrapcss_preprocess_page(&$vars) {

  $css          = $vars['css'];
  $pixel_break  = (int) variable_get('wrapcss_breakpoint', '480');

  // Ensure that we have a value and that value is numeric
  if (isset($pixel_break) && is_numeric($pixel_break))
  {
    $breakpoint   = '(min-width: ' . $pixel_break . 'px)';
  }
  // If not, just default to 480
  else
  {
    $breakpoint   = '(min-width: 480px)';
  }

  // copy [all] to [breakpoint]
  $css["$breakpoint"] = $css['all'];

  // Remove stylesheets from [all]
  unset($css['all']);

  // Import back in
  $vars['styles'] = drupal_get_css($css);
}


It's probably because you're not showing the Drupal messages in your theme.  Take a look to ensure you have the following (somewhere, probably in your page.tpl.php file);

<?php print $messages; ?>

Note that you've made some other mistakes though (not related to your issue) - First, you should use $form_state['values'] to gain the values when using _validate(); second, you can lose the two drupal_set_message($message, 'error'); lines as they aren't doing anything?


Store user_password() in a variable. Change your code to this

    function lawyer_register_form_submit($form, &$form_submit)
    {
     $new_password = user_password();
     $edit = array(
      'name' => $form_submit['values']['name'],
      'pass' => $new_password,
      'mail' => $form_submit['values']['mail'],
      'init' => $form_submit['values']['mail'],
      'status' => 1,
      'access' => REQUEST_TIME,
      'fname' => array(LANGUAGE_NONE => array(array('value' => $form_submit['values']   ['fname']))),
      'street_address' => array(LANGUAGE_NONE => array(array('value' =>  $form_submit['values']['street_address']))),
      'phone_no' => array(LANGUAGE_NONE => array(array('value' => $form_submit['values'] ['phone_no']))),
      'county' => array(LANGUAGE_NONE => array(array('value' => $form_submit['values'] ['county']))),
      );
      $to = $form_submit['values']['mail'];
      $subject = 'New account created';
      $headers = "From: something@somewhere.org\nContent-type: text/html";
      $body = 'A new user account has been created for you at Something.org.
 Your login details are as follows:
Username: '.$form_submit['values']['name'].'
 Password: '$new_password'

 Please login to Lawandmoney.org and change your password.
';
       if($form_submit['values']['send_message'] == 1){
         mail($to,$subject,$body,$headers);
         }
       user_save(drupal_anonymous_user(), $edit);
       drupal_set_message("Successfully Register. Please check your Email for login    deatils.");

     }


How to alter checkout panes based on order contents

You're seeing them hidden on the admin page because you're making no differentiation here in your code that would restrict the checkout pane info altering to only occur on checkout pages for customers, not administrators.

I'm divided. I recently created a checkout experience with an optional checkout pane, and I ultimately decided to alter the form directly instead of altering the checkout pane info. Part of it was that desire to ensure I had an identical definition on the front end / back end for all customers, but I'm not sure it was strictly necessary.

If you do end up altering the form instead, you need to supply new custom validate / submit handlers for the conditional checkout panes that wrap their default handlers and only invoke them if the pane was actually presented on a checkout form.


To use the description field directly in twig I found an easier way. Simply add the file field in Views, then rewrite the results and add the token for description and file. Now you can use the field directly into twig file.

Otherwise You might have to do good use of Kint or DSM to find out where does description field come up.


Custom module javascript Drupal.behaviours doesn't seems to load

When attached make sure to use the correct name of the "library"

Inside your mymodule.libraries.yml file.  The first line is your library name.

I use a different name inside my library file, and I attached a wrong library name.

 function mymodule_preprocess_block(&variables){
     $variables['#attached']['library'][] =
      'mymodule/mylibraryname';
 }

My library file mymodule.libraries.yml

mylibraryname:
  js:
    js/promotional-overlay-block.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once
    - core/drupalSettings


How can I set a message if db_delete deleted one or more rows

Sure, db_delete() returns an object so you can continue working with the object, but the last method called (the method whose return value your conditional is really checking) in your statement is Query::execute, which returns boolean TRUE or FALSE indicating whether the query worked. So, ultimately the whole statement:

db_delete('drealty_fields')
  ->condition('conid', $conid)
  ->execute();

Should return TRUE or FALSE since you're ultimately executing the Query::execute method. The workflow is just that you call db_delete(), which returns an object, Query::condition, returns an object, then Query::execute returns boolean, but your conditional is just getting and checking the return value of the last method called - execute - rather than the return value of db_delete(). Essentially, the db_delete() return value was already operated on by continuing with a condition, and the condition's return value is inconsequential because it was operated on by execute, thus the execute's return value is the only one really getting sent back to the if statement. Make sense?

So, in essence each of these examples should give the same results:

$query = db_delete('drealty_fields');
$query->condition('conid', $conid);
$success = $query->execute();
if ($success) {
  // Do something.
}

$query = db_delete('drealty_fields');
$query->condition('conid', $conid);
if ($query->execute()) {
  // Do something.
}

if (db_delete('drealty_field's)->condition('conid', $conid)->execute()) {
  // Do something.
}


How can I display content from tab that was active on save?

Add a text field OR boolean field to your content type, let's call it "Active Tab".

Using jQuery you can make it when tab x gets clicked, it auto fills the text field OR auto checkmarks the x boolean box. (You can hide this field with CSS if you want).

Use a template file to control the display/output. So simply in your twig template file perform an conditional statement

{% if content.field_active_tab.0 == 'x' %}
  {{ content.field_something }}
  {{ content.field_something_else }}
{% endif %}

{% if content.field_active_tab.0 == 'y' %}
  {{ content.field_something2 }}
  {{ content.field_something_else2 }}
{% endif %}


The views were supposed to be displayed in the panels not viceversa. Why not created a panel with header and footer for placing views instead?


Drupal 8: SQL Insert with 10.000 datasets exceeds 300 MB PHP memory via batch_set()

Ivan Jaros is correct, right now you just do the work twice.

You're expecting something that is not possible.

Batch saves the operations data in the database, it has to. So you save one huge array only to load it again and store it in a separate table.

A batch makes only sense if you can actually split up the processing into smaller bits and not have all the data in one large array.

Specifically for node access processing, the API for this already exists, no need to re-invent the wheel. See node_access_rebuild(), which can do this either  in the current request (not recommended for a large amount of data) or with a batch. And you can see that there is only one batch operation without data, but if you look at it, you can see it is doing a pager query to process the whole list of nodes (there are Drupal sites with millions of nodes).


How to make filter criteria fieldset in a view to be collapsible by clicking on a link using tpl file overriding default file?

I got the above working by writing a function in the module as shown in the link

/**
 * Implements hook_preprocess_views_view().
 */
function my_module_preprocess_views_view(&$vars) {
  if ($vars['view']->name === 'my_view') {
    // Wrap exposed filters in a fieldset.
    if ($vars['exposed']) {
      drupal_add_js('misc/form.js');
      drupal_add_js('misc/collapse.js');
      // Default collapsed
      $collapsed = TRUE;
      $class = array('collapsible', 'collapsed');
      if (count($_GET) > 1){
        // assume other get vars are exposed filters, so expand fieldset
        // to show applied filters
        $collapsed = FALSE;

    $class = array('collapsible');
  }
  $fieldset['element'] = array(
    '#title' => 'Refine your search',
    '#collapsible' => TRUE,
    '#collapsed' => $collapsed,
    '#attributes' => array('class' => $class),
    '#children' => $vars['exposed'],
  );
  $vars['exposed'] = theme('fieldset', $fieldset);
}
  }
}


You could use either of these two modules Automatic Nodetitles or Automatic Entity Label to hide the title field. Use tokens to give the groups a name and hide the field on the edit form.


Create a page to edit all fields from a custom content type

Create a view filtered on your content type and include a "NODE: EDIT LINK" in the FIELDS along with all the rest.  You can then click on that to edit the node. Anything fancier requires digging into views tpls and custom node edit code.


Share users database from one Drupal database with other Drupal Installs (separate databases, not just prefixed tables in the same db)

Instead of using table prefixes, you can use a reference to another database as a prefix. For example, core database holds the shared users / permissions, drupal_website database is your actual website.

$databases['default']['default'] = array(
    'driver' => 'mysql',
    'database' => 'drupal_website',
    'username' => 'db_username',
    'password' => 'db_password,
    'host' => 'ip_db_server',
    'prefix' => array(
         'default' => '',
         'users' => 'core.',
         'users_roles' => 'core.',
         'sessions' => 'core.',
         'role' => 'core.',
         'role_permission' => 'core.',
         'authmap' => 'core.',
    ),
);

Minor drawback, your database needs to be stored on the same mysql server and each database uses the same credentials (username / password) for the connection.


Which module to use for tracking pages browsed by users?

The best tracking out there is google analytics and its not a module. You simply add the javascript provided by google to every page in your site and access all the info and much much more on google's analytic dashboard.

To add the javascript provided by google to your site other check the drupal module Google Analytics or add it yourself through a template file or drupal's add js function


This is definitely an error where the HTML of the 404 page is referencing the image via a relative path rather than an absolute path.

Screenshot of the page + source

Change the HTML of the page to use the image source path '/sites/default/files/pictures/404-error.png'


IMHO, Views Slideshow doesn't really make things easier (unless maybe if you don't want to write a single line of code).

I prefer to create a normal view (displaying fields or a rendered entity, whatever you like) and use jQuery Cycle to turn the views rows into slides. You just need to:

download the jQuery Cycle plugin to your theme's javascript directory
add a 'Drupal behavior' to a custom javascript file which initiates the jQuery Cycle (see the example code on the jQuery Cycle site)
make sure both javascript files are loaded by adding them to your theme's .info file

jQuery Cycle can definitely rotate continuously, just look at the demo's on its homepage.


Rules Link - Insert into System Node Content Template Variant

I appear to have found the answer to my original question above and solved it, though I'm not too sure if it would be the ideal (correct) approach, but it's ideal for now.
After reading this post Use content panes as blocks I approached my issue by using a Mini Panel to include the said Rules Link, it worked fine.
Put simply, I just created a Mini Panel, included the Rules Link as Content (see how in the above post), saved, then went back to my original Node Template Panel Variant, edited and included as a new Content in the Panel Editor, then saved that Panel. Voila!

You may have to fiddle with the Override Panel headings etc to get rid of any unwanted shown text: i.e Panel Name (I justed wanted the Link URL to trigger workflow and not the actual Mini Panel Title, so use the 'Override' Title option). It couldn't be that easy? well it is.

Sometimes I think we may over complicate Drupal, now in my opinon we shouldn't, we just need to see the wood from the trees. Clearly I'm learning Drupal, so will you.


Some tips about your solution:

1- It looks right to me. I would try keep the logic separate from the template. I'd also declare my own template to avoid problems. Another style plugin, for example a custom style plugin, could use the original template.

HOOK_preprocess_views_view_unformatted(&$vars){
  if(!empty($options['grouping'])){
    $vars['heading_classes'] = $grouped ? ' class="group-heading"' : '';
    // My own template
    $vars['theme_hook_suggestions'] = 'views_view_unformatted_group';
  }
}

/*
* Implement hook_theme
*/
HOOK_theme($existing, $type, $theme, $path){
  return array(
    'views_view_unformatted_group' => array(
     'variables' => array(),
     'path' => 'PATH/TO/YOUR/MODULE',
     'template' => 'views_view_unformatted_group',
  ),
}

Template views_view_unformatted_group.tpl.php

 <?php if (!empty($title)): ?>
 <h3<?php print $heading_classes; ?>><?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
  <?php print $row; ?>

<?php endforeach; ?>

2 - The default function that manage the grouping is render_grouping_sets() in an style plugin object. The documentation warn about that:

  Plugins may override this method if they wish some other way of handling
     * grouping

The unformatted list, html list, grid and table style inherit the default methods and they don't override it.

3 - If you have nested groups, Views wrap the parent group with the next function in theme.inc:

function theme_views_view_grouping($vars) {
  $view = $vars['view'];
  $title = $vars['title'];
  $content = $vars['content'];

  $output = '
';
  $output .= '
' . $title . '
';
  $output .= '
' . $content . '
' ;
  $output .= '
';

  return $output;
}


Problem with the body field after upgrading to 7.7

Are you using OG?  Because that could be causing the issue.

Things to do

If OG is installed, but not enabled delete it.
Clear Cache
Update all modules up to their most recent versions
Run Update.php (do whenever a module is updated or deleted)
Uninstall Views and reinstall it

Issue about this problem here > http://drupal.org/node/1001060


Replace integer field value with stars in twig template

For the field template there are two approaches to get the integer number from a field:

Node object

{% set difficulty = element['#object'].field_difficulty.value %}
{% for i in range(1, 5) %}
  {% if i <= difficulty %}

Find the rendered number

You can try to find the number in #markup:

{% if loop.index <= item.content['#markup'] %}

The node object is the better approach, because the way how the number is rendered can change when updating the code or changing the configuration.


How to extend a specific node type form?

AFAIK forms are tied to operations at entity-type level, so you don't have any hook to only alter the form for a particular bundle. Since what you want is to inject certain services for a given bundle what you can do is to implement a chain of responsability pattern through service collectors. This allows you to inject only the service collector to your form and delegate to the collection to evaluate which service should apply for your given bundle. And finally the resolved service is the one that would concentrate the responsability. I could provide you with a deep example but could take some time, let me know if a code sample still needed.

UPDATE

This will be the solution in a near future, since sub-classing is the feature you are referring.


How to render a variable which is having a wysiwyg type format?

You should use check_markup for that:

$item = variable_get('web_pagetext', ['value' => '', 'format' => '']);
$formatted_text = check_markup($item['value'], $item['format');


If you dont want to write custom code you can use the
views limit group module

  This is a basic Views style plugin that allows for a limit on the number of rows displayed within a grouping field.


If you look in the settings.php for your site, there should be a template for overriding strings in the interface (anything in the t() function).

You would add something like this to the settings.php file:

$conf['locale_custom_strings_en'][''] = array(
  'Old string'      => 'New string',
);

I haven't used it, but there's a module that makes this easier: String overrides.


How to reset the id of the orders generated by Commerce module

The commerce order module defines two tables, commerce_order and commerce_order_revision; you should truncate both of those to clear the data and reset the AUTO_INCREMENT counter.

In MySQL:

TRUNCATE TABLE commerce_order
TRUNCATE TABLE commerce_order_revision

Or using the API:

db_truncate('commerce_order');
db_truncate('commerce_order_revision');


The message The file could not be created indicates a permissions issue to me. Make sure that the webserver has the ability to create files in all the places in needs.


I ended up using Rules to automatically populate a text field with the linestring data LINESTRING(lat lon, lat lon) after every new entity add or existing entity update, with the condition that both geofields (sender and receiver) were filled. Created another geofield to hold the LINESTRING, geocoded from the text linestring field as WKT. Ran VBO to update all existing nodes. Plots well in IPGV&M and should handle itself automatically from now on.


how can I make a welcome popup window upon visiting the website

You are looking for Splashify module, it also have the option to popup on any page.

  Display a splash page anywhere on your site by redirecting the user,
  showing a lightbox, or displaying a popup. This module is designed to
  be search engine friendly, mobile device friendly and offers multiple
  configuration options.

or

You can try TinyBox (Simple Splash). see the demo

  The main purpose of this module is to provide Splash Screen/Window as
  simple as possible.

or

take a look at Splash Offer module

  Allows the management of one or more "splash offers", which are modal
  popups with an accept or reject form. If a user accepts the offer then
  a new page will open with a provided accept url. If they reject the
  offer, the modal will close.


How can I use Migrate API to migrate taxonomy with an unknown level of parent child relationships in tact?

Maybe too late but for the sake of being complete: I think you'll find the answer here Using Drupal 8's Migrate API, how can I map a nested (hierarchical) taxonomy term to the imported entity?
First migrate the terms without parents. After that update the parent-field.


For this issue there's a prerequisite,that is, your download method must be 'private', otherwise there's no chance for drupal to call your 'hook_file_download', it's important!

Here's an example from drupal's file module, change $file->filename to what you want, then return to HTTP headers.

/**
 * Implements hook_file_download().
 *
 * This function takes an extra parameter $field_type so that it may
 * be re-used by other File-like modules, such as Image.
 */

  function file_file_download($uri, $field_type = 'file') {
     global $user;
     // Get the file record based on the URI. If not in the database just return.
     $files = file_load_multiple(array(), array('uri' => $uri));
     if (count($files)) {
         foreach ($files as $item) {
         // Since some database servers sometimes use a case-insensitive comparison
         // by default, double check that the filename is an exact match.
         if ($item->uri === $uri) {
             $file = $item;
             break;
         }
      }
   }
   if (!isset($file)) {
     return;
   }

  //...........................other codes.........................

  // Access specifically denied.
   if ($denied) {
     return -1;
   }

  // Access is granted.
   $headers = file_get_content_headers($file);
   return $headers;
  }


How do I migrate my site without doing a direct DB export and site upload?

What you should have done is remove sites/all/default/settings.php;
Now copy and rename the: sites/all/default/default.settings.php => sites/all/default/settings.php

Phase 2
Migrate the database to the production server
Phase 3
Copy the drupal directory from your dev to production server
Phase 4
On the production server hit the following Your_Domain_Name.com/install.php
follow the install instructions and set the database settings and you will be redirected to your site with config.
Phase 5
run cron to make sure eveything is running ok and update if necessary


How to add multiple terms to a taxonomy via feeds and tamper

Feed Tamper gives you a feature to import multivalued field data using any separator like comma(,) using implode plug-in

If you have csv file like below

You need add implode plugin for that field in tamper tab in feeds form

For a detailed tutorial refer this Awesome link!!!!


How could the contextual filter "Content: Nid" return the TNID instead of NID?

This PHP code should work:

$node = node_load(arg(1));
return (isset($node->tnid) ? $node->tnid : $node->nid);

The better way (without evil eval()) is to provide own plugun of type 'argument default' which will do work. Look at Content ID from URL argument default plugin as an example.


How to modify if a field is required in a form?

It can be tricky to bybass D8 entity validation scheme in this way.
Why don't you just set this field settings as "not required" and then set

$form['field_fieldname']['widget'][0]['#required'] = TRUE

when

\Drupal::currentUser()->id() != 1


How to programmatically create node with image file saved from remote source?

Finally have figured out. The following code works fine:

$file = file_save_data(file_get_contents($image_url), file_default_scheme().'://tmp/'.basename($image_url));
$file->status = 1;
$node->field_image['und'][0] = (array)$file;

node_save($node);


Specifying a custom node id when creating new content

In the UI no, and you should never interact with the database directly.

But you can do this with the API easily:

$node = Node::create(['type' => 'article', 'nid' => 5]);
$node->enforceIsNew(TRUE);
$node->save();


node_view does not show the comments box

You probably need to use the node_show() function instead; it outputs the node as well as its accompany comment thread and comment form. node_show() relies on node_view() to print the node itself, but also calls comment module's code to build the rest.

One good rule of thumb for tracking down these scenarios is to visit the api.drupal.org site, look up the function that you're using to output a portion of the information you need, and look at the functions that also call it in Drupal core.


How can I determine in the body of a hook implementation what hook it is implementing?

Where my confusion comes in is when I go to specify parameters or document the function. What parameters does the function take? What hook does it implement?

Preprocess hooks are only provided a single parameter: $variables. The hook that you're implementing is literally hook_preprocess_HOOK. The HOOK part of it is the identifier for the theme entry, as defined in a hook_theme() implementation somewhere.

So if you have this:

function MODULE_theme() {
  return [
    'foo' => [
      'variables' => [],
    ],
  ];
}

Then, by convention, you can implement hook_preprocess_hook like so:

/**
 * Implements hook_preprocess_HOOK() for foo templates
 */
function MODULE_preprocess_foo(&$variables) {
  // ...
}

Note the docblock; the convention is to use for XXX templates, where XXX is a description of the item being preprocessed. If you search for _implements hook_preprocess_ in the core folder, you'll find a lot of these as examples.

  So, once I have written a hook implementation (i.e. my_theme_preprocess_block or my_theme_preprocess_page__user__edit), how can I definitively know what hook I have just implemented?

By definition, you already know :) You created the function with a certain name, so you know which theme entry you're preprocessing variables for.

  like for the block - hook_preprocess_HOOK is very generic, how can I be sure I'm not implementing something more specific that I just missed in my Googling?

Because there can only ever be one theme entry for a given identifier, you won't run into this problem.

  something I should know about the difference between template_preprocess_whatever and hook_preprocess_whatever functions that if I knew that thing I wouldn't be confused

Hopefully, along with the above, this will clear things up:

template_preprocess_HOOK is, again by convention, used by the module implementing the theme entry, to provide the base variables. It's always run first, before hook_preprocess_HOOK is invoked, so it helps those defining theme entries to ensure important variables and processing are done up front before the rest of the system gets involved.
hook_preprocess_HOOK is essentially for other modules to preprocess the variables, rather than for the module implementing the theme. There's nothing to stop that module from implementing hook_preprocess_HOOK as well (it's just a naming convention and no special checking is made), but it could be undesirable to do that if some initial processing needs to be done, a la template_preprocess_HOOK.


Given a taxonomy term id, how do we get the value of other fields; specifically the machine_id?

The machine name is the vid:
if you search for machine_id inside taxonomy module there is no machine_id field declared.

But if you look at core/modules/taxonomy/config/schema/taxonomy.schema.yml you can see that:

vid:
  type: string
  label: 'Machine name'

So to get the vid (Machine name) you should use getVocabularyId
something like:

$product_name_id = $product_name_reference->getValue()[0]['target_id'];;
$product_name = \Drupal\taxonomy\Entity\Term::load($product_name_id);
// Vid or machine name.
$vid = $product_name->getVocabularyId();


Using entries from custom block library in twig template?

Use Twig Tweak and

{{ drupal_entity('block_content', 123) }}

This renders only the block content, without a block template.


Use image from view as background image of div in page.tpl.php

Sure.  Just look at what's inside $views and grab the path/url of the image there and stuff that into $background_image and then do something like:

<div class="container-inner clearfix" style="background: url(<?php print $background_image; ?>)">

Sidenote:  it might be better to this in a preprocess hook and pass in this as a variable instead of putting this logic in your page.tpl.php file, eg, something like:

function my_module_or_theme_preprocess_page(&$vars) {

  // $views=views_embed_view('photos', 'block');
  $views=views_get_view_result('photo', 'block'); // appears to work easier :)
  $background_image=// however you get the url/path to the image from $views;

  $vars['background_image']=$background_image;

}

which will create a $background_image variable that is now available inside page.tpl.php.


Are there any easier ways to update a site than following the official instructions?

If you have access to ssh in your server install drush (drupal shell) http://docs.drush.org/en/master/install/

This will only need to be done once and and then it will be easy to apply drupal core updates from the command line

drush up drupal

or any other module updates

drush up views

But I would recommend applying ALL security patches at once (core and modules security updates) using

drush upc --security-only

all the above commands will do all the necessary actions as described in the instructions that you linked above and in case of a bad update the updates are reversed with error messages displayed.

To learn drush read https://www.ostraining.com/blog/drupal/drush/ but the installation instructions might be a little outdated. You can also learn more drush commands at drushcommands.com


Embed one entity form into another and save both

Instead of trying to do your own thing, you should try Inline Entity Form module. This module is made for this specific case (creating / editing entities within entity forms).

I know a lot of work has been put in to this to improve workflow in Drupal Commerce, which means this should be working well. I haven't tested it out myself, but since Drupal Commerce depend on it in Drupal 8 as well, it should be quite stable already.

The module works by adding a widget to the entity reference field that creates the form, so it should be pretty much plug and play. The only requirement is that the user has a reference to your custom entity.


Do features uninstall variables when a module is uninstalled?

No, it does not. Features do not implement an uninstall hook, and as such don't get a chance to clean up after themselves.


How to post three nodes of same content type in three different blocks in the front page?

Create 3 separate block views, each will display 1 node. make sure they are offseted.

This will display 2nd top node of the content type 'automobile' that is promote to front page.

Then configure them at admin/structure/block


Drush rsync permission woes (files directory)

Permissions issues are fairly complicated.

First off, the "failed to set times" message occurs because only the file owner can perform this operation.  The solution to this problem, then, is to insure that the 'remote-user' element of your Drush site alias is the same as the owner of the files on the target machine.  When pulling files to the local machine with drush rsync, it works best if you run Drush as the same user that the files are owned as.

What specific sets of permissions you choose after that is largely up to you, as there are a number of options that will work fine.  What I do is make all web server code files owned by a 'www-admin' user on the live site, and owned by my local user on my dev site.  On both live and dev, the files group is the webserver group, usually www-data, with directories that the webserver can write to being group-writable (and all others are set to not be group-writable, of course).  Any file created by the webserver will by necessity be owned by the webserver, of course.

This works well for most situations; however, it does mean that if you rsync %files from dev to live, you won't be able to overwrite anything that was uploaded by the webserver.  You might consider this a useful feature, though, as it prevents accidental overwrites.


More specific way to override THEME_process_page() function?

In the case of the content types, Drupal invokes only the preprocess and process functions for the page; it doesn't invoke a different preprocess function basing on the content type of the node being shown. Drupal invokes the following functions (the same order is followed for the process functions):

template_preprocess(&$variables, $hook)
template_preprocess_page(&$variables)
MODULE_preprocess(&$variables, $hook)
MODULE_preprocess_page(&$variables)
ENGINE_engine_preprocess(&$variables, $hook)
ENGINE_engine_preprocess_page(&$variables)
ENGINE_preprocess(&$variables, $hook)
ENGINE_preprocess_page(&$variables)
THEME_preprocess(&$variables, $hook)
THEME_preprocess_page(&$variables)

"MODULE" is the short name of a module, "ENGINE" is the short name of the theme engine used for the currently used theme, and "THEME" is the short name for the currently set theme.

You could say to Drupal to call different preprocess functions, but the hook that would add them doesn't have information about the content type of the node being shown. hook_theme_registry_alter() could be used to add new preprocess functions to a theme function, but all the preprocess function added would be all executed.

function mymodule_theme_registry_alter(&$theme_registry) {
  if (isset($theme_registry['page']) {
    $theme_registry['page']['preprocess functions'][] = 'template_mymodule_additional_preprocess_handler';
    $theme_registry['page']['preprocess functions'][] = 'template_mymodule_last_preprocess_handler';
  }
}

This is only necessary if the preprocess function is not one of the functions that Drupal would invoke.

If you need to use a different template file basing on the content type, then a preprocess function can suggest the template files to use; in Drupal 7, this means to use code similar to the following one:

function mymodule_preprocess_page(&variables) {
  if (!empty($variables['node']) {
    $variables['theme_hook_suggestions'][] = "page__" . str_replace(array("/", "\\", "\0", '-'), array('', '', '', '_'), $variables['node']->type);
  }
}


The code $rows[] = array(); will become a row in the array itself and will not just create an array as you probably want.

Change $rows[] = array(); to $rows = array();


footer link to a page with hash changed content ready

You need to add your jquery to document.ready as well as click, that way when a user goes to the page it will load the proper tab for you.

Something like this:

jQuery(document).ready(
    function()
    {
        //bind click event
        jQuery("#tab1").click(show_tab);

        //handle document load
        show_tab();
    }
);

function show_tab()
{
    ...
}


How to choose to which group new content will be visible?

One have to add a field to content type: og_group_ref.


How do I create or modify a custom filter?

Did you install the Custom Filters module? (https://www.drupal.org/project/customfilter)

Works fine for me after I install the module.


Add JavaScript into a specific content type

I can't comment on the proper Drupal 7 equivalent, but in Drupal 6 sites I do this in a template_preprocess_page.

I will have some logic to make the decision (either based on arg() or page_manager_get_current_page() from panels), and then prepend $vars["scripts"] with the external script.  I prepend so that I don't run into dependency trouble with any local scripts.

I will also sometimes set up a new region called $global_scripts for thinks like Google API and SWFObject that I want to load from a CDN, and this gets printed out before $scripts in the page template.

To be honest, though I normally have all JS on all pages so that the files get cached.


conditionally hide a field based on another field's value (without using templates)

Implement hook_field_access($op, $field, $entity_type, $entity, $account).

To find out how the arguments are structured, var_export() them in your first implementation (or better yet, dpm() them).


How to change the order of date module fields on edit by language?

I came across the issue today. Found there is an option to change the date format for Date field.

FYI: It is under "More Settings". Cheers


Show block on nodes and only for node author

In views, add a relationship on "Content: Author", then add a filter "User: Current" and configure it so it uses the relationship you added and has "Is the logged in user" = "Yes".
Install the Rabbit Hole module and its node sub module and configure it (on the edit page for the offer content type) to give a 404 error for those nodes. Then configure the rabbit hole permissions so that admins can bypass rabbit hole if you need that ability. I would recommend adding this module as opposed to writing some custom code to do this.


How can I show the receiver name in a rules email

You cannot, the message is the same for all users of a certain role in this case. I think you have, first, to get the users of a certain role (php custom code) and then for each user fire an other rule or a custom hook_mail with the account as argument


disappeared comment fields in content type, how to put them back

Basing on the code for comment_field_extra_fields(), I think that what you are noting can be explained with the comment_subject_field_$type persistent variable being set to a value different from 1. ($type is the machine name of the content type.)

function comment_field_extra_fields() {
  $return = array();

  foreach (node_type_get_types() as $type) {
    if (variable_get('comment_subject_field_' . $type->type, 1) == 1) {
      $return['comment']['comment_node_' . $type->type] = array(
        'form' => array(
          'author' => array(
            'label' => t('Author'),
            'description' => t('Author textfield'),
            'weight' => -2,
          ),
          'subject' => array(
            'label' => t('Subject'),
            'description' => t('Subject textfield'),
            'weight' => -1,
          ),
        ),
      );
    }
  }

  return $return;
}

comment_form() contains the following code.

  $form['subject'] = array(
    '#type' => 'textfield',
    '#title' => t('Subject'),
    '#maxlength' => 64,
    '#default_value' => $comment->subject,
    '#access' => variable_get('comment_subject_field_' . $node->type, 1) == 1,
    '#weight' => -1,
  );

Only when the 'comment_subject_field_' . $node->type persistent variable is set to 1 the users have access to that form field.

Changing the value of that persistent variable to 1 should restore those form fields you are expecting to see.


I have found a solution for the problem. Follow the steps.

Add a field 'Path' above the 'Title' field.
Exclude 'Path' field from display.
Uncheck the link to content from 'Title'
In Title->Rewrite Results check output this field to custom link and set path as {{ path }}.

OR

Add a field 'ID' above the 'Title' field.
Exclude 'ID' field from display.
Uncheck the link to content from 'Title'
In Title->Rewrite Results check output this field to custom link and set path as /node/{{ nid }}.

It both works.


You need to give the 777 directory permission to your temp folder. Like....
sudo chmod 777 -R /var/www/html/yoursite/sites/default/files/temp/

Please check images for more understanding. enter image description here

and command for give 777  permission to that directory like...


Your custom field is added after the query is performed by views, and a the sort is done as part of the query, therefore your sort doesn't know about your custom field.

I'd probably try to store the percentage in a field on the content type and then you'll be able to sort using the normal views sort handlers.


How do I remove the language_content_entity query from the canonical URL?

Just to illustrate once again what you are supposed to do with the first duplicate question's answer:

/**
 * Implements hook_page_attachments_alter().
 */
function MYTHEME/MYMODULE_page_attachments_alter(array &$attachments) {

  foreach ($attachments['#attached']['html_head'] as $key => $head) {

    if ((isset($head[1]) ? $head[1] : FALSE) == 'canonical_url') {

      $href = isset($head[0]['#attributes']['href']) ? $head[0]['#attributes']['href'] : FALSE;

      if ($href) {
        // Strip ?language_content_entity=en from the end of the URL if exists.
        $href = rtrim($href, '?language_content_entity=en');
        // Strip ?language_content_entity=es from the end of the URL if exists.
        $href = rtrim($href, '?language_content_entity=es');
        // Then set the new value.
        $attachments['#attached']['html_head'][$key][0]['#attributes']['href'] = $href;
      }
    }
  }
}


whats the best way to run 2 sites but use same database with same prefix on Drupal 7?

It is quite possible in Drupal. Make sure settings.php on both the instances are identical (I assume both the instances are hosted on a single server).

However, better way to manage such a scenario is to use version control.


You are dealing with a caching issue. I just added the quiz module to a fresh install of Drupal 7.28, made a quiz with one question with three choices, and when I viewed it there were three options. So far so good. Then, I went back and added two options to that question, but when I viewed it I didn't see the two new options show up.

All I had to do was take one version of the quiz and the next time I loaded the quiz the new options showed up. I suspect each user gets a cached version of the quiz when they start taking it, which would make sense in that you don't want to have a different/changed quiz for someone who is halfway through taking one.

I haven't used the quiz module at all, but it looks like it has steady, active development, which is good. You could look into Drupal Webform module as an alternative or search for Drupal Learning Management Systems, if an LMS is really what you are building.


Per the question you linked to, the Rules module will do this very well and can be used to call your custom actions when criteria are met during pre-save, validation, or other stages you might need.

It's worth pointing out that, since you want custom nodes created, you're likely to already need to be writing custom code. In this case a better approach might be to write an implementation of hook_nodeapi() (Drupal 6) or hook_node_{operation}() (Drupal 7) that means you can fire your own custom code at specific points during node creation.

Take a look at this question about how to make nodes programatically, and also this article with more detail about the process in Drupal 7 (only in Google cache). Extract of the article:

  1 Initialize a node object

 $node = new stdClass(); // We create a new node object $node->type =
 "page"; // Or any other content type you want $node->title = "Your
 title goes jere"; $node->language = LANGUAGE_NONE; // Or any language
 code if Locale module is enabled. More on this below * $node->path =
 array('alias' => 'your node path'); // Setting a node path
 node_object_prepare($node); // Set some default values. $node->uid =
 1; // Or any id you wish

  *We set LANGUAGE_NONE for $node->language, if you don’t have the locale module enabled, the node will not be assigned any particular
  language. So that's why we put here the constant LANGUAGE_NONE. In
  Drupal, nodes and fields can exist in more that one language, so if
  your site is multilingual you should specify the language code for
  your field. You can configure languages and get language codes by
  going this path in Drupal administration: Configuration -> Regional
  and language -> Languages.

  2 Add a body field

// Let's add standard body field
$node->body[$node->language][0]['value'] = 'This is a body text';
$node->body[$node->language][0]['summary'] = 'Here goes a summary';
$node->body[$node->language][0]['format'] = 'filtered_html'; // If
field has a format, you need to define it. Here we define a default
filtered_html format for a body field

  3 Add custom fields

// Let's add some CCK/Fields API field. This is pretty similar to the
body example  $node->field_custom_name[$node->language][0]['value'] =
'This is a custom field value'; // If your custom field has a format,
don't forget to define it here
$node->field_custom_name[$node->language][0]['format'] = 'This is a
custom field value'; // And etc. you can add as much fields here as
your content type has. The sky is the limit... and the server specs,
of course ;)

  4 Add file / image fields

// Some file on our system $file_path =
drupal_realpath('somefile.png'); // Create a File object $file =
(object) array(   'uid' => 1,   'uri' => $file_path,   'filemime' =>
file_get_mimetype($file_path),   'status' => 1, );  $file =
file_copy($file, 'public://'); // Save the file to the root of the
files directory. You can specify a subdirectory, for example,
'public://images'  $node->field_image[LANGUAGE_NONE][0] =
(array)$file; //associate the file object with the image field:

  5 Add a term to a node

$node->field_tags[$node->language][]['tid'] = 1;

  field_tags here is the name of a term reference field attached to your
  content type, 1 is a term id you wish to assign to a node. Simple!

  6 Save a node

$node = node_submit($node); // Prepare node for a submit
node_save($node); // After this call we'll get a nid


It seems like you would like for one login to give access to Drupal site administrative functionality, and also give access to specialist non-Drupal functionality.

The easiest and most flexible way to achieve this is might be to add an extra link to the Drupal administrative menu. When someone logs in, that new link would be there prominently along side the other Drupal administrative links.

The link could point to another website, to non-Drupal pages and scripts on the same server, or to Drupal pages generated by a custom Drupal module you created.

Perhaps the biggest advantage of putting your custom code inside a custom Drupal module would be that you could use Drupal's access control system: logging into Drupal with the right role would automatically grant users (and only these users) access to your custom functionality.

Generally speaking, taking existing code and turning it into a Drupal module so that it outputs it results "through" Drupal in a minimal but viable way should be easy.

Fully converting your code to take advantages of all Drupal's API features (theming, UI widgets, etc., etc.) would be a much bigger task. It's not necessary for your stated goal, it's more something you might consider for the sake of improving the robustness of your code by leveraging the quality of Drupal's APIs.


How do I split the CCK e.g. add node form into a wizard?

Check out multistep node form

  For each step you can define which fields should be included in this
  step. "Fields" includes core-fields like "Title", "Body" or "Authoring
  information" as well as fields defined by other modules (e.g. Date).


Change field type with hook_update_n for a module

You just need to add precision and scale to the field config settings:

// API way.
$field = field_info_field('field_rin');
$field['settings']['precision'] = 10;
$field['settings']['scale'] = 2;
field_update_field($field);

// Raw way (shorthand, you'll want to add error checking).
$data = unserialize(db_query("SELECT data FROM {field_config} WHERE field_name = 'field_rin'")->fetchField());
$data['settings']['precision'] = 10;
$data['settings']['scale'] = 2;

db_update('field_config')
  ->fields(array('data' => serialize($data)))
  ->condition('field_name', 'field_rin')
  ->execute();


Inherit areas of parent or ancestor page

It depends how arbitrarily flexible the layouts need to be but:

For the layout switching you could probably use Omega and Delta http://drupal.org/project/delta

Then write your own custom context condition that says "does this page have a parent with the layout X?" then use the reactions provided by Delta to switch to layout X for the closest parent.

For the defining/storing what layout is associated with each "page" you could just use the Field API. If each "page" is a node then it will be easier for you, otherwise you might have to also define a new type of Entity for your site.


How to share only a particular link in a node using social media,instead of complete node?

If you're open to using an alternative module (instead of the Social Media module), you can get this to work for at least Facebook and Twitter by using the Rules module instead, combined with these modules:

Facebook rules (for Facebook, of course ...).
Twitter (for Twitter, of course ...).

For (way) more details on that, refer to my answer to "How to post the node link in social networking if node is published?", which also explains what the options are (that I'm aware of) for Google+.


Adding an 'All' option to a views exposed filter

OK... I think I may have cracked it.

function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_state['view']->name == 'myview') {
    // Add our custom All buttons.
    $form['myfield']['#options'] = array("-ALL-" => t("- All -")) + $form['myfield']['#options'];
    array_unshift($form['#submit'], 'mymodule_exposed_form_submit');
  }
}

function mymodule_exposed_form_submit(&$form, &$form_state) {
  if (!empty($form_state['values']['myfield']['-ALL-'])) {
    $options = $form['myfield']['#options'];
    unset($options['-ALL-']);
    $form_state['values']['myfield'] = $options;
  }
}

So basically I add in my 'All' item at the top of the select. Then I add my own custom submit handler before Views' one.

In my submit handler, I check for the presence of the All option, and if its found, I adjust the selected options so that all options are selected except for the All option.

Seem to work :)


After doing some research, it turns out that there is active development being done in the jQuery_Update module. Specifically, you may reference this post .

The issue with the jQuery_Update module is that it would only update your Drupal 6 jQuery install to v. 1.3.0. With the patch that is applied in the aforementioned post, you are able to update all the way to jQuery 1.7.

An alternative to this solution would have been to load jQuery from another location and use the noConflict() function. Drupal has some excellent documentation regarding this.


Is it possible to index custom page content?

Yes of course you can. You can use the hook_node_update_index() for this:

function YOURMODULE_node_update_index($node) {
   // here is an example that fetches content from an url and appends it to
   // to the data that will be indexed
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
   curl_setopt($ch, CURL_URL, "http://example.com/readme.txt");
   $content = curl_exec($ch);
   curl_close($ch);

   // return the extra content that needs to be indexed for this node
   return $content;
}

The above will of course only work if your custom pages are stored as nodes in Drupal. For instance if you have a node that is called contact which shows content generated externally, then you need to fetch the same content in hook_node_update_index() for this specific node.


Recording the time it takes to process a form

I use HttpWatch to monitor load times:

http://blog.httpwatch.com/2008/05/14/using-httpwatch-to-measure-page-load-times-for-new-and-existing-users/

You should be able to get the numbers you want with the free version.


Can we add different class to first row and last row of view?

You would probably be fine with just doing this with css ( see Beebee's comment on your post), but I will answer the question.

You can use loop.first and loop.last in twig. Here is an example I used to make it work in a menu.

<ul class="menu">
    {% for item in items %}
        {%
            set classes = [
            'menu-item',
            item.is_expanded ? 'menu-item--expanded',
            item.is_collapsed ? 'menu-item--collapsed',
            item.in_active_trail ? 'menu-item--active-trail',
        ]
        %}
        {% if loop.first %}
            <li {{ item.attributes.addClass('first-element') }}>
               {{ link(item.title, item.url) }}
               {% if item.below %}
                  {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
               {% endif %}
            </li>
        {% endif %}
        {% if loop.last %}
            <li{{ item.attributes.addClass('last-element') }}>
                {{ link(item.title, item.url) }}
                {% if item.below %}
                    {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
                {% endif %}
            </li>
        {% else %}
            <li{{ item.attributes.addClass(classes) }}>
                {{ link(item.title, item.url) }}
                {% if item.below %}
                    {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
                {% endif %}
            </li>
        {% endif %}

    {% endfor %}
</ul>


How to use features-export drush command?

I figured out the syntax.

First, you have to learn the name of the component. Use the features-components command for this.

Then, when you know the component, do drush features-export my_module_name 'component_type:component_name'. That will create a module with the component you specified in it.

So in my case, I would do drush features-export my_module_name 'field_base:field_address_1.

If you want to add multiple components, you have add them to an existing, enabled module. So if I want to add another component to the features module I just created, I would do

$> drush en -y my_module_name
$> drush features-export -y my_module_name 'field_base:field_address_2


Allowing users to create multiple "notebooks" of nodes

We did the on a Drupal 6 site a few years ago.

If you want a single notebook, or have a fixed number of notebooks, then you can use Flags.

Our client wanted an unlimited number of notebooks, so we went the node references.

Basically, we created a "notebook" content type, with a few fields on it.  One of the fields held the noderefs of everything that was saved.  We may have also had some metadata for each saved item.  It's a mostly straightforward approach, but it involves a decent of plumbing to add/remove things (the unlimited number of notebooks complicates some scenarios), and you also need to consider all of the use cases you want with regards to how notebooks will be managed.

If we had to do this again with Drupal 7, then I would likely still go with nodes and entity references, potentially using field collections to bundle the entityref with metadata for a saved item.


Show block on term page if term has no children

I've answered it over here, Check if taxonomy_get_children($tid) is empty, Then term has no children.


Notice: Undefined index: und in include()

Before assigning the values to the field directly you must check if it contains any value or not otherwise you will get the notice like above, try to check the value something like below (the below code is for reference only, you can modify it as per your requirement):

<a href="<?php
print isset($node->field_house_coupon_link[LANGUAGE_NONE]) ? $node->field_house_coupon_link[LANGUAGE_NONE][0]['url'] : ""; ?>"
style="color:#<?php print isset($node->field_house_coupon_link_hex_code[LANGUAGE_NONE]) ? $node->field_house_coupon_link_hex_code['und'][0]['safe_value'] : ""; ?>">
<?php print isset($node->field_house_coupon_link[LANGUAGE_NONE]) ? $node->field_house_coupon_link['und'][0]['title'] : ""; ?>

Also it is recommended to use LANGUAGE_NONE instead of und: The language code used when no language is explicitly assigned. Defined by ISO639-2 for "Undetermined".


How do you find where a module's directory is located?

Look at the {system} table.  In particular, the name column will be the module name (ie, the basename of the .info and .module files).  The filename column will be the full filename, with path, to the .info file for the module, relative to the DOCROOT of the installation.  See system_schema() for more information.


Be aware that [P] requires mod_proxy to be enabled:

RewriteEngine on
RewriteRule /n/(.*)$ http://xxx.xxx.xxx.xx:80/n/$1 [P]


How can I make required cck date field "not required" by hook_form_alter?

To alter date field required to disable, you can use following snippet in your form alter

$form['#field_info']['field_date']['required']=0; //field_date use your field name


How to process single queue item using QueueWorker on cron runs?

Queue workers are meant to be processed in batches, not 1-each-cron-run.

If you want to process only a single item every cron run, then use the cron-hook.


How to remove comma between taxonomy terms?

Here's a nice blog post on styling taxonomy in node.tpl.php (or node-contenttype.tpl.php): http://oliverdavies.co.uk/blog/how-style-drupal-6s-taxonomy-lists-php-css-and-jquery

Looks like you should check your node.tpl.php for something like <?php if ($terms): ?> and then you might see where the commas are being added and strip them out. This will depend on what theme you are using.


How can I render a view in different languages during queue process, using PHP?

I do not yet understand why, but $view->preview($display_id, $args) allows the language-switching to work.

It is very similar to my view execution code above, but instead of calling execute() on $view->display_handler, I call preview() and that works as desired.

$view->pre_execute();
$view->hide_admin_links = TRUE;
$view->preview = TRUE;
$output = $view->display_handler->preview();
$view->post_execute();

I generate the view for each $user->language and insert that into the email.

Perhaps this will help someone else.


Is it possible to use the Forena module in conjunction with the Flot module?

I'm not aware of a way to use the Flot module in conjunction with the Forena (disclosure: I'm a co-maintainer) module.

About "Virtually any JavaScript library may be used with Forena ...": have a look at the feature request # 2364427, especially these comments in it:

Comment nr 7, which is about a module for using Forena data with the d3js library.
Comment nr 15, which is about a related sandbox project.
Comment nr 18, about the D3 strategy.

Another approach is to write your own "renderer", as a variation of the FrxSVGGraph renderer (which extends FrxRenderer), and which is how the current support for the PHP SVGGraph library is implemented.


Why Isn't #value valid for 'textfield' form types in Drupal 7?

Form API is an abstraction over regular HTML form elements, so there are cases where attributes don't match up exactly.

In the context of Form API, #value is for values you don't want the user changing, and doesn't make sense with respect to text <input> controls.

Instead, you want to use #default_value, which is for values you do want the user to change. That is:

$form['mytextfield'] = array(
   'type' => 'textfield',
   '#default_value' => 'Foo',
);

is the same as:

<input type="text" value="Foo" />

If you want to mimic the behavior of Form API's #value (i.e. provide a default value and prevent the user from changing it), use the #disabled property:

$form['mytextfield'] = array(
   'type' => 'textfield',
   '#default_value' => 'Foo',
   '#disabled' => TRUE,
);

For more information about the internals, check out form_builder(), which constructs the render array for the form and _form_builder_handle_input_element(), which replaces #value with the value of #default_value prior to rendering.


Taxonomy Term Reference Tree Widget has this option.
install and select it as your taxonomy reference widget and check Select parents automatically in field instance setting form


In my case it was the the problem of reverse proxy. It is fixed now.


How to call a SOAP function to send Drupal user data to a SOAP server?

You say you use the wsclient SOAP binding but your code doesn't use it. Instead, your code uses a direct query to the PHP SOAP interface.

This thread discusses the difference between the two binding and which one is preferrable.

From the module's readme file:

You can create web service descriptions in code, see for example
wsclient_examples.module
You can easily invoke web services by loading the description and executing
an operation (the operation name can be used a dynamic method name):

$service = wsclient_service_load('google');
$result = $service->translate('Hallo Welt', 'de|en');


Is there a simple boolean formatter that allows custom content?

You can give a try to custom_formatters in Drupal, this module allows you to do things without writing a code


Iterate through all children of an element

A simple recursive function will do the trick:

function allow_access(&$root_element) {
  $root_element['#access'] = TRUE;
  foreach (element_children($root_element) as $key) {
    allow_access($root_element[$key]);
  }
}
allow_access($form);


Hide Fields in Edit Page based on Role and Content Type?

How does field permissions, custom permissions, not work for you?

  Example: Using field permisions, I am able to "hide" Field AA by not allowing Content Editor A (Role of Monday) to Edit, or View. But...it also hides the Field AA in Views. That's not what I want. The Editor should still be able to see the Field in any View.

In the above picture, Monday is not going to see the field when he edits the page, but will be able to see the field when its displayed by views.

This is the solution to the Example you provided. In your original question, it would be the role of Tuesday who needs to look like that.


Can I create two views with the same paths?

If I understand correctly, yes you can simply achieve that using views.

Go to your views and add an "Attachment" to the 'page' view. Set Filter Criteria accordingly. You can also achieve that using Views Block.


how to override module's theme function in a custom module?

You can create a new module use hook_theme_registry_alter like module simplelogin
like this:

/**
 * Implements hook_theme_registry_alter
 *
 * {@inheritdoc}
 */
function YOUR_MODULE_theme_registry_alter(&$theme_registry) {
  $theme_registry['page__simplelogin'][preprocess functions] = [
    0 => 'simplelogin_preprocess_simplelogin',
    1 => 'YOUR_MODULE_preprocess_function'
  ];
}


You probally haven't added permissions for anonymous user to do a GET/POST request to the given endpoint. Go to permissions, search for rest and enable "Access GET on [rest resource]" (Access GET on Node rest resource resource)


Where is the code for added user registration fields?

In the field settings, tick "display on user registration form".

All of the database stuff is taken care of automatically in drupal so you'll rarely have to worry about that stuff unless you are adding your own custom modules that require tables.

What are you trying to accomplish with these tables? Views etc. will have access to them.


When shouldn't you use t(), st(), etc. with readable string literals?

Descriptions and titles in hook_menu() *
Descriptions in hook_schema() **
watchdog() messages *
Field/instance definition labels and descriptions ***

* potx extracts the strings
** don't get translated
*** can be translated with contrib, eg. i18n_field


Why can not Drupal find my theme for a custom block?

You're calling a non-existent theme function. Your code should be:

return theme('poll_dialog_output', array(
    'title' => $static_title,
    'content' => $static_content,
    'link' => l('Poll', 'some url'), array('attributes' => array('target' => '_blank'))),
  )
);

or, even better:

return array(
  '#theme' => 'poll_dialog_output',
  '#title' => $static_title,
  '#content' => $static_content,
  '#link' => l('Poll', 'some url'), array('attributes' => array('target' => '_blank'))),
);

The main point is that the name of the theme function you call needs to match what you've used in hook_theme().


How to generate content to Drupal 7 with a PHP-script?

You can use contrib module for that purpose

Devel

  Generate content

  Accelerate development of your site or module by quickly generating
  nodes, comments, terms, users, and more.

Dummy content

  DC allow your custom module to provide demo nodes as soon as the
  module is installed - this helps with populating blocks, views, and
  generally showcasing your module's functionality. This is very useful
  when showcasing a module's functionality to a client. For example,
  rather than installing the Forum module and having to manually create
  forum nodes, the DC API can be used to pre-populate the site with
  forum-type nodes as soon as the Forum module is enabled. Additionally,
  rather than having purely Lorem Ipsum-type content, you can define
  relevant pieces of text and images, giving the content a more complete
  & realistic look & feel.

Note:  Both modules will create random content.


How can I change a content entity to a config entity?

ContentEntity and ConfigEntity are very different. My advice is to just start over.


Page not found - Even after I implemented Hook_Menu()

With the code you posted you will get a blank page.

If you actually return something from your callback you will get a proper page, with no 404 error.
A menu callback has to actually return something.

For example, this works:

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

  $items['paypal/payment/ipn'] = array(
    'title' => t('Paypal Payment IPN'),
    'description' => t('Paypal Payment IPN'),
    'type' => MENU_CALLBACK,
    'page callback' => 'paypal_payment_paypal_ipn_callback',
    'access callback' => TRUE,
  );

  return $items;
}

function paypal_payment_paypal_ipn_callback() {
  dpm("here");
  return 'test';
}

Also, make sure your module is named "user_type_registration" or else your menu hook will not get picked up.


Drupal's DateTime field isn't ISO 8601 compliant, (doesn't save datetime values in the standard format you're expecting 2017-12-21T17:06:29).  You need to convert the value to UTC format for storage.  One approach is to initialize a date variable, convert it, and then pass as the value in your form field.

$currentDate = new DrupalDateTime();
if ($currentDate instanceOf DrupalDateTime && !$currentDate->hasErrors()) {
  $currentDate->setTimezone(new \DateTimeZone('UTC');
  $db_friendly_value = $currentDate->format('Y-m-d\TH:i:s');
}

$form['start_date'] = [
  '#type' => 'datetime',
  '#title' => t('Start Date'),
  '#default_value' => $db_friendly_value
];

Specific notes about working with the DateTime API in D8 can be found in this "New DateTime API" post.

This specific formatting issue was reported for the datetime module here.

Comment 6 shows the recommended approach to converting the date into the proper format for saving.


Unfortunately this isn't very easy using the Form API currently.

There's an issue open to add this functionality (it goes all the way back to 2008) that would theoretically allow you to do something like this:

$form['optiontest'] = array(
  '#type' => 'select',
  '#title' => t('Option test'),
  '#options' => array(
    array(
      '#return_value' => 0,
      '#value' => t('First option'),
      '#attributes' => array('class' => 'first', 'title' => t('First option')),
    ),
    array(
      '#value' => t('Option group'),
      '#attributes' => array('class' => 'group', 'title' => t('This is an optgroup')),
      '#options' => array(
        array('#return_value' => 2, '#value' => t('1st sub-option')),
        array('#return_value' => 4, '#value' => t('2nd sub-option')),
      ),
    ),
  ),
);

But unfortunately there are nothing but failed patches attached to the issue at the moment.

The only way I can think of to do it at the moment would be to add a #process function to the select element, and add the class(es) to each option when they're broken down individually.


I did it using hook_form_alter().

If you have a field with an inline entity form:

$form['field_newsletter_content'][LANGUAGE_NONE]['entities'];

Then you can change the '#weight' property on the individual entities.

So, to change the weight of element 0 to 1, do this.

$form['field_newsletter_content'][LANGUAGE_NONE]['entities'][0]['#weight'] = 1;

And if you change the weight of element 1 to 0, then they will have traded places in the inline entity form.


Entity field query issue to correctly sorting my results

I can't make Molot's comment an answer, but I'll post one for posterity (and to close out this question).

The issue involves your data field type, integer vs. string. When the field is a string, sorting in SQL query will place the rows in lexicographic order, where the first character value is given precedence. When the field is an integer, sorting in SQL query will place the rows in numeric order, where the entire value of the number is used.


What about using Adaptive Theme or sky (based off the first)? These are designed with multiple screen sizes in mind and you have a community of folks to share knowledge with.


How to get referenced fields of a particular node/content type?

Once you have a $node object, you can get the referenced field value by the following code:

$node->get('field_reference')->referencedEntities();

Here, field_reference is a field of type Entity reference revisions referencing to the paragraph entity.


drush core-cli has been removed in Drush 5

  Drush 5 supports bash completion which is much more native and
  superior to the old core-cli command, which has been removed.

More information: Core-cli command removed in favor of Bash completion


Content not displaying formatting - removes HTML despite settings

If text format is correct and filters are correct, verify that the display format of your both content types (Article & Basic Page) is not set to Plain text but Default (or Summary or trimmed, ...).

It is under Structure > Content Types > Basic page | Article > Manage Display > Body field (format column).


Set up the relationship. Under the Relationships section click + to add a relationship.

Under "Add relationships" you will see all fields listed.
Drop down the Groups menu and select "Content".
Locate your node reference field, for example 'Content: Reference user (field_reference_user)'. Check the box to the left of it.
Click the Add button.
Check the box labeled 'Require this relationship', and click the Update button.

Add a Contextual filter for Node ID. Set the default value -> get ID from URL
Add a field. Click + next to Fields. Under Groups, select Node, and choose Node: Title. Under Relationship, select your node reference field, e.g., Reference user, click Update.

Create a view on a node reference field will explain you in detail


You can try something like this

// $node represents the node object
$wrapper = entity_metadata_wrapper('node', $node);
$instructors = $wrapper->field_instructor->value();

Now in instructors you will have each instructor user object and you can print what ever information you want to print from it.


Need clarification on installing site with DRUSH on localhost

Use this command to install Drupal.

drush site-install standard --db-url="mysql://scratch:1@localhost/scratch" --account-name=scratch --account-pass=1 --account-mail="founder@satearn.com"

Note: Move to the folder drupal-7.x folder and run this command from there. This command should be run from the place where your drupal files are located.
It would be better just to rename it drupal instead of drupal-7.x for easiness.
I tested it right now and its working.


Code for "All pages except those listed" in Show block on specific pages

I made this stuff copying from Core's block.module:

//This block will not show pages when these pattern match
$pages = <<< EOT
adsense/*
node/add/*
adsense/*
contact
privacy
tags/*
terms
about
check-for-expired-job
taxonomy/term/*
EOT;

$pages = drupal_strtolower($pages);
$path = drupal_strtolower(drupal_get_path_alias($_GET['q']));
$hide_block = drupal_match_path($path, $pages);
if ($path != $_GET['q']) {
    $hide_block = $hide_block || drupal_match_path($_GET['q'], $pages);
}
if($hide_block)
{
return false;
}

//Now do other processing stuff


No access to admin page after change my server and domain

I had the same problems and there are the several steps that you should do for solving your problems:

1.Add the Error reporting debug ability in settings.php by adding these lines:

error_reporting(-1);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

These lines should be comment out after debug or after solving problems.

2.Browse the website and see what error information that you will get. If there is error with timeout or memory problem. Please change the memory_limit or max_execution_time if your hosting support to do that.

3.If there are some problems with the PHP version(There are some differences between PHP 4 and PHP 5). You will consider to upgrade or not.

4. Sometime there are several issues that are related to database or .htaccess. You'll see on the debug information and try to fix one by one


Apache solr filter based on array values

I finally figured it out. Just a small change to what Clive suggested will solve the issue.

$query->addParam('fq', "entity_id:(10915 OR 11013)");

The above code gives me the expected response, i.e., result of node 10915 and 11013.

Hope this helps :)


I asked a member of the Drupal security team about this and he referred me to https://www.drupal.org/drupalsa05FAQ#comment-9255523.

This points to a user attempting to exploit SA CORE 2014 005, but failing due to the site being patched. Cesar's attempt to reproduce triggers the PDOException, but does not (and cannot) result in actual SQL injection.


How to redirect to another page using the url alias?

Here you can see an example that works for me:

I use 'internal:url-alias'

use \Drupal\Core\Url;
...

$search_page = '/en/faith-community/find-a-parish';
$form_state->setRedirectUrl(Url::fromUri('internal:' . $search_page));


How can I have node pages with Fivestar or comment fields cached properly?

I realized this was an issue because I was using the Honeypot module. Honeypot disables caching on all pages where there is a form. I updated the setting in the module to exclude node pages and it fixed the issue.


Call another field inside preprocess_views_view_field

Ok,
I solved it like this:

function THEMENAME_preprocess_views_view_field(&$variables) {
  $view = $variables['view'];
  $field = $variables['field'];
  $rows = $variables['rows'];

  if ($view->id() == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME') {
    if ($field->field == 'FIELD_NAME') {
      foreach ($view->field as $fieldId => $field) {
        if ($fieldId === 'ANOTHER_FIELD_NAME_IN_VIEW') {
          $my_output = $view->style_plugin->getFieldValue($row->index, $fieldId);
        }
      }
      $variables['output'] = $my_output;
    }
  }
}


How do I determine a page's content type for non-node pages?

Use template_preprocess() for detecting node on page and pass additional variable as flag to template file, like:

$variables['display_region'] = TRUE;

Maybe Panels can help you too.


The module Views data export claims to do it:

  Style plugins are included that support exporting in the following
  types:

CSV
Microsoft XLS
Microsoft DOC
Basic TXT
XML.

So you should be able to construct a view of fields or rendered entities and select the display for a doc file.

See a similar question here: Export node report base on Word and Excel template


Display ubercart product image given a product nid

It's tricky without some more information but something like this:

$product = node_load($nid);
$image_path = $product->field_image_cache[0]['filepath'];

print theme('imagecache', 'product', $image_path, $product->title, '');


Didn't read the linked site, but:

Image styles are managed here "admin/config/media/image-styles"
Image Field settings are managed here: Visit "Structure" -> Content types -> Edit %your-content-type% -> Manage fields tab -> Click edit link in the row of %your-img-field%


show/hide a menu item based on specific user role

All you gotta do is configure your menu block

Then under Visibility > Roles, check mark ☑ the roles that you want to be able to view this block menu.


How to get the current request object:

Procedural

In procedural code get the request from the static wrapper \Drupal:

$request = \Drupal::request();

Service

In a service get the request from the injected request stack:

$request = $this->requestStack->getCurrentRequest();

Controller

In a controller you can pull the request from the route argument stack by including a typed request parameter. An example from UserController:

use Symfony\Component\HttpFoundation\Request;

  public function resetPass(Request $request, $uid, $timestamp, $hash) {
    // use $request
  }

It's not necessary to define the route parameter in the route definition. The request is always available.

Form

In a form method get the request from getRequest():

  public function submitForm(array &$form, FormStateInterface $form_state) {
    $request = $this->getRequest();
    ...
  }

Don't use the injected requestStack property directly, because it is not available for all Form API callbacks.