Contextual Filters using YYYY and MM I am attempting to set up a list of articles that will display like so

2014
January
February

2013
January
Feb

I've set up my view, but once I use the YYYY contextual filter, it simply sorts it

2014
2013

And I cannot get the months to display. Any suggestions would be greatly appreciated

When I print the array the [url] returns /posts-by-date/2014

I am trying to have the array return posts-by-date/2014/[month]

I have done this by setting up two displays of my view

Display 1 is a page display, with the path 'foo/date/%/%'.  This then gets a pair of contextual filters, the first is for the year (the first argument).  The second is for the month (the second argument).

Display 2 is a page display, with the path 'foo/date/%'.  This gets a single contextual filters, the year.


Programmatic Content on a Node - preferably a non-code solution Trying to generate content ONLY when certain user roles are selected (and these roles would stack up, so lets say user 1 had roles A and B, they would have content for both roles A and B - logical AND), but only on certain pages.

How would I go about creating this?

Basically I want the logic to flow as such:

display content[default];

if userrole == A {
display content[A];
}
if userrole == B {
display content[B];
}

I'd prefer not to write any code, because A) I want it easily modifiable for the client and B) Well, it isn't my site!

Plus, code issues tend to be messier than module issues in my experience.

I've heard Panels or Ctools might be able to do this, but I'm unfamiliar as to how.

I think you can achieve this using the Context module. Here is a quote about it (from the module's project page):

... allows you to manage contextual conditions and reactions for different portions of your site. You can think of each context as representing a "section" of your site. For each context, you can choose the conditions that trigger this context to be active and choose different aspects of Drupal that should react to this active context.
Think of conditions as a set of rules that are checked during page load to see what context is active. Any reactions that are associated with active contexts are then fired.


hook_menu wildcard auto-loader for webform submission? In hook_menu() array keys, you can specificy wildcard tokens to autoload certain objects, such as %node to get the node object.

Is there a wildcard autoloader token for webform submissions? Some googling I've done has returned no results.

I've also grepped the codebase of the webform module for autoload, also to no results.

It is looking for a _load() function. In the case of node, user, or taxonomy term arguments (eg %node), it is looking at node_load, user_load, etc.

If you passed %mymodule_foo as the wildcard, then it would look for mymodule_foo_load().

Therefore, if there is a webform submission _load function that loads a submission, thats what you want to use as the wildcard.

The wildcard you want to use is %webform_menu_submission. Webform has a corresponding _load function for it:

/**
 * Menu loader callback. Load a webform submission if the given sid is a valid.
 */
function webform_menu_submission_load($sid, $nid) {
  module_load_include('inc', 'webform', 'includes/webform.submissions');
  $submission = webform_get_submission($nid, $sid);
  return empty($submission) ? FALSE : $submission;
}

Note that this function also needs a $nid argument to work.

  Registered paths may also contain special "auto-loader" wildcard components in the form of '%mymodule_abc', where the '%' part means that this path component is a wildcard, and the 'mymodule_abc' part defines the prefix for a load function, which here would be named mymodule_abc_load(). When a matching path is requested, your load function will receive as its first argument the path component in the position of the wildcard; load functions may also be passed additional arguments

See:

https://stackoverflow.com/a/13788403/295112
https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_menu/7.x
http://cgit.drupalcode.org/webform/tree/webform.module#n342


Is it possible to uninstall a module which is causing some errors? I have installed Views Bulk Operations but it is causing errors since it needs PHP 5.2.9 while my hosting is PHP 5.2.6.
I have no option to turn it off, it has a red cross.

How to remove this module?

Yes, you can uninstall it, here is the easiest way-

If you have phpmyadmin access then-

You can disable a module via phpMyAdmin by login to phpMyAdmin. Then you must locate the database where Drupal is installed. Once you have done so look for the "system" table. Click and open it. Click to browse the table. Find the record for the module that is causing the problems and select the edit function. Set the status to "0" and save. So this will disable the module, now you can access your site and can easily login to backend and uninstall the module.


unwanted site name in url I've just copied my drupal website from local to server, everything is fine except the url of the site is http://www.mydrupalsite.com/mydrupalsite.com/index.php (although there is no folder named mydrupalsite.com)

The server directories and files are like this:

root

.htaccess
mydrupalsite.com

index.php
other drupal files...
.htaccess (drupal one)

myothersite.com

...

I don't think the root htaccess file has something to do with it, because myothersite.com has no problems with it. Is it possible that the .htaccess file of the drupal is causing it? If so, how to prevent it?

I made some changes and tried this in root .htaccess, but it still doesn't work:

RewriteEngine on
RewriteOptions MaxRedirects=2
RewriteCond %{HTTP_HOST} ^([a-zA-Z0-9]+).([a-zA-Z0-9-]+).([a-zA-Z]+)$
RewriteCond %{QUERY_STRING} !^(.*)redirect=1(.*)$ [NC]
RewriteRule ^(.*)$ /%2.%3/$1?redirect=1&%{QUERY_STRING}

To sum it up, I found out that this structure has been created by previous admin and should not be changed (as there are two domains). I guess the problem could be solved by removing the /mydrupalsite.com/ when present in url with .htaccess somehow, but finally I've been said it does not matter, so I left it as it is.

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

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

RewriteBase /mydrupalsite.com


How may I show the top 4 most recent result and then randomize in Views? I currently have a view; I would like to select the top 4 most recent nodes, and then display them in a random order.

I think it would work if they were all posted on the same day.
I have a "sort by date," and then I am using the random seed module to randomize the results.

However, if they occurred on different days, the random does not take effect because it is sorting first by day.

Does anyone have any advice?

I'm not sure if I understand your requirement correctly but you can the following:

Create a views of node (teaser, fields.. whatever you need)
Sort by date (following the granularity you need)
Add a "Global: Random" sorting


How to view the query in Views 3? I want to look at the MySQL query built by Views. In views 2 it just shows while I can't seem to find it in the View 3 UI. Is it still available?

You can choose to display the query; it's a checkbox called "Show the SQL query" on the Views settings page (admin/structure/views/settings).


View page not filtering content according to its language I used devel to generate dummy content for a content type named recipe, and at the moment I have 10 recipes. 5 in English and 5 in Portuguese.
I create a view(page view) that shows all the recipes when the user goes to /recipes, and select it to render only the recipes in English.

When I visit the url: domainname/recipes I see all the recipes including the ones in Portuguese.

Below is my configuration:

How do I filter out the recipes that are not in English?

UPDATED:
How can I add a menu to that same view?

Click "Add" on "Filter Criteria" on the left column. Then add a filter called Content: Translation language and set it to Content language selected for page


DNS settings in Aegir I successfully set up Aegir hosting in my Ubuntu based VM. At the time of new site creation I face some problems. I got message saying the new site successfully installed but when i click "Log into site" I get a "page not found error". I understand there will be DNS issue, how can I resolve this?

While trying same thing in my local pc. I get to the new site by modifiying my hosts file.  Is it possible to get the site without altering my hosts file?

Check out item 2 on this page on setting up sites in Aegir.

  Login to your DNS control panel at your domain registrar, or wherever
  your nameservers are, and setup the DNS for the domain name to point
  at your Aegir server. It's worth including a wildcard record - ie an
  'A' record for '*' to resolve to your aegir server - then you can
  easily setup new sites on subdomains without having to ever setup DNS
  again!

This video also looks pretty neat, not sure how much it'll help though.


"Add link" attempt for a Menu yields 500 error I have tested with fresh installs of Commerce Kickstart down to version 2.6, the error happened. I even disabled all modules related to the Menu module or with menu in the name, no luck. I also disabled and then enabled the Menu module, no luck. However, I tested version 1.19 and it did no yield this error.

Change MYSQL max_allow_packet_size.

Incase you are on MAMP you can add --max_allowed_packet=32M to /Applications/mamp/bin/startMysql.sh and restart MAMP.


Dealing with compressed JSON string from external API I'm trying to call the Stack Exchange API but it sends compressed JSON strings and I can't uncompress it.

$request = drupal_http_request('https://api.stackexchange.com/2.2/users?order=desc&sort=reputation&site=stackoverflow');
$uncompressed = gzinflate($request->data);
$json_response = drupal_json_decode($uncompressed);

I'm getting an error like this: Warning: gzinflate(): data error in adventure_profile_profile() (line 104 of /home/justine/www/adventure/sites/all/modules/custom/adventure_profile.module). (where line 104 is $uncompressed = gzinflate($request->data);).

Am I doing something wrong?

Ok, I'm sorry I just figure it out. I wasn't looking at the $request->headers to see what method to uncompress I have to use. Here is the solution:

$request = drupal_http_request('https://api.stackexchange.com/2.2/users?order=desc&sort=reputation&site=stackoverflow');

if (isset($request->headers['content-encoding'])) {
  if ($request->headers['content-encoding'] == 'gzip') {
    $request->data = gzinflate(substr($request->data, 10));
  }
  elseif ($request->headers['content-encoding'] == 'deflate') {
    $request->data = gzinflate($request->data);
  }
}

$json_response = drupal_json_decode($request->data);


D7 theme field items of a "List (text)" input as In Drupal 7, I have a field for a custom node type that is a text list "List (text)" with a widget input type of "Check boxes/radio buttons". When displayed on the front-end the following HTML is generated:

XHTML

CSS 3

PHP

How can I theme this output as an HTML
 instead? Something like this:

XHTML

CSS 3

PHP

I should note that I'm overriding output using a node--custom_type.tpl.php file.

The "right" way of rendering a list, that is, one that interacts properly with all the other systems in Core is theme_item_list.

Code example:

// In this case, $result is a list of nodes returned from a database query.
$list = array();
$list['type'] = 'ul';
$list['title'] = 'List of nodes';
$list['attributes'] = array('class' => array('list-of-nodes'));
$list['items'] = array();
foreach($result as $record) {
  $list['items'][] = l($record->title, 'node/' . $record->nid);
}
$output = theme('item_list', $list);

This should be applicable in your node.tpl as well.


Is it possible to create a list of pages in a view even if a user doesn't have access to those pages? I'm creating a set up in Drupal 7 using Organic Groups and the Subgroups module where there is a Company group, and each company can have multiple Project groups. I'd like to allow users that have access to a Company Group to see all Projects underneath that company in a View, regardless if they're part of the project group or not. From there, a user can either view the project page, or they can subscribe to the project group.

Is it possible to give a user access to a parent group and allow to see all of its child groups in a View, but restrict viewing a page in a child group?

Have you tired disabling SQL Rewriting?

In the advanced fieldset in the right column when editing the view, click Query Settings

There is a checkbox "Disable SQL Rewriting"
which has help text "Disabling SQL rewriting will disable node_access checks as well as other modules that implement hook_query_alter()."

Try checking that checkbox and saving the View


Menu block is not being displayed on the front page I'm using the Menu Block content type to provide a list of the secondary level menu items down the left hand side of the website.

it works perfectly other than on the front page where I can't seem to make the menu Block display.

I'm using a Theme heavily based on Bartik (just with logos and colours changed), I can't find a specific front page template and have no idea what else to do.

I have changed the site configuration to use a basic page as the Home Page (but with this or the default home page it still doesn't work.

Anyone got any suggestions please?

Dave

This sounds like a bug that I ran into myself and has been brought up here: http://drupal.org/node/1468420 (submenus of a parent menu item that links to the front page (<front>) do not show when viewing the site's front page). At the time of writing the bug has not been fixed, but there are 2 workarounds that might help you out:

Set the menu link with the <front> path to 'show as expanded'.
Do not use <front> as the menu link path, but instead use your actual front page path (same as in 'admin/config/system/site-information').


Render blocks in custom page I followed steps given in this link to create a custom Page.

Page is created and 'Hello world' is printing in the page, now i want to render some blocks in that page. How can I achieve this task?

Given that you're using a custom controller for your page, you have the option to load the block from your controller, or place the block in another region outside of that part of the page that the Controller controls.

For blocks such as global elements such as headers and footers, I would recommend you place them through the CMS at /admin/structure/block

For blocks that sit above or below the content that your controller loads, you can also place them from /admin/structure/block or you can load them from within the the controller.

If you need to place content above and below your block, you'd probably want to load it programmatically in your controller.

Here's a guide on loading blocks programmatically.

basically in your myPage() method that is returning the build array, you'd want the build array for the block you want to load.

$build['events'] = \Drupal::service('plugin.manager.block')
  ->createInstance('my_events_block')
  ->build();

$build['recent_insights'] = \Drupal::service('plugin.manager.block')
  ->createInstance('recent_articles', ['title' => 'Some Recent Articles', 'offset' => 0])
  ->build();

return $build;

The code above works for the types of blocks that you custom create in your module, such as at /mymodule/src/Plugin/Block/RecentArticles.php

It doesn't work for loading an instance of a block that was created through the CMS.

For those you need to use:

$block = \Drupal::entityTypeManager()->getStorage('block')->load('myblock');
$build['myblock'] =  \Drupal::entityTypeManager()->getViewBuilder('block')->view($block);


csv file imports only the last row when imported in drupal 8 webform I have a csv file which contains the entries from drupal 7 webform. I uploaded the csv file in drupal 8 webform. It imports the data, but only the last entry is shown in the drupal 8 webform's results.

This is the csv file:
columns A-D : IP Add, UUID, Phone Number, Email.  (dummy entries).

When importing the mapping from the csv file, it shows me the below options:

I select the matching columns on the destination(submission) and then click import.
After importing this is what drupal displays:

Only the last row from the csv file is updated in the webform.

The UUID for all your CSV records is 1 and when they are being imported, each row is overwriting the previous row. You also need to include the column headers as the first row in the CSV.


Single Sign On using PURL domain modifier and different TLDs I have an organic groups implementation using purl and spaces to set the active space when you visit a domain modifier such as example1.org vs example2.org.  The cookie domains are different, so I'm wondering if there is any single sign on solution that will allow sessions to be transfered from one domain to another in some fashion.

Should I use something like facebook connect, and not allow users to sign onto the site with their regular drupal credentials?

Have also been looking into this the last few days and came across this

http://drupal.org/project/services_sso_client

Seems that it will do exactly what you want to do.


How to restrict user to chat with another user based on their payment and subscription? I'm new to Drupal. I need to make a consulting website, where I need to restrict user from chatting. The user can chat only with the consultant they paid for. User can participate in forums as they are free of cost.

Any suggestions about how to implement this?

Note: for normal chat concept, I use DrupalChat.

From the DrupalChat project page:

  ... provides optional integration with ... Flag Friend module.

And issue # 936350 states:

  ... Would it be possible to show only friends from the Flag Friend module?

Since this issue has status closed(fixed), you should be able to use the Flag Friend module like so:

After the payment was completed, grant the user some permission to be allowed to "flag" the consultant the user paid for.
After such flagging is done, the user should be able to chat with such consultant.


How to modify if a field is required in a form? Use case: I have added a required field for users. When user 1 (or an administrator) adds a user, the field should not be required.

Code that doesn't work (in Drupal 8):

function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    if (\Drupal::currentUser()->id() == 1) {
      $form['field_fieldname']['#required'] = FALSE; // No effect
      $form['field_fieldname']['widget']['#required'] = FALSE;
    }
  }
}

Changing the widget "works", but the validation fails. The solution for Drupal 7 doesn't seem to be usable anymore.

$form['field_fieldname'][<lang>][0]['value']['#required'] = FALSE;

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

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

when

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


How to check if a new node is correctly created using Entity Metadata Wrapper $wrapper->save()? I'm programmatically creating a new node using Entity Metadata Wrapper.

How to check if last instruction:

$ewrapper->save();

creates correctly the new node without errors?

Check that the entity has an identifier:

if ($ewrapper->getIdentifier()) {
  // Save happened.
}

A better approach might be handling any errors:

try {
  $ewrapper->save();

  // Try to do something with $ewrapper->getIdentifier()
}
catch (\Exception $e) {
  // Recover...
}


Is there a nodecomment equivalent/replacement for D7? When I build help ticket systems for folks on D6, I use one content type for the ticket and a second content type with Nodecomment for replies. This lets me ensure that only the ticket owner and the internal helpdesk can see ticket history, and keep internal-only notes unpublished (vs no ability for internal notes with a comment).

Is there an equivalent for this in D7, or a better approach to take with contrib, or do I need to write a custom module to handle this?

@Chris You started me down the right path, thanks so much! I've tested and can implement it this way without writing any custom code:

Create 3 content types: Helpdesk Ticket, Ticket Internal Note, Ticket External Note.
Create a role called Helpdesk Volunteer.
Put a node reference field on Ticket Internal Note and Ticket External Note using the node reference URL widget.
Use the Content Access module (currently still in dev) to restrict view/edit/delete of the Ticket Internal Note content type to users in the Helpdesk Volunteer role.
Create a view with EVA that attaches to the Helpdesk Ticket content type, set to display both internal and external notes.

Afterwards, it's just a touch of prettification and theming as needed. Add a file attachment upload field and a ticket category. Maybe implement messaging/notifications to have email notifications and reply-by-email. Fully functional helpdesk on D7!


month of the date in Italian Use the module date-7.x-2.6, to insert a date dd / mm / yyyy in my content type. My problem is that when I view it, would that be translated into Italian for example "22 Settembre 1009" and now appears so: "22 Sep 1009". Thanks!

On the "Manage Display" page for your content type (under admin/structure/types), you can adjust the format to use to display the date.

To adjust the formats, you can configure the date and time settings (admin/config/regional/date-time).


How do I query for the next three dates using EntityFieldQuery or Views? (7) This is my first question, so please don't be too harsh.  I've been trying for the last couple days to solve this with no luck.

I have a content type called "Event" which contains a custom date field for the 'start date/time' of the event. What I need is to be able to list events for the next THREE days after the current timestamp.

Keep in mind that it doesn't count empty days, so if there are no events for tomorrow, for example, it won't count that as an empty day.  Instead it would list the events out for the next day, and the following (assuming there are events for those days).

If I were able to access the custom date field through straight SQL, I would first get the 3 dates I need, and the query would look something like this:

SELECT DISTINCT(DATE(`date_field`))
FROM {node}
WHERE `type` = 'event'
AND `field_start_test_date` > NOW()
ORDER BY DATE(`date_field`) ASC
LIMIT 3;

I've been unable to accomplish this with Views or EntityFieldQuery. I'm also willing to create my own joins using SQL, but from what I've read, that's discouraged.  I'm open to any suggestions.  Please let me know if I need to be more specific.

Thanks!

The query you've got in your question would be the equivalent of this EntityFieldQuery:

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'event')
  ->fieldConditon('field_start_test_date', 'value', REQUEST_TIME, '>')
  ->fieldOrderBy('field_start_test_date')
  ->range(0, 3);

$results = $query->execute();
if (!empty($results['node'])) {
  $nodes = node_load_multiple(array_keys($results['node']));
}

I've assumed that date_field was supposed to be field_start_test_date and that the date column is a UNIX timestamp type. You'll need to make a couple of slight changes if those assumptions aren't right.


drush up fails to update, though it says it deos Here's my output...

# drush up drupal-7.39
Failed to get available update data for one project.                                                                                [error]
Update information last refreshed: Wed, 09/16/2015 - 14:21

Update status information on all installed and enabled Drupal projects:
 Name         Installed version  Proposed version  Status
 Drupal core  7.38               7.39              Specified version available

Code updates will be made to drupal core.
WARNING:  Updating core will discard any modifications made to Drupal core files, most noteworthy among these are .htaccess and robots.txt.  If you have made any modifications to these files, please back them up before updating so that you can re-create your modifications in the updated version of the file.
Note: Updating core can potentially break your site. It is NOT recommended to update production sites without prior testing.

Do you really want to continue? (y/n): y
Project drupal was updated successfully. Installed version is now 7.39.
Backups were saved into the directory /root/drush-backups/civi2crm/20150916182131/drupal.                                                                           [ok]
Backups were restored successfully.                                                                                [ok]

And then if I immediately try the same thing again, I see that it still doesn't think it install 7.39.   I can confirm that /user#overlay=admin/reports/updates tells me that I am still running 7.38

# drush up drupal-7.39 -y
Failed to get available update data for one project.                                                                                [error]
Update information last refreshed: Wed, 09/16/2015 - 14:21

Update status information on all installed and enabled Drupal projects:
 Name         Installed version  Proposed version  Status
 Drupal core  7.38               7.39              Specified version available

Code updates will be made to drupal core.
WARNING:  Updating core will discard any modifications made to Drupal core files, most noteworthy among these are .htaccess and robots.txt.  If you have made any modifications to these files, please back them up before updating so that you can re-create your modifications in the updated version of the file.
Note: Updating core can potentially break your site. It is NOT recommended to update production sites without prior testing.

Do you really want to continue? (y/n): y
Project drupal was updated successfully. Installed version is now 7.39.
Backups were saved into the directory /root/drush-backups/civi2crm/20150916182138/drupal.                                                                           [ok]
Backups were restored successfully.

Any thoughts why I can't update Drupal.  And, in case it matters, I'm using Drupal to run CiviCRM.   And I think that is the "project" that it failed to get update data for.  But I believe I have to manually update CiviCRM by copying files and stuff, so that seems okay to me.   But perhaps I'm wrong on that.  But I can't see why, since I JUST want to patch the Drupal Core with the security update.

"Backups were restored successfully" means that Drush failed at some step, and restored your old version of Drupal over the recently updated version.  Try setting file ownership &/or permissions; run with --debug, and perhaps you will see more information about why the upgrade is failing.


How to select multiple values for Drupal Facets (Facet API + Search API) I am using Facet API + Search API to develop Filtering for the data within my site. I am also using Ajax Facet Filters to process the selection as soon as it's clicked.

It all came out great but there's one slight problem. I can only select one option per category. As soon as I select an option, all the inactive options hide and only the active (clicked one) shows.

I want the option to select multiple option but with my settings of Facet API & Search API, there seems to be no option.

Here's the picture to explain.

I'll be very thankful for any assistance.

Best.

picture taken from :- https://drupal.org/node/1669600#comment-6190924

I found the first comment here to answer this question.

  the OR operator is required for the facet instead of the default AND.
  If the implementing search module you are using supports OR facets,
  you will have an option in the "Global settings" fieldset located in
  the bottom left hand corner of the facet's display settings form.


what permission is need to access to content page? I have created a role and a user assigned to it. I want to give access to  '?q=admin/content/node' to this role to see all the contents of the site. what permission should I set for this role? I am using Drupal 6.26.

According to the node module a user must have a role that is allowed for 'administer nodes'.


Drupal 7: Cannot see Module Changes Is there any kind of cache applied to the Modules?

I am developing a module but I am not able to see the last changes I made (Adding a new Role programmatically), even after cleaning all caches.

install code (update):

function nutrition_install()
{

    //Create New Role
    $role = new stdClass();
    $role->name = 'nutricionist';
    $role->weight = 1;
    user_role_save($role);

  node_types_rebuild();
  $types = node_type_get_types();

 // add the body field to the node type
  node_add_body_field($types['meal']);

  // Load the instance definition for our content type's body
  $body_instance = field_info_instance('node', 'body', 'meal');

  // Configure the body field
  $body_instance['type'] = 'text_summary_or_trimmed';

  // Save our changes to the body field instance.
  field_update_instance($body_instance);

  // Create all the fields we are adding to our content type.
  foreach (_meal_installed_fields() as $field) {
    field_create_field($field);
  }
  // Create all the instances for our fields.
    foreach (_meal_installed_instances() as $instance) {
        $instance['entity_type'] = 'node';
        $instance['bundle'] = 'meal';
        field_create_instance($instance);
    }
}

Unless you are using some sort of opcode cache, the code in your module itself won't be cached. Some hooks will only be run in certain cases and/or have cache. Most likely this is what is giving your problem.

A possible solution would be to uninstall and reinstall it again. (don't just disable the module, but uninstall it). Doing so removes a lot of the information about the module and could fix the problem.

If you gave more detail on the code/hooks you were using, a more detailed answer could be given.

Update

hook_install is run when the module is installed. This is a once per install only, so changing the code after the module is installed won't do anything. A new install is the only way to test the changes, after proper cleanup have been made.


mysql errors after upgrading php and mysql recently upgraded server to php 5.6.5 and mysql 5.6.22. running drupal 7.

after the upgrade we started having issues.

the server seems to run well for a week or so before starting to throw error pages with:

Notice: PDO::__construct(): send of 128 bytes failed with errno=32 Broken pipe in DatabaseConnection->__construct() (line 307 of /path/to/site/includes/database/database.inc).
Notice: PDO::__construct(): send of 128 bytes failed with errno=32 Broken pipe in DatabaseConnection->__construct() (line 307 of /path/to/site/includes/database/database.inc).
Notice: PDO::__construct(): send of 128 bytes failed with errno=32 Broken pipe in DatabaseConnection->__construct() (line 307 of /path/to/site/includes/database/database.inc).
Notice: PDO::__construct(): send of 128 bytes failed with errno=32 Broken pipe in DatabaseConnection->__construct() (line 307 of /path/to/site/includes/database/database.inc).
Warning: Cannot modify header information - headers already sent by (output started at /path/to/site/includes/database/database.inc:307) in drupal_send_headers() (line 1233 of /path/to/site/includes/bootstrap.inc).
PDOException: SQLSTATE[HY000] [2006] MySQL server has gone away in lock_may_be_available() (line 167 of /path/to/site/includes/lock.inc).
Notice: PDO::__construct(): send of 128 bytes failed with errno=32 Broken pipe in DatabaseConnection->__construct() (line 307 of /path/to/site/includes/database/database.inc).

when this happens, not every page shows the error, more like 25% or so.

so far i have had no luck tracking down the cause of the error. it seems to 'reset' if i stop/start mysql. such that if i stop/start i can get another week of no problems and then it begins again. this was making me think that it is a problem with a mysql setting related to connections or something, but i am no expert in this area and so am asking here.

after googling and seeing many posts suggesting to increase 'max_allowed_packets', we tried this but still the same issue occurs.

I added the following items to my.cnf which fixed my PDO broken pipe issues.  I am using a homebrew installation of mysql on a macbook pro with 16GB RAM:
key_buffer_size = 384M
max_allowed_packet = 100M
table_open_cache = 512
sort_buffer_size = 2M
read_buffer_size = 2M
read_rnd_buffer_size = 8M
myisam_sort_buffer_size = 64M
thread_cache_size = 8
query_cache_size = 32M
query_cache_size = 128M
query_cache_size = 256M
Try number of CPU's*2 for thread_concurrency
thread_concurrency = 8
innodb_buffer_pool_size=512M


Is there a way to display some content fields in a separate block? I would like to display some content fields in a separate block so that I can manage the position of these like other blocks and also put them near to other blocks such as the search widget.

I am using display suite for laying out the content but don't think that this will serve my requirement to position some content fields further away from the the main content. One specific example I have is displaying the content's taxonomy fields below the search widget (which is in a block).

You could create a view which selects the field you want from a node. Use contextual filters to get the Node Id in your view.


Drupal db select IN, group by count need a bit of help please, when i write my query like this it works fine

    $query = db_query('select * from form_submissions where address in (select address from form_submissions group by address having count(address) > 1 ');
    $submissions = $query->execute();

but when i write it with drupal it should work like this? but it dont

    $query = db_select('form_submissions', 'sfs')->fields('sfs', array());
    $subquery = db_select('form_submissions', '')->fields('address', array())->groupBy('address')->having('count(address) > 1');
    $query->condition('address', $subquery, 'in');

    $submissions = $query->execute();

can someone see what im doing wrong?

$query = db_select('form_submissions', 'sfs')->fields('sfs', array());
    $subquery = db_select('form_submissions', 'sfs')->fields('sfs', array('address'))->groupBy('address')->having('count(address) > 1');
    $query->condition('address', $subquery, 'in');

    $submissions = $query->execute();


Menu link on hover is showing & instead of & I have a Webform that provides a menu link. The webform is available in three languages (dutch, french, english).

For the dutch version I have a menu title of Informatie and description Vragen & Antwoorden.

But when I hover the link I don't get Vragen & Antwoorden. But i get Vragen &amp; Antwoorden.

He changes the & symbol to & . I also got this with ' . He changed it in &#039;.

How can I fix this?

UPDATE:

These are the menu settings of my webform:

UPDATE 2:

This only happens when I try to translate and use ' (apostrophe) in my translation. He will form the ' to &#039;.

Like this:

Try to turn off Provide a menu link in Menu settings of your webform and to add menu link to webform page in your menu, /admin/structure/menu > list links (of your menu) > Add link instead.

If this doesn't work you can override themable output in your theme template.php file or in a custom module. Look at this post.


Custom Entity Type and Bundle Creation I've been building custom entities for a while now, but have been using the entity construction kit (eck) to build them. This has limitations as it requires you to #1 depend on the package for new installs, and #2, wrap your entities into a feature and hope there aren't conflicts later.

I would like to get into the world of building out the entity types programatically, on module install, as well as removing them on module uninstall.

I was recently diving into an ECK created entity I made that I exported into a feature, and it looks like the feature for the entity type is in the correct format for if you were to programatically create the entity. I have been trying to learn by looking at documentation on how to build a custom fieldable entity (with bundle) for a while, but all the documentation I have found has either been inconsistent, or spread all over the place making it difficult to follow.

My question is, could I in theory copy the field_instance.inc, field_base.inc, and the features.inc (where the entity is defined at), and plug that into my modules hook_install() and create my entity inside of the install file, instead of having to rely on ECK and features? I should note that I am also using the conditional_fields module so that I can dyanmically show/hide certain fields inside of this entity and save time on building my own ajax functionality, so I would probably need to build the entity out so that the fields can be updated from the Fields UI if needed (but usually they'll be updated in hook_update_N.

After some research and some helpful suggestions from another user, I ended up taking a look at the core modules user and node and got a pretty good understanding how to make base entities and attach fields to them. I suggest anybody who is stuck trying to figure out how to do it do the same as once you see it in live working code it's pretty easy to understand.


Composer install dependency error drupal/drupal dev-master I'm managing my site dependencies via composer, most of the times works really well. Now I installed my site on a new server, using the exact same code-base as before (but with composer 1.8.0 instead of 1.7.x as before though). On running composer install I get the following error:

  don't install drupal/core 8.6.4|remove drupal/drupal dev-master
  remove drupal/drupal dev-master|remove drupal/core 8.6.4
  Installation request for drupal/drupal dev-master -> satisfiable by drupal/drupal[dev-master].
  Installation request for drupal/core 8.6.4 -> satisfiable by drupal/core[8.6.4].

Usually I can solve these sorts of errors but this time I'm having a hard time. What's the meaning of drupal/drupal dev-master, because usually you do not specify this anywhere directly?

I ran into the same issue. My issue was related to upgrading to a new Drupal core minor version (ex: 8.6 to 8.7). If that's not the case for you, then my steps may be unnecessary.

I was able to resolve it by removing the core directory of Drupal. Then run composer update drupal/core --with-dependencies. I believe the issue stems from the core/composer.lock file having conflicts with what you are trying to install.


how to install drupal with myisam and different collation How to install Drupal with MyIsam instead of InnoDb and with utf8_unicode_ci collation?

I know there are ways to change/convert both afterwards, but maybe its possible to specify it as installation parameter - it would be simpler.

You can do during the installation or you can convert

For the installation, before you launch the install.php, you need to edit the "/includes/databases/mysql/schema.inc file.

// Provide defaults if needed.
$table += array(
  'mysql_engine' => 'MyISAM',    //Changed from Innodb to MyISAM
  'mysql_character_set' => 'utf8',
   mysql_collation' => 'utf8_unicode_ci',  //Added the collation
);

$sql .= 'ENGINE = ' . $table['mysql_engine'] . ' DEFAULT CHARACTER SET ' . $table['mysql_character_set'] . ' COLLATE ' . $table['mysql_collation'];

in case  you want to convert already created tables. put the site on maintenance mode and use phpmyadmin to convert the engines and collations


libraries-override not working I'm trying to figure out how I can remove the default css libraries of Drupal 8 on the theme I'm working on. I tried using libraries-override: to remove a specific CSS but it doesn't seem to be working. The css file is still showing. As you can see the align.module.css is still showing on Google Network Tab. I'm not sure if the method I'm using is deprecated or incorrect

name: Barebones
description: Drupal light
type: theme
core: 8.x

base theme: stable

libraries-override:
  system/base:
    css:
      component:
        /core/modules/system/css/components/align.module.css: false

libraries-override:
  system/base: false

You can override a library using the filename as key.

libraries-override:
  system/base:
    css:
      component:
        css/components/align.module.css: false

But if your asset was already overwritten by another module (e.g. classy theme overriding a core system asset), you have to use the full path instead, example:

libraries-override:
  system/base:
    css:
      component:
        /core/themes/stable/css/system/components/ajax-progress.module.css: false

Also see this issue.


How to call function from PHP file (or another module) in JS file from my custom module? After this question, I try to write custom module to add support Views Infinite Scroll to Background Images module. Here is my code:

my_module.module

/**
 * @file
 * Module file for Background Image for Views Infinite Scroll.
 */

/**
 * Implements hook_page_build().
 */

function my_module_page_build() {
  // Settings.
  drupal_add_js(array(
    'viewClass' => '.view-content',
    'nodeClass' => '.node-content',
  ), 'setting');
  // Add JS to page.
  drupal_add_js(drupal_get_path('module', 'my_module') . '/js/my_module.js');
}

/**
 * My function.
 */

function my_module_function() {
   // Code here
}

And ./js/my_module.js

/**
 * @file
 * This is main script of Background Image for Views Infinite Scroll.
 */

(function($, Drupal) {

  Drupal.behaviors.my_module = {
    attach: function (context, settings) {
      $(Drupal.settings.viewClass).on('DOMNodeInserted', function() {
        // Code here
      });
    }
  }

})(jQuery, Drupal);

How call function my_module_function() in my JS file?

You can add a menu callback in your module, that will be used by JS to send-receive values from PHP.

/**
 * Implements hook_menu().
 */
function my_module_menu() {
  $items = array();
  $items['my-module/my-function'] = array(
    'title' => 'Ajax callback for my function.',
    'page callback' => 'my_module_function',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function my_module_function() {
  // Remember you have to print your results if you want to
  // send any values back to JS.
  print 'Hi, there!';
  drupal_exit();
}

Now in your JS code, you make an Ajax call and, optionally, get values back from PHP (if desired).

$.ajax({
  url: Drupal.settings.basePath + "?q=my-module/my-function",
  done: function(data) {
    // If my_module_function returns any value, it will come in the data variable.
    alert(data);
  }
});


how to use a submit handler which is in an .inc file I am adding a submit handler to the drupal commerce submit form:

module_load_include('inc', 'my_module', 'cim_profile');
$form['buttons']['continue']['#submit'][] = 'my_module_create_cim_profile';

The submit handler is located in a .inc file. I assumed that the code above would load the .inc file to be used by the submit, but that doesn't seem to be the case, I keep getting an error that the file isn't found.
When I tested the module include with

 $inc = module_load_include('inc', 'my_module', 'cim_profile');
dpm($inc);

it did print out the path to the .inc file, so I know it was located.

How can I load my .inc in so that it is available for the submit handler?

You want form_load_include() instead:

Ensures an include file is loaded whenever the form is processed.
...
Use this function instead of module_load_include() from inside a form constructor or any form processing logic as it ensures that the include file is loaded whenever the form is processed. In contrast to using module_load_include() directly, form_load_include() makes sure the include file is correctly loaded also if the form is cached.


Theme Suggestions for User Page I want to create a separate html.tpl.php for user pages and user edit pages like html--user.tpl.php and html--user--edit.tpl.php.

For nodes I have added:

if (isset($node) && $node->nid) {
  $vars['theme_hook_suggestions'][] = 'html__' . $node->type;
}

in template.php.

Is there a way to do this for user pages as well?

You can use this template for the user page: user-profile.tpl.php

For the user edit page you can take a look at this page: Customize the User Edit page in Drupal 7 - an example.

UPDATE: To add CSS and JS to specific page you can do it like outlined below in a custom module.

/**
 * Implements hook_page_build().
 */
function MYMODULE_page_build(&$page) {

  if (request_uri() == 'path') {

    drupal_add_js( // arguments );
    drupal_add_css( // arguments );
  }
}


How to autofill text fields in form? I have two pages, on the first page, the user types in an ID. Using hook_form_alter, I then override the submit function and add my own functionality that will then grab information from a database about the id, such as their name and email.

It then directs the user to a second page with empty fields asking for name, email etc. My question is, what is the easiest way I auto-fill these fields with the data fetched previously?

thanks!

You should check out https://drupal.stackexchange.com/a/54387/4387

function MYMODULE_some_form($form, &$form_state) {
  // If the form has been submitted, output something related to the submission
  if (!empty($form_state['values']['some_field'])) {
    // Get data from database and show second step fields.
    $form['user_name'] = array(
      '#type' => 'textfield',
      // ...
    );

  }
  else {
    // Otherwise build the normal form (first step).
    $form['user_id'] = array(
      '#type' => 'textfield',
      // ...
    );
  }

  return $form;
}

function MYMODULE_some_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}


Show all child nodes of a taxonomy term D7 Ok, so I've been ripping my hair off for the past 2 days now.
I'm developing a web-site with a car catalog which contains the following hierarchy (taxonomy hierarchy):

-brand1
--model1
--model2
--model3
-brand2
--model1
--model2
--model3

...and so on.

What I'm trying to achieve is when a user selects a parent term (brand), they'll see all the nodes from all the children terms. Currently a parent term doesn't display anything.

I already Googled my problem but none of the solutions seem to work for me (or it's possible I'm doing something wrong).

My configuration is as follows:
Drupal 7.2x
Views 3.7
Taxonomy Menu 1.4 module - used for generating menu trees from vocabularies.
Pathauto 1.2

I use views to display the whole vocabulary - and it works as intended.

Can some one please give me a step-by-step guide on how to achieve this? Especially if it involves Views, as I'm still a noob with Views.

Is it possible the Taxonomy Menu module is causing trouble?

Actually there's a very easy (built-in) method...

Go to admin/structure/views, find the view named Taxonomy term, and enable it
Go to admin/structure/views/view/taxonomy_term/edit
Click Advanced (on the right)
Click Content: Has taxonomy term ID (with depth)
Select a Depth of 1 or more
Save all your changes

Now, assuming the term id of Brand 1 is 1, when you visit www.yoursite.com/taxonomy/term/1, you should see all the child nodes listed. You can also create path aliases to make paths like taxonomy/term/1 more "pretty".

Hope that helps...

:)


Views Conditional Range I would like to be able to input a range in my views conditional ,

e:g:

If (age > 0 && age <= 10)
{
 ...
}

How can I achieve this using Views_Conditional?

In Views, you can add multiple Filters for the same field/column, and configure each one separately. So you can add one filter for "age is greater than 0", and "age is less than or equal to 10". Filters use an AND operator by default, so you should be all set with that, but FYI you can also change the operator to OR (you can also mix operators).

The only limitation may run into is whether or not "is greater than" and "is less than or equal to" are available options in the filter handler for the particular field you're filtering on. Number fields can do that, as far as I know... but strings can't (for example).


How to show the content of a group on the group page when using the Group module? Using the Group module, you can create a group, say 'group ABC', and create or update some nodes so that they belong to that group. But when you visit the "Group ABC" page, you don't see those nodes. Moreover, by browsing the nodes you don't see anything indicating those nodes belong to "Group ABC".

How to list the nodes that belong to a group on the Group page?

Note: This module is available for both Drupal 7 and Drupal 8, and this question applies to both releases.

To show the content of a group, you need to create a view. The Group module provides Views 'relationships' to any node's parent group.

With that, these are the steps required:

Create a view about content.
Add a relationship to the parent group.
Add a contextual filter on the group's id (gid).
Create a page, a block, a content pane, etc (whatever fits your needs).

Below is an export of a (simplified) view created (in Drupal 7) using the steps described above:

$view = new view();
$view->name = 'group_content';
$view->description = 'Show all nodes that belong to a specific group';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Group content';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Group content';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 0,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Relationship: Content: Parent group */
$handler->display->display_options['relationships']['parent_group']['id'] = 'parent_group';
$handler->display->display_options['relationships']['parent_group']['table'] = 'node';
$handler->display->display_options['relationships']['parent_group']['field'] = 'parent_group';
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Sort criterion: Content: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'node';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;
/* Filter criterion: Group: Group ID */
$handler->display->display_options['filters']['gid']['id'] = 'gid';
$handler->display->display_options['filters']['gid']['table'] = 'groups';
$handler->display->display_options['filters']['gid']['field'] = 'gid';
$handler->display->display_options['filters']['gid']['relationship'] = 'parent_group';
$handler->display->display_options['filters']['gid']['exposed'] = TRUE;
$handler->display->display_options['filters']['gid']['expose']['operator_id'] = 'gid_op';
$handler->display->display_options['filters']['gid']['expose']['label'] = 'Group ID';
$handler->display->display_options['filters']['gid']['expose']['operator'] = 'gid_op';
$handler->display->display_options['filters']['gid']['expose']['identifier'] = 'gid';
$handler->display->display_options['filters']['gid']['expose']['required'] = TRUE;
$handler->display->display_options['filters']['gid']['expose']['remember_roles'] = array(
  2 => '2',
  1 => 0,
  3 => 0,
  4 => 0,
  5 => 0,
  6 => 0,
);

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'group-content';


How to create a better (more userfriendly) admin interface for non-technical "admin user"? I'm trying to make Drupal admin interface easier for non-technical users.
Actually, I'm trying to "create" a new interface for these kind of users. I'm using Views, VBO, Rules etc. to make a better admin interface experience without scaring them with a complex structure.
Easily;

edit, enable/disable blocks,
edit-rearrange main menu,
manage users,
manage contents,
manage files, images etc. uploaded via Drupal interface,

What should be done to increase user experience of this admin interface?
Is there any must-use module you suggest?

I don't use this myself as I prefer the slimer Administration Menu, but I think Navbar is more newbie friendly


Module's new release not showing link to download I created a new branch for a module I co-maintain, today. I followed the instructions and the branch is showing up. But, the problem is that the download links and dates are absent.

How do I create them? What extra work needs to be done?

Drupal.org automatically create download file for the module's revision, so you need to wait for the same.


In a writing a Views style plugin, how can I create a text input that accepts Twig? I am writing a Views style plugin, and I have a text field (input) that I want to be able to accept Contextual Filter arguments (or potentially field values). I am envisioning it working the same as the input that shows up when you click "Override title" under the "WHEN THE FILTER VALUE IS AVAILABLE OR A DEFAULT IS PROVIDED" fieldset. So, for example, you could add {{ arguments.nid }} into the text field.

This (below) is my current form element/text field that I'd want to be able to accept the arguments. I looked into the Views codebase, but was wasn't able to figure out how Views implements accepting arguments in a text field.

$form['display']['title'] = [
    '#title' => t('Chart title'),
    '#type' => 'textfield',
    '#default_value' => $options['title'],
    '#parents' => array_merge($parents, ['title']),
  ];

Any help would be greatly appreciated!

To replace argument tokens in a Views plugin you need:

$tokens = $this->view->build_info['substitutions'];
$value = $this->viewsTokenReplace($value, $tokens);

If you've based your plugin on StylePluginBase you can use StylePluginBase::tokenizeValue, which additionally replaces row tokens as well.


How to set the permission for each file separately for downloading? want to add a functionality of uploading files so that users can download these files.

First is there any module to provide this functionality (Uploading files from admin and then on front end, users can download these files).

Second If I upload some files then can I set the permission on the specific files.
My requirement is that some files will be only downloadable for registered users. The anonymous user could not be able to download the file.
And the 2nd scenario is that some files will be required the admin approval. Means if a user click on the file for download, a notification will be sent to the admin, then if admin approved it then the user can be able to download the file.

Any Idea about this.

Thanks in Advance.

You have to set your site's file management to private, and then use a module or code your own management stuff using the files API.


Link to node in views I have a view which has 2 displays :

List : Which is a unformatted list that contains a page
Table : Displays the nodes titles in a table.

What i need is to make the title in each row of the second display redirect to the corresponding node in the first display, regardless of the "item per page" and sorting.

May be this can be a good way to start with
1.I think you will need views_infinite_scroll module for the list view.
2. Set your views listing path as path/%
3. For list view set row classes as nids
3. Now with custom jquery code you take the nid from url and do a $.scrollTo(..) and nids set as row classes may help you finding the appropriate position to scroll to.
does it make sense?


The differences between date time zone handling There are several options for time zone handling, Site's time zone, Date's time, User's time zone, UTC and no time zone conversion. What are the differences between them?

One case would be a television broadcast where everybody in the world would experience simultaneously. Would User's time zone be correct to use? If the broadcaster put 8:00pm while living in New York someone in California would experience this at 5:00pm.

Or, the case, a poetry slam is happening in New York City and anybody who wants to experience it will have to physically be there at 8:00pm meaning it might be happening at 5:00pm in California but that doesn't matter to the person in California. What matters is that they are at the place at 8:00pm in New York so the time shouldn't change no matter where the user is or what time in their timezone the poetry slam is going on.

The Date module's documentation page describes the difference between the 5 options fairly well.

From that page:

There are 5 different options for field Time zone handling:

Site's time zone - When entering data into the field, the data entered is assumed to be in the site's time zone. When the data is saved to the database, it is converted to UTC. When retrieved from the database, the data is converted to the Site's time zone for annonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.
Date's time zone - With this option enabled, the date field adds a select box to explicitly specify the time zone for the date entered. When the date is saved to the database, it is not converted & the time zone information is saved with the date. When retrieved from the database, no conversion is performed and the date is displayed exactly as entered.
User's time zone - When entering data into the field, the data entered is assumed to be in the user's time zone. When the data is saved to the database, it is converted to UTC. When retrieved from the database, the data is converted to the Site's time zone for annonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.
UTC - When entering data into the field, the data entered is assumed to be in UTC time zone. When the data is saved to the database, it is converted to UTC (e.g. no conversion necessary). When retrieved from the database, the data is converted to the Site's time zone for annonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.
No time zone conversion - The date entered is not converted when saved to the database. When retrieved from the database, the data is NOT converted and is displayed exactly as entered.


How to add a tabbed menu on group main page (panel)? I managed to get panels working with og 7.x-2.1 following:
- http://modulesunraveled.com/organic-groups/part-3-organic-groups-layout
- http://www.initsix.co.uk/organic-groups-panels-and-views-drupal-7

Now I'd like to add a tabbed menu on the "main og content", where I mainly divide by content-type (documents, agenda, forum, news..).

I tried to follow http://www.austinprogressivecalendar.com/blog/creating-drupal-panels-tabs in order to create tabs, where each tab is a panel.
However I don't know how to eventually add what would be my (sub) panel to the main content of the group page, and more in general I wander if there is a less cumber stone way to implement it.

I got a working and straight solution (tabs are panel style) using panels_tabs.

panels_ajax_tab seems more nice (and more clean from a designer point-of-view), but it is also more cumbersome as it only accepts mini-panels as tab elements, and then I'm not sure how to pass the group information down from the main panel to the mini-panel and finally the embedded view panel.

Further panels_tab load all the page at once and then just hide the unused tabs, so if too many views are loaded the page can take pretty much long time to load !


Clear entity cache before render I secured some file in an s3 bucket using s3fs.
My problem is : the "Expires" argument send to build the file URI is not reset each time the object is call in my API.
time doesn't change if I don't clear the cache with drush
$expires = time() + 10;

So I tried to use hook_entity_view :
if ($entity->bundle() === 'my_bundle') {
    foreach ($entity->getCacheTags() as $tag) {
      $tags[] = $tag;
    }
  }

Doesn't work
Drupal::entityTypeManager()->getStorage($entityType)->resetCache();

Nop
\Drupal::service('cache.render')->deleteAll();
\Drupal::service('cache.entity')->deleteAll();
\Drupal::service('cache.data')->deleteAll();

deleteAll or invalidateAll, none of it work.
drupal_flush_all_caches();

Nothing, I'm starting to think I have config problem...
If someone can save me !
UPDATE
It seems hook_entity_load works with my API, it clear the cache correctly.
The problem remains when i'm trying to watch the content in my Drupal website, in the content view.

Ok everything is fixed, there were 2 points :

Clean the cache when the media 'masterclass_private_video' is called, so the request to AWS s3 has the correct "Expires" timestamp when call by my VueJs API.
Clean the render cache of the content view in my drupal backend.

Clean the media cache for the API :
function mymodule_entity_load(array $entities, $entity_type_id)
{
  $tags = [];
  foreach ($entities as $entity) {
    if ($entity->bundle() === 'masterclass_private_video') {
      foreach ($entity->getCacheTags() as $tag) {
        $tags[] = $tag;
      }
    }
  }

  if (!empty($tags)) {
    Cache::invalidateTags($tags);
  }
}

Clean the page cache :
function mymodule_node_view_alter(array &$build, Drupal\Core\Entity\EntityInterface $entity, \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display)
{
  if ($entity->bundle() === 'masterclass' || $entity->bundle() === 'masterclass_chapter') {
    $build['#cache']['max-age'] = 0;
    \Drupal::service('page_cache_kill_switch')->trigger();
  }
}

To be clear, the goal is to reset the $expires, so the AWS s3 works :
function mymodule_s3fs_url_settings_alter(array &$url_settings, $s3_file_path)
{
  $split = explode('/', $s3_file_path);

  if (in_array('private', $split)) {
    $file_path = getenv('AWS_CLOUDFRONT_ENDPOINT') . $s3_file_path;

    $expires = time() + 86400;
    $private_key_filename = '/var/www/my-drupal/keys/pk-cloudfront.pem';
    $key_pair_id = getenv('AWS_S3_KEY_ID');

    $canned_policy_getters = Drupal::service('mymodule.aws.signature')
      ->getCannedPolicyGetters($file_path, $private_key_filename, $key_pair_id, $expires);

    $url_settings['custom_GET_args'] = $canned_policy_getters;
  }
}


Display product variations in table There is currently a "product page" that contains combobox with the different variation values for that product category, but I'm curious if it's possible to add a table display to the product page to show all variations of that category within a table so a user can see what's available instead of manually drilling into every combobox?

Create a view with base table "Commerce product. "

Add necessary fields. Title, Price, Add to cart form, etc will be essential.
Add Relationship "Commerce Product: Referencing Node".
Add Contextual filter "Content: Nid". This view will list the products referenced by a product display node.

Install module Viewfield.
Add a view field to the product display content type, and set the view created in the first step as default value. Give [node:nid] as argument.
Configure the node display as you please.


Tab Tamer - Hiding tabs based on Roles Tab Tamer Module only does but so much. I want to hide a tab for anonymous users and have it active for other admin users. This just turns it off completely. Any ideas?

I added this code. Not sure if it does the trick. I need to set a hide based on permissions correct?

/**
 * Implementation of hook_menu_alter().
 * Remember to clear the menu cache after adding/editing this function.
 */
function MODULENAME_menu_alter(&$items) {
  // Removing certain local navigation tabs that are either undesired or need to be custom relocated.

  // Set these tabs to MENU_CALLBACK, so they still register the path, but just don't show the tab:
  $items['node/%node/track']['type'] = MENU_CALLBACK;
  $items['user/%user/track']['type'] = MENU_CALLBACK;
  $items['search/user/%menu_tail']['type'] = MENU_CALLBACK;

  // Fully unset these tabs and their paths, don't want them at all. This breaks the path as well:
  unset($items['user/%user/example']);
}


Horrible frontend performance on large CCK forms = poor UX. What are my options? I have a pretty large node form for one of my content types. Let's say it has about 100 fields. A lot of these fields are text values with unlimited values, so the user uses an AJAX button to 'Add another item' to each of these. Visually, this form isn't all that intimidating, because I've used Field Groups to keep things reasonable.

Problem: Clicking 'Add another item' is freaking slow. Like really slow.

I figured it was server performance, but then I checked it out in Firebug - the request isn't actually taking that long, but WOW - client side CPU usage (in Chrome, Firefox and any other browser I've tried) hits 100% and stays there for up to 11-12 seconds, and then the AJAX request completes.

That's insane.

So at this point I'm not sure what my options are. Can I break the form apart somehow? Workflow-ng style? A lot of people mention Field Groups as a way to organize a ton of fields, but that doesn't help performance, obviously.

Any help appreciated.

I have exactly this problem and I can confirm answer #1 - using a multi-step form improved performance, although it was still slow.

The problem is that when the Ajax fires, the entire form is rebuilt in the background. This appears to make huge demands on the server CPU if the form is large.

A multi-step form is a good way of improving things but unfortunately will not always be appropriate - in my case, the client rejected it because they felt it was too annoying to have to progress through the form in a step-by-step linear way. They wanted to be able to jump from tab to tab without saving in between.

Other than fixing Drupal core so that rebuilding the form does not require 20 seconds of max CPU, the only solution I can think of is to try the site out on a high-CPU hosting package, e.g. on Amazon AWS. This will be my next step.

Without knowing much about Drupal core and Ajax, I would call this a bug of sorts. I have heard that the performance of Ajax is being improved in Drupal 8 so I seriously doubt much effort will go into resolving this in D7.

If I had known all this at the start of my project I might have tried solutions such as combining several node forms on one tabbed panel - to break up the server load in more creative ways.


When removing a file it still is present on the machine When deleting a node the files attached to that node are removed from the server just fine. However if I edit the node and remove the file there, it stays on the server even after deleting the node.

Is this normal? Is there a way to fix that?

Permanent files have a status FILE_STATUS_PERMANENT.

  Indicates that the file is permanent and should not be deleted.

  Temporary files older than DRUPAL_MAXIMUM_TEMP_FILE_AGE will be
  removed during cron runs, but permanent files will not be removed
  during the file garbage collection process.

When you remove a file from a node, the file_managed record may simply be marked as status = 0 or anything other than FILE_PERMANENT, in which case, it's deleted during system_cron (if no entry in the file_usage table).

Basically, if you have cron running, it should be fine.


How do I access an Entity Reference's field values? I have 2 content types.

BaseContent:
Field1: Title
Field2: ID#

RelatedContent:
Field1: [Entity reference to a BaseContent]
Field2: **[Automatically insert the value of the referenced BaseContent here]**

But I can't work out how to do the part in the **s.

I feel like it should be easy, but nothing I have tried has worked.

Can I do it with any of the following:

-Tokens?

-Entity References using a Views Selection Type and relationships?

-Programatically with PHP (using the Computed Field module?)

If so, how?

any help much appreciated!

The rules module can do this for you.  Set up a rule to fire when (new?) content is saved, set a condition that the content be of type RelatedContent and has a value in Field1.  Then set the action to be saving a value in Field2 using the available tokens of the referenced node from Field1.  It should be something like [Field1:entity:target_field]

You can do the same thing in php code with hook_node_presave.

Entity reference with a view to limit the selection options would be better used if you just wanted Field1 and wanted to pick the entity to reference based on the value that you would be storing in Field2 if you had a Field2.  This is because the view can be used to show you the label using the value of that other field, but leave the key as the entity id needed to be stored in Field1.  Since entity reference can be used for a data connection by views, rules, code, etc this is a common practice to reduce your database size and not store the same data in more than one place.  However, it is a little more complicated to configure than just using rules.


Quick Edit module permissions I have enabled Quick Edit module on my Drupal 8 website and it's working ok, I have edit link in the toolbar to show all edit icons for edit menu on page.

Problem is in new user role. I have new user role and I enabled Access in-place editing permission for users in this role, but there is no option to edit anything on the page or edit link in toolbar.

What I'm missing? Is there some additional permission that I need to grant for this role (they already have permission to administer blocks)?

I found the problem, it's stupid.

I forgot to add permission to access to contextual links for this user role, so that's it.


How to display exposed sort in views using one drop-down widget? By default Views 3.0 module for Drupal 7 uses two drop-downs to display exposed sort. First drop-down to select field name, and other one - to select sort direction.

How do i can exposed sort in one drop-down?

You can use Better exposed filters module for that purpose. It has such option to combine sort field and directions in one select list.


Inject SQL_CALC_FOUND_ROWS into db_select()? I've recently learned that SQL_CALC_FOUND_ROWS can give the number of rows in a table from almost any SELECT statement. It's raw SQL syntax is SELECT SQL_CALC_FOUND_ROWS field1, field2, ... FROM ...

Is there an existing way I can that inject that syntax into db_select()?

I want to use this for creating a pager, so I'm already selecting some rows in the first place. It would be handy to get a count out of the query I'm already running. Doing a separate count query would be extra work in my case.

As made evident in Compare db_query() and db_select() performance, db_query() is faster than db_select(), which should then be used when you need to make the query you are executing alterable from other module via hook_query_alter(), for example when you need to get a list of nodes for which a user has access.

If that is not your case, then you can use db_query() and using the query you are showing is quite straight as db_query("SELECT SQL_CALC_FOUND_ROWS field1, field2 FROM ...").


Drupal 8: Upload Validation form alterations ignored I'm trying to ignore the auto down scaling of large images and replace the validation step with a hard check that the size matches the maximum size provided. I'm trying to do this through the HOOK_form_alter hook and while it appears to be affecting the form render array, the AJAX request seems to ignore my changes and run the default upload validation steps.

Here's what i'm doing:
In the seven.theme file:

function seven_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $imageForValidation = NULL;

  if (isset($form['field_name_here'])) {
    $imageForValidation = $form['field_name_here'];
  }

  if ($imageForValidation != NULL) {
    // Validate
    $imageForValidation['widget'][0]['#upload_validators']['myTheme_image_validator'] = array();
    unset($imageForValidation['widget'][0]['#upload_validators']['file_validate_image_resolution']);
  }

  return $form;
}

function myTheme_image_validator($file) {
  $errors = array();

  // This doesn't even get called.

  return $errors;
}

I've debugged with xdebug and the render array is indeed getting affected, but the result of uploading an image is always the same as the default setup. At the very least I expect the unset validator to not get run, but it still downscales.

Has anyone got round this issue before?

Clive was spot on. Turns out I wasn't passing my variable by reference. I was thrown off by (what is now old hat in Drupal 8) returning the form variable at the end of the form_alter hook.


Customizing Search File Attachments result page I'm using search_file_attachments module for my search, And also Search combine module to show all the results in one page. In the search results page, I like to maintain a structure. I need to show the node title instead of attached file name, and redirect to node url instead of attached file path when a user click on a result. So implement the template_preprocess_search_results() in my module overwrite the results. I tried to figure out the array result using devel.

function template_preprocess_search_result(&$variables) {
  dpm($variables);
}

And this my Devel results:

I cannot see any node details here, I guess this module only searching files in the folders. I'm finding a way to get the node details related to this results. Hope you guys got my question, Thanks in advance,

Finally I ended up with some advanced search modules, Which made the search so much better. I used Apache solr and Apache solr attachments modules. This gave me ability to make my search results in a customized way via hooks. I use hook_apachesolr_process_results() to change my results.

First I add a extra field to the file type entities in the solr index, which contain the node title.

/**
 * Implements hook_apachesolr_index_document_build().
 */
function mymodule_apachesolr_index_document_build(ApacheSolrDocument $document, $entity, $entity_type, $env_id) {
    //dsm($entity_type);
    //if the type is file
    if($entity_type == 'file'){
        //add a field node title
        $title = code for getting the node tile of this file
        $document->addField('ts_field_node_title', $title);
    }
}

Now this extra field will be available in your search results. So you can directly use the title instead of file name.

/**
* Implements hook_apachesolr_process_results().
*/
function mymodule_apachesolr_process_results(&$arg) {

    for($i = 0, $l = count($arg); $i < $l; $i++) {
        //if entity type is file change the title
        if($arg[$i]['node']->entity_type != 'node'){
           $arg[$i]['title'] = $arg[$i]['fields']['ts_field_node_title'];
        }
    }

}

Peace! :)


In Drupal 7 Views, how can I display a block on every page of a view? I am trying to display a SimpleAds block for every page of my view. How can this be accomplished?

Clarification: I would like to display the block once for each page of results. I am using the infinite pager module.

Simple:

https://drupal.org/project/block_views

Also related:

How can I show a block in a view page, excluding it's paginated pages


Deprecate multisite in 8.x for removal in 9.x I am thinking about implementation of some sites with multi-site and idea of solution (one code-base) is perfect for me even if shared table is not supported any more (my question about shared table is here also i'm aware of domain module too).

After some search, I found this topic about plan to deprecate multi site in 8.x and removal in 9.x.

My questions  are:

How serious is deprecation in 8.x and removal plan of multi-site in drupal 9? the topic is in category of plan for two years.
Even if removal happens in 9.x, we have to expect some migration path to removal of 9.x or not? In my idea this migration didn’t happen for shared tables.
Proposed solution for removal of multisite in mentioned topic is

  The modern approach to multi-site is: git — Same code, different
  sites. Under your control. And well-maintainable.

I can’t understand it. How does it works?

You have a few questions there, so I'll hit them individually:

  How serious is deprecation in 8.x and removal plan of multi-site in
  drupal 9? the topic is in category of plan for two years.

It's hard to say. Controversial topics like that can go in circles for years in the open source community. As you can see, that topic started over three years ago, and still has not reached a conclusion, and may well never reach one.

  Even if removal happens in 9.x, we have to expect some migration path to removal of 9.x or not? In my idea this migration didn’t happen for shared tables.

It will be fine even if you are sharing tables, as you can just migrate each multisite to a new individual site. You may have to do a special database dump and import to get the shared tables into your new system. I did this once when migrating from D6 to D7 for my company site - I was using multi site, and in the upgrade, I just created two sites out of the one.

  I can’t understand it. How does it works?

Git keeps all your code in a repository, which you can clone as necessary. So any time you need to spin up another site, you just clone the code, and you have a new Drupal instance. As you update sites over time, you can merge the code changes from one repository to another.

In my own company system, we have a central repository for each project. Any time someone new works on the project, they clone the code from the central repository, and they have an exact copy of the site. We then clone the repository to the webroot, so that it is available over the web. When people make changes to the code, they push the changes to that central repository, and then anyone can pull them at any time to their own repository, and/or the repository stored in the webroot of the public site.


How to rename image filename and make same as title field value Can somebody also help me to rename the image name same as title field?

I have a image content type where we have title and image field and when I submit the form I want to rename the image name same as the title field. This way I can make my image more meaningful by including keyword in the image name. Right now you can write about 'A' in the title field and you can upload images 'B' and that I don't want.

It looks like you should be able to do this using the Filefield Paths module. This will allow you to use tokens based on node fields to rename the file on upload.


dblog not working, page shows a 500 Internal server error My problem starts in a contact form with an upload box, it does everything right and sends the email, except that, on upload it shows:

  Warning: strtr() [function.strtr]: The second argument is not an array in syslog_watchdog() (line 105 of syslog/syslog.module)

So I found this post to resolve my problem above, but it just showed me another problem, a problem with dblog, the page shows me a 500 error, I can't access it.

I couldn't find any help to solve this matter so if anyone knows some way to figure out what is causing this, I would appreciate it.

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


Token Not Working On Auto Node Title and Auto Entity Title I am using drupal 7, auto node title 7.x-1.0, and token 7.x-1.4. I am trying to hide content type title field and set title value based on other field value, so i use auto-node title and token module. But, when i try to set the default value of the title using token, the token didn't work.

Then, after searching for a while, i've found this post:
Token replacement pattern is not working

So, i try to install auto entity title 7.x-1.1 module and disable my auto node title. But, the token still not working. Anyone could help me?

Thanks in advance.

This won't work indeed... It has to do with the way Drupal saves nodes. It starts with the title, and then reads and writes the rest of the fields.

The quick and dirty way is to use the rules module, and on node creation or edit, save the node again. I have been using this technique and can confirm it works.


How to manipulate a Views grid output order? For the content region of my homepage (under Drupal 7) I have 3 columns in which I need to display 3 different content types:

Regular article teasers (only image + summary as a link to full article)
Daily quote/citation/message (article with a short citation)
Advertising node (Advertising content type article)

Visually I have to respect the orderng of this layot (aren't designers wonderful):

===Column 1======Column 2=======Column 3=

=======Article=======Article=========Quote=======
=======Article=======Article=========Article=======
=======Advert=======Article=========Article=======
=======Article=======Article=========Article=======
=======Advert=======Article=========Article=======

I made a views block, which outputs a grid of a 3 columns and 5 rows filtering only articles "Promoted to the Frontpage". So far everything ok.
Now following design decisions I'm trying to find a way to order the output of this view and particularily respect the positioning of the 2 Adverts elements, which will always be displayed in the 3rd and 5th row of the 1st Column. Same thing for the third column where the Quote element should always occupy the first postion on the 3rd column.

I'm a Views rookie so is there any Filter/Condition/etc that I'm missing and it would help me to achieve the required grid layout?

Thanks

===============================================

SOLUTIONS

After some research I found two methods to accomplish this that I'll go briefly in details in case other users come across the same needs as me.

Using Node in Block module. In the Node in Block general Settings, I created 3 blocks and assigned the content types I want to list. The great thing about this module is that it gives the option to give friendly names to the blocks themselves but also to the Fieldset labels. Very user friendly for content editors who just want to click and select on labels that have a meaning and especially for languages other than English.
In the render mode options there are a couple of options. For now, I chose the teaser but I have to check on how to further style or hack to accomplish the required look.
I gave to content editor role, the permissions to manage the Node in Blocks queue and now they've got a nice list of the nodes assigned to the block(s) during the node creation.
What I missed the first time I installed this module was that it exposes a Row Weight option. Now editors can nicely drag and drop the nodes in any order they see fit.
For further positioning and styling I installed the BlockClass module and added a class to each block to individually style/position them.
Another way to deal with this is to use Nodequeue module, create a queue list and add contents to it during node creation/modifications. Order the queue items as desired, then expose the contents of the Nodequeue list by creating a Views block with a grid output. At the moment the advantage of going through this compared to Node in Blocks, is that with Views every field can be assigned a class or the html output can be overridden, which would allow me to match 100% the required look. Since I'm not completely familiar with views and the workflow implications this will have for the editors, I'll just keep this in case the first scenario doesn't give me full styling liberty.

As always there are several ways to achieve things with Drupal, and that's what makes it exciting.

Tunox

There are three module (two that come with ctools) that you probably should be looking at.
Page Manager, Views content panes, and Panels

Also, one of the best screen cast tutorials addressing views can be found here:
http://dev.nodeone.se/en/list-group-content-with-page-manager

The focus is OG, but the way views is being used seems to directly apply to what you described.


Stop caching images in views, force reload of jquery image slideshow when images are externally updated In D7, I have a panel that contains a view that contains a jquery image slideshow.

Every day, the images that compose the slideshow are updated by a cron job---ie, every day's new images override the old ones (they are given the same names).  So, say I have image1.png, image2.png and image3.png---every day these files are overwritten with new pictures.

I have added the following anti-cache protections in my meta section to both the page/panel and the view itself:

<meta http-equiv="Cache-Control" content="no-cache, must-revalidate">
<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<meta http-equiv="refresh" content="300">

I have also turned off all caching on the server of any duration, and of javascript/css.  I also run the external cron with the cron-key after the image overwrite occurs.

Yet it seems that the only way my slideshow ever updates to reflect the new content of the image files is when I do an F5 or ctrl+r hard reload.

I don't want to ask my users to do this, so how can I force a reload and cache-clearing beyond the measures I've already taken above to get the browser to recognize that the images in the slideshow have changed on the server?

(I saw this recent similar post, How to tell if an image was updated, but it seems to apply to images created by Drupal, rather than created externally and pumped in.)

Update:

I have also added, in light of @mikeytown2's comment below, the following to my .htaccess file:

 # Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Enable expirations.
  ExpiresActive On

  # Cache all files for 2 weeks after access (A).
  # ExpiresDefault A1209600
  ExpiresDefault A600 #NOTE, this means ALL sites expire in 5 minutes by default!

  <FilesMatch \.php$>
    ExpiresActive Off
  </FilesMatch>

</IfModule>

The .htaccess is in my public folder.

Even with this, which should be telling Drupal that all caches from my page expire at 5 minutes, I am still not seeing an update when new images replace old ones of the same name in my slideshow.

I have made sure to completely clear my cache and await an external cron, and the old images remain cached in the browser and/or server.

with firebugs net panel click on image1.png, select cache and get this information

Last Modified
Last Fetched
Expires

Your currently setting the html page to not be cached in the browser (which is already the case by default). If the images are hosted on your server, you need to adjust your apache .htaccess rules and have these images not be cached. Drupal's default htaccess uses a 2 week cache for everything other than php scripts. You need to make an exception for your images with filesmatch. Example:

# Requires mod_expires to be enabled.
<IfModule mod_expires.c>
  # Match image1.png, image2.png, etc...
  <FilesMatch ^image\d+\.png$>
    # Disable browser caching.
    ExpiresActive Off
  </FilesMatch>
</IfModule>

If the images are not hosted on your server simply append a question mark with the current unix time to the end of the image src. Example:

image1.png?1317717247


How to change the order of fields in the Drupal Commerce Checkout Form I'm using Drupal Commerce 7.x. I have added some fields to the checkout form in the customer profile. Specifically I've added 'Title' and 'Organization'. I'd like to move some of the fields around because they aren't in the order I'd like, but I can't figure out how to move them.

For example, right now the order is:
1. Country (I def. don't want that first)
2. Full name
3. Address
etc.

I want it like this:

Full Name
Title (new field)
Organization (new field)

I tried using a module that does this (just as an example, obviously, since only two fields are listed here). Am I on the right track?

<?php
function CommerceAlter_form_commerce_checkout_form_alter(&$form,
&$form_state, &$form_id) {
   $order = array('edit-customer-profile-billing-field-title',
'addressfield-container-inline');
    foreach ($order as $key => $value){
      if (isset($form[$value])){
        $form[$value]['#weight'] = $key;
      }
    }
}

But it didn't do anything.

Note: I was unsure how to reference the fields. The first one above called 'field-title' is the ID for that field and the second listed for addressfield (which is in the form by default) is by class .addressfield-container-inline).

Changing field order on the checkout form can be done by going to admin/commerce/config/checkout

Then just drag the items up and down to arrange them in the order you wish.


hook_form_alter() and hook_nodeapi() to alter fields and insert additional data on insert I have the code below, and I want to update the fields on my node using hook_nodeapi(). How do I set the fields on insert?

/*
 * Implements hook_form_alter().
 */

function feature_contact_form_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'contact_form_node_form') {
    $form['field_user_agent']['#type'] = 'hidden';
    $form['field_ip_address']['#type'] = 'hidden';
    $form['buttons']['submit']['#weight'] = 1;
  }
}

/*
 * Implements hook_nodeapi().
 */
function feature_contact_form_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
  if ($node->type == 'contact_form') {
    if ($op == 'insert') {
      function getRealIpAddr() {
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
          $ip = $_SERVER['HTTP_CLIENT_IP'];
        }
        elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
          $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
        else {
          $ip = $_SERVER['REMOTE_ADDR'];
        }
        return $ip;
      }

      $ipaddress = getRealIpAddr($ip);
      $node->field_user_agent = array($ipaddress);
      $node->field_ip_address = array($_SERVER['HTTP_USER_AGENT']);
    }
  }
}

As mentioned in the comments any extra fields you add to to a node form won't automatically be persisted to the database, the node module only takes care of the fields that it knows about.

Traditionally there are 2 options:

Use CCK instead and add fields to the node that way. Then you don't need to take care of data storage/loading yourself.
Add your own table for data storage using hook_schema(), making sure you have a column for nid (node id). Then in hook_nodeapi() use the insert and update ops to run a db_query() to insert/update the data in that table for the current node.

Then you just need to load that data back from the DB on to the $node object in the load op of hook_nodeapi(). Your data will then be available at $node->field_name when you have a node object loaded with node_load().


Output field with double quotes in twig We have a field, field_text, that we are displaying on the Basic Page content type. It needs to display with double quotes " using twig template. We tried the following below, but it is displaying without the " in the beginning and end.

How can we display the field_text with double quotes (") in twig?

What we tried:

node--page--full.html.twig

<script type="application/ld+json">
  {# None of the following worked #}
  "name" : {{ content.field_text.0 }}
  "name" : {{ '\"' ~ content.field_text.0 ~ '\"' }}
  "name" : {{ '\"' }} {{ content.field_text.0 ~ '\"' }} {{ '\"' }}
</script>

Try with the value of the field and then concatenated with " like the second way:
I tested it with the following:

"name" : {{ content.field_text_test.0['#context']['value'] }}

"name" : {{ '\"' ~ content.field_text_test.0['#context']['value'] ~ '\"' }}

"name" : {{ '\"' }} {{ content.field_text_test.0['#context']['value'] ~ '\"' }} {{ '\"' }}

Here is the result:


get same result from db_query() as views query I know I can get a views result programatically with:

$view = views_get_view('view_name');
$view->execute();
$response1 = $view->result;

I can get this views sql query from the views ui (views->settings->show sql).  If I place this query in a db_query() and get the results with:

$query = "... "; //long sql query from views ui (in my case with left_joins which reference field collections
$result = db_query($query);
$response2 = $result->fetchAll();  //different than $response1 above?

the responses returned from $response1 (from views) and $response2 (from db_query) are different, namely, the $response2 doesn't contain my field data (or at least not all of it).  I'm not sure if this has anything to do with the fact that I'm using field collections.  It also seems to not work when using the different fetch() functions.   If I run this query through phpmyadmin it produces the same limited results as $response2 (from db_query) so I'm wondering if views runs something aside from the query.  I'd like to find out what the method result() does for the views object, but I'm not sure where that is in the docs or where the function is in my views source.  If someone can show me where that is, that would also be helpful.

Your view most likely has tags getting attached to it, like node_access. Or if you're using grouping on the View that may make a difference in the result property.

Like Nikhil suggested to add that hook somewhere in a custom module just to see what $query has in it. And if you have the Devel module installed you can pass that query like so:

dpq($query);

If it ends up being the case that you have tags being added to the views query and need to mimic that, I'd recommend switching over to the dynamic queries and doing an $query->addTag(...);


Block configuration form values are not translated I have the following code in my custom block:

    public function blockForm($form, FormStateInterface $form_state) {
    $form = parent::blockForm($form, $form_state);

    $config = $this->getConfiguration();

    $form['headline'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Block headline'),
      '#default_value' => isset($config['headline']) ? $config['headline'] : NULL,
      '#required' => TRUE,
    );

      return $form;
    }

and:

    public function blockSubmit($form, FormStateInterface $form_state) {
      $this->setConfigurationValue('headline', $form_state->getValue('headline'));
    }

The configuration is saved correctly, but only for English language.
The block translation doesn't show my variable (headline) in the translatable configuration.
What am I doing wrong?

Thanks

You have to provide a schema in /config/schema/mymodule.schema.yml of the type block_settings.

Example:

block.settings.example_configurable_text:
  type: block_settings
  label: 'Example configurable text block configuration'
  mapping:
    block_example_string:
      type: text
      label: 'Block contents'

From the example module http://cgit.drupalcode.org/examples/tree/block_example/config/schema/block_example.schema.yml

Configuration values you map as type: label (single line of text) or type: text (multiple lines of text) are translatable.


How to create a tab using Views? I am using Drupal 7 and I have content type events. It has many node pages created used by events content type.Event names and years are fields in event content type. I want to create years as tabs.When clicks years(tabs)it will show all events names happened in that year. I don't know how to create tabs using views.

When creating a page view using views, it gives you the ability to assign a menu for that page, in this situation you can define all views with same parent path like parent/view1 , parent/view2, then in middle box when adding menu item you can select views as menu tab entry while default menu tab can be assigned for the view you want to be shown when navigating to parent path.


How to use cron with views cache? I have a dashboard with about seven views that are each very expensive. Most of the views can be computed hourly, but I would prefer cron to run them rather than the unfortunate user. How can I have cron refresh the views cache and never a user?

Something like this should work:

Set the Views to cache data.
Implement hook_cron(), and delete the cached data from the cache_views and cache_views_data tables.
Programmatically request the URL which contains the expensive Views to rebuild them (this could be done via CURL, file_get_contents(), etc.)


programmatically check if any field in a node is edited I have a content type blog, it has several fields.If any one of the fields changes I want to call a function. How do I check even if one field has been changed.
I tried checking comparing timestamp and revision_timestamp values available for $node and $node->original objects in hook_node_presave. But it did not help.
Can someone help me with this?

what you could do is add custom validate handler and in there load node

$my_node = node_load($form_state['nid']);

What this will do is load node with values that are currently in the database. of course you should make sure that above is not invoked if you are adding new node.

Now, you have your 'old' values in $my_node and 'about to be saved' values in $form_state['values']. Loop through both and compare values.

This is not the most effective way but it should work.

Use debug() from devel if you are not familiar with $form_state['values'].