db_query performance This is a more general question about db_query() performance.

I have this function to create an API resource with Services module, and I need to get about 10 fields belonging to several nodes.
Basically I have a list of nids and create an array containing information from their fields. The nodes have a lot more fields than I need so doing node_load to get the info is really slow, so at the moment I am geting the info using db_query() calls for each field that I need.

My question is: would it perform better if I only have one db_query with about 10 inner joins? or should I leave it as 10 separate db_queries?

I am going to do some performance tests, but I thougt someone might have some insight or explanation on why one would perform better tha. the other.

Install entitycache - it will load the nodes quickly from a persistent cache ( e.g memcache, but db ok )
Use EntityFieldQuery to fetch the relevant nodes.

e.g:

  // Get published articles created in last 7 days.
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
        ->entityCondition('bundle', 'article')
        ->propertyCondition('status', 1)
        ->propertyCondition('created', strtotime('-7 days', REQUEST_TIME), '>');
  $result = $query->execute();
  if(!empty($result['node'])){
    // These will be loaded from entitycache
    $nodes = node_load_multiple(array_keys($result['node']));
    // Process result nodes
    foreach($nodes as $node){
      // Do stuff
    }
  }


How much RAM does a basic installation need? I am looking to downgrade from a dedicated to a VPS server (several, to spread it out) and was wondering if 512MB will do? I have Boost with all core caching enabled, and mostly anonymous traffic.

It depends on a number of factors:

What contrib modules are you using? The bare minimum Drupal needs to run is 32 MB, but that truly is the bare minimum. Contrib modules and doing anything moderately complex with code will increase your memory requirements. While you're using Boost which is great, you still need to generate the cache, which requires RAM. But unless you're doing something really intensive, I've found you can generally be fine with 128 MB for PHP.
What web server are you running, and what type of load are you expecting? If you're running Apache with its default settings, it'll eat up a lot of memory: generally 128 MB or more. Optimizing your Apache environment or switching to a less memory-intensive server will free up more memory, but it's up to you if that's something that's possible.
Are you running your database on the same server? MySQL has its own memory requirements, and you'll find it takes up the bulk of a shared server's memory. You'll bump up to the memory limit on a small VPS pretty fast, especially if you're running InnoDB or have a large site. The general recommendation is somewhere between 70-80% of RAM should be allocated to MySQL running InnoDB, which is ~360 MB on a 512 MB instance: not a lot of room for PHP and Apache (or anything else).
Are you running any other service on the same server? If you're running Memecached, Varnish, APC, Jenkins, or any other service common to a Drupal environment, they all take up memory, and in many cases, a lot of memory.

If you're running a small Drupal site with an optimized Apache configuration, database on its own server, and no other service, I've found 256 MB to be the bare minimum. 512 MB is okay, not great, if you need to run the database on the same server and want to enable APC, but you still be looking for ways to save RAM.

I personally run the database, caching, and continuous integration services on other servers and use a Micro EC2 instance (613 MB RAM) for most Drupal installations I do. But I'll bump that up to a Small instance (1.7 GB, overkill, but there's nothing in between) if the site's going to get a lot of traffic.


How can I get the width or height of an image field image into a twig template? I'm using PhpStorm/xdebug/MAMP to look at the variable I want to access:

I have tried using the following to get at the data:

{% set image_width = content.field_image.0['#item'].values.width %}

and

{% set image_width = content.field_image.0['#item'].values.width.value %}

Neither of these lines produce any data.

Any help is greatly appreciated!

You can't access the array values because it is protected. But you don't need to, because you can get the properties from a field item directly:

{% set image_width = content.field_image.0['#item'].width %}

BTW the content variable is a render array with no fixed structure. The presence and position of #item changes dependent on the field formatter and other core, contrib or custom code.

So it's better to use the entity object, for example the paragraph entity in a paragraph template:

{% set image_width = paragraph.field_image.0.width %}


How do change address field titles to another language in Ubercart? In D7 you could just rename the title and type them in a different language.

But in D8, there is no such option like in D7.

Installing the Ubercart translation solves the issue. Import the file using the Interface Translation module.


Changing the output of a views field I'm using Drupal 8, with a view of type Log entries. I'm trying to rewrite the output so it adds additional text but the field is already formatted by the time it gets to the twig file. Where is the field being rendered? I'd like to override the rendering for just this field in just one view. Thanks.

Use replacements ..
You can simply edit the field and tick the box Next to "Exclude from display" this will hide the field, then you can Add a new field of type "Custom text"
In the "Text" section scroll until you see "REPLACEMENT PATTERNS" expand that and grab the {{ field_name }} < the field you want to use.
then in the text section put
{{ field_name }} your additional text.


Caption Filter works in Preview, but not in regular view of node I am using the caption filter module, which is working fine on a couple sites I manage, but on one specific site, when I use the markup and click on preview, it works perfectly, but if I save the node and then view it normally, it is clear that filter is not processing as it outputs the filter markup as plain text.

I am mystified as to why an input filter would work in preview, but not after its is saved.  I keep thinking it might be a permissions issue, but I can't identify anything that would seem to trigger this.

Any suggestions to narrowing down this issue would be greatly appreciated.  And I do have the caption filter as the last one, per the instructions and same with a similar site that I do not have this issue.

OK, I figured this issue out.  This particular content type was using a custom template and I forgot to push the body content through check_markup(..) before outputting it.


How do I get the blog teaser view display on a content type? I know. I write English language really bad, horrible. I apologize.

I created a blog (with the core's blog module. Also I have a content type called my-content-type :). I need the blog teaser view is displayed in my my-content-type.

I installed Display Suite. So, my-content-type has the Display settings option. With this option I can choose the desired view, in my case the teaser view. OK, very good! Now, but how do I get the blog teaser view is displayed in my-content-type?

Can I do this without Views?

Greetings!

Short answer:

Yes, you could do it without views. But, it wouldn't be ideal.

Long answer:

Display suite module will let you control the display of the particular content type and its fields. It won't allow you to control the display of a different content type from the other.
E.g. For your my-content-type, it will allow you to change the display settings of the fields of this content type.

If you wish to display teasers of nodes of the blog content type, on the node pages of my-content-type, you will have to do the follow the steps below:

Without views:

Create a custom module.
Load the blog $node using node_load on my-content-type node page.
Using node_view on the $node get the node in the teaser view of the node.
Use drupal_render to render the loaded teasers in a custom block created using hook_block_info.
Place this block in an region only on the my-content-type node page.

With views:

Create a view block of content of type blog.
Select the display method to be content, and select teaser from the settings.
Apply additional settings (filters, relations) as required.
Place this block on the node page of my-content-type.

In other words you let views build your query for you. And you also get an additional advantage of using other features provided by the views module like caching, etc.


How to show a block only on the nodes which the user created I have a block that I only want to display in nodes that the current user created. What's the best way of going about this?

Thoughts so far

I can access $user (and therefore the UID) anywhere, so I need to compare this to the node author UID. The only problem is finding a place where I can also pull in the current node information to find out it's author.

I really don't want to put php in a block (bad practice and all) and I couldn't see where I'd do this in context.

If I can't find a better way then the backup plan is to create an automatic field on node creation which contains the authors UID, then use this in page.tpl.php to set a class which will apply display:node to the block whenever the author UID =! user UID.

EDIT: Solution

The block I was trying to effect was in a custom module, so I took Yuriy's code and put into the modules hook_block_view. The result was this:

function mymodulename_block_view($delta = '') {
  $block = array();
  switch($delta) {
    case 'mymodulename_form':
            if (preg_match('#node/([0-9]+)#', $_GET['q'], $matches)) {
              if ($node = node_load($matches[1])) {
                global $user;
                if ($user->uid !== $node->uid) {
                  $block['content'] = array();
                } else {
                  $block['content'] = drupal_get_form('mymodulename_form');
                }
              }
            }
    break;
  }
  return $block;
}

I think this is what's going on:

preg_match and $_GET are used to take the node path from the current page. This returns: "node/xx". This is then used to load the correct node which is then matched against the global UID. An if function then either empties the block content or fills it.

I don't understand your reluctance to use php in a block, particularly in the block visibility settings.

If you set the block to display only on the pages where the following php code returns true, then the following, or something similar, should do the job for you.

<?php
global $user;
$node = menu_get_object();
return ( $user->uid == $node->uid );
?>


Access the field class from within FieldItemList (D8) When I would like to get the values inserted in a form, I use:

$form_state->getValue('myfield');

If I would like to have some information on the field definition, I use:

$form_state->getFormObject()->getEntity()->myfield->getfieldDefinition();

Every time I check the class resulting from the following statement:

$form_state->getFormObject()->getEntity()->myfield

It is of the type Drupal\\Core\\Field\\FieldItemList which is fine for getting/setting the values

Suppose that "myfield" is of the type "language_field" defined in \Drupal\languagefield\Plugin\Field\FieldType\LanguageItem.

This class have a public function

public function getNativeName()

To get the full name of the language.

But My question is: how to access this function fromwithin the FieldItemList object? (Same problem arise with many other field type)

Added info:

With the help of @Eyal, I could access my object method:

$form_state->getFormObject()->getEntity()->myfield->get($delta)->getNativeName();

But this is valid only if the entity is already saved.

In the case of a new (or edited) item, the entity doesn't store the new value. Here is the code for what I am trying to explain:

The 2 variables will have the same value if I open and save the form without change, but this will not be the case if I update the item at delta=1.

function my_validate($form, FormStateInterface $form_state) {
  $val_by_entity=$form_state->getFormObject()->getEntity()->myfield->get(1)->value;
  $val_by_form_state_value=$form_state->getValue(['myfield', 1, 'value']);
}

You first need to understand that the entity object in question does not have a property called myfield.

Drupal uses something called magic properties to mask the get method required for retrieving the field item list. See FieldableEntityInterface::get() for more information.

The second thing you should know, is that drupal treats all fields as multi value. That means that a field that is defined to have a single value would still be represented a list with a single item.

Finally, to answer your question, you can either use the FieldItemListInterface::get() method to get the field item object, it you can access it as though it was an array.

$entity->get('myfield')->get(0);

OR

$entity->myfield[0];


How to modify the search index? There's a search index for the Apache Solr module. However, I don't see any way to change this index. It seems that various fields and items are added to the index without rhyme or reason.

If I wanted to index a field called "keywords" how would I go about this? Do I have to use the method described in Adding Customized Fields to the Apache Solr index in Drupal?

Basically, there's a keyword field, which will have comma separated values of keywords, and I want to index this for Apache Solr search.

You should use hook_apachesolr_index_document_build in your custom module. This hook helps to extend basic SOLR Document object and adds custom fields for indexing.

If 'Keywords' field has machine name 'field_keywords' hook implementation may be as below

/**
 * Implements hook_apachesolr_index_document_build().
 */
function MY_MODULE_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) {
  if ($entity_type == 'node') {
    // Adds 'Keywords' field as a separate field to Solr index.
    $document->keywords = isset($entity->field_keywords[LANGUAGE_NONE][0]['safe_value']) ?
      $entity->field_keywords[LANGUAGE_NONE][0]['safe_value'] : '';
  }
}


Display random view result every x rows I'm trying to display an ad every six rows of a view. I'm thinking of using another view that contains all the ads and displaying a random result of that every 6 rows of the main view.

Drupal 7 & Views 3.14

I have tried to do this but gotten stuck on the displaying something every 6 rows. Here is my code:

...code irrelevant, unedited coded copied from the template file in views module folder...

    <?php foreach ($rows as $row_count => $row): ?>
      <tr <?php if ($row_classes[$row_count]) { print 'class="' . implode(' ', $row_classes[$row_count]) .'"';  } ?>>
        <?php foreach ($row as $field => $content): ?>
          <td <?php if ($field_classes[$field][$row_count]) { print 'class="'. $field_classes[$field][$row_count] . '" '; } ?><?php print drupal_attributes($field_attributes[$field][$row_count]); ?>>
            <?php print $content; ?>

        <?php endforeach; ?>

      <?php if ((($row_count % 6) == 0 && $row_count !== 0): ?>
This is the row after every 6th multiple
<?php endif; ?>
    <?php endforeach; ?>

UPDATE: I figured out a way to print a random result. Just add randomize as the only sort in the view. However, I still can't get the printed view result to be in the appropriate location.

Okay, I solved it by using by using an unformatted list instead of a table.

Here is my code in the end:

<?php if (!empty($title)): ?>

<?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
  $numRows = 6; /* Which row do you want the view to appear? E.g. 6 means that rows 6, 12, 18, etc. will have the view */
  if ((($id - ($numRows - 2) ) % ($numRows - 1)) == 0 && $id !== 0):
?>

<?php print views_embed_view('VIEW_MACHINE_NAME', 'DISPLAY_ID',''); ?>

  <?php endif; ?>
<?php endforeach; ?>


Modify values that are received via Feeds_ex I've setup Feeds_ex module using JSONPath. One of the value I import is language code and it has next format: [language-country], i.e. [en-US] or [en-UK].

Right now I do import full value 'en-US', however I need to get only 'en' and get ridd of '-US'.

What is the good/best practice to modify value that I receive from Feed?

Thanks.

Try hook_feeds_presave().

Just explore $entity object. You will get some idea.

Below is a example code.

$entity->lang_country[LANGUAGE_NONE][0]['value'] = 'en';
// After split [language-country] store your lang here.

Update:
Also check feeds_tamper


How can I show average votes of fivestar nodes? I want to make a survey with Drupal, using Fivestar fields. So, I created a new content type called "survey" and added fields "field1, field2, field3, ..." The user can add content "survey" and the results of the voting are saved in nodes.

Now, I want show an average for all nodes with the content type "survey": Display the average of the individual fields of the survey. How can I do it?

Consider a table similar to this one:

The Views Calc module can be used to transform that table so that the calculations in the last rows (with Count, Sum and Max) get added to it. So that the table looks similar this:

By replacing the columns '# Fish', 'Weight' and 'Big Fish' in the example above with 'field1', 'field2' and 'field3' (as in the question), and by asking for the 'average' to be added (instead of Count, Sum or Max), it should answer the question I think, no?

To ask for the 'average', just select it from the selection list as shown in this screenshot (instead of the ones selected in that screenshot):

For more details (step-by-step instructions), refer to the community documentation about the Views Calc module.


HELP! Can't make glossary using taxonomy term name I'm using Drupal 8.0.2 and I'm trying to create a glossary of taxonomy terms by name. I have setup the view as follows:

Unformatted list
Fields: Taxonomy term: Name
Filter: Taxonomy term: Vocabulary (= Fruit Name)
Sort: Taxonomy term: Name (asc)

Stopping here the preview shows all Fruits by name (a-z) as expected.

Now when I add the following Contextual Filter:

Taxonomy term: Name
Type: Fixed
Fixed value: a
More: Glossary mode
Character limit: 1

The preview is empty, and the page returns a 500 error. I have done this successfully many times using Content: Title, but it never works using Taxonomy: Name. Can anyone tell me why this won't work using taxonomies?

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

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


Access denied when trying to import single configuration item I am using Drupal 8.9.2 and trying to import a view using the Configuration Management UI in the admin. I did this with no issue importing the view from my local dev environment to our dev server, but when I try to do the same thing on our test server, I get "Access Denied".
The way I did this was by going to my local environment and going to Configuration > Development > Configuration synchronization > Export. Then choosing "Single Item". Under "Configuration Type", I chose "View" and then selected my view. I then copied this code and went to my dev server and went to Configuration > Development > Configuration Synchronization > Import and chose "Single Item" and chose "View" for "Configuration type". I pasted my code in and clicked submit and my View was successfully imported and all was well. Now when I do this exact same process on my test server, when I get to the part where I submit my pasted code and click submit, I get:

Is there a specific directory that I must not have access to on the server? Or Drupal doesn't have access to on the server? I'm not sure what happens behind the scenes during this type of import process. In my settings.php I have this for the config sync stuff:
$config_directories['sync'] = '../config/sync';

And I checked that directory and it does have read/write permissions. Is that even the directory I need to check as far as permissions go for a single item config import?

OK, so this one was determined to be an Akamai issue for sure. There were some measures that it takes if it thinks it is a denial of service attack and for some reason that was what was happening. Our admin adjusted some settings and the error went away.
THANKS


Pseudo-field for custom entity without hook I developed custom entities in the code, using entity references :
A <- R -> C. Entity "R" contains references to "A" and "B".

I'd like to add a pseudo-field in entity "A", configurable in view display, that could render referencing entities (mean "R" entities referencing "A" with a given field "F").

Since I made my own classes for the entities, I'd really like to continue that way and prevent using hooks. I know I could achieve this with views, but it seems more logical, reusable, and quicker, to put it in entity code.

Is there a way to add the display field to my entity without using hook_entity_extra_field_info() ? For example could I create my own FieldEntityManager ?
Is EntityViewBuilder the right place to render the field with my own data ?
In a more generic way, would it be possible to develop a custom field type "referencing_entities" that I could reuse in every referenced entities I have ?
Would it be only a field formatter since I don't need to store anything ? Is it possible to access to the entity from the field to query referencing entities ?

As time goes by there's Extra Field now.

  Provides a plugin type for extra fields in entity view.

  This module allows developers to add custom fields by simply providing
  a plugin. Site builders can use these fields in entity view modes as
  normally. Extra fields do not store data and do not have a field
  widget. Extra fields typically combine existing entity data and format
  it for display.


Are taxonomy fields exposed to views? I am trying to create a view of nodes that have a taxonomy reference field. I can get the taxonomy term but do not see the taxonomy fields that I've created exposed to views. Google searches do not reveal anyone else having the same issue. Am I missing something right under my nose?

Are you using Relationships? It's right there in the views edit page. Since you're showing nodes, you are probably going to need to declare you want to show taxonomy term fields.


How to change authoring information with Rules? I'm trying to create a rule that fires upon saving a node with a few conditions.  The rule takes the current author, and sets it in a field called "field_original_author" and after that changes the value of the current author information to a particular author.

It does the first bit but not the second. Even if I only use the second part, it still doesn't change the author information into the other author that I specified.

What gives?

I can't remember exactly, but you can create an action "Fetch entity by ID". Add user as the entity type, and create another action "Set a data value" with selected data [node:author]


List all content of the same Author I have a view on a node page. How do I get it to list all content that has the same author as the current node?

Are you using 6 or 7? In 6 you'll need to add an Argument; in 7 a contextual filter. Either way, it works pretty much the same.

Create a block display.
Add the fields you want (usually just the title for a simple list.)
Add either an argument or contextual filter for the author uid.

Then under "Action to take if argument is not present", choose provide default value. For the default value, choose PHP Code, and add this code to the box:

if (arg(0) == 'node' && is_numeric(arg(1))) {
    $node = node_load(arg(1));
    $uid = $node->uid;
}
return $uid;

Save your view; then clear all caches.

Note that the use of contextual filters renders the preview unusable; you'll need to actually add your block to a page to see it.


Load a full menu with active trail I need to load a full menu for navigation in a custom theme with active trail, and can't find any way to do it, but that can't be right.  I can't imagine such an obvious and widespread use-case having no core support, but I've scoured menu.inc and found nothing.  The functions offered range from inadequate (no active trail) to completely unusable (menu is missing children for the CSS dropdowns/submenus outside the active trail, and even empty when needed most, such as on broken links).

I've tried using the following functions in my THEME_preprocess_page hook:

menu_tree (only renders siblings of the active trail--the navbar can even end up empty)
menu_tree_page_data (same result)
menu_tree_all_data (contrary to the documentation--luckily--this method does not return hidden items, but there's no active trail)

So far as I can tell, my only options are to copy and rewrite several functions from menu.inc, or to load two separate menus and apply deep analysis/merging to find and duplicate the active trail from the incomplete menu into the complete one--and this is just as bad because the data structures don't match.  Is there no other way to get a full menu with active trail?

Also, what if I do go with the latter option using menu_tree_all_data?  Will I end up exposing links that aren't properly going through access checks, or have similar issues?  How the heck does Drupal itself load a full menu, like the Navigation menu which doesn't go away while visiting other parts of the site?

I did find another nearly identical question but no one answered it and that was 9 months ago.  This is for a project that's already running well behind schedule due pretty much exclusively to unforseen Drupal-related issues, so any pointers are much appreciated.

EDIT: Whoops...tried to be thorough and missed a major detail :P  I'm on Drupal 7.

I just want to add my experience to the lot. I had similar issues using Drupal menu. The solution I used is:

Set all menu items with children to "Expanded". This as to be done manually: Structure > Menus > List links, edit links which has children, check the Show as expanded checkbox.
Use menu_tree_page_data function (example: $menu_tree = menu_tree_page_data('main-menu')) to get the menu, with all its children AND with active trail.
Create a renderable array using menu_tree_output function (example: $renderable_array = menu_tree_output($menu_tree)) to prepare the menu for rendering.
Use the renderable array as content for my custom block, but you could call drupal_render($renderable_array) to get the rendered HTML representing the menu.


how to update a field created with field_create_instance I'm building a module which implements hook_enable to create fields.
But as I'm developing I noticed a error in my code causing fields to be created in a wrong way.

Is there a way to update these fields?
preferably using code so I can also use this code to hide these fields from lets say a user profile once the module is disabled.

here's my code that I used to create those fields:

//calling my function
popover_create_user_field('field_firstname', 'Voornaam', 'textfield', 1);

/**
 * field creator helper function
 */
function popover_create_user_field($field_name, $field_label, $field_type, $visible_on_registration_form = 1) {
    // Check if our field is not already created.
    if (!field_info_field($field_name)) {
        $field = array(
            'field_name' => $field_name,
            'type' => 'text',
        );
        field_create_field($field);

        // Create the instance on the bundle.
        $instance = array(
            'field_name' => $field_name,
            'entity_type' => 'user',
            'label' => $field_label,
            'bundle' => 'user',
            // If you don't set the "required" property then the field wont be required by default.
            'required' => TRUE,
            'settings' => array(
            // Here you inform either or not you want this field showing up on the registration form.
                'user_register_form' => $visible_on_registration_form,
            ),
            'widget' => array(
                'type' => $field_type,
            ),
        );
        field_create_instance($instance);
    }
}

Lets say I want to update the user_register_form visibility to 0 so it will be hidden.

You can use a combination of field_info_instance() and field_update_instance():

// Load the instance
$instance = field_info_instance('user', $field_name, 'user');

// Make whatever changes you need to, e.g.
$instance['settings']['user_register_form'] = 0;

// And save it again
field_update_instance($instance);


Issues with workbench moderation I've installed workbench and tried to work with it. I followed the step-by-step instructions given in the video here and I was almost successful in creating the content and moderating it between the two kinds of user one is Publisher and the other is content-creator.

Content-creator creates the content and forwards it to needs-review, now the publishers gets the access to the content in the needs-review tab. And the moderation should be done between these two users.

Here, my issue is when the content-creator creates a content - he is unable to see his content in his profile (I mean either in 'MyContent', 'MyDrafts' and 'Needs review'). And the same case with the other user (publisher)- the Needs-review tab looks empty even though there is some content created by 'content-creator'.

To keep it short, MyWorkbench tab looks empty- the Needs-review tab, MyContent tab and MyDrafts tab are empty. The only way the content appears is in Content tab.

I'm not aware of workbench module, I've followed all the instructions given in the video. I'm missing any?? Please give your answers.

Thanks in advance.

I faced the same issue where 'Needs Review' tab appeared empty after the workbench moderation state for conten type is set to 'Needs Review' or 'Draft'by the creator.
I applied a patch from drupal.org and it worked. Please find the below patch and apply it in your Workbench Moderation module.

https://www.drupal.org/files/node_revision-1363990-2.patch

Let me know if you still face an issue.


What should be the optimum values for Minimum cache lifetime and Expiration of cached pages i am working on a mobile app. Using drupal json views i am parsing the data and displaying on the device. It takes nearly 10 sec to load 10 records on the device. Initially i thought this might be due to slow internet, but that is not the issue. Later i came to know this is something related to cache. So can any one help me to minimize the loading time by suggesting minimum cache lifetime and expiration of cached pages .

The values of minimum cache lifetime and expiration of cached pages depends on how frequently the content on your site changes and for how long the external caches can show stale data from your site.

To get more info about these check https://drupal.stackexchange.com/a/83342/4876

However in your case I am not sure if these will matter. You should probably consider looking at Views Content Cache That might improve the performance in your case.


Changing node values directly to database exhibits erratic behaviour I needed to create a new field for each node in my website that would have as its value a concat of two existing fields.

I firstly inserted the new rows in the newly created field table, and then updated each of the rows with he corresponding information.
But when I check on the browser in the edit page of several nodes some of them have the correct value inside the field while others have that field blank. The strange part is that there is no apparent difference in the database between the nodes with a value in the field and those that have it blank.

After investigating the issue I copied all the table to its correspondent revision table, leaving revision_id as 0. This didn't solve the problem.

I know I'm not supposed to directly modify the database like this but it has half-worked and I was wondering if there's a way to execute a method or a module so all nodes will have their field filled, or if I should erase all contents of the table and use db_update() or node_save() to do the job.

thanks in advance

The safest way would be adding field data and saving it with node_save. If you write it to the database, you have to also duplicate the record to the revision table of that field and keep track of vids. The API will just do this for you. You do not (should not) write field data via db_insert or other functions like it. Doing so may irreparably harm your database.

To apply the data retroactively, I would advise that you create a batch op via Batch API. Query up all nodes, create batch operations, and in your batch callback, process the node and save it with node_save.

There is a docs page on getting started with the Batch API.

Here is a blog post that demonstrates a basic batch job that is close to what you'd want to start out with. You'd want to populate the $operations array with node ids, and every time the batch callback is called, the node id is passed. Then you load the node with it, set the field, then save the node.

edit: tutorial author also provides a Drupal 8 version.


Drupal Commerce: Can I split payment over multiple credit cards? I need to enable my customers to be able to split payments over multiple credit cards.  Is it possible with Commerce, and where can I find documentation to that end?

No

It is not possible now. It was requested, and it is Closed (won't fix) - if you want it, you need to code it yourself.

  This isn't something Commerce can do out of the box, and I'm not entirely sure it would fit in. However, in a contributed module, you should be able to look at the order balance before moving forward to the checkout completion page and requesting additional payment from the customer if necessary. For now, I'm just going to have to mark this "won't fix" as no easy ideas come to mind for how we could make this abstract enough to solve in core. The main problem in core would be how you visualize the outstanding balance and accommodate both on-site and off-site payment methods.


Search Api custom field type I have a field that concatenates multiple taxonomomy terms  into a single text field. I have altered the existing module concat_field.

This all works fine but I cannot get search API to recognize the field (it worked with an older version of search api)

I have added this to the module:

function concat_field_property_info_callback(&$info, $entity_type, $field, $instance, $field_type) {
  $property = &$info[$entity_type]['bundles'][$instance['bundle']]['properties'][$field['field_name']];

  $property['type'] ='text'; //tried concat_field as well which is the type in concat_field_field_info
  $property['getter callback'] = 'entity_metadata_field_verbatim_get';
  $property['setter callback'] = 'entity_metadata_field_verbatim_set';
  $property['label'] = 'Concat field';
  $property['description'] = 'concatenated field';
  unset($property['query callback']);
}

Any clue what i am doing wrong?

I think you need to follow following approach:

 /**
 * Implements hook_entity_property_info_alter().
 */
function modulename_property_info_alter(&$info) {
  $info['node']['properties']['concat_field'] = array(
    'type' => 'text',
    'label' => t('Concatenated form of all the taxonomies that has been added to the node'),
    'sanitized' => TRUE,
    'getter callback' => 'modulename_search_api_property_concat_field_callback',
  );
}

/**
 * Getter callback for concatenate terms field.
 */
function modulename_search_api_property_concat_field_callback($item) {
  /** Do all your processing/functionality here. **/
  return <resultant concatenated value>;
}


How to get the list of nodes edited by an specific user? I need to be able to see all the nodes that have been edited by an user and be able to download that info, I've been searching for a module but I can't find one.

On the log messages report I can see that info but I can't download it and also it only shows the data for the last month.

This is how i ll get all nid of revision of an user :

  All node revision are store in the node_revision table.

  $connection = \Drupal::database();
  $query = $connection->query("SELECT DISTINCT(nid) FROM node_revision where revision_uid = 1");
  $result = $query->fetchAll();
  //devel module
  kint($result);

node_revision aren't entity so the only way you have is to do a manuel query.

  And if you need to filter by content type :

      $connection = \Drupal::database();
      $query = $connection->query("
      SELECT DISTINCT(node_revision.nid)
      FROM node_revision
      LEFT JOIN node ON node_revision.nid = node.nid
      WHERE node_revision.revision_uid = 1 and node.type='page'"

);
      $result = $query->fetchAll();
      //devel module
      kint($result);

In this table you can get the revision_log field too.

Then you can use entityManager for load all your node :

 \Drupal::entityManager()->getStorage('node')->loadMultiple($nids);

you need to build your $nids array with the query result.

You can load all revision too by node id.


Display/Print both full content and teaser in node.tpl I want to display both full content and teaser content at the same time in node.tpl.php Here is an example of what i want to display

Mini Table

Full Table

        TEASER DISPLAY

        FULL CONTENT DISPLAY

I search for it but didn't find the answers. Please Help

I think this would be worked for you.

for teaser use

$rendered_teaser = render(node_view(node_load($node->nid), 'teaser'));
print $rendered_teaser;

and for full use

$rendered_full = render(node_view(node_load($node->nid), 'full'));
print $rendered_full;


How to create custom VBO action? I need to update term references on nodes without updating the "changed" timestamp on the node.
If I use VBO with "modify entity values" as action I can update the term reference but it will also update the "changed" timestamp.

How can I code a custom VBO action?

First, an explanation of why the changed timestamp gets updated. Actions can declare the attribute

'behavior' => array('changes_property')

in their hook_action_info entry. This attribute causes VBO to automatically call Entity API's entity_save function after the action has been called. This function ends up calling node_save, which updates the changed timestamp.

To avoid this behavior, simply create your own custom action by implementing hook_action_info in a custom module and follow the action_example of the Examples module. Make sure that your hook_action_info omits the attribute

'behavior' => array('changes_property')

Your action function will need to save the node or any other data by manipulating the database directly, or by making sure that you're using a function that doesn't trigger a node_save call.


Redirect to login on form submit I want to allow users to fill and submit a form even if they are not logged in, however if they are not authenticated yet, they should be redirected to login first, and after a successful login the submitted for will be really processed.

I will try to explain the solution that I did with a simple example:

function mymodule_menu() {
  $menu_items['custom/path/xyz'] = array(
    'page callback'   => 'mymodule_page_callback',
    [...]
  );
  [...]
}

function mymodule_page_callback() {
  // If there is a form_id_state saved in session, then
  // this is a redirect after login. Call the submit function again.
  if (isset($_SESSION['mymodule']['form_id_state'])) {
    $form_state = $_SESSION['mymodule']['form_id_state'];
    unset($_SESSION['mymodule']['form_id_state']);
    //drupal_form_submit('mymodule_form_id', $form_state);
    mymodule_form_id_submit(NULL, $form_state);
  }

  // Do normal things here.
  [...]

  return drupal_get_form('mymodule_form_id');
}

function mymodule_form_id_submit($form, &$form_state) {
  $op = $form_state['values']['op'];
  if ($op == t('Save') and !user_is_logged_in()) {
    // Save $form_state to session and redirect to login.
    $_SESSION['mymodule']['form_id_state'] = $form_state;
    drupal_goto('user', array('query' => drupal_get_destination()));
  }

  // Do normal form processing here.
  [...]
}

So, if user clicked Submit but he is not logged in, he is redirected to login with drupal_goto() and with come-back instructions, but first the state of the form is saved in the session.

Then, on page display, we check first whether there is a form state saved in session. If yes, then call again the form submit function, so that the processing of the form is finished (this time the user will be logged in).

All this seems a bit hackish to me. I wonder:

Are there any drawbacks to this approach?
Which is the best way to submit the form again,

calling the drupal_form_submit('mymodule_form_id', $form_state) (commented),
or calling the form submit function directly mymodule_form_id_submit(NULL, $form_state);?

Is there any better way to do it?
Is there any Drupal way to do it?

I have seen that this is a frequently asked question among the Drupal developers. So, maybe there is any standard answer for it.

This might help in terms of understanding Rules: https://drupal.org/node/878718

And in terms of flow, I think you could use a rule via the Rules module to direct them to a login page specific to them (people who have just filled out the form), and then the Login Redirect module to redirect them back to the form/submit action after they login. That's assuming the information they entered would remain in the form. You'll probably have to do some experimenting with that.

Jennifer


Showing icons to represent content types Is there a simple way to have the site display a content type icon just before the "Submitted by..." function? I know I can do this conditionally in node.tpl.php like

if ($type==blog_post) echo '<img src=blog_post.png />';

etc. But this seems cumbersome. I have seen this done as part of Drupal Commons and others. Is there a module that can handle this or any other systematic changes to how the metadata is displayed?

This is set up by the node.module via preprocess()ing in variables:

// Display post information only on certain node types.
if (variable_get('node_submitted_' . $node->type, TRUE)) {
  $variables['display_submitted'] = TRUE;
  $variables['submitted'] = t('Submitted by !username on !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date']));
  $variables['user_picture'] = theme_get_setting('toggle_node_user_picture') ? theme('user_picture', array('account' => $node)) : '';
}
else {
  $variables['display_submitted'] = FALSE;
  $variables['submitted'] = '';
  $variables['user_picture'] = '';
}

These are then used like this in (the standard core) node.tpl.php:

<?php if ($display_submitted): ?>

    <?php print $submitted; ?>

<?php endif; ?>

So, it would be pretty easy to do something along these lines in your theme's template.php file:

function YOURTHEME_preprocess_node(&$variables) {

  if ($variables['display_submitted']) {
    $variables['submitted']='type . '.jpg">' . $variables['submitted']; // or whatever/however you want to do this
  }

  // any other preprocessing goes here

}


How to call a block inside a view page? I am working with Drupal 8. I have a view page and added a twig for that.

I want to call a block inside my view page. How can I do that?

Here is some possible ways to do it:

1. using no extra modules

Click ADD next to header or footer area and look for GLOBAL: Rendered entity - Block.  The configuration asks for view mode and block id

2.  using  Views block area module

You can use Views block area module that will allow you to insert a block as a field or in header or footer area.

3.  using preprocess / twig

if you want to add the block using your twig template in your THEMENAME.theme file using a preprocess function

function THEMENAME_preprocess_XXX (&$variables) {
    $block = \Drupal\block\Entity\Block::load('id_block');
    $variables['myBlock'] = \Drupal::entityTypeManager()
        ->getViewBuilder('block')
        ->view($block);
}

and then inside your twig file use this

{{ myBlock }}

To find appropriate preprocess function look in your twig file comments.

For example if you want to use views-view--unformatted.html.twig you can see in the comments

* @see template_preprocess_views_view_unformatted()

which means include in your .theme file THEMENAME_preprocess_views_view_unformatted() function


Pass JSON array to drupal function I have a JSON array, and I want to pass it to drupal function to work with the data. what are the possible ways to do that?

any code sample would help

The function drupal_json_decode() (D7 only) can convert a json string to the corresponding php data structure.

In Drupal 6, you can directly use the PHP function json_decode(), just remember that you need PHP 5.2+ for that.

As I almost assumed, the part you're having problem with is not converting the JSON string to a PHP structure you can work with, but sending that from the client side to the server, so that you can access it with PHP (Try to provide more information what exactly you want to do when asking questions and you'll get better answers).

drupal_json_decode() is, in fact, just the very last step in the whole process. You obviously can't access that function (or anything else that is PHP) directly from jQuery, so you need to send it with jQuery.post() to the server, where it can be processed.

To be able to do that, you first need to define a endpoint where the data can be sent to by implementing hook_menu(), for example your_module/endpoint. In the page callback that you defined there, you can read the sent data in from php://input, for example with $json = file_get_contents("php://input");. Then, you can use the mentioned function to parse $json.


How can I stop Drupal from tracking or collecting IP addresses? Is there a way to stop Drupal from tracking or collecting IP addresses of visitors? The specific need case is for a site that wishes to be able to say no identifying information is kept of visitors (it sounds seedier than it actually is).

I recognize that Apache logs are going to do this, and that will need to be handled separately, but I'm wondering if there's any way to prevent this in Drupal (or if you have suggestions on how to obfuscate incoming visitor IPs, that would be helpful as well)

As mentioned in clives comment you could override $_SERVER['REMOTE_ADDR'] in your settings.php to obfuscate incoming visitor IPs. Drupal's ip_address() function than would return your obfuscated IP to any module that attempts to log IPs (like dblog).
Just be aware that any static or random address would conflict with a part of Drupal's flood control mechanism (the part that blocks IPs after too many failed login attempts; default: 50 within one hour). A static IP would expose you to the risk of locking every user out of the system. A random IP would render it useless.
Hashing the IP should work. The module cryptolog seems to to what you want and takes care of the flood control issue. From its project page:

Cryptolog enhances user privacy by logging ephemeral identifiers rather than actual client IP addresses in Drupal's database tables and syslog.
When Cryptolog is enabled, Drupal 8's \Drupal::request()->getClientIP() and Drupal 7's ip_address() output a 128-bit HMAC of the client IP address (in IPv6 notation), using a salt that is stored in memory and regenerated each day.
Because Cryptolog uses the same unique identifier per IP address for a 24-hour period, it is still possible to do some statistical analysis of the logs such as counting unique visitors per day. In addition, unlike other solutions of setting $_SERVER['REMOTE_ADDR'] to either one static IP address or a completely random IP address, Drupal's flood control mechanisms still function as normal.


How to wrap a fields or other elements in div block? I want to wrap these elements in one div (this div should be before div class = row) but I don't know where to add this div

Example:

I am using Bootstrap theme and views_bootstrap module.

In case you want a simpler answer with no coding needed just use Views Fieldset.
So install the module, add your row class on the view (Format > Settings > Row Class).

Then add a fieldset (Fields > Add > Global: Fieldset), in the settings of the fieldset choose div and to the HTML classes add the column classes. Don't forget to to go to Fields > Rearrange and put your fields in the fieldset group.

That's it.


Unable to set date field programmatically Somehow my custom fields ('datum' and 'high') are not set in the following script. Could someone tell me what I am doing wrong?

    function erstelle_kursenodes() {

$content = file_get_contents('http://www.xmlcharts.com/cache/precious-metals.php?format=json');

if(empty($content)){
    echo 'KEINE API-VERBINDUNG';
} else {
$cuobj = json_decode($content);
  // add node properties
  $newNode = (object) NULL;
  $newNode->type = 'kurs';
  $newNode->title = 'XAUUSD';
  $newNode->uid = 0;
  $newNode->created = strtotime("now");
  $newNode->changed = strtotime("now");
  $newNode->status = 1;
  $newNode->comment = 0;
  $newNode->promote = 0;
  $newNode->moderate = 0;
  $newNode->sticky = 0;
  // add fields
  $newNode->field_datum[$node->language][0]['value'] = date('Y-m-d h:i:s', strtotime("now"));
  $newNode->field_high[$node->language][0]['value'] = number_format($cuobj->usd->gold * 31.1034768, 2, '.', '');
  // save node
  node_save($newNode);
}}

'datum' is a regular date field

'high' is decimal integer with two digits after a point

It is a format issue that you are choosing to save.

    $newNode->field_datum['und'][0]['value'] = date('Y-m-d h:i:s', strtotime("now"));
//Here in place $node->language pass 'und' and then try.
//Just save a node directly from backend, let say it is saved with node id 10.

$nid = 10;
echo "<pre>";
print_r(node_load($nid)) ;
echo "</pre>";

Now check which format it is using to save. Pass same format once statically and then make it dynamic. Hopefully it will resolve your issue.


When is a module shown as 'Unsupported' in the list of available updates? In the available updates, there are few modules with the note unsupported.

What does that note actually mean?

In Drupal 8, that string is output from UpdateManagerUpdate::buildForm(), which contains the following code.

  case UPDATE_NOT_SUPPORTED:
    $type = 'unsupported';
    $entry['title'] .= ' ' . $this->t('(Unsupported)');
    $entry['#weight'] = -1;
    break;

The UpdateManagerInterface::NOT_SUPPORTED constant simply means the current release is no longer supported by the project maintainer. The maintainer doesn't intend to further develop the module code, not even to fix security issues. If you look at the project page, you will notice the following note, given under the Project information section.

  Unsupported
  Not supported (i.e. abandoned), and no longer being developed. Learn more about dealing with unsupported (abandoned) projects

As such, the update page is suggesting to find another module with the same, or similar, features because, in case of security issues, chances are nobody is going to fix them, and the module would need to be uninstalled, to avoid site issues.

In Drupal 7, a similar string is output from theme_update_status_label(), which contains the following code.

case UPDATE_NOT_SUPPORTED:
  return '' . t('Not supported!') . '';

The UPDATE_NOT_SUPPORTED constant has the same meaning saw for Drupal 8, and it was introduced in Drupal 6.


Share Unpublished nodes through a link that needs a user authentication I am trying to share unpublished node through its URL to a specific role.

What I am trying is that when that user (with the specific role) opens that link, he'd have to login to open the URL.

Is it possible?

Thanks

Access unpublished

  Easy to use module grants access to view unpublished content to anyone
  who has a unique URL and appropriate permissions. Visitor can be
  anonymous or authenticated user with the user role.

  When administrator or users with enabled privileges visit (or save)
  unpublished node, can see link for direct view that unpublished
  content. Unique URL link is displayed as Drupal message or in node
  content.

  Administrator can enable view an unpublished node for any roles with
  "View unpublished contents" permission. If it is set for anonymous
  users, anyone who know the link with hash key, can view the
  unpublished node. View only, not edit.

  Default URL parameter is "hash" and can be changed on configuration
  page for more security or customization.

  Module is useful for proofreaders, content checkers etc. Webmaster
  does not need to create user accounts and can keep the website safer.
  Each node has its own unique hash key (like Google Docs).


How do you clear menu caches programmatically? I am developing a custom module. In this module, I want to delete menu caches programmatically. For this, I have used

\Drupal::cache('menu')->invalidateAll(); // for clearing the menu cache
\Drupal::service('plugin.manager.menu.link')->rebuild(); // rebuild the menu

But somehow, menu cache seems not being cleared and still the old menu is being displayed. How can I force Drupal to have my updated menu being displayed?

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

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


Paragraphs module decoupled structure I'm looking to use the Paragraphs Drupal 8 module with a decoupled installation of Drupal 8 but would like the structure made in the admin area to be output in the JSON API responses.

How can I modify the JSON API responses from Drupal 8 to include this page structure data?

If anyone wants to know, having it decoupled & outputting structure information is a requirement I've been given.

It sounds like you want a compound document, the JSON:API mechanism that provides other referenced entities in a resource (e.g. a "page" content node that references other paragraphs). This is done via adding an include query parameter with a value that refers to a field's relational ID. An inclusion request will add an included array property with the related entity resource objects.

See the docs on Includes in the JSON:API docs for more concrete examples in action.

Since you mentioned it, ordering included resources isn't possible (IIRC); you might be able to infer order based on the Paragraph field. JSON:API is designed for minimal configuration and maximum adherence to the JSONAPI spec so you're limited to a couple of mechanisms to modify the output of the structured data.


Problems getting Default Content module to work with Features I'm trying to export some Default Content when creating a drupal 7 distribution.  Noticed that Phase II is using Default Content module to set default content for OpenPublic.  I can't find any documentation on how to get the module to work.

How do you get the Default Content Module to work?

Figured this out.

After you enable the Default Content Module, there will be a new setting for each Node by where you can select Revision information, URL path settings, Comment settings, etc.

This new setting is Machine Name.  You make a machine name for the node of the default content.

Then when you make a new feature (I guess it is best practice to have all of the default content nodes in one feature so when you deactivate the feature all of the default content will turn off and the features will still work) there will be a new component "Content Item".

This will have all of the machine names that you made while creating/editing nodes.

Hopefully someone will find this useful so they don't bang their heads against the wall like I did.


Any way of not to render the pane in panel using custom module? I dont want to use PHP visibility rule  to add a custom condition but I want to hide a pane based on some condition. How can I do that?

What you're looking for is called a access plugin, those are how Page manager (and by extension Panels) control both access and visibility settings.

This question: What are Ctools plugin (content type, access, etc), and how does one create them? has a lot more details and implementation examples.


Running simpletest tests with clean urls on nginx Having Drupal 7 on nginx with enabled clean urls.
nginx config:

location @drupal {
rewrite ^/(.*)$ /index.php?q=$1 last;
}

When trying to run tests getting message:

  You are not authorized to access this page.

Looks like Drupal cant resolve correctly /batch?op=start&id=28 path.
Tests running ok if clean urls disabled.

Any advise on nginx or drupal config to resolve this?

You should rewrite Drupal 7 URLs using  rewrite ^ /index.php last;. The more complete setup is (copied from my development setup):

server {
  listen 80;
  listen [::]:80;

  root [...];
  index index.php;
  server_name [...];

  location = /favicon.ico {
    log_not_found off;
    access_log off;
  }

  location = /robots.txt {
    allow all;
    log_not_found off;
    access_log off;
  }

  # Deny all attempts to access hidden files
  location ~ /\. {
    deny all;
    access_log off;
    log_not_found off;
  }

  location / {
    try_files $uri $uri/ @rewrite;
  }

  location @rewrite {
    # Some modules enforce no slash (/) at the end of the URL
    # Else this rewrite block wouldn't be needed (GlobalRedirect)
    rewrite ^ /index.php last;
  }

  # pass the PHP scripts to FastCGI server listening on my unix socket
  location ~ \.php$ {
    include snippets/fastcgi-php.conf;
    fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    fastcgi_intercept_errors on;
    fastcgi_buffer_size 128k;
    fastcgi_buffers 256 16k;
    fastcgi_busy_buffers_size 256k;
    fastcgi_temp_file_write_size 256k;
    fastcgi_read_timeout 1200;
    # With php5-fpm:
    fastcgi_pass unix:/var/run/php5-fpm.sock;
  }

  client_max_body_size 100M;

  location ~ ^/sites/.*/files/styles/ {
    try_files $uri @rewrite;
  }

  location ~* \.(js|css|png|jpg|jpeg|gif|ico|woff|ttf|svg|eot)$ {
    expires max;
    log_not_found off;
  }
}


How do I create a base content type and subtypes ("bundles")? I've been trying to figure out how to create a base content type and subtypes (bundles) in Drupal 8, but haven't been able to figure it out.

For example:

Base Content Type

Base Event (fields: event name, start/end dates and times, location, etc.)

Subtypes (Bundles)

Seminar
Conference

I looked into:

ECK (Entity Construction Kit) module: didn't seem to be working 100% in Drupal 8.  Using their example, I was able to create a 'Vehicle' ECK base type and 'Car' and 'Truck' ECK subtypes, but wasn't able to define any fields for the 'Vehicle' base type that would be shared between 'Car' and 'Truck'.  Also, the types appeared under 'ECK Types' in 'Admin > Structure', so not sure if they would be usable throughout Drupal in the same way that regular Content Types are used/referenced?
Paragraphs module: doesn't seem to the right module for this

It looks as though I have to do this through code somehow, but couldn't find any clear documentation that explains step-by-step how to do this in Drupal 8.

Any help would be greatly appreciated.  Thank you.

Creating entity is quite complicated, but it will be easier if you generate a base code with Drupal console command first.

drupal generate:entity:content [options]

  Options

  --module  The Module name.
  --entity-class    The content entity class
  --entity-name The content entity name
  --base-path   The base-path for the content entity routes
  --label   The label
  --has-bundles Entity has bundles
  --is-translatable Content entity translatable

I post some useful tutorial / documentation here:

https://www.acquia.com/resources/webinars/creating-custom-entities-drupal-8
https://www.drupal.org/developing/api/entity


How can i insert a comment form between parent comment and comment replies？ i want hide the comment reply，when user click the “2 replies” button will slide the replies，after slide out the replies i also want to show a comment form that people can post a reply easily.   anyone can help? Thank you so much.

I don't know if it's correct way but maybe help somebody.

    function theme_preprocess_node(&$variables, $hook) {

$test_pid = array();
$test_cid = array();
$keys = array_keys($variables['elements']['comments']['comments']);

foreach ($keys as $k) {
    if (!is_numeric($k)) {
      continue;
    }
$pid = $variables['elements']['comments']['comments'][$k]['#comment']->pid;
$cid = $variables['elements']['comments']['comments'][$k]['#comment']->cid;
$test_pid[] += $pid;
$test_cid[] += $cid;
$variables['elements']['comments']['comments'][$pid]['#comment']->has_children = TRUE;
$last = $k;
}

// find all last children in comments
$Mcomment_children= array();
foreach($test_pid as $key=>$p){
    if (in_array($p, $test_cid)) {
         $Mcomment_children[$p] = $test_cid[$key];
    }
  }

  foreach($Mcomment_children as $last_children){
    $variables['elements']['comments']['comments'][$last_children]['#comment']->last_children = TRUE;
  }
  $variables['elements']['comments']['comments'][$last]['#comment']->last = TRUE;
}

In comment template file (comment.tpl) you can close div with children last. I used display suite but it's the same.

<?php if($comment->has_children !== true): ?>
</<?php print $ds_content_wrapper ?>>
  <?php endif;?>
  <?php if($comment->last_children === true): ?>
</<?php print $ds_content_wrapper ?>>
  <?php endif;?>


Using Rules link to Un/Publish content Have anybody tried this?

Currently I am using Publish Content Module to Un/Publish contents, but the module doesn't support Confirmation action, if somebody hits Publish/Unpublish it just does the action straight away without asking confirmation.

I have been looking for the solution and Rules Link modules advertises it as its promo feature. Being a newbie I am not much aware of Rules power, so, any hint how could I Publish/Unpublish content with this would be very helpful.

So, far I tried by creating new Link which displays in my content type, When I click the link it asks for confirmation, but I couldn't figure out how to exactly Publish/Unpublish the content after that.

I solved a similar problem with the Flag and Rules modules. I created a flag called 'Published' for nodes and two rules that are activated when content is flagged/unflagged with this flag. These are my settings:

'Published' flag

Bundles: Article
Display in entity links: Display link as field
Link type: JavaScript toggle

If you need the flag for (an)other content type(s) too, you simply have to check the box in the flag settings.

'Published node' rule

Event: A node has been flagged, under 'Published'
Action: Publish content: Parameter: Content: [flagged-node]

'Unpublished node' rule

Event: A node has been unflagged, under 'Published'
Action: Unpublish content: Parameter: Content: [flagged-node]

If you want to, you can add some extra actions to the rule (e.g. display a message).


Adding more Data to a Commerce Feed Upload Currently I'm working on a Commerce Kickstart 2 storefront, to remake our company website in Drupal, a store front for selling Television Repair parts. I have a little HTML/CSS experience under my belt, but no real experience with Drupal outside of a couple tutorials. While I have figured out how to upload listings from the old website through tutorial videos and the Commerce Feed module, I could use a resource on how to add more information a CSV upload, more than a SKU, Name, Price, Image and a Description. Is it possible to add data to the CSV regarding Manufacturers, Part Number, intended TV Model, Condition of the part, and other useful information that users could sort and search for products with, or would any sorting and tagging have to be done after the objects are uploaded into the system? If there is a common method, where would be a good resource to start with to figure out what I need to do?

A Commerce feed fundamentally isn't any different to a regular feed so if you need additional data attached to your product you should be able to create the additional fields you need on your product type and in Feeds map the data from your CSV to the Product Type fields in Commerce.

With regards to sorting, wouldn't you be doing that in Views when you're actually displaying the imported products?


Hiding language names in "Language switcher" block and displaying only country flags I would like to hide language names (like "English", "Español", "Magyar", etc.) in the "Language switcher" block, and display only country flags, because I have Language icons module installed, and the flags are unambiguous enough for navigating between different languages.

I already set language elements to be displayed in an "inline" style and hide language switcher block's title in my stylesheet file (in a Zen sub-theme) like this:

#block-locale-0 li{
    display:inline;
    list-style-image: none;
}
#block-locale-0 .title{
    display:none;
}

OK, in the meantime I found the perfect solution which I earlier just simply overlooked: there's a really simple configuration option in Language icons module's settings in http://<yoursite>/admin/settings/language/icons (D7: http://<yoursite>/admin/config/regional/language/icons) .

You have to set "Icon placement" option from "Before link" or "After link" to "Replace link", which results in displaying only the country flags.

Here are some screenshots (on the admin site I'm currently using RootCandy Dark):

BEFORE:

AFTER (on the admin site):

AFTER (on the main site's right sidebar [design is strongly under development :P]):


How to migrate Webform data from Drupal 6 to Drupal 7? I have a Drupal 7 installation with the Webform module enabled. I recreated a Drupal 6 webform and now want to migrate data from the Drupal 6 installation to the Drupal 7 installation. Is this possible?

You can migrate Drupal 6 webform data to 7 using the Mirgrate Webform module.

  It will migrate all nodes of the webform node type (with the default D6 fields using migrate_d2d backend), all the configuration* of the webform's settings, the form components, email destinations, submissions and associated submission data, in addition to any validation configuration you have (from webform_validation module). It grabs the "last downloaded" data too, in case your users were downloading sequential batches since the last time they were on the site.


Output ctools_modal_form_wrapper() with translatable items in the form i have translation strings already for this form.
if i output it with:

  return drupal_get_form('user_login');

then the translation works

but if i render it for the modal form then the translation doesn't work.

return ctools_modal_form_wrapper('user_login', $form_state); with translatable items

so how can i enable the tranlation for the ctools_modal_form_wrapper also?

This is an open issue for ctools modal_form and is in need of some more data / feedback to push the issue forward. The specific bug is called out here and appears to be related to the language header that is used in the modal form window:

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

There is a potential patch for this here:

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


All database settings are set to 'A' I'm encountering a very weird problem where my database settings look like this in database.inc:openConnection()

array(1) {
  ["default"]=>
  array(6) {
    ["driver"]=>
    string(1) "A"
    ["database"]=>
    string(1) "A"
    ["username"]=>
    string(1) "A"
    ["password"]=>
    string(1) "A"
    ["host"]=>
    string(1) "A"
    ["port"]=>
    string(1) "A"
  }
}

It's after I moved the site to a new host with Ubuntu 14.04, so PHP and MySQL are now on a different version.

Another related strange thing is that drush sql-connect is not returning anything.

The result of global $databases; var_dump($databases); looks normal.

Silly me. I copied some lines from D6 settings.php. After adding an extra ['default'] here: $databases['default']['default'] = array(... things are working fine again.

Note 1: Probably good to not delete this question as someone else might run into something similar at some point.

Note 2: Will be nice if Drupal 8+ will have a more informative way of error reporting.


Where is the "Send mail to all users" action? I installed and configured the Rules module.

When I try to add a rule like notifying a new comment to all users, I do not see the Send mail to all users action.

Is that normal? Is there any other module to install?

Yes it is normal that you do NOT see "Send mail to all users", because there is no such Rules Action in D8 (nor in D7). In D7 there is a Rules Action like "Send an eMail to all users of a selected role", but that one is not (or not yet?) available in D8.

However, within group "System", there is the Rules Action "Send eMail". If you  use that one, with "Send to", you can specify 1 eMail address per line. So if you enter the eMail address for each user on a single line, you have a kind of work around for what you're trying to do.

What you probably want to do later on (when the Rules module is more mature), is to use some type list of all your users, and use that list in combination with a "loop" (a typical Rules Action). If this was a D7 question, you could use the Views Rules module to create a view of all your users, and use that for such list.

With that, either you have to be patient a bit, or use the work around suggested above ...


Panopoly WYSIWYG exclude buttons configurations Can anyone tell me if it's possible to configure the Panopoly wysiwyg to we can have different buttons available to different roles?

At the moment, without have to create a module, I can't find a configuration area which will allow the exclusion of certain buttons for some roles.

Since Panopoly WYSIWYG module does not provide this kind of configuration out of the box, you will need to add additional text formats and WYSIWYG profiles. When configured, export them to your own Features project. If you customize the WYSIWYG profile provided by Panopoly WYSIWYG, be sure to export those using Features Override module (provided in full distro and if using Panopoly Core I believe.)

WYSIWYG profiles merely build on top of existing text formats which have restrictions by roles.

The alternative, however, is to use hook_wysiwyg_editor_settings_alter() and possibly remove buttons based on role, that way.


How to save in a different subfolders the attachments of my users? I want each user's attachments (they will be school assignments docs, photos, maps) to be saved in user's own subfolder in order to be able to collect them easily and separately.

How would this made possible and what are the best modules to utilize in order to achieve it?

In Drupal 7, the core File module and the Token module (https://drupal.org/project/token) will let you do this.

In the settings for your file field, specify a file directory using a user token. I recommend prefacing the token'd directory with users/ (or something) so that you can easily find all of these files separate from other files on the site.

For example to use the user ID as the directory, set the 'file directory' to

users/[user:uid]

You can see all the user-related tokens available to you on your site at admin/help/token.


How to programmatically require a field using Inline Entity Form I have a node form using an inline entity form widget for either selecting or creating taxonomy terms to be referenced from the node.  The field should be required at a certain moderation state, but in the early stages of moderation the field does not need to be required.  I'm trying to make this change in hook_form_alter
I tried comparing the values of $form in the alter function when the field had been set to required, and when it hadn't.  The only differences were within $form['field_name']['widget']:
$form['field_name']['widget']['#required'] => 0
vs.
$form['field_name']['widget']['#required'] => 1
and
$form['field_name']['widget'][#element_validate] => Array
                (
                    [0] => Array
                        (
                            [0] => Drupal\inline_entity_form\Plugin\Field\FieldWidget\InlineEntityFormComplex
                            [1] => updateRowWeights
                        )

                )

vs.
$form['field_name']['widget'][#element_validate] => Array
                (
                    [0] => Array
                        (
                            [0] => Drupal\inline_entity_form\Plugin\Field\FieldWidget\InlineEntityFormComplex
                            [1] => updateRowWeights
                        )

                    [1] => Array
                        (
                            [0] => Drupal\inline_entity_form\Plugin\Field\FieldWidget\InlineEntityFormComplex
                            [1] => requiredField
                        )

                )

Just adding $form["field_name"]["widget"]["#required"] = TRUE; to the alter didn't change anything, and trying to add the #element_validate bit lead to an error:

User error: "0" is an invalid render array key in Drupal\Core\Render\Element::children() (line 97 of core/lib/Drupal/Core/Render/Element.php).

How can I programmatically require an inline entity form field in a hook form alter?

I'm not sure if this will work out of the box for you, but I wrote this module https://www.drupal.org/project/require_on_publish to solve a similar problem. You might be able to borrow some of the ideas in there around adding constraints to custom fields to achieve your desired functionality.


How to limit entity reference for new nodes only? In an institutional website, there's an archive section listing all events (content type: Event). Each event is coordinated by an event manager (content type: Event Manager). CT Event has an entityreference field to select an Event Manager. The available options are defined by an entityreference view. This process works well so far.

Next, I needed to limit the available managers depending on their status. The status is a simple boolean field in the CT Event Manager defining if that manager is still active or retired. This limitation also works such as new events can't be assigned to retired managers.

However, if I want to edit an (old) event which was managed by a now retired manager, I can't save the node since the reference is not valid anymore.

My question is, how can I restrict the number of available managers for new events but still maintain the relations between old events and retired managers?

You need to render views in the Entity Reference field.

Add a reference type display in a view.
Add a nid and title field in the view.
A list of views will be displayed in the field configuration. Select specific view in field's configuration.

Edit:

May be adding hook_form_alter to form can do the trick for you.

function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'your_node_form') {
    // $form['#node'] if it is node edit form.
    // $form['reference_field']['#options'] = $altered_list
  }
}


Using Drush how can you see the last user that logged in? Using drush, how can you see the last user that logged in? What about the last 5, 10, 20?

drush sqlq "SELECT name FROM users ORDER BY login DESC LIMIT 10"

Tweak LIMIT to change the number returned.


node translations and too many menu items I use Drupal 7, locale and the i18n modules. I've setup a mini site with node translation.

I have the following EN nodes:

node/1 About
node/2 Terms
node/3 FAQ
node/4 Contact

and the following FR nodes:

node/5 A propos [translation of node/1]
node/6 Contacter [translation of node/4]

The main site is the English one and the French menu will always be equal or a subset of the English one (same structure).

I've implemented the site using 2 menus, one for EN (4 links + Home) and one for FR (2 links + Home). This works but doesn't scale well if I have many (500) nodes per language and:

I decide to add a new language
I decide to reorder some nodes around (change parents etc)

I've also implemented the site using 1 menu (the "Main Menu") and it contains all links (4 links + 2 links + Home). This works but still has the previous disadvantages and in addition:

links are mixed when the user is selecting parent menus

So, my question is, assuming I need a 1-to-1 mapping from EN to FR, or a subset of EN but with the exact same structure, isn't there a simpler way to solve this? Ideally I'd want to have a single Menu which would specify something like:

/about -> node/1, /fr/about -> node/5
/terms -> node/2
/faq -> node/3
/contact -> node/2, /fr/contact -> node/6

Is this possible?

No it's not possible because each menu link can point to a specific (one) node. When using node translation the different translations of a node are other nodes.


Forced rendered node view results in empty node links In order to send html email using drupal/swiftmailer I load and view a node.

Then I pass it to the rendere. In the email sent, generated node__links are empty. As node_links uses #LazyBuilder, Im then not sure to use the correct way.

hook_mail

function mymodule_mail($key, &$message, $params) {
   switch ($key) {
       case 'mail_node':
           $message['from'] = \Drupal::config('system.site')->get('mail');
           $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
           $message['subject'] = t('Mail subject');

           $node = Node::load($params['nid']);
           $view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');

           $body_data = [
               '#theme' => 'mymodule_mail_node',
               '#content' => $view_builder->view( $node ),
           ];

           $message['body'][] = \Drupal::service('renderer')->render($body_data);
       break;
       }
 }

mymodule--mail-node.html.twig

 {# simply render the whole body #}
 {{ body }}

output results in mail

<!-- THEME DEBUG -->
<!-- THEME HOOK: 'links__node' -->
<!-- FILE NAME SUGGESTIONS:
    x links--node.html.twig
    * links.html.twig
-->
<!-- BEGIN OUTPUT from 'core/themes/classy/templates/content/links--node.html.twig' -->

<!-- END OUTPUT from 'core/themes/classy/templates/content/links--node.html.twig' -->

When I render the same content into an html page, node__links are correctly filled.

Any recommandation would be appreciate.
Thanks

Use renderPlain():

$message['body'][] = \Drupal::service('renderer')->renderPlain($body_data);

From the documentation:

  Renders final HTML in situations where no assets are needed.

  Calls ::render() in such a way that placeholders are replaced.

  Useful for instance when rendering the values of tokens or emails,
  which need a render array being turned into a string, but do not need
  any of the bubbleable metadata (the attached assets and cache tags).

Source: Renderer::renderPlain

"When I render the same content into an html page, node__links are correctly filled."

render() in a page works, because the page has a render context for the metadata to bubble up, so that the placeholders can be replaced later.


Multiple registration forms I have multiple user role and different registration forms for each role.
It means that for each registration form, there are different fields.

I when a user select her role, the registration form should change.
can I have several registration forms?

First thing you should be aware of, is that you probably don't want to expose the roles to the user during registration, at least not all of them. If you do, then any user would be able to create an admin account, and gain access to the backend.

You can't easily make different registration forms, but you can instead create a multi step form. Step one would be general user information where the user selects which role / type of user to create. The second step would have unique fields depending on the role selection.

The example module has a lot of great examples including how to create multi-step forms.


How to make calendar block show site events? I have a website in which I use the Calendar module in combination with a content type I created. While I manage to achieve the calendar page to show up the events in their dates, how can I make the same for the calendar block? For example when an event has a "from date" of 20 August, I want the calendar block to have that 20 August date as a link to the event.

I think that you probably want to use the views module to create a custom block that contain the calendar items.  Here is an example...

http://drupal.org/node/1250714


What is the correct way to document the schema for a YAML file? As a module developer, I'd like to convert some of my Drupal 7 info hooks to YAML discoveries in Drupal 8, but it's not clear to me how to document the schema of a YAML file for consumers. For a hook, of course, I would define hook_whatever() in mymodule.api.php. What do I do for *.whatever.yml? What is core doing?

There is no "documenting" of hooks in D8 except the mymodule.api.php as you've already mentioned(+ impleneting hook_hook_info).

The YAML files are only for:

services
routes
menu local tasks
menu local actions
libraries
module info
simple configuration
simple configuration schema

Now you've mentioned "info" hooks. In Drupal 8 these are Annotations and their implementations are Plugins. If this is assumption correct then see the documentation in here https://drupal.org/developing/api/8/plugins for plugins - what they are, how they work and how to use them.


How can I add a currency field to a content type? I would like to have a field that accepts U.S. dollar amount. I installed the module: https://www.drupal.org/project/currency. Structure > content type > I do not see a field type "Currency". I am not sure how I can add a field to accept USD amount.

How can I add the price field to the content type?

So to add a decimal field.

edit your content type.
manage fields
add new field
select Decimal from the Field Type dropdown.
Click the 'Save' button
Change 'Scale' to 2. These are the cents.
Click the 'Save field settings' button.
In the Prefix field add '$'.
Click the 'Save settings' button


What is the difference between the Trigger and Rules modules? Both the Trigger and the Rules modules provide many event-driven actions, but there are still several difference. What's the major difference between them? When should I pick one module instead of the other one?

Loosely speaking, Rules is much more generic than triggers. As Johan Falk mentions, "you could say Rules is an extended version of Triggers.. it is technically true, but does not really cover at full extent."


How to remove Neighborhood and Address 2 fields in commerce kickstart? In shipping information form there is these 2 fields( Neighborhood and Address 2 ) which I need to remove but I can not find the solution. Any help?

If you log in as admin:

Got to: admin/commerce/customer-profiles/types
Select the "manage fields" for the correct profile
Edit the Address field
Under "Format handlers" there should be checkboxes to hide the fields you do not want to show.

To do via code, see Use only one address field


Public file system path problem The "Public file system path" setting in admin/config/media/file-system was always reflecting the directory name of my multi site directory.

I don't know what caused the problem, but it doesn't automatically set the right dir anymore and I need to manually change it when I create a site.

Does anybody have an idea of what might cause this behavior?

I have solved the problem by reverting to a older version of the database. I haven't been able to trace the real cause of the problem.

It had something to do with "Backup and Migrate" module, because that was the only real change between the versions.


Why are DIVs in the wrong order in Zen theme I'm guessing (hoping) there is a good reason that the DIVs in the Zen theme are in reverse order.

In "Main", the natural order should be Banner, Navigation, Content. Instead the template is rendering them backwards and then using CSS to re-order them in the correct position.

Why?  It is causing me massive grief.

I should point out that the "Banner" DIV is my own customization of the theme. It actually shows up in the correct natural order. So - really the issue is why is Content rendered BEFORE Navigation?  Doesn't make logical sense; is there a technical reason?

I'd guess it has mainly to do with SEO.

From SEO Tutorial:

  In the HTML code for the page, the body text should be as close to the
  beginning of the code as possible, because there is a limit to how far
  down into a page a search engine spider will go to try to find text.
  So make sure your text comes before some really long JavaScript menu
  in the code for the page, or else the search engine won't make it far
  enough into the page to index the text. The search engine spider may
  never see the text if it is buried way down at the end of the code.

From 27 Quick Tips to Top Search Engine Rankings:

  If you have a persistent (on most or all of your pages) navigation bar at the side of each page, your table is almost certainly set up in
  such a way that it pushes your page's body text down the HTML
  document. Search engines give prominence to keywords nearer the
  beginning of a HTML document. So, design your HTML table so that the
  navigation bar is placed after your main body text.


Should I enter data as English and then translate to my language? For data entry for taxonomy terms and field names should I enter data in English and then translate to my own language?Entering directly in my own language has no problem.I just want to know if there is any rule for this.

Well, if you've a only one language website, you can directly enter the values directly in your own language. You can also install your language pack that you can find on localize.drupal.org.

If you gonna start a multi-language website, you should (and its easier) to start everything in english and after start to translate. But in that case, is already important since the beginning to active all languages that you need.


Add a module as cron job I have a module file which fetch data from a link. I have to run this module as a cron everyday. How can I do it?

You have to implement hook_cron to run you task periodically on drupal cron.

function hook_cron() {
  // Your code here
}


Automatically close webform after submission I have created a Webform with some terms & condition. I have added this webform in node/upload page. When user access node/upload page webform comes as overlay on the page. When user selects all terms & condition and submits it redirects to another page which as close link. When close link is clicked webform hides.

What I want is instead clicking on close link to hide the webform. When user submits the terms & conditions the webform must be hidden. How can i achieve this. I have added screen shot of webforms.

I have added this code to get the webform in node/upload page

 if (!isset($user->data['guided'])) {
  $form['#attached']['js'][] = drupal_get_path('module', 'my_module') . '/js/my_module_ajax.js';
}
ctools_include('modal');
ctools_modal_add_js();
if (!isset($user->data['guided'])) {
$form['guideline'] = array(
  '#markup' => '
' . t('Review and follow the guidelines outlined in the Submission guidelines before uploading an item.', array('@guideline-page' => url('modal_forms/nojs/webform/' . 31))) . '
',
  '#weight' => -0.01,
);
}

You need to use hook_form_alter() and on submit of the form you need to set action like this

$form["#submit"][] = "ajax_modal_form_submit";

and add function

function ajax_modal_form_submit($form,&$form_state) {
    ctools_include('ajax');
    ctools_include('modal');
    $form_state['ajax_commands'][] = ctools_modal_command_dismiss();
    $form_state['ajax_commands'][] = ctools_ajax_command_reload();
    drupal_set_message(t("You detail submitted successfully!"));
  }


How to load and display a view with Ajax in Drupal 7? This is the first time I've ever tried to load a view using Ajax in Drupal7 and I would be appreciated if you help me from scratch. I've spent hours to learn how to do this but I still failed!

I created a view called image_gallery, it has three blocks called hd,tablet and phone and it displays set of images.I created a tab and I want to display and load these blocks (generally views) with Ajax. this my HTML:

HD

Tablet

Cellphone

                <?php print views_embed_view("image_gallery","hd") ?>

I set the Use Ajax to "yes" in the views UI. this is my jQuery code:

$("#image_gallery_tab ul li").click(function(){
        var id = $(this).attr("id").slice(-1);
        $(".igc").css("display","none");
        if(id==2)
            {
            $.ajax({
                url: Drupal.settings.basePath + 'views/ajax',
                type: 'POST',
                dataType: 'json',
                data: 'view_name=image_gallery&view_display_id=tablet', // Pass a key/value pair.
                success: function(response) {
                  $("#igc2").innerHTML=response.display;
                },
                error: function(data) {
                 alert('An error occured!');
                }
              });
            }
    });

but it displays nothing. what is wrong here and what shall I do?
thanks

For anyone who ends up here looking for an answer, this is how you do it. First you need to enable "Use AJAX" under Other settings in the view and take note of the "Machine Name" as that is your display ID:

Then, this is how you pull it with JS using jQuery ajax:

$.ajax({
  url: Drupal.settings.basePath + '/views/ajax',
  type: 'post',
  data: {
    view_name: 'your_view_name',
    view_display_id: 'page', //your display id
    view_args: VIEW_ARGUMENT_HERE, // your views argument(s)
  },
  dataType: 'json',
  success: function (response) {
    if (response[1] !== undefined) {
      console.log(response[1].data); // do something with the view
    }
  }
});


How can I use hook_comment_view? I have added a new field to comment table, called "paragraph_id", I have also added a field to comment form that ask users which paragraph they want to put comment on and what they enter will be saved in "paragraph_id" field.

So now I want to show the value of "paragraph_id" in the comments, beside showing the subject and the body of the comment.

There is a hook called "hook_comment_view" , and it can be used to add additional data to the comment before theming.

This is the hook:

function hook_comment_view($comment, $view_mode, $langcode) {
  // how old is the comment
  $comment->time_ago = time() - $comment->changed;
}

I tested this hook by changing it to the following:

function Annotations_comment_view($comment, $view_mode, $langcode) {
  // how old is the comment
  $comment->subject= $comment->paragraph_id;
}

and instead of subject it showed the data in paragraph_id field. But how can I add a new field to comment display form, for example called : Comment on Paragraph

and then write this:

function Annotations_comment_view($comment, $view_mode, $langcode) {
  // how old is the comment
  $comment->Comment on Paragraph = $comment->paragraph_id;
}

First, PHP is case sensitive - don't start your function names with capital letters, it's bad practice, capitals are generally reserved for Classes.

Secondly, if you haven't already, install the devel module, it's really useful.

Then you can look at the structure of the $comment object that is passed to the hook by putting dpm($comment); inside your hook.  Make sure you give yourself the permission to view devel information.

Once you can see the structure of the variable it should make sense what drupal is doing with it.  You can add a new element to the form simply by editing the $comment variable:

$comment[#myNewElement] = array(
  'property1' => 'value1',
  'property2' => 'value2',
  'property3' => 'value3',
);

You can learn about the various form elements and their properties at the Drupal form API.

You will probably need to query the database to get your display value before you set the element.

Happy coding!


How to get an import of a very large Drupal database working? I'm using Vagrant and OracleVM to run Drupal 7. I've got the site up and running and I'm trying to get my database imported. So far I've run drush cc and cleared the drush cache, and then I did

drush sql-cli < mydb.sql

The drush command is taking a super long time and I'm not sure if it's even doing anything. The database file is just under a gigabyte.

What can I do to get this working, or is there a better method?

I'm not sure how much overhead drush puts on top of large SQL imports, I've only used it for smaller imports and queries. You can try the mysql client as an alternative that would remove the drush overhead.

If you can install pipe viewer on your VM you can view the progress of the command consuming the import.

pv mydb.sql | drush sql-cli

Or without the drush overhead

pv mydb.sql | mysql -u <DB_USER> -p<DB_PASS> <YOUR_DB>


Checking for an empty entity reference field in hook_node_validate In checking whether a form field contains an entry, it has been typical to do something like:

if (sizeof($form_state['values']['my_field'][LANGUAGE_NONE]) > 0)

because an empty field would still be an array, but an empty one. With entity reference fields, an empty field looks like:

$form_state
  values
    my_field
      und
        0
          target_id=''
          add_entityconnect_my_field_0_ = "New content"
          edit_entityconnect_my_field_0_ = "Edit content"

so that testing for the empty array fails. One could check to see if the target_id is empty, but I'm wondering if there's a way to test the form field for empty without needing to go down to that level.

Take a look at entityreference_field_is_empty(), which at least will get you up a level by checking if target_id is empty on your behalf.


How to let a role be able to administer part of permissions? For example, uid 1 grants role A some permissions as Article: Create new content, Basic page: Create new content, then users with role A can grant these 2 permissions to other roles in the same interface as /admin/people/permissions.

I use Permissions Lock to achieve this.  You can give your role A the 'administer permissions' ability and then lock off all of the ones that you do not wish them to have access to.  It's a bit backwards in that you have to go through and tick all of the checkboxes except the ones you want to provide, but it works.

Also you need to check it each time you install new modules or go through an update that provides new permissions as the new permissions default to 'available'.


How to prevent a View from rendering via a hook? I want to prevent an attached view from running depending on some coding parameters.

I've tried using hook_views_pre_view() to prevent it from running, but I can't figure out what options to set on the view to accomplish that. Tweaking attached or rendered doesn't seem to do anything.

function ding_eresource_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'eresource_list' && $display_id == 'attachment_1') {
    // Prevent rendering if parent view has some option set.
    if (!empty($view->old_view[1]->barr)) {
      // This does not work. How can it be done?
      $view->attached = FALSE;
      $view->rendered = TRUE;
    }
  }
}

How can it be done?

Wanted to do similar but just $view->executed = TRUE; made the query in the view still run. Looking at view::build(), I understood you need the following code, to prevent anything running further in the view (displays and query).

$view->executed = TRUE;
$view->built = TRUE;

To make it clearer, the code you should use is the following one.

function ding_eresource_views_pre_view(&$view, &$display_id, &$args) {
  if ($view->name == 'eresource_list' && $display_id == 'attachment_1') {
    // Prevent rendering if parent view has some option set.
    if (!empty($view->old_view[1]->barr)) {
      // This does not work. How can it be done?
      $view->executed = TRUE;
      $view->built = TRUE;
    }
  }
}


How to add a new condition to access callback function in hook_menu_alter? I need to add a new condition to access callback function for a menu path.

For it I write hook_menu_alter and redefine there new access callback function.

function mymodule_menu_alter(&$items){
  $items[node/add']['access callback'] = 'mymodule_custom_callback';
}

And I have a question. I want this function to not overwrite previous access callback function, but add a new condition, which would be added to previous conditions for access callback.

How to do it most correctly ?

And is it possibly to do it not knowing the name of default access callback function ? For example, default access callback function for path node/add is _node_add_access().

You can call default access callback function in your custom access callback and if default access callback return TRUE, then you can check your own conditions and return TRUE/FALSE. Check example below:

function mymodule_custom_callback() {
  // If node access return TRUE.
  if (_node_add_access()) {
    // Do your processing here.
    if (condition) {
      return TRUE;
    }
    else {
      return FALSE;
    }
  }
  return FALSE;
}

  And is it possibly to do it not knowing the name of default access
  callback function ? For example, default access callback function for
  path node/add is _node_add_access().

In such cases, you can either find it by debugging (print $items['node/add']; exit;) or you can append that as an access argument and call it from your custom callback. Something like below:

function mymodule_menu_alter(&$items){
  $items['node/add']['access arguments'][] = $items['node/add']['access callback'];
  $items['node/add']['access callback'] = 'mymodule_custom_callback';
}

function mymodule_custom_callback($function) {
  // If node access return TRUE.
  if (function_exists($function) && $function()) {
    // Do your processing here.
    if (condition) {
      return TRUE;
    }
    else {
      return FALSE;
    }
  }
  return FALSE;
}