How to get more info on error during clone? When cloning one of my sites I get the following error:

  SQLSTATE[HY000]: General error: 1267 Illegal mix of collations
  (utf8_general_ci,IMPLICIT) and (utf8_unicode_ci,IMPLICIT) for
  operation '='
  - error

I am unsure how to find where this is happening. I would appreciate any help!

This looks like an SQL error and not an Aegir one so I'd recommend searching for that error specifically.  However, the conventional way to get more output for a failed Aegir task would be to run the following on the CLI:

drush @hostmaster hosting-task --force --verbose --debug TASK_ID


View with contextual filter using a taxonomy reference from a node In a view showing for example products (nodes) filtered by a taxonomy term (product type), I can easily set a contextual filter to select the product type term to be displayed.

Is there a way to get the value for a contextual filter in such a view from another node?

Usage example: Using the example above, I have a content type that presents a product type (taxonomy term) in depth with text, images etc. I want to specify a term in a reference field in the product type presentation and have a block that displays all product for the selected term.

Is that type of filter possible?
I am guessing the same approach can be used in D7 as well as D8 if possible without using third party modules.

If my question is unclear I will be happy to elaborate my case further.

Views are complicated, so pardon me if i don't have this entirely right in the first go.

So as I understand things, you have one node that references a taxonomy term representing a product type, and you need to get a view on this node page to show other nodes (possibly of a different content type) that reference this same taxonomy term (possibly along with others). If that is correct, you should be able to do this with two relationships and a contextual filter. Both are found under the advanced settings portion of the view edit pane.

The first relationship you want to add is 'Entity Reference: Referenced Entity - A bridge to the Taxonomy term entity that is referenced via field_your_taxonomy_field'. This gets us from your 'result' nodes to the term you want to filter on.

The second relationship to add is 'Entity Reference: Referencing entity - A bridge to the Content entity that is referencing Taxonomy term via field_your_taxonomy_field_on_the_entity_we_are_viewing_the_view_from'. You set it up to use the first relationship as its relationship.

Last, you set up a contextual filter on 'Content: Nid' using the second relationship.

Edit
Since you are inside a block, you will also want to tell the view how to get the context (node ID) from the URL. Under the 'WHEN THE FILTER VALUE IS NOT AVAILABLE' you will want to select 'Provide default value' and in the resulting dropdown, select 'Raw value from URL'. Path component 1 should be correct. Save and update the view.
End Edit

To test this, pick the NID of a node where you might be viewing the view and put the NID in the 'Preview with contextual filters' box and click update preview. Did you see what you wanted to see? If so, great!


WYSIWYG CKEditor is altering source text on reload. Why? I created a paragraph with a text field that uses CKEditor text editor with Full HTML enabled. I switched to the Source view and pasted the following code into CKEditor.

<!doctype html><html lang="en">
<head>
    <meta charset="utf-8"><title>The HTML5 Herald</title>
    <meta name="description" content="TheHTML5Herald">
    <meta name="author" content="SitePoint">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head><body>
    <script  src="https://code.jquery.com/jquery-2.2.4.min.js"  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="  crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
</body></html>

Very simple, I was just testing to see if it accepted script and link tags out of the box. After I saved the page and went back to edit it, the source view only showed:

<meta charset="utf-8">
<title></title>
<meta name="description" content="TheHTML5Herald"><meta name="author" content="SitePoint">
<link href="https: //stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" /><script  src="https: //code.jquery.com/jquery-2.2.4.min.js"  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="  crossorigin="anonymous"></script><script src="https: //stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>

Note that it removed the doctype, html and body tags. What's weird is that in the database, the value for this field in this node is still exactly what I pasted in (with all the tags). Is there a hook or filter that is altering this before it is rendered? How can I prevent this to make sure it always displays what I previously pasted in?

I'm using Drupal 8 and the CKEditor version is 4.7.2 according to the JavaScript console.

WYSIWYG CKEditor is altering source text on reload. Why?

Simply because it makes no sense to print them. I'm sure they added this as a preventative measure to prevent people from writing bad HTML. There is no way to turn this off, for your own good, lol.

If you look at html.html.twig template file, where your CKeditor code will render is already inside the <body> tag, so it makes no sense to re-declare the <html> nor <head> nor <body> tags when they already have been declared.

<!DOCTYPE html>
<html{{ html_attributes }}>
  <head>
    <head-placeholder token="{{ placeholder_token|raw }}">
    <title>{{ head_title|safe_join(' | ') }}</title>
    <css-placeholder token="{{ placeholder_token|raw }}">
    <js-placeholder token="{{ placeholder_token|raw }}">
  </head>
  <body{{ attributes }}>
    {#
      Keyboard navigation/accessibility link to main content section in
      page.html.twig.
    #}
    <a href="#main-content" class="visually-hidden focusable">
      {{ 'Skip to main content'|t }}
    </a>
    {{ page_top }}
    {{ page }}  <--- YOUR CKEDITOR CODE WILL PRINT HERE...
    {{ page_bottom }}
    <js-bottom-placeholder token="{{ placeholder_token|raw }}">
  </body>
</html>

  <script  src="https://code.jquery.com/jquery-2.2.4.min.js"
  integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
  crossorigin="anonymous"></script>

For starters, Drupal 8 comes with jQuery, there is no need to add it, simply you just need to mark it as a dependency to your js file and then and only then, Drupal will load it. See How to include jQuery Once on your Drupal 8 pages

Loading scripts via CKeditor is considered bad practice. So the question becomes, how can I properly add the .css and .js bootstrap file?

Option A

Create a library file for your theme if it doesn't have one already

mytheme.libraries.yml

bootstrap4_cdn:
  css:
    theme:
      https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css: { type: external, minified: true }
  js:
    https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js: { type: external, minified: true }
  dependencies:
    - core/jquery
    - core/jquery.once

Note: In .yml files spacing matters, so make sure the indentation is exactly the same.

Then on your theme.info file add

libraries:
  - mytheme/bootstrap4_cdn

For better understanding, I encourage you to read Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme.

Option B

Use the bootstrap library module, which will add the library for you. (Basically does option A for you)

Option C (better yet)

If you want to create a Drupal 8 boostrap 4 theme, then you could create a Drupal Subtheme and use Bootstrap Barrio as your base theme.

Why a sub theme? Because themes are no different than Drupal Core or Contrib modules, if you hack them directly and then download an update for it, you will lose all your changes.


How to run cron automatically after node published? cron has to run after some time  of node publishing.I tried like this

 function custom_module_cron{
//($updated = node published time)
if(date("Y/m/d H:i:s") == date("Y/m/d H:i:s",$updated+60)){
//code here
}
}

but its not running automatically. Can anybody help ?

have you managed your cron configuration, if no then go to /admin/config/system/cron and set your cron settings to run on that interval of time.

Hope it solves your issue.


Drupal 7 Wildcard menu like txt-txt-% is not locating I wanted to create wildcard menu like text-text-% in drupal 7.

But It works for if the menu is like text-text/% how can I make the above menu format to locate the action.

 $items['pin-code-%'] = array(
        'title' => 'Country list',
        'description' => 'Country pincode',
        'page callback' => 'country_pincode',
        'access callback' => true,
    );

Wildcard menu items for root level is not supported.
Partial match wildcards are not supported either.

You can, however, remap incoming requests to a proper menu router that Drupal supports by implementing hook_url_inbound_alter. Unless there is a strict requirement to use the path pattern you mention, I wouldn't go for this solution because this hook is executed to every request, including normal pages and Ajax requests.


How to build a simple data comparison rule? I am working on Drupal 8.7.10 and I have installed a fresh Rules 8.x-3.0-alpha5.

Could someone help me to start a very simple rule? I am still struggling with the "new" Rules.

All I need is to send an email to a specific role when a specific field has changed.

"Rulesly" speaking, after a node has been updated, if the unchanged field value is different from the changed field value, then send an email to the manager, with a link to the updated node.

P.S. : I have also started to work with Business Rules so if someone can build this with this module, that sounds good too!

OK, I would then recommend Business Rules to build that kind of data comparison rule.

1- Create a first Variable "Value from Entity field" to store the original value of your field.

2- Create a second Variable "Value from Entity field" to store the current value of your field (i.e. the saved value after updating node)

3- Create an Action "Send an email"

4- Create a Condition "Variable data comparison" to compare the two variables you built in 1 and 2. Available variables are listed, use {{your_variable_name}}. Use the right operator, here I needed != (different from).

5- Inside your Condition, add the Action "Send an email" (in section "Items to execute if condition succeed")

6- Create a Rule based on an event "After updating Entity", define the context (entity type and bundle, here content and content type) and insert the Condition you built in 4. You should see a nice flowchart with your Rule label (white), then your Condition label (blue) and if YES, your Action label (green).

That's a start.

Hope this helps.


How do I build a search form with filter options / checkboxes? I'm a noobie to Drupal - recently "converted" from WordPress.

I want to create custom search forms that use checkboxes to allow visitors to search in a specific content type.  Sorry for the shady example, but the search form on the front page of the Pirate Bay is exactly what I'm looking for. It would also be great to be able to set the default option based on context - if the user is on a page of a particular content type, that content type should be set as the default in the search checkboxes.

I've installed Drupal 7, Apache Solr search, and the Facet API. I'd give a link, but it's installed locally on mamp for development.

I want the custom search form because the site I'm building has a lot of different - and interrelated - kinds of information separated into different "areas" of the site defined by content type.  One area is for social service resources, another is for social service organization profiles, another for trainings and workshops, etc.  Each of these use Views to display related information in other content types (i.e. "Related Trainings" listed in the sidebar of a resource page).  In essence, the site maps out the entire social service system in our community and serves as an information center for clients and case workers.

When someone visits our site looking for emergency shelter, for example, the information they are looking for is in the "Resource" content type and I don't want them getting a deluge of info from trainings, org profiles, forums, etc.  Another example would be a case worker wanting training on how to apply for Social Security disability benefits for a client - I want them to be able to choose to restrict search results to the "Training" content type.  Faceted search seems to be able to allow users to drill down and refine results, but I want them to be able to filter before getting results.

Anyone know how I might do this?

Take a look at this module, it may be what you need: http://drupal.org/project/custom_search.
It extends drupal built-in search module.
You can add filters for content types, taxonomies etc in drop-down triggered when searching.


Making columns into sort asc/desc in search api-based view I've created a search page using Views and 'search api'. I've got my results showing in tabular format with the labels in a  above the results returned.

But I can't figure out how to make each label/column header a sort. I want the user to be able to click the label in the column header to then sort that column by ascending/descending.

Anyone know how to make that possible?

I figured this one out. I have to set the field to 'string' in Search API configuration > index > edit. The default is 'fulltext', which sounds right, but isn't for this usage.

Then you have to change the settings for the format: table to make the field sortable.


How would I use the Field Validation module with Addressfield to make just city and province/state required? I have set my addressfeild to be completely optional, however, I want to use the field validation module to ensure they at least fill out city and province/state.

Any thoughts?

On your node type field administration page, click the validate for your address field. Click the Required field validator link. On the validator form you want to:

Add your arbitrary Rule name (e.g. Address State)
In Column, select locality or administrative_area for City & State respectively.
Add your custom error message in the Custom error message field.
Click Add rule to add the validator.

Once added for both city/state this will force the address field's city/state to be entered.


Trigger a module function after a node is saved or updated successfully in the database I have used this function hook_node_insert() , but it does not help me because this hook runs before the node is actually saved in the database. I am indexing nodes to a third party application whenever a node is inserted, updated or deleted. The application sends request to the node URL, but using hook_node_insert(). It's giving me an invalid document location error because the node is not actually inserted yet.

Is there any hook invoked after a node is saved or updated in the database?

I followed this approach, without success.

function  my_module_node_insert($node) {
  if (!$node->type == 'article' || !$node->type == 'page') {
    return;
  }
  my_module_do_index($node);
}

You may be able to use Hook Post Action and then use this hook:

function my_module_node_postinsert($node) {
  if(!$node->type == 'article' || !$node->type == 'page' )
      return;
  my_module_do_index($node) ; // indexes the node
}

Give it a try and see if it helps!

The project link: https://www.drupal.org/project/hook_post_action


Is there an interactive PHP testing tool for Drupal? I'm in the middle of trying to create some contextphp code and drupal_set_message debugging is getting old fast. Is there any tool that would allow me to specify a url "context" (e.g. /node/6) and then have a PHP editor that could dynamically execute the code in the window as if it was running in that context?

If you are running locally, you can install Netbeans and Xdebug and set break points, watches and everything.

If you want just a little better then drupal_set_message() you can run devel and the output from dpm() will be formatted by Krumo. That's at least helpful.


Unserialize error in Drupal Commons 3 for unathenticated pages I've having the darnedest time finding a solution to the following error that is seen on my login screen to Drupal Commons 3 running on Drupal 7.22.

Notice: unserialize(): Error at offset 52 of 77 bytes in registration_entity_settings() (line 863 of /var/www/html/profiles/commons/modules/contrib/registration/registration.module).

We are additionally using FBOauth. Outside of that this is a new install.

To try to disect the issue a bit more I added the following right above the unserialize call.

 859     if ($result) {
 860         print '<pre>';
 861         print_r($result);
 862         print '</pre>';
 863         $result['settings'] = unserialize($result['settings']);
 864     }
 865   }

This dumps what is in $result['settings']. I thought perhaps a value was incorrectly serialized in the first place, but I cannot see what the issue might be. The output dump...

Array
(
    [entity_id] => 5
    [entity_type] => node
    [capacity] => 0
    [status] => 1
    [send_reminder] => 0
    [reminder_date] =>
    [reminder_template] =>
    [open] =>
    [close] =>
    [settings] => a:2:{s:12:"from_address";s:17:"admin@example.com";s:22:"multiple_slots";i:0;}
)

This error disappears once I'm logged in. This is a sandbox/development box.

Since this was a development server, I just blew away the current install and database. This hasn't occurred since a reinstall of Commons 3.


Closest nodes with Locations and Views I'm using Drupal 7 with Views 3 module and Location 3 module installed.

I have a content type that has a Location type field and I would like to build a view that given a latitude/longitude input and a maximum distance i have to retrieve all the nodes that are in this range. Is that possible with views or I have to build something by my own (in this case can you show me the way on how to implement it).

Thanks a lot for your help

Danilo

Resuming the question problem is the following:

I have a problem setting a View to show the closest nodes of another (I'm using last dev version of views and locations on drupal 7). So my scenario is the following:
I have 2 differents node types (A and B) both with a location field. I want to build a view that given a node A (with a determinate location) a have to retreive all the nodes B in a distance of 2Km.
So to do that I created a view with the following filters:

Content: Type = B
Location: Distance / Proximity, with the parameters

{origin:"node's lat/lon from views nid argument"}
{Node ID argument to use: (it doesnt allow me to select any data)}
{Location to use:"CCK Location: field_A_loc"}.

I also added a contextual filter. I selected as contextual filter:

{Content: Nid}

and I added % to my path so now the pat is /myviewpath/%. This allow me to choose the value:

{Content: Nid} in the field "Node ID argument to use" of the filter "Location: Distance / Proximity".

So i try to run the view but I get no results when the view is called as mydomain.com/myviewpath/3 where 3 is a A node.

I also tried to do not use the contextual filter (that does not allow me to set the "Node ID argument to use" in the "Location: Distance / Proximity, with the parameters" filter) and running the view mydomain.com/myviewpath/node/3 but in this case I get the list of all B nodes..

What I'm doing wrong setting up this view??

Thanks in advance for your help

Yes, you could set up a view, filtering on Location: Distance / Proximity, and configure what the origin or "starting point" is, eg, the location of the logged in user, a node that has a location, or, in this case, a static lat/long, and then have it display whatever fields in the filtered nodes you want.


Set the default value for a password field on a custom form I have created a custom user register form. I want to set the default value for the password, and confirm the password fields.
My point is that, whenever form error occurs, the password fields get cleared. Users don't need to type the password again and again.

I think you are choosing password type field. Like below  for password and confirm password fields.

'#type' => 'password',

Password does not support '#default_value' property. So fields getting cleared.


entity_lookup for user entity type I'm trying to link a field in my spreadsheet file to a user that is previously created with a migration from the same spreadsheet. The Backup column consists of multiple names divided by the backward slash (Firstname Lastname/Firstname Lastname)
migrate_plus.migration.profiles.yml:
process:
  field_backup:
    -
      plugin: explode
      delimiter: '/'
      source: 'Backup'
    -
      plugin: entity_lookup
      value_key: name
      ignore_case: true
      entity_type: user
      bundle_key: uid
      bundle: people

migrate_plus.migration.users.yml:
process:
    name:
      plugin: concat
      source:
        - 'Firstname'
        - 'Lastname'
      delimiter: ' '

The backup field is just skipped when migrating the profiles. The only error I'm getting is when i go to a profile page and check the log messages.

User error: "attributes" is an invalid render array key in
Drupal\Core\Render\Element::children() (regel 97 van
/var/www/html/web/core/lib/Drupal/Core/Render/Element.php) #0
/var/www/html/web/core/includes/bootstrap.inc(587):
_drupal_error_handler_real(256, '"attributes" is...', '/var/www/html/w...', 97, Array) #1 [internal function]:
_drupal_error_handler(256, '"attributes" is...', '/var/www/html/w...', 97, Array) #2
/var/www/html/web/core/lib/Drupal/Core/Render/Element.php(97):
trigger_error('"attributes" is...', 256) #3
...

Can you not use entity_lookup for users or am I doing something wrong in my configuration?
Any help would be much appreciated

If your entity_lookup is searching Users then the bundle, I think, should also be user since there is no people bundle.


Pass custom variable to an entity reference templete i have the following problem in Drupal 8.

In custom content type there is a field, which is a multiple entity reference to the same content type. The field is set to use custom view mode, where only title and body fields are displayed. Kind of sub-pages structure. Also the content type has a boolean field, which determines whether the body field of sub pages (entity reference) should be displayed or not.
So in my theme_preprocess_field() hook i can get the boolean value, but i don't know how to pass it to the entity references, so in my node--mypage--grid-item.html.twig i could check for that flag and determine should be content.body be rendered or not.

Thank for any hints.

Create two view separate modes for your entity reference, one for each boolean value. In preprocessing, modify the view mode of the entity reference depending on the value of the boolean field.

This is a code example I'm using for paragraphs to change the view mode of a referenced media entity:

function mytheme_preprocess_paragraph__image(array &$variables) {
  $paragraph = $variables['paragraph'];

  if ($paragraph->hasField('field_imageratio')) {
    $imageViewMode = str_replace('media.', '', $paragraph->field_imageratio->target_id);
    if (isset($variables['content']['field_image']['0']['#view_mode'])) {
      $variables['content']['field_image']['0']['#view_mode'] = $imageViewMode;
    }
  }
}

I think you can largely reuse the logic above, field_imageratio should be replaced by your boolean field, field_image should be replaced by your entity reference field.


Importing XML using feeds API I have some data of type Images where I want to import in the format of xml named 'images.xml' which containing images url and information.

I want to import this file programatically using feeds API.

How can I achieve this?

for this i use following code:

$source = feeds_source($importerId);
$config = array(
  'fetcher' => array(
    'plugin_key' => 'FeedsHTTPFetcher',
    'config' => array(
      'auto_detect_feeds' => FALSE,
      'use_pubsubhubbub' => FALSE,
      'designated_hub' => '',
      'request_timeout' => NULL,
      ),
    ),
  'parser' => array(
    'plugin_key' => 'FeedsXPathParserXML',
    'config' => array(
      'sources' => array(
        'xpathparser:0' => 'url',
        ),
      'rawXML' => array(
        'xpathparser:0' => 'xpathparser:0',
        ),
      'context' => '//image',
      'exp' => array(
        'errors' => 0,
        'debug' => array(
          'context' => 0,
          'xpathparser:0' => 0,
          ),
        ),
      'allow_override' => 1,
      ),
    ),
  'processor' => array(
    'plugin_key' => 'FeedsNodeProcessor',
    'config' => array(
      'expire' => '-1',
      'author' => 0,
      'authorize' => 1,
      'mappings' => array(
        0 => array(
          'source' => 'xpathparser:0',
          'target' => 'url',
          'unique' => FALSE,
          ),
        ),
      'update_existing' => '0',
      'input_format' => 'full_html',
      'skip_hash_check' => 0,
      'bundle' => 'images',
      ),
    ),
  'content_type' => 'images',
  'type' => 'images',
  'update' => 0,
  'import_period' => '-1',
  'expire_period' => 3600,
  'import_on_create' => 1,
  'process_in_background' => 0,
  );
$source->importer->addConfig($config);

$featcher_config = $source->getConfigFor($source->importer->fetcher);
$featcher_config['source'] = $url;
$source->setConfigFor($source->importer->fetcher, $featcher_config);
//$source->save();
//node_save($source);
$source->startImport();

But this code show "Download of failed with code -1002" and no images are import...

It depends somewhat on your use case. For example are you scraping the images off a web page or are you using a direct image file URL.

If you are scraping from a web page you can use the feeds image grabber module.

That module provides additional settings where you can configure a CSS selector for the page that is in your XML file.

The module will then request that page and scrape the image from it based on the selector you configured then add the image to the imported item.


How to handle large select lists in content types? I need to add a city field for a content type in D7. I'm getting it from a federal census table and it's going to be around 35K+ records. Any thoughts on filtering this list down by state and/or county? Without some kind of filtering, I'm afraid I'll bring Drupal to it's knees. BTW, I can't just use a taxonomy list because I need to key the list on a city ID. I also will have county ID info. So, I really need to filter the counties list to just those for the state the user has selected, then the cities by that county.

Here's the general structure:
User selects
   State ->  County-> ->Cities.

I tried looking at the references module but the reference field I created didn't seem to be filterable.

Thanks for any assistance!

Sounds like a perfect job for Simple hierarchical select

Simple hierarchical select defines a new form widget for taxonomy fields to select a term by "browsing" through the vocabularies hierarchy.
The widget is available in node forms and as Views exposed filter.

You can add your locations as a hierarchical taxonomy, and SHS will AJAX-load child terms into a new inline select, then children of those in a new select, and so on. Something like


default value for entity reference field I have a form with an entity reference field and I need to add a default value. I've tried

$form['field_op_product']['und'][0]['target_id']['#default_value'] = $product_node->nid;

but, that doesn't work. Any idea on how to do this?

The widget type is "AutoComplete"

From the sample code given in question, I assume the hook_form_alter() is used. You should first load the referring node, get the Node Title and Node ID from it, and then set the default value using both. This works.

Setting the default value using Node ID alone will not work.

$entity_node = node_load($nid);
if ($entity_node) {
    $form['field_op_product'][LANGUAGE_NONE][0]['target_id']['#default_value'] =
        "$entity_node->title ($entity_node->nid)";
}


Applied JS to Drupal theme doesn't work correctly, but it works fine outside Drupal Applied this JS http://jsfiddle.net/tbq8eo8b/10/ to webforms. As you can see in fiddle, it calculates total amount. When in Drupal, it gives 0 no matter what amounts you select, it always prints 0. What's wrong?

Drupal code:

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

/*Add your js code here*/
    var $selects = $("select").change(function (e) {
        var total = 0;
        $selects.each(function() {
            var val = this.value.match(/\$(\d+)/);
            total += val ? +val[1] : 0;
        });
        $(".total").val(total);
    });

}

};
}(jQuery));

Also console prints:

TypeError: $ is not a function
$("select").change(function ()

}(jQuery));

should be

})(jQuery);

in your last line of code.


programmatically get default value from translated body field per language I am trying to get a default value loaded programmatically into every body field when we add translate from english, but it doesn't seems to work using form overwrite fields

I tried using $form[][] = 'value'; but not working

as I also unable to pull the default value that is already set via field_translations.

I used form_alter for the options

can anyone please point me some clue of which method I used for the custom module

thank you!

eventually, I fixed it myself by using the hook form alter and custom db_query to load the locales tables and then match the LID to get the source and target language and then manually overwrite the default language for every new translated language.

so my problem is solved, thank you guys for helping out.


Send email only if a field has a certain value I am using webform in Drupal 7 and have a case where I need to send an e-mail only if a certain select field has an option selected. I have installed Rules and Webform rules but am a bit stuck on how to get this going.

In my webform I have the field called type (which is nested in a fieldset called shipping). My 3 options in the field are Ground, Air, Ocean. What I would like to do is send an email (using Rules due to a pdf that is attached to the email) only if the option selected is Ground.

Is this possible with Drupal 7 and rules / webform rules?

I would use a technique similar to what is described in my answer to "How can I compare data comparison with values submitted in a webform?". For short:

Add an extra Rules Action to Add a variable, with a value assigned to it equal to your Webform data you want to use (and with an appropriate data type). You'd need 1 such variable for each Webform component for which you want to access its Webform data.
In your subsequent Rules Actions you can refer to the value of these variables you just added (that's the clue!).


How do I display the submitted data in the same page? I created a custom form in Drupal 7. I need to display the submitted data in the same page showing the form, without using drupal_set_message(). Is it possible?

You can use $form_state['rebuild'];

If $form_state['rebuild'] = TRUE; has been set then a new copy of the form is immediately built and sent to the browser. Instead of a redirect to new page.

Example:

function example_form_submit($form, &$form_state)
{
  // we return the submitted value to the form
  // by storing it in $form_state['storage'] and rebuilding
  $form_state['storage']['some_value'] = $form_state['values']['some_value'];
  $form_state['rebuild'] = TRUE;
}

You can refer https://www.drupal.org/node/2171993

Another way store the "$form_state['values']" in session.

Take @clive answer How to display an HTML table after the form submission on the same page as the form? as reference.


Why are nodes not saving, and redirecting to edit instead? When editing a node and attempting to saving it, the user is redirected to the edit form with no error message and the node is not updated. This situation is similar to the problem described in "Nodes do not save, but instead redirect to edit page again", but in Drupal 6 and in all content types. The nodes have at least one field, FileField, which is common to all nodes but I haven't had any problem with it in other sites. There're no errors, nothing in the logs. I'm clueless.

Edit:
I've identified that the problem is with content types that have a FileField field. Sadly, I still don't have a clue of what could be causing the problem.

It was the FileField that was causing the problem. I still don't know why but I removed it and the node could be saved again.

Edit:
It seems the problem is caused by CCK fields. Nodes without CCK fields are not experiencing this problems.


How to manage text on my site that's not node content? I have text on my site that isn't node content, such as:

footer legal text
"Subscribe to our newsletter"
"Browse our categories"
etc.

I need to save my development work as a Feature but I also need content editors to be able to edit the text. But I don't want to give them permission to edit all blocks. In the not too distant future, the site will be extended to another region so this content will also need to be translated.

Is there a technique / solution designed for housing this data?

I could create a new content type and create a new field for each piece of text. I could easily print the field in TPL files but it might be a little harder to print it in blocks. I also don't know if its performance inefficient to do this, does the whole node object get loaded when you print a single field?

I've heard about (but not used) the Nodeblock module. It looks like this would work but I don't know how easy it will be to work with the Features module (I don't think you can feature nodes).

One nice thing about the first method is that the field label could be descriptive eg "Footer legal text" which would make the translation side of things easier.

Consider using the Bean module for this. Here is a quote about its project page:

  Think of a Bean as a method to provide new types (compared to node this would be a content type) which then provides an add content interface to create as many blocks as you require (see screenshot below). The bean content can then be placed around the site just like any other block.

If you'd grant content editors the appropriate Bean permissions, it appears to me that you might be close to a possible solution to what you're looking for.

The video tutorial Drupal Bean module tutorial - using Bean Admin UI provides a great introduction to really understand the power of this module, and the kind of things you can do with it (by only using site building techniques, no custom coding involved). It also shows how the Bean module transforms Drupal blocks into fieldable entities.

PS: This module only started as of D7, and is already integrated in core in D8 ...


Don't show latest content on frontpage How do I make it so Drupal doesn't automatically show latest content on frontpage?

One way -- possibly the easiest way -- is to create a page containing whatever you want to be displayed on the home page, then going to www.yoursite.com/?q=admin/config/system/site-information if you're using Drupal 7 (or www.yoursite.com/?q=admin/settings/site-information if you're using Drupal 6), and then changing Default front page from node to node/1 (assuming the page you created was normally located at www.example.com/node/1).


Finding out the machine name of a field when using Views When using Views, I always use fields instead of content. But I noticed that Views does not show the machine name of a field and it only assumes that you already know it. Is there some other way to find out the machine name?

Knowing the machine name lets me access the field directly like so

print $fields['machine_name_here']->content;

Go to the settings page of a view, and click on "Theme information"; then you look at the IDs of each field.  For example, if "Theme information" shown this information, then "last_comment_name" would be your machine name.

  Field Node: Last comment author (ID: last_comment_name):


How to update to jQuery v1.11.1? I'm trying to implement a full screen bootstrap carousel base on this tutorial. He mention to use the jQuery version 1.11.1. And I was wondering what is the best way to upgrade to this version. I'm currently using the jquery_update module but this module does not have the ability to upgrade to jQuery version 1.11.1.

I believe that I can use the CDN by pasting the below code in the my page template.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

But I'm looking for the best practice to insert this jQuery version 1.11.1 on my Drupal site ?

In 2012 a similar question was ask "How do I update jQuery to the latest version I can download?" and one of the solution was to use the module [jQuery Multi] to have different version of jQuery.4

Anyway what it the best method to update jQuery v1.11.1 ?

Use the module Jquery Update:

  Upgrades the version of jQuery in Drupal core to a newer version of
  jQuery.

For 1.11, I believe you will need to use the DEV version, and take a look at this item in the Issue Queue for updating to that version.


Uploaded images classified as files rather than under the media tab In Drupal 8 if you go to admin/content there is a tab for Files and a tab for media.

I believe it is the media entity browser what distinguishes what area an uploaded file will be placed, but I could be wrong on this.

My question is, as well as that, is there an easy way to move files which have been uploaded and placed under the files tab by accident into the media tab without having to re-upload them all?

Thanks for any help on this

Files tab is a view you can add filter by editing this view and based on your filter they can be removed from files tab. Then you can again work on filter of Media tab so that they can display under media tab.

It is up to you what filter criteria you have to move them from one tab to another tab.


How do I access the Drupal class from a standalone PHP file? How do I use the \Drupal class in an standalone PHP file?

You can make use of drush php-script command.

drush scr /path/to/file.php


Feature stuck on Overridden - "Overrides" column empty, "Default" not I have a feature which is constantly stuck at overriden, no matter how times I try to revert or re-create it. I have gone through the standard checklist, including uninstalling and reinstalling, and checking the correct includes are present in .info file and .module file.

On the "Review Overrides" panel, however, I have the attached screenshot. Noticed that the default contains an array full of field settings, but the overrides just contains FALSE:

It would seem that my database doesn't contain this info when it should, and refuses to take it from the Feature?

UPDATE:

I checked the .info file and they seemed all in place; however I suspect that the second cause indicated by the accepted answer below could be the problem. There are currently two modules that remain in a persistent "Overidden" state, and they both share: "CTOOLS EXPORT API -> context:context:3" and "FEATURES_API -> api:1". On initial investigation it would seem that these two items are inherent in the feature, although perhaps I could remove the CTOOLS EXPORT API item by removing the ctools dependency? Argh...

There's two possible reasons for this that I can think of: one is that the .info file for your feature is out of step with the other files. This can happen when you are creating or updating a feature and you don't wait for the little animated timer gif to stop before clicking on another option. It occasionally happens for other reasons, such if you do a git merge automatically with changes from another developer.

To fix this, you generally need to go through your .info file one item at a time and check it corresponds to the other files, so there are no items in any of those files that are not in the .info.

The other reason is if two features overlap in some way. If you have the same configuration item in two features, one of them will usually fail to revert. You may need to refactor your features to prevent this.


Add active class to link  using l() Seems so elementary but how does one get the active state onto the
 of a link when manually using the l() function?

<?php print l('Hapiness','my/hapiness/complete', array('attributes' => array(), 'html' => FALSE)); ?>

The above of course outputs the link in a list item with an active class on the link if the page is current, but how do I get that class onto the
?

You can't. The l() function is only responsible for rendering the HTML link, it has no concept of the tag it's being wrapped in (or indeed if it's even being wrapped in another tag at all).

The simple answer based on your question is to add it manually:

<?php print l('Hapiness','my/hapiness/complete', array('attributes' => array(), 'html' => FALSE)); ?>


Best way of translating fixed text in Drupal 7 I am using t() with context to translate strings for a multilingual site. I would need a user to translate all language strings, but she/he does not need to know Drupal, just will feel an Excel. The problem is that I must provide the original string, the context, and the URL where it appears, and I do not know how to extract them from the database, as the string is stored as a BLOB. I am using this trick of function but still do not get the URL. Any help will be appreciated.

In the function I am copying and pasting all t() ocurrences that I have added in modules, template.php, etc.

function My_Module_list_translations(){
    $translation[] = t2('All', array(), array('context' => 'listado_sabias'));
    $translation[] = t2('Write one or more words', array(), array('context' => 'formulario_noticias'));
    $translation[] = t2('CATALOGUE', array(), array('context' => 'menu-personalizado'));

    echo "
";
    foreach($traduccion as $value){
        echo '
' . $value["contexto"] . '	' .  $value["es"]  . '	' .  $value["en"]  . '
';
    } // foreach
    echo "
";
} // function

function t2($string, $empty, $context){
    $array_dev["contexto"] = $context["context"];
    $array_dev["es"] =  t($string, array(), array('context' => $context["context"] , 'langcode' => 'es'        ));
    $array_dev["en"] =  t($string, array(), array('context' => $context["context"] , 'langcode' => 'en'
       ));
    return $array_dev;
} // function

I would recommend looking at the String Overrides Advanced module it allows your Users to search for strings to translate into other languages using a friendly table, which it looks like you're trying to make yourself.

You're providing context here but the context you provide is not really the purpose of context. Context should describe the context of the string or word to help in the translation (not simply the place on the website the string shows up -- which is largely meaningless). An example of a context is:
https://api.drupal.org/comment/44448#comment-44448

which shows "Order" is a verb and not to be confused with a Noun for "drupal Commerce Order".

Note: I speak and write English and Spanish, when you write PHP code your php code should be in 1 language and not a mix of languages to be clear to developer(s) what you're code says. You shouldn't need to be bilingual to work on a piece of code. It makes your code needlessly complicated.


Migrate content from drupal8 to drupal8 programmatically with Node::load and Node::create Basicly I want to migrate content from one drupal8 instance to another. they are mostly identical with some small changes.

first step is to migrate the content type via drush gen module module and drupal-console drupal config:export:content:type

then i export the content type via script:

<?PHP
define('DRUPAL_DIR', __DIR__ . "/web");

use Drupal\Core\DrupalKernel;
use Symfony\Component\HttpFoundation\Request;

require_once DRUPAL_DIR . '/core/includes/database.inc';
require_once DRUPAL_DIR . '/core/includes/schema.inc';
$autoloader = require_once DRUPAL_DIR . '/autoload.php';

$request = Request::createFromGlobals();

$kernel = DrupalKernel::createFromRequest($request, $autoloader, 'prod');
$kernel->boot();
$kernel->prepareLegacyRequest($request);

use Drupal\node\Entity\Node;
use Drupal\Component\Serialization;
$serializer = \Drupal::service('serializer');

echo "Node Export Starting... \n\n";

// Nodes
$node_ids = \Drupal::entityQuery('node')->condition('type', 'content-type')->execute();
echo count($node_ids);
$single_nodes =  \Drupal\node\Entity\Node::loadMultiple($node_ids);
$data = $serializer->serialize($single_nodes, 'json');
file_put_contents('nodes.json', $data);

i serialize it and write it into a file.

on the new page I install the exported module to receive all fields for the content type + dependencies and so on.

if I try now to run my importer script i get serveral errors that the (exported) nodes can not be created.

 $json = json_decode(file_get_contents(__DIR__ . "/import/nodes.json"));
foreach ($json as $nid => $nodeImport) {
    $node = Node::create($nodeImport);
    $node->save();
}

Node::create() doesnt seems to accept whole exported/loaded NodeArrays nor casted arrays like (array)$nodeImport

Am I missing something?

You might consider using Migrate module for this task. For pulling entities from external database use Drupal 8 migration module.


Deployment of full database dump still causes error I want to deploy my local DB to a staging server.

The local DB dump was exported with all tables. Including the "cache_" prefix table structures with no data exported.

After deployed to staging (with Jenkins), I got exceptions like Plugin missing error or field missing.

  Uncaught PHP Exception RuntimeException: "Unable to determine class for field type 'daterange' found in the 'field.storage.node.field_date_range' configuration" at /var/www/html/lightnest/releases/20200227152907/docroot/core/modules/field/src/FieldStorageConfigStorage.php line 164

I cannot run update.php or rebuild.php because this error will popup again.
I also cannot run drush commands as I have no direct access to the staging.

Am I missing anything?

You can run Drush commands remotely from another server using methods such as site aliases.
https://docs.drush.org/en/master/usage/#site-aliases

So you might be able to run registry rebuild https://www.drupal.org/project/registry_rebuild

which sometimes helps with class errors.


Use sass variable and mixins from base theme in sub theme I need some help regarding sub theming with sass. The sub theme setup is as follows :

There is a base theme base which has sass variables and mixins defined.
I run grunt and compile the sass.
There is a subtheme of base called microsite with similar sass structure as base but no styles as presently it uses only the base styles.

Q. How do I use the sass variables and mixins defined in base theme inside microsite theme?

Eg - 1 : Inheriting the base color palette.

I have a color palette defined under base theme with my color variables. themes/custom/base/sass/core/variables/_palette.scss

I want to use these palette variables in defining styles in my microsite subtheme at themes/custom/microsite/sass/base/color/_buttons.scss.

Eg - 2 : Inheriting the base gradient mixin.

I have a linear-gradient mixin defined under base theme at themes/custom/base/sass/core/abstractions/_linear-gradient.scss

I want to use this mixin in defining styles in my microsite subtheme at themes/custom/microsite/sass/base/color/_buttons.scss.

There's no special process because it's Drupal or sub/parent theme relationships, just import what you need. E.g.

@import '../../../../base/sass/core/abstractions/_linear-gradient.scss';


File field upload in modal/dialog I have a custom content type with file field as one of the fields. For theming/UI purposes I should make this file field as clickable button. And only when user clicks on it, he/she gets modal window with upload/file browse or file name if there already is a file uploaded.

I've accomplished this with using jQuery Update module and from there with help of jQurey UI Dialog (https://jqueryui.com/dialog/) and custom module with JS code:

(function ($) {
Drupal.behaviors.module_custom = {
attach: function (context, settings) {
//appending button
var $inputButton = $('<input type="button" value="Līgums" id="open_modal" />');
$inputButton.insertAfter($(".field-name-field-file"));
//hiding file upload wrapper div
$('.field-name-field-file').hide();

//initializing modal dialog window
$( ".field-name-field-file" ).dialog({
  autoOpen: false,
  show: {
    effect: "blind",
    duration: 1000
  },
  hide: {
    effect: "explode",
    duration: 1000
  },
  width: 500
});

//launching modal dialog when button is clicked
$( "#open_modal" ).click(function() {
  $( ".field-name-field-file" ).dialog( "open" );
});

  });

}
  };
    }(jQuery));

This all works from UI/theming perspective but it brakes file upload. When modal window opens and file is uploaded I got error "An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (8 MB) that this server supports." no matter how small file is (event if it is 1 KB). I suppose this issue is related how AJAX upload is handled. Any ideas what is issue here?

For sure this is due to some problem with your sever setting, contact your web hosting company and talk with them regarding the issue.

It could be due to ModSecurity that scans incoming http requests for any malicious scripts. There may be an issue with the script causing mod_security to stop the script. ModSecurity is an is an open sourceweb application firewall Apache module, which help in providing an external security layer that increases security, and help in preventing attacks.

In the event that mod_security is causing the error, you will need to contact tech support to have them look at the logs to see what is exactly causing mod_security to flag the uploaded file. You may need to Disable mod_security via cPanel Modsec Manager on your specific domain if there is no work around. Otherwise, tech support will need do this for you.

The other reason could be the size you are allow to upload that can be change in your server setting. It is also important to check apache max_execution_time.

If you have control over your server then you can try to change your php file

post_max_size = 128M upload_max_filesize = 32M max_execution_time = 5000
max_input_time = 5000
memory_limit = 1000M

Source

If not solved then Other Reason May be :
Check the .htaccess or settings.php for conflicting Code
Edit the .htaccess file to see if there are any overrides in the code. Some server configurations allow .htaccess settings to override your file upload size. Comment any code that controls the files upload size and save the changes.

The settings.php file also can hold overrides for the file upload size. Edit the settings.php directly on the server or you can change the settings through the Drupal dashboard by going to Administer > Site configuration > File uploads and updating the settings from there.


How to create a menu navigation on a Views page that uses contextual filters? I have a projects content type and I want there to be a menu for each project that would have Project Overview, Project Details & Team Members.

So in Views I created a page at projects/ which would be the overview page that filters based on project title.

Then I have a page at projects/%/details, and another at projects/%/people.

So how would I either create a menu that I could put in the sidebar or somewhere that would work for any project, or maybe use tabs instead? Whichever is fine, but if you could teach me how to do both that would be cool.

I tried using the menu settings under Page Settings in Views, but I couldn't get it to work.

Open the view where you had created the pages at projects/%/details or projects/%/people.

Under page settings where you had the path filled, add these additional settings to create a Menu tab or a Contextual link.

Go to Menu and select Menu tab as the type and fill in the title. If you want the link to be present as a contextual link, check the box which says context.

You can also set access permissions on who can see this tab depending upon the permission type you had selected.


Create user profile using content type or add additional fields to the default registration form I am good enough to build an entire drupal 7 website but my problem goes below:

I am in the process of building a very simple drupal website for all volunteers in my country.
So every volunteer will have a profile page on the website where volunteers can search for each other, send emails to each others and even send sms to each other in addition to other basic features.

And so to create such website there is two way that i am little bit confuse which one to use: (any suggestion please)

Method 1:
Add any additional field such as city ,district, bio, age, birtbday, phone number, profile picture, blood type, education degree, languages spoken.... directly inside the registration form by going to account settings in configuration page.
And so i will use the "User" entity to pull out the information required for the creation of blocks, views....

Method 2:
Let the volunteer register to the website by using the default registration form where only email address and password are required.
And after completion of registration the user will be redirected to create a node of content type "Volunteer" where all the required fields mentioned above will be available.
Also i will use the node limit module to limit the creation of 1 node per content type per user.
And so i will use the "Volunteer" content type to pull out the information requited for the creation of blocks, views....

Which one is the best to go with ?
Are there any limitation for any of the above method in case i need to expand the website in the futur ?

Please note that i know how to do everything mentioned above, only i need suggestion about what method is the best and why ?

Thank you,

I think there are two more possibilities. One, use social media integration to get as much information as possible to pre-fill the profile. Two, use panels to create a form that will collect a minimal number of required fields from your user profile. Overall, reduce the number of required fields and let users fill out their profiles gradually, with a little nudge from your site. If you ask them to fill out a large number of fields just to get started you may end up with a high form abandonment rate.

I would avoid creating a new Volunteer content type. It may just be my opinion, but I like to follow Occam's razor and avoid the proliferation of entities.


File Upload, overwriting every time I am using the Migrate module, and I need to upload a CSV file before every migration run.  I've created a module that allows me to upload a file.

My first step was to make sure I had the logic correct for overwriting a file, so I have the following code:

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

if ($form_id == 'migrate_ui_dashboard_form') {
  $form['fldset'] = array(
   "#type"        => "fieldset",
   "#title"       => "CSV to Import",
   "#collapsible" => "TRUE",
   "#collapsed"   => "FALSE",
   "#weight"      => "-98",
 );
$form['fldset']['csv_file'] = array(
   "#type"   => 'managed_file',
   "#title"  => t('Choose a file'),
   "#upload_location" => 'private://user_migration',
   "#upload_validators" => array(
      "file_validate_extensions" => array('csv'),
   ),

 );

$form['fldset']['actions'] = array(
   "#type"    => 'submit',
   "#value"   => t('Uploady'),

 );

}

return $form;

}

That creates the file upload widget etc.

The following is what I do upon form submission:

 function migrate_htmlfiles_form_submit($form, &$form_state) {

  $file = file_load($form_state['values']['csv_file']);
  //TODO: rename file to user_migrate.csv
  $file->status = FILE_STATUS_PERMANENT;
  $file->replace = FILE_EXISTS_REPLACE;
  file_save($file);
}

The file uploads fine, and then when I refresh the form, and do another upload, that works but the file is not overwritten, but is incremented.

What you're describing is the expected behaviour for a managed_file widget. If you dig through the functions you eventually get to file_managed_file_save_upload(), which is responsible for actually saving the file.

That function calls file_save_upload() without the 4th parameter, which is $replace.

Since the default for that parameter is FILE_EXISTS_RENAME, file_save_upload() has no choice but to use in that context.

When you refresh the page, the original file that was uploaded has not been cleared up; in fact it won't be until the temp file cron job runs. So Drupal is "correctly" ensuring that the original file doesn't exist, because the managed file field is telling it to rename, not replace, files.


On the 404 page, look for an XML file and read it in. If it doesn't exist, display 404 message I am wondered if the following is possible: I need to display some XML data on the fly; these should only be created temporarily (ie not nodes or entries in a database and therefore not readable by Google). The URLs for these and the other XML files I import into nodes have the same structure, generated by a third-party system; so I need the page to be generated if the node doesn't exist (so I guess on the 404 page you will be redirected to).

I thought something like this might work. Any pointers?

<?php
  $hdr = $_SERVER['HTTP_REFERER']; //Format of http://example.com/item/######
  $idnr =  substr($hdr, -6);
  $file = simplexml_load_file('http://api.service.com/customerID/item/'.$idnr);

  if (file_exists($file)) {
    // Put my XML fields here.
  } else {
    //Echo 404 message
  }
?>

EDIT After reading Alfred Armstrong's and develkar's answers I guess what I could think about is something like this: In the module_menu callback function: Look for a node with that URL alias. If that doesn't exist, load the XML. If THAT doesn't exist, return a 404.

Drupal let you specify custom 403 and 404 error pages:

admin->settings->error-reporting

Your custom error page may be PHP, so you can place any logic in it you want, including the one you suggest.

Edit: As already stated by develkar, if you do not want this indexed by Google or other search engines, you disallow it in you robots.txt.


Changing the initial value of an exposed view filter I'm trying to programmatically set the starting value of an exposed view filter (so that it initially loads the view with data matching that value).

I've managed to change the filter field value with this code in a views_pre_build hook (doesn't work in pre_execute or pre_render):

$view->display[$view->current_display]->handler->handlers['filter']['field_year_value']->value['value'] = $year;

But the view still loads with the value from the view filter's config value.  How can I get my change reflected in the view when it loads?

For some reason a site I was adding a feature to had a years taxonomy vocabulary, with a number of terms, one for each year in a range. So I wanted to auto set the exposed filter to the current year, but to do so needed to set the filter value with the tid of the right term.

I implement hook_views_query_alter().

check if the view is the right name and if the view doesn't have any user selected input (this view only had one filter).

You have to alter the value for the filter's query value

You have to unset the exposed filter area markup and regenerate it.

 function mymodule_views_query_alter(&$view, &$query) {

      if($view->name == 'executive_committee' && empty($view->exposed_input)) {
        $current_year = date('Y');
        // find year term id
        $term_query = new EntityFieldQuery();
        $tids = $term_query->entityCondition('entity_type', 'taxonomy_term')
          ->propertyCondition('name', $current_year)
          ->propertyCondition('vid', 3)
          ->execute();

        if(!empty($tids['taxonomy_term'])) {
          $tids = array_keys($tids['taxonomy_term']);
          $current_year_tid = reset($tids);

          // set values to the views object and query objet
          $view->exposed_data['field_year_tid'] = $current_year_tid;
          unset($view->exposed_widgets);
          $view->exposed_raw_input['field_year_tid'] = $current_year_tid;
          $query->where[1]['conditions'][2]['value'] = $current_year_tid;
          // rebuild the exposed form
          $form_state = array(
            'view' => $view,
            'display' => $view->display_handler->display,
            'exposed_form_plugin' => $view->display_handler->get_plugin('exposed_form'),
            'method' => 'get',
            'rerender' => TRUE,
            'no_redirect' => TRUE,
            'always_process' => TRUE, // This is important for handle the form status.
          );
          $form = drupal_build_form('views_exposed_form', $form_state);
          $form['field_year_tid']['#value'] = $current_year_tid;
          $view->exposed_widgets = drupal_render($form);

        }

      }
    }


How to attach a JS library to page or block with #attached? I have seen something like the following document for forms:

$form['myelement']['#attached']['libraries_load'][] = array('myAwesomeLibrary');

However, this does not work in render arrays for pages or blocks.  At least, not in Drupal 7. When attaching a JS library to a render array in a page or block, should I use the 'libraries_load' or 'library' key within the '#attached' array?  Neither seem to work.

Of course, it's possible to use the 'js' key along with libraries_get_path, but I'm not sure that's best practice for Drupal 7, and it doesn't really take advantage of the path in hook_libraries_info.

This might be a simple case of misunderstanding. The difference between libraries_load and library #attached keys can be confusing.

['#attached']['libraries_load'] is for libraries defined through hook_libraries_info which is in turn a part of the Libraries API module. If a module has defined a hook hook_libraries_info but your installation doesn't have the Libraries API module installed, then that library will never load. The libraries_load key of #attached will not fire for the same reason. Ideally though, this module with the hook_libraries_info should have a dependency on the Libraries API module if it was written correctly.

['#attached']['library'] is for libraries defined through drupal core library api hook_library. This should always work without any additional modules, provided you've defined a hook_library in your module (and not hook_libraries_info)

Hope this helps you get a clearer idea of what's exactly wrong. You can't have these interchanging, and just trying libraries_load or library randomly to see if they work. Both require a certain prerequisite (see above) to function correctly.


User's homepage depending on their organic group Is there a way to set the homepage of a user depending on their organic group. So when a user clicks the site logo, they will be redirected to something like /test-page/%group. When I created a panel page it specified that I could not use % which would have been perfect.

I am using Drupal 7.

There is a module (Frontpage) that allows to set a different front page for anonymous users, and authenticated users.

The module allows third-party modules to alter the page to which the users are instead redirected, or to alter the structure array used to render the page.

As alternative, you can create a custom module that, using code similar to the one used by Frontpage, redirect users to a specific page, basing on specific criteria.

The module should implement hook_menu() and associate a menu callback to, for example, http://example.com/frontpage; the page callback of that menu item should simply verify a condition is verified, and then redirect the users to a specific URL.

The code skeleton could be something similar to the following:

/**
 * Implements hook_menu().
 */
function mymodule_menu() {
  $items = array();

  $items['frontpage'] = array(
    'page callback' => 'mymodule_frontpage_view',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

function mymodule_frontpage_view() {
  // These variables can be useful to redirect the users
  // to specific pages, basing on the language currently set for
  // the content, or on the fact the user is logged in.
  $langcode = $GLOBALS['language_content']->language;
  $logged_in = user_is_logged_in();
  $usergroups = og_get_groups_by_user($user);
  $group = og_load($gid);
  $groupnode = $group->etid;
  $redirectpath = 'node/'.$groupnode->nid;
  drupal_goto($redirectpath);

}


Can I change the post's created date format? Can I change the date format without touch the code level? I only have admin access. Tried to search for solution but all of them are code level.

Yes you can. As an admin you can access "Administration » Configuration » Regional and language » Date and time", where you can define date formats and and display types. The latter you can then use in the "Manage display" part of an entities field configuration, or in the view display options of date fields.

Edit: If that doesn't work (which it doesn't for default node displays) and adding preprocess code is not an option (as the OP declares), another option is to hide the "created by" output (content type settings) and adding an own date field that you can fully control. This one will not, out of itself, be set to the current date when creating a node. Though, that might be an option in the field settings, have to look.

Anyway, code level change would be trivial, but without touching code, this is one of those Drupal WTF moments.


How to handle a Drupal core change that have an impact in the next release of a contrib module? Reading the Drupal Changes records I found that drupal_get_message() and drupal_set_message() replaced by Messenger service so lets suppose that I have a module that use the drupal_get_message() function and I want to replace it with the new Messenger service. If I do it my module only will works starting from Drupal Core >= 8.5.

So, in this point what is the correct way to produce the next module release?

Should I restrict the next release to a specific Core version adding a comment in the release notes or should I create a new branch (lets says 8.x-2.x) to implement this changes and have two module versions like 8.x-1.x (working for Core < 8.5) and 8.x-2.x (working for Core >= 8.5)?

There is no need for a new branch in your module as long as your own API doesn't change IMHO. The version definition will prevent that users update too early.
There is also no need to continue providing versions compatible with old core versions, they are no longer supported.

If it's just about deprecated usages, there's no reason to hurry, you can easily wait a few month/next core minor before starting to use it to give your users time to update. All those deprecated functions will only be removed in the 9.x branch, so you have plenty of time to update. It's different if core broke something in your module and you're forced to update asap or if there is a completely new API that you'd want to use.

See also last paragraph on PHP 7.1 requirement for Doctrine packages: Their PHP version dependency is similar to your Drupal core dependency.


Spanish Version Showing English In View I inherited maintenance of a Drupal 7 site and I don't have much experience with drupal but there is a content type called 'Materials' that we would like to be able to view it's listing representation in different languages.  So /materials lists everything in English, but /es/materials should list everything in Spanish but it has both Spanish and English entries.  How can I eliminate the English entries so only Spanish ones will show.  And, why are English entries displaying in the first place?

Here is the language config for the Materials content type, followed by the Materials Views configuration:

Use the Internationalizations Views module, which extends the i18n module with multilingual support for views.

Also, to make view results correspond to the language switcher, add a filter for Content Translation: User's Current Language, which is the language that an authenticated user has set in the user settings (it is NOT the same as the current browser language or the site language).

If no option for the User's Current Language is available in the filter criteria form, then verify your configuration at Configuration -> Languages -> detection and selection: The order should be URL, Default, User and not something like Default, URL, User (as mentioned also in https://www.drupal.org/node/1701854#comment-6279474).

Note: The Internationalizations Views module only has an alfa version for D7, but right now there are over 41K users using this version. Therefor I think "DEV" is not a valid release qualifier for that version anymore, because +41K users can't be wrong, right?


Problems upgrading to PHP 5.5 I upgraded my server from php 5.3 to php 5.5 based on this link.
I disabled the apc.so in php.ini, disabled apc module.

Drupal 7 multi-site.
/home/default/public_html is the root folder for
/home/domain_1/public_html,
/home/domain_2/public_html,
/home/domain_3/public_html,
/home/domain_4/public_html

three of these domains work as usual; visitors links all work and admin can log in and administer the three websites

the fourth site reports an error:
visitors cannot see the site - the WOD is really
Fatal error: Call to undefined function apc_delete() in /home/default/public_html/sites/all/modules/apc/drupal_apc_cache.inc on line 289

I cleared bootstrap cache and cleared the variable but to no effect.
drush cc all, drush rr, and drush cron core did not improve this situation.

What else should I look for? Any other suggestions?

What you do when you remove a PHP extension used from a module you installed is uninstalling the module and then removing the PHP extension.
In this case, you also need to do something more: Since you are using the APC module as alternative Drupal cache, you need to remove the lines added to the settings.php files. Probably you will find the following lines.
$conf['cache_backends'][] = 'sites/all/modules/apc/drupal_apc_cache.inc';
$conf['cache_class_cache'] = 'DrupalAPCCache';
$conf['cache_class_cache_bootstrap'] = 'DrupalAPCCache';

Alternatively, you could find the following ones.
$conf['cache_backends'][] = 'sites/all/modules/apc/drupal_apc_cache.inc';
$conf['cache_default_class'] = 'DrupalAPCCache'

In any case, you need to remove the $conf['cache_backends'][] = 'sites/all/modules/apc/drupal_apc_cache.inc'; line, and any line in settings.php that references the DrupalAPCCache class.
References

The README file for the APC module

Side note
This is one of few cases where disabling a module, or uninstalling it without deleting its files, doesn't stop Drupal from using it. In fact, Drupal uses the following code.
  // Allow specifying special cache handlers in settings.php, like
  // using memcached or files for storing cache information.
  require_once DRUPAL_ROOT . '/includes/cache.inc';
  foreach (variable_get('cache_backends', array()) as $include) {
    require_once DRUPAL_ROOT . '/' . $include;
  }

It doesn't check the files are for a not enabled or not installed module. As long as it finds the files, it uses them. If then the code is using a non existing function (as in your case), it will raise a runtime error.


Define permissions for Actions? function custom_mod_action_info() {
  return array(
    'custom_mod_delete_user_cats' => array(
      'label' => t('Delete a users cats'),
      'type' => 'user',
      'configurable' => FALSE,
      'triggers' => array('any'),
    ),
  );
}

This action is later used as VBO in a View.

I've defined an action like above in a custom module. How can I set some permissions so only users with a specific role can run this action?

For D7, I can see two answer depending on what behaviour you prefer:

VBO has a sub-module action permissions.  Enable this and it creates a permission for each action - see module page.  If the user lacks permission then the action is not even available for them.
If you need more granular permission that depends on the entity, then the "function which performs the action" can enforce it.  For example see views_bulk_operations_user_roles_action.  If the user lacks permission for some of the entities then the action won't take effect for those entities.  However there is typically not really any feedback to tell the user.

For D8, there is ActionInterface::access, see docs.


Move template function to custom module I have a function in my template.php file but I've now created a module that manages these particular tasks so I want to move the function over.

This is what I have in my template.php file:

function MYTHEME_menu_tree__main_menu($variables){
    return '
' . $variables['tree'] . '
';
}

This works file but when I move it into my custom module (mymodule.module file) if doesn't work.

I've tried this:

function MYMODULE_menu_tree__main_menu($variables){
    return '
' . $variables['tree'] . '
';
}

and this:

function MYMODULE_preprocess_menu_tree__main_menu($variables){
    return '
' . $variables['tree'] . '
';
}

but not happening.

Can anyone see where i'm going wrong? or am I way off on this and it can't be done like this?

hook_theme_registry_alter() allows a module to step in to override registered theme callback functions. In your case, you're looking to override the menu_tree__main_menu entry and replace its callback function:

/**
 * Implements hook_theme_registry_alter().
 */
function MYMODULE_theme_registry_alter(&$theme_registry) {
  if ($theme_registry['menu_tree__main_menu']) {
    // @TODO: override
    // $theme_registry['menu_tree__main_menu']['function']
    // $theme_registry['menu_tree__main_menu']['type']
    // $theme_registry['menu_tree__main_menu']['theme path']
    // for your new module theme function
  }
}

See the Return Value section of hook_theme() for more information on what a theme registry entry contains.


Is there a module for saving current block setup? Would be handy to be able to save the current block setup, so after one changes around blocks, it could be reset to a previous state.

You can try either of these modules (quotes included are from their project pages):

Features Extra:

  ... provides faux exportables (via Features) of several site-building components.

  To export a block, install FE Block, edit your block, give it a "machine name," export it with Features. You can export block settings (region settings, visibility settings, ...) of any block, and the content of blocks created with the Block module from Drupal core.
  The D7 version supports the Block Class, i18n block and Block Cache Alter modules.

Boxes:

  ... a reimplementation of the custom blocks (boxes) that the core block module provides. It is a proof of concept for what a re-worked block module could do.

  The module assumes that custom blocks are configuration, and not content. This means that it is a reasonable action to ask for all blocks at one time, this is in fact exactly what the core block module does.


Can I only traverse a DatabaseConnection object once? I have a database query result, and I want to go through the records twice. However, the second time I go through it, nothing happens. It seems you can only iterate through this object once?

My code looks like this:

$query = db_select( ... );
$result = $query->execute();
if ( $result->rowCount() > 0 ) {
  foreach ( $result as $record ) {
    ... processing happens here
  }
}

// now loop through again, to mark records as processed, upon success.
foreach ( $result as $record ) {
  ... additional processing here
}

And the additional processing doesn't happen.

As a work around, I added $records = $result->fetchAllKeyed(); before the initial processing, and then the result object had no records!

I found nothing in the documentation about resetting the object or anything.

Is this how the object works? Can I reset the iterator again, or must I fetch the keys initially to have an array that I can iterate over many times?

This is expected behaviour; Drupal wraps around PDO and this is how PDO query functions behave also. Have a look at Is it possible to rewind a PDO result for a more in-depth discussion.

The standard way to get around this would be to use either fetchAllKeyed() as you've mentioned, or fetchAll() instead. The latter will produce an array of object results that can be iterated over as many times as you want.

$query = db_select( ... );
$result = $query->execute();
if ( $result->rowCount() > 0 ) {
  $data = $result->fetchAll();

  foreach ($data as $item) {
    // do something with data
  }

  foreach ($data as $item) {
    // do something with data again
  }
}


Uncaught PHP Exception: Query tagged for node access but there is no node table, specify the base_table using meta data Can anyone give me a hint where this error could come from?

When a user tries to access a specific node in the login-area of my Drupal 8 website, he randomly gets a white screen with the message "The website encountered an unexpected error. Please try again later."

I look at the apache error logs on the server and see the following error message:

  Uncaught PHP Exception Exception: "Query tagged for node access but there is no node table, specify the base_table using meta data." at /mywebsite.com/html_d8tst/core/modules/node/node.module line 1107, referer: http://mywebsite.com/user/251

node.module line 1107 says:

// Bail out if the base table is missing.
if (!$base_table) {
  throw new Exception(t('Query tagged for node access but there is no node table, specify the base_table using meta data.'));
}

I don't understand what exactly goes wrong when the error occurs. And unfortunately, I don't even see any pattern in which use cases the error occurs.

It's only on this specific node. Sometimes it works, sometimes not. The node is of a specific content type which only logged-in users have access to. It contains several views, some of them are user-specific.

This https://www.drupal.org/project/drupal/issues/2664748 seemed to be a similar problem, but the post was about Drupal 8.0.x-dev and was fixed. I'm working with Drupal 8.6.13

I would be glad of any hints!

For anyone else running into this, I was able to get it to go away by checking all my blocks' permissions, especially the ones related to user information, and for me, the culprit was the User Activity Log block. Once I added the Visibility setting that only authenticated users had access to the block, the error went away.
Looks like the Drupal devs aren't having this module fail gracefully for unauthenticated users.


Drupal 7 Private Files - How to override security in custom module Is there a hook to override access to images stored in the private file system when theme_image_style is used to output the image?

Image styles are served from the public file system, and there's no hook to control access to public files, so unfortunately not.

There's no simple solution, but there is a working solution: Image Style Access

  Allows granular access control to images and image style derivatives.

I've had a quick look through the code and you won't find a better starting point than that module. Quite a straightforward idea actually, it introduces a menu router item for each ./styles/[image-style] folder, controlled by an access callback.

It does mean you now have the overhead of a full bootstrap for all image styles, but since you want to check access based on the DB there's no other way to do it.


A way to have an unchecked "end date" input field? The date module gives the possiblity to collect an end date.
The thing is, in the node creation form, 'Show end date' is checked by default and the date calendar popup field is displayed.

I would like to have the opposite scenario.
With the End date field hidden by default, and it would only appear if we check the 'Show end date' checkbox.

Thanks to anyone who can help with this

We can do this easily using hook_form_alter hook, by setting #checked value of checkbox to FALSE. Since the date module doesn't add both fields at initial form load, we've to add #after_build to form where we can modify #checked value of checkbox (i.e. show_todate field) in form.

Below is the sample code for hiding the end date in date field. For this we've to add a Date Type field (field name as field_date) with ability to add end date in article Content Type. After which we've to implement hook_form_alter and checked if current form is add new article form to make sure we don't override node edit field value. And then added #after_build to add article form. Which then set the #checked value to FALSE.

/**
 * Implements hook_form_alter().
 */
function [MODULE_NAME]_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'article_node_form':
      if (empty($form['nid']['#value'])) {
        $form['#after_build'][] = '_modify_end_date_form';
      }
      break;
  }
}

/**
 * Proxy function to call _modify_end_date_form_after_build().
 * @param type $form
 * @param type $form_state
 * @return void
 */
function _modify_end_date_form($form, &$form_state) {
  return _modify_end_date_form_after_build($form, $form_state);
}

/**
 * After_build callback for Article Content Type.
 * @param type $form
 * @param type $form_state
 * @return void
 */
function _modify_end_date_form_after_build($form, &$form_state) {
  $form['field_date'][LANGUAGE_NONE][0]['show_todate']['#checked'] = FALSE;
  // $form['field_date'][LANGUAGE_NONE][0]['show_todate']['#value'] = FALSE;
  return $form;
}


How to generate a stack trace upon errors I am sysadmin trying to debug a Drupal site. In my server logs I can see Drupal making the same requests again and again to our Solr instance until PHP eventually runs out memory, and Apache returns a 500 error.

How can I configure Drupal to log a stack trace somewhere on the disk?

You can use the Devel module, and select one of the "Krumo Backtrace" options it provides in its configuration page at admin/config/development/devel.

Make sure to visit admin/config/development/logging and select "Errors and Warnings" or "All Messages". If you have the Syslog module, or any other logging module enabled, you may need to disable it and enable the Dblog module.


multilingual blocks in drupal6 I use drupal 6 . I have some menus in the site. I 'm going to add other language support to my website. I know how to create multilingual content (nodes) but I don't know how to do it with menus like navigation menus.

would you help me?

If you install the Internationalization suite of modules, you can enable the Internationalization blocks module (called Translate Blocks).

This will allow you to assign a language (or languages) to each block.

This way, you can create a menu for each language and then assign a language to each menu block.

Note that there is also a Translate Menu module in the Internationalization suite.  This module allows you to create one menu with items of multiple languages.  However, this can get confusing and complicated very fast and is often difficult to maintain over time.  For this reason, most people create separate menus for each language as described above.


how to access node variables in region preprocess function? I have variable in the node preprocessor:

function theme_preprocess_node(&$vars , $hook) {
    $vars['default_product_price'] = $vars['elements']['product:commerce_price'][0]['#markup'];
}

Currently, the variable 'default_product_price' is not available in the region--sidebar-second.tpl.php file. How would i make this variable available in region template file or page template file? Thank You

The template files for nodes and pages don't share any variable; that is true also for their preprocess and process functions.

Assuming we are talking of a node field implemented with the field API, then what follows applies:

The page preprocess and process functions have access to $variables['node'] which contains the node object, in the case the page is a node page

function mytheme_preprocess_page(&$variables) {
  if (!empty($variables['node'])) {
    $node = $variables['node'];
    // …
  }
}

The function to access the content of a entity field is field_get_items(), which returns its raw content
The function to render a entity field is field_view_value()

The following code should work.

  function mytheme_preprocess_page(&$variables) {
    if (!empty($variables['node'])) {
      $output = '';
      $node = $variables['node'];
      $items = field_get_items('node', $node, 'field name');
      foreach ($items as $item) {
        $field_output = field_view_value('node', $node, 'field name', $item);
        $output .= render($field_output);
      }
      // Set $variables with the value you need.
    }
  }

Unfortunately, $variables['view_mode'] is passed only to the node preprocess/process functions; that value would be helpful to field_view_value(), as its last parameter is the view mode.


How to modify taxonomy term path in the page render array? I'm trying to change the path of a term before it's displayed on a node page. I'm using this preprocess function in template.php:

function bartik_preprocess_node(&$variables) {
    $variables['field_photo_topic']['0']['taxonomy_term']->uri['path'] = 'photo/test';
}

The path won't change, what am I missing? This is the dpm output:

This question makes perfect sense if photo/% and video/% are views.  It might be even better to map taxonomy/term/% to topic/%, and then make a single view with a path topic/%/%, where one argument is the content type and the other is the taxonomy term. However, you may also use the paths you suggest by building two views (or two pages in one view), each with its own path.

On to your main question, though. Changing items in the render array is easy, but it can sometimes be hard to figure out what needs to change and when. It is a general problem with render arrays that sometimes there are shadow copies of info that are available for your reference. Changing these copies does not affect the rendering of the page, because they are only copies of the item that is used to build the actual page.  The problem with the code in your question is that it was altering a copy of the target link; the master information that you need to change to affect page rendering appears somewhere else in the data structure.  You need to adjust the copy that appears inside the 'content' item.

Here is some code that works for a similar content type:

function MYTHEME_preprocess_node(&$vars) {
  if (array_key_exists('content', $vars)) {
    $content = &$vars['content'];
      if (array_key_exists('field_photo_topic', $content)) {
        foreach ($content['field_photo_topic']['#items'] as $index => $info) {
          $tid = $info['tid'];
          $content['field_photo_topic'][$index]['#href'] = 'photos/' . $tid;
        }
      }
  }
}

From here, you can use pathauto to map photos/% to a pleasing URL to your photos + taxonomy term view.


Trying to rewrite url for a custom module with an extra custom variable using PathAuto I needed to create a custom module to show product information. It's a custom module because the data comes from a remote database. This module has a block which I add to a basic page.
(It was my first drupal website from some time ago, and I know it's not the conventional method.)

Now in this module I do a $_get call from a product id in the url. For example if the page is /product?id=50, it will get the product of id 50 and show that information in the block.
Now at request of the client the url needs to look like /product/50 for SEO reasons. Also true for categories for example categories/boots instead of categories/category=boots

I tried using http access file but I can't get it to work. Also see: Drupal does rewrite url but can't load css/themes

Now they suggested to use Pathauto module. So I've installed the module. But it won't create those url's taking the custom variables into account.
Is there a way so I make Pathauto take into account those extra variables needed for my $_get? Or is there a better method?

I've never used this module before, so noob proof advise is appreciated.

You have a 2-step problem.

1) User friendly URLs

Pathauto is the wrong solution. Setting URLs in custom modules is the job of hook_menu.

function mymodule_menu() {
  $items['product'] = array(
    'page callback' => 'mymodule_product_view',
  );
  return $items;
}

function mymodule_product_view($id = 0) {
  //Do database call here for product id = $id
}

Using this simple example, you can visit the page product/50. Drupal will then call the mymodule_product_view function with the second parameter (in this case 50) as the arguement.

2) Creating a block to show product information

What you need to get is the product name or id. If that is already in the url you can use arg(2) assuming your URL is "examples.com/product/50". Here is the api page for Drupals arg function.

Ideally you would then do database calls etc. with this arguement within a custom modules block. You can find out how to create a block in custom code here


How is domain_taxonomy_access module configured? I am trying to use the domain_taxonomy_access module, but I do not know how it is configured.

How I do so that the user of a certain domain can manage their newsletters?

I am trying to implement the solution shown here: https://www.drupal.org/project/domain/issues/558692

Thanks

I have found the solution by myself.

I use domain access with simplenews, i need the Domain Simplenews to,

What you have to do, is go to:

structure / taxonomy / [yourtaxonomynewsletter]

Then edit some term of the taxonomy and at the end of the configuration called Term source domain there is an option to set the domain to the taxonomy.


How to add extra field after caption and title on images Is there a way with Drupal that I can add more fields on the one of caption and title when uploading images?

The file entity module will allow you to add fields to your files (including images) like you would with nodes.

You can then add whatever fieds you like and configure how those fields display use them in views etc.


Disable ajax from exposed form filter only Is it possible to disable the Ajax from the exposed form filter only and not the whole view action [sorting - paging] !?

You can use better exposed filter module for this
Set Use AJAX to Yes under Advanced -> other section
Set Exposed form style to Better Exposed Filters and keep auto submit option disabled in BEF Settings.


Drupal overlay is not working for content links I have installed my own custom theme in Drupal 7.29.
Overlay is not working for my content links such as

http://localhost/node/add#overlay-context=.
http://localhost/node/add
http://localhost/node/add/page
http://localhost/node/add/article

But for other links overlay works just fine

http://localhost/node/add/page#overlay=admin/structure
http://localhost/node/add/page#overlay=admin/structure/block
http://localhost/node/add/page#overlay=admin/structure/types

Overlay Working

Overlay not Working for content links

Please help me solve this problem. Any help is appriciated

thanks

First of all, make sure that the user that is trying to use the overlay has the appropriate permissions to do so (the permission is called: "Access the administrative overlay"). If you are trying to add/edit content as admin, then that's not the problem.

Also, make sure that in admin/appearance page, the option "Use the administration theme when editing or creating content" is selected. Notice, that if a role does not have the permissions to use the administrative theme (or the overlay for that matter), the users with the specific role will be adding/editing content through the default theme of your site.


Custom permissions for unpublished content I'm running in to a problem with my drupal 8 site. I want to give access to unpublished content. I found a solution using a hook.

I want to create a custom module these don't seem to work.

I found this for the unpublished problem:
"View unpublished content" permission for non-author

It looks like a solid solutions for my problems but I can't get them to work. I can enable the modules created, and it doesn't give any errors.

My view_unpub.info.yml file:

name: View Unpublished
type: module
description: 'View Unpublished Content'
package: SVDS
core: 8.x

My view_unpub.module file:

<?php
function view_unpub_permission()
{
    return array(
        'unconditionally view unpublished content' => array(
            'title' => t('Unconditionally View Unpublished Content'),
            'restrict access' => TRUE
        )
    );
}

function view_unpub_node_access($node, $op, $account)
{
// We're only bothered about the 'view' operation at the moment
    if ($op == 'view') {
// If the user has access to our new permission, let 'em at it
        if (user_access('unconditionally view unpublished content', $account)) {
            return NODE_ACCESS_ALLOW;
        }
    }

// For everything else let the system decide.
    return NODE_ACCESS_IGNORE;
}

The code you are showing is not completely ported to Drupal 8. In particular:

hook_permission() is not used anymore from Drupal 8; what you need is describing the module permissions in view_unpub.permissions.yml
user_access() has been removed
Constants like NODE_ACCESS_ALLOW have been removed

As example of hook_node_access() implementation, see node_node_access(), which also shows what replaces user_access() in Drupal 8.

function node_node_access(NodeInterface $node, $op, $account) {
  $type = $node->bundle();
  switch ($op) {
    case 'create':
      return AccessResult::allowedIfHasPermission($account, 'create ' . $type . ' content');
    case 'update':
      if ($account->hasPermission('edit any ' . $type . ' content', $account)) {
        return AccessResult::allowed()->cachePerPermissions();
      }
      else {
        return AccessResult::allowedIf($account->hasPermission('edit own ' . $type . ' content', $account) && $account->id() == $node->getOwnerId())->cachePerPermissions()->cachePerUser()->addCacheableDependency($node);
      }
    case 'delete':
      if ($account->hasPermission('delete any ' . $type . ' content', $account)) {
        return AccessResult::allowed()->cachePerPermissions();
      }
      else {
        return AccessResult::allowedIf($account->hasPermission('delete own ' . $type . ' content', $account) && $account->id() == $node->getOwnerId())->cachePerPermissions()->cachePerUser()->addCacheableDependency($node);
      }
    default:

      // No opinion.
      return AccessResult::neutral();
  }

The rest of the code seems fine, to me. Check all the files you are using, and see if they need any change to make your modules work in Drupal 8.


How should I name  the node template files for my theme? I'm a bit confused about how to name my template files. It's the first time I started to mess with templates in drupal 7 and somehow I don't get it.

I want a template file that changes the behavior of my blog posts which are on my front page. In Drupal 6 a file named node-blog.tpl.php was all I needed to mess with my blog posts.

I tried the same with Drupal 7, but it didn't work. I searched for an answer and read that the following function should be relevant for choosing the template files.

function template_preprocess_node(&$variables) {
  ...
// Clean up name so there are no underscores.
  $variables['theme_hook_suggestions'][] = 'node__' . $node->type;
  $variables['theme_hook_suggestions'][] = 'node__' . $node->nid;
}

I also read about some conversion between '-' and '_' because '-' could not be used in function names. So I tried a few variants.

node__blog.tpl.php
node--blog.tpl.php
node-blog.tpl.php
node_blog.tpl.php

None of them is recognised by Drupal. What am I doing wrong?

The following should work:

node--blog.tpl.php

Make sure that you also have a node.tpl.php in your theme folder and that you cleared the cache.

See also Page template suggestions are not working for more information.


How to customize how field is displayed in view UPDATE: Thanks to Molot I now see how I can edit the output of the view using the specific tpl file for that field. However I'm still not sure how to refer to that field and print it within that tpl file.

I have a file field in a custom content type that I'm displaying in a view. I want it to spit out the path to the file and nothing else in the view so I can do whatever I want with it. I have customized the views-view-unformatted-nameofview.tpl.php so it doesn't wrap the entire view with the default drupal divs and classes, like so:

<?php foreach ($rows as $id => $row):
    print $row;
endforeach; ?>

Which works but is there a way to customize how it spits out a specific field?
Even though I customize the html style to none it still tries to do things like display a custom icon for my file which I don't want. I'm also rewriting the output of the field in the view like so

I want to embed it into an img tag but what I end up with is

    maps.svg

When all I want it to display is

I would normally use an image field but it doesn't seem to allow to add svg as an acceptable file type. I'm open to other ways to go about it, but even if that's the case it'd still be nice to know how to edit the field output in views. I'd rather not install a pre-existing module if at all possible. However I would understand if that is the only reasonable course of action.

If you just want to rewrite the file field in Views to something like

All you have to do is

add that File Field in Fields section
Inside the File Field configure, select "URL to file" on Formatter
Inside the File Field configure rewrite results section, check the "Rewrite the output of this field" and rewrite something like "" on Text area. Then click Apply.