Notice: Trying to get property of non-object Here is my code:

function THEME_preprocess_block(&$variables) {
    $variables['user_profile'] = menu_get_object('user');
}

I print the field "name" using print $user_profile->name, and I get the following error:

  Notice: Trying to get property of non-object in include() (line 71 of SITE\sites\all\themes\parce\block--block--2.tpl.php).

I assumed $user_profile was not an object and I tried print render($user_profile['name']), which returned me:

  Fatal error: Cannot use object of type stdClass

What is going on? I checked the Drupal API reference, and menu_get_object() should return me an object.

You didn't print line numbers of the second error so I don't know if they happen on then same line. Maybe your notice is from something else.

What you could try is to print out the variable using print_r, vardump, debug or use the Devel module which creates some wrapper functions like dpm to print variables with Krumo.

It should be impossible that the same variable is an object and isn't an object at the same time. But it's hard to say more with the info you provided.

Update:
From your comments, I can see why you are getting the errors:

print $user_profile->field_country['und']['0']['value'];

Error >> Notice: Undefined index: und ...

print $user_profile['field_country']['und']['0']['value'];

Fatal >> Cannot use object of type stdClass as array

The problem as I marked in the error message is that und is not defined in the field value. So $user_profile->field_country is ok but $user_profile->field_country['und'] is undefined. The reason could be that it doesn't have a value set or that the language for the field isn't undefined. You should like I suggested above, print out the variable to see what it contains.


How do I get fields of a certain field type? I've seen how to get lists of fields by entity and bundle with field_info_instances() and field_info_field(), but I'm not seeing a way to get all fields of a particular type.

I was able to cook this up to do exactly what I want:

function field_get_fields_of_type($type) {
  $fields_info = field_info_instances();
  $return = array();
  foreach ($fields_info as $entity => $bundles) {
    foreach ($bundles as $bundle => $fields) {
      foreach ($fields as $field_name => $info) {
        $more_info_because_type_isnt_included = field_info_field($field_name);
        if ( $more_info_because_type_isnt_included['type'] == $type) {
          $return[$field_name] = $more_info_because_type_isnt_included;
        }
      }
    }
  }
  return $return;
}

dpm(field_get_fields_of_type('entityreference')); // prints out all entityreference fields

But that seems to be an awful lot of code, and and awful lot of looping to get something that should probably be reachable through the field API.

Does anyone know of a Field API function that will more efficiently retrieve the data I'm looking for?

I came across this the other day and remembered seeing this question, so here it is, a somehow very unknown function (I have neveer seen anyone mention it in a blog or anything):

field_read_fields()

and the companion function:

field_read_instances()

For example, get all taxonomy term fields:

$taxonomy_fields = field_read_fields(array('type' => 'taxonomy_term_reference'));

Or get the instances for a field with the a machine name of field_image:

$image_field_instances = field_read_instances(array('field_name' => 'field_image'));


Trying to pull phone number and combine it with carrier, cannot find phone number variable I am running a website that has users input phone number and carrier when they register. Using the Phone module to collect the phone number and a select list field to collect the carrier. How can I retrieve these variables so that I can combine them to make a phone email address (eg. 123456789@vzwtxt.com)

I have a plan for combining them I just need to know how to get the phone number out of the array based on the uid so that I can combine it with the carrier.

Thank you!

if you don't already have it, get DEVEL module. In your tpl file, use dpm($account); this will output the array. From there you can determine the proper element names.

it would be $field_phone_number[0]['value']; a trick to figuring out the exactly lineage is to progressively use dpm, ie: dpm($account), dpm($field_phone_number), dpm($field_phone_number[0]), etc. this is an easy one, but arrays can get in depth and complicated within Drupal

Devel:

  Helper functions for Drupal developers and inquisitive admins. This
  module can print a summary of all database queries for each page
  request at the bottom of each page. The summary includes how many
  times each query was executed on a page (shouldn't run same query
  multiple times), and how long each query took (short is good - use
  cache for complex queries).
      Also a dprint_r($array) function is provided, which pretty prints arrays. Useful during development. Similarly, a ddebug_backtrace() is
  offerred.


Invalidate cache on ConfigFormBase submit I have a ConfigFormBase called TextConfiguration where I have defined several fields for the address, phone number, etc...

These variables are shown in the contact form on my website. When I modify them and enter as anonymous in /contact, the value is not updated.

I've tried this in my ConfigFormBase form submit, but it does not work.

// Additionally, clear cache to prevent mismatch data.
$tags = $this->config(static::COMPET_SETTINGS)->getCacheTags();
if ($tags) {
  Cache::invalidateTags($tags);
}

I'm doing something wrong? I need to configure or do something to get it to update the data when a value is changed? Thanks all!

Edit: Example of how I'm rendering the fields.

You have to add the cache tags to the rendered output of the config field:

$form['example'] = [
  '#markup' => $settings->get('name'),
  '#cache' => [
    'tags' => $settings->getCacheTags(),
  ],
];


Custom 404 error page issue I want to have a custom 404 page that displays some additional information. I need to display the requested path that was not found and some pages suggestions based on that path (this is based on some internal logic that I don't think is relevant to my question).

Here is what I did:

I defined the default 404 page to be page-not-found in admin/config/system/site-information

Then in my module I used hook_page_alter() to define my pages suggestions (if drupal_get_http_headers("status") is 404 Not Found), and the request_uri() to be shown on the 404 template page I created.

I have tried to save these values in different ways (session variable, ctools cache, everything I have tried leads to the same issue — see below).

In mymodule.module:

/**
 * Implement hook_menu
 * @return mixed
 */
function mymodule_menu() {
  $items['page-not-found'] = array(
    'title' => '',
    'page callback' => 'mymodule_page_not_found',
    'file' => 'inc/functions.inc',
    'access callback' => TRUE,
  );
  return $items;
}

/**
 * Implement hook_theme
 */
function mymodule_theme() {
  return array(
    'mymodule_page_not_found' => array(
      'template' => 'templates/404',
    ),
  );
}

In inc/functions.inc:

function mymodule_page_not_found() {

  return theme('mymodule_page_not_found');
}

Problem is, if I request a non existing URL for example mysite.com/not-found-page-1 then request mysite.com/not-found-page-2 the information displayed on the 404 page template when I query the not-found-page-2 corresponds to the values I saved when requesting not-found-page-1.

Any idea why I always get the data of the previous query?

The trouble is, hook_page_alter() is called after your theme function is called.  So if you're setting things there it's too late.

I don't know why you're doing it this way.  Why not generate your suggestions in your page callback: mymodule_page_not_found().  Then pass them to the theme function.

Something like this:

/**
 * Implement hook_theme
 */
function mymodule_theme() {
  return array(
    'mymodule_page_not_found' => array(
      'template' => 'templates/404', // Not relevant to your question, but you should consider renaming this to mymodule-page-not-found because of a "bug" in D7; see discussion here: https://www.drupal.org/node/342350
      'variables' => array('suggestions' => array()),
    ),
  );
}

function mymodule_page_not_found() {
  // ... generate list of $suggestions ...
  return theme('mymodule_page_not_found', array('suggestions' => $suggestions));
}


What's the correct way to include JavaScript dependencies into modules? With Composer we can require PHP dependencies for our modules. What's the right way to include third party dependencies such as a jQuery plugin into a module?

There are a couple of ways you can do it. One way is to define a remote JS resource in your libraries.yml.

See the "CDN/Externally hosted" section here: https://www.drupal.org/docs/8/theming-drupal-8/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-theme

I do this for AddThis (which can be done at the theme or module level) and Fontkit. This is an approach you can take with jQuery plugins that are available via CDN. As long as that resource is available, all you have to do is attach it when needed.

For Javascript that has no external hosting, like CKEditor plugins, I write in the README to download the plugin to libraries/(plugin name) of the docroot. There is no way, that I know of yet, to automate that process. This also requires writing into hook_requirements in the install file of the module to check that the file exists on the server before installing.

Another way, you could have composer do a bower install or npm install:

https://stackoverflow.com/questions/25122187/using-composer-to-install-npm-and-bower-packages-on-production-i-e-no-devdepen

Though, it would require the user to have all of those tools installed, and to be a composer user. One gap for that right now is if someone grabs the tarball off drupal.org or uses drush to get your module, none of that would work and they'd still be missing packages. Pathing could also be a headache when trying to write these commands to work for everyone, as well. Composer usage hasn't gained as much traction yet as it needs to beyond developers, but it will become more important moving forward. For example, modules requiring PHP packages (like Search API) simply cannot be drush installed or downloaded from drupal.org and manually placed - a method many, many site builders still use.

Others would say to just stick it in your module, but unless you wrote the plugin, that is against the Drupal licensing/contrib guidelines regarding third party code.


Custom form in pop-up I need to show a custom feedback form when canceling an event.

I used a jQuery modal form for this purpose, but I want to use any Drupal 6 module, or functionality, to save the feedback for future purposes.

Is there any module I can use?

There are two ways of doing this:

Using Modal Frame API
Using CTools

I've used both to successfully create modal popups with embedded forms. In both cases I first needed to create the form using Drupals form api and then assign an event for either MFA or ctools to bind to.

Overall I found MFA easier to get something up and running but ultimately ctools is more powerful and will give you a better understanding of a module that is now used widely throughout contrib modules.

Both modules documentation is the best place to start, MFA has great documentation pages and ctools has some excellent sample modules in the project itself.


Which Rules Event in the Rules module gets triggered after clicking on a link? If I click on a link in a node, I want to know which Rules Event in Rules gets triggered that I can use.

Notes:

On the home page, there are a lot of views blocks. So in that node title (or image or whatever is being clicked), in that link, I want to use some Rules Event.
I want to know if I click on that link, which event in Rules can be used in order to invoke. I tried Rules Event Content is viewed, but it didn't work.

Whatever you want to happen via Rules module when some link is clicked, if you're using Rules Event 'Content is viewed', you'll probably be too late:

the content (or whatever the clicked link is about) is already being shown, so if the Rules Conditions are satisfied, the Rules Actions will be performed. That is what 'Content is viewed' is all about.
if you didn't want to content (or whatever the clicked link is about) to be visible at all, well sorry, but you're too late.

If however you did want something to happen BEFORE showing the content (or whatever the clicked link leads to), then you should use Rules Event 'Drupal is initializing'. Refer to 'How to specify a Rules event like "Content is 'going to be' viewed"?' for way more details on this.

Attention: Rules Event 'Drupal is initializing' gets triggered on every (repeat: every) page load in a Drupal site. So for performance reasons, you really want to limit the number of active Rules that use this Rules Event to an absolute minimum, i.e. as your last resort (if anything else fails).


Removal of Node Reference, Drupal 6 Ok, trying to process a script, both PHP and JavaScript, where I am moving a particular content type NODE from one reference to another. This is the structure:

I have a PROJECT
Inside each PROJECT are PAGES
Inside each PAGE are CALLOUTS
and Inside each CALLOUT are PRODUCTS.

What I want to do is take a PRODUCT from one CALLOUT to another CALLOUT. I am able to merge these, but now what I want to do is delete the first instance. An example:

I have PRODUCT AAG-794200 that is on PAGE 6 CALLOUT A. I am merging that PRODUCT with PAGE 6 CALLOUT B.

I can get the product to merge, but now I need to remove it from CALLOUT A. Here is my code:

$merge = explode(',', $merge); //Merge SKUs
$mpages = explode(',', $mpages); //Merge Pages
$mcallouts = explode(',', $mcallouts); //Merge Callouts
$mcallout_nid = explode(',', $mcallout_nid);  //Merge Current callout

$length = count($merge);
$e = 0;
while ($e < $length) {
    //Where is the SKU going to?
    $to_callout_letter = strtoupper($mcallouts[$e]);
    $to_page_num = $mpages[$e];
    $sku = $merge[$e];
    $from_callout = $mcallout_nid[$e];

    //Where is the SKU coming from?
    $other_callout = node_load($from_callout);

    //Need page ID of current callout for project purposes
    $page_nid = $other_callout->field_page[0]['nid'];
    $page = node_load($page_nid);
    //Need the project NID
    $project_nid = $page->field_project[0]['nid'];

    //We need to get the NID of the page we are going to
    $page_nid = db_query('SELECT * FROM content_type_page WHERE field_page_order_value = "%d" and field_project_nid = "%d" ORDER BY vid DESC LIMIT 1', $to_page_num, $project_nid);

    $page_nid_res = db_fetch_array($page_nid);
    $to_page_nid = $page_nid_res['nid'];

    //We need to get the NID of the callout here
    $co_nid = db_query('SELECT * FROM content_type_callout WHERE field_identifier_value = "%s" and field_page_nid = "%d"', $to_callout_letter, $to_page_nid);
    $co_nid_res = db_fetch_array($co_nid);
    $to_callout_letter_nid = $co_nid_res['nid'];

    $callout = node_load($to_callout_letter_nid);
    $long = count($other_callout->field_skus);
    $deletecallout = array();
    foreach($other_callout->field_skus as $skus) {
        $s = 0;
        while ($s < $long) {
            if($skus['nid'] == $sku) {
                $callout->field_skus[] = $skus;
                $s++;
            }
            else {
                $deletecallout[] = $skus;
                $s++;
            }
        }
    }

    foreach($other_callout->field_images as $old_image) {
        $callout->field_images[] = $old_image;
    }
    foreach($other_callout->field_line_art as $old_image) {
        $callout->field_line_art[] = $old_image;
    }
    foreach($other_callout->field_swatches as $old_image) {
        $callout->field_swatches[] = $old_image;
    }

    $callout->field_copy_text[0]['value'] .= $other_callout->field_copy_text[0]['value'];
    $callout->field_notes[0]['value'] .= $other_callout->field_notes[0]['value'];
    $callout->field_image_notes[0]['value'] .= $other_callout->field_image_notes[0]['value'];
    $callout->field_status[0]['value'] = 'In Process';
    node_save($callout);

This causes the PRODUCTS to MERGE, but not delete the original.

Thanks for any help. I know it's something simple, and it will be a palm-to-face moment.

So the answer to this was easier than I thought.  I loaded the $other_callout node, and then unset the $key, utilizing the following code:

foreach($other_callout->field_skus as $key=>$value) {
if($value['nid'] == $sku) {
        $sku_rec = $value;
        $sku_rec_key = $key;
    continue;
    }
}

unset($other_callout->field_skus[$sku_rec_key]);

node_save($other_callout);

Thanks for the help guys, I appreciate it.

Drupal on.


Allow a role to create users I'm looking for a way in which we can assign a select role, the ability to create, edit, and delete users within another role. While its possible to use the "Administer Users" permission for this, it opens up the parties who will be assigned with this role to do all sorts of bad things. Ideally, we would like to limit to what role of user this faux administrator is able to excise.

We've explored using some of the options here, such as Administer Users By Role with some patches to the core User module (I know, but it was outside of my decision) with no success.

Use the Subuser module. This module allows users to be given the permission to create subusers. The subusers may then be automatically assigned a role or roles. The parent of the subusers then has the ability to manager the users they have created.


Adding a 'search tips' link next to the search button in a views-based search I'm using a Drupal 7 views-based search. I have a search button in there of course. I'd like to add a link next to it called 'search tips' that goes to a 'basic page'. Anyone know how to add a link there?

This is the code I have so far:

<?php

  /*
    * Implementation of hook_form_alter()
    */
  function search_tips_link_form_alter(&$form, &$form_state, $form_id) {
    if($form_id == "views_exposed_form") {
    // there's a submit button in here I'd like to add a link after that...
    // not sure how to place a link with this function.
    }
  }

You need to:

Find the specific view exposed form by using the #id array key.
Find for the search button array key.
Use the #suffix form key to append your link.

A helpful tool to look into the array structure is by using the dsm() function from Devel module.

Additional information for best practice is that use the l() function to structure your link.

So it would look something like:

if ($form['#id'] == 'views-exposed-form-test-page') {
  $form['submit']['#suffix'] = l(t('Search tips'), 'link-to-basic-page');
}


Views formatting: liquid number of columns? I have a Views page that creates a 3-column grid layout.  These look just fine on a desktop browser.

On a mobile browser, each column is too thin to usefully read the text that's displayed, and it looks pretty awful, even if I use media queries to scale the text down.  I'd like to go to a single-column layout on these sorts of screens.  Is there a good way to do this?  Ideally, a CSS-only approach would be best, since I've managed to get my layout fluid using only CSS thus far.

You'll need to move away from using a table layout to one that uses divs instead, e.g an 'unformatted list' views style.

It's quite easy by piling a set of floated divs into a container.

If the container width changes, the number of items per 'row' also change.

e.g, something like this for the view items.

.views-row{
  float:left;
  margin:8px;
}


populating nid in a custom field When creating a new node, I need to populate/fill a custom field with a value of the current node's id. What hook should I use to fill my custom field with newly created nid ($node->nid)?

I tried to use hook_node_presave but it was NULL, currently I am thinking to use hook_node_insert but as documentation says :

  after the node is inserted into the node table in the database,

Does that mean if I assign the new value to my custom field it will be/not be saved to database?

I guess I found a solution for this problem:

function mymodule_node_insert($node) {
  $node->field_custom_field['und'][0]['nid'] = $node->nid;
  node_save($node)
}

I saved the changes to database with node_save()


Taxonomy terms as arguments to an entity-reference view I have a two content types that are classified by terms of a certain vocabulary.

The first content references another by an entity reference field (auto-complete).

What I need is as following:

When I'm creating the first content type, I choose a taxonomy term from the term reference to classify the content.

Then the entity reference field only show the nodes that are classified by the selected term (the entity reference is being filtered by a view to show the nodes of the second content type).

Does anyone has a working solution?

Entity reference autofill may help you. Here is a quote about it (from its project page):

  ... gives Entity reference fields an option to populate other form fields with data from selected referenced entities.


how to change node edit path from node/[nid]/edit to node/[nid]/update? I have Pathauto which changes node/[nid] to having a path of [title]; I then use subpathauto to change node/[nid]/edit to [title]/edit.

But now how can I change the edit fragment? I want to change all instances of edit to update. so the URLs would be [title]/update instead of [title]/edit.

I cannot use arguments or wildcards in Pathauto, so I cannot specify a path like */*/edit to be */*/alter, but that is effectively what I would like to happen.

I think this is a legit request as long as you add an additional alias as opposed to overwriting system paths.

I would implement hook_node_insert() and then use path_save() to set your custom edit path on node creation. You will also probably need to make sure that this hook runs after the Pathauto module has set its path, so you can use the alias it sets as part of your additional edit alias.


Drupal 7 : Tons of HTTP requests from Media Vimeo module I am using the Media module

And two of its sub-modules - YouTube and Vimeo

As a result - front end page for some reason sends 4 HTTP requests for each Vimeo video on the page and they totally slow down page loading - http://snag.gy/dKEjv.jpg

Question :

If there is somebody familiar with these modules or with Vimeo API - could you explain what are these requests for?

Those HTTP requests look like (slightly broken) video analytics tracking requests via the service conviva.
It might be possible to opt-out of conviva with Vimeo
See also Make Vimeo Faster - Opt Out of Conviva


How to display an overlay image in modal window (Colorbox) upon hover I have a series of images set up to display in modal lightbox-type windows – specifically, using the Colorbox module.

The goal is for each image to be paired with a companion graphic overlay which is displayed upon hover over the Colorbox display.
Think of it as (1) the photo, and (2) the "circles and arrows" overlay (maybe .gif or .png with transparent whites).

Can anyone verify its feasibility and suggest a path to this result?

You would probably have to write some custom javascript / jquery in your theme's JS file and call the colorbox function on hover. For example:

$('.img-1').hover(function(){
  $('.img-2').colorbox();
});

That's only the starting point. Once it is working with just 2 images, the next step would be to dynamically pair all the images so the javascript knows which image to show on hover.


who is responsible for printing [safe_value] I would like to know who's responsible for printing ['safe_value']

$node->body['und'][0]['safe_value']

because for some reasons, it is missing when I checked it using dpm($node), I only see ['value'], ['summary'], and ['format'].

All my modules are up to date and I'm using i18n(multilingual).

To augment MZ's answer, while a node_load() will load the node, a node_build_content() is required to get all these extra types of fields.  In this case, that would be the Field Module's Text Module that creates this sanitized field based upon the filter in use on that field.


Twig dump not working (PHP Warning: Leaked 2 hashtable iterators ) I'm trying to create a custom markup for a views-block. What I want to do is similar to what someone is trying to do here (How to create a custom markup for a views-block?).

My view-block has 3 items and I want to create a template where I can individually place them using HTML code. At the moment it just gets rendered from {{ content }} in my block--views-block--latest-block-1.html.twig. I guess I'd need to check how the three elements are stored in the content so that I can individually place them in my HTML markup.

The Twig dump function however doesn't seem to work. I get the following error message when loading my webpage:

PHP message: PHP Warning: Leaked 2 hashtable iterators in Unknown on line 0

What's going on?

Probably because there are some recursive data structures in there. Try installing kint from the devel project, I'm not sure right now if it replaces dump() or if it provides an alternative kint() but one of those should give you much better output.


How to change how WYSIYG styles things? Instead of using HTML underline tags, I want the WYSIWYG editor (CKEditor) to wrap a span around the highlighted text. Does anyone know how I can achieve this? Thanks!

Sure see this great blog post titled WYSIWYG Module + CKEditor: Taming the Beast by Fuse Interactive. I am not affiliated with the company nor the author of it -- it's simply a great resource.

Linked in those blog comments is a link to the CKEditor Configuration Options documentation, which is what you'll end up altering to make this happen.

In the blog post they supply their own config settings for the editor in javascript. I believe you can set all these values in hook_wysiwyg_editor_settings_alter, the settings for the Styles look like:

  { name : 'Float Right', element : 'div', attributes : { 'style' : 'float:right;' } },
    { name : 'Float Left', element : 'div', attributes : { 'style' : 'float:left;' } },

Where this defines a style called Float Right that wraps the selected text in a div with some inline styling. I believe you can easily assign classes instead of inline styles as well.

This should be a huge jumping off point for you to figure it all out. Best of luck!


How to create a global language selector page at domain root with i18n when the global language has a prefix? I am looking for a solution to create a language selector at www.domain.com. My site has multiple languages (en, de, fr). All the languages are using a domain prefix. This results in:

www.domain.com/en (default language)
www.domain.com/de
www.domain.com/fr

Now I want a global language selector at www.domain.com without any redirects. The module https://www.drupal.org/project/language_selection_page is almost what I'm trying to accomplish, but this is using a redirect. I was told this is bad for SEO (redirect).

What is the best way to accomplish this?

Consider creating a special "homepage" node, for which you set the "language" to "Language Neutral" (any path will do, even no path if that's what you'd prefer). And use its node ID (preceeded by 'Node/') as the value for "*Default front page *" within admin/config/system/site-information.

From then on, you can create any content for that node as your language selection page, which of course should include a link to each language specific "starting page".


Product Page Uploads and Automatic Updates Right now my website has ubercart. I was wondering if there was a way to make it so when a user uploads a file with a description/price/etc that the product page would automatically update with their new upload.

I'm making a user based artist website. Where the users can upload their own art works and sell either a digital copy of their work or a physical copy (their choice ultimately), and I was wanting some help with the logistics of doing such a thing.

The website is currently running with Ubercart and all of its required addons AND the CorporateClean theme.

Any help would be very appreciated.

You probably will have to alter the 'ubercart product-content type' and add some taxonomy fields to create the categories (electronics etc.). (Not sure if ubercart has this by default.)

Then you will have to use a view to override the ubercart product page. Look into views and Contextual filters. You can for instance create a block (user-product-block) and use a contextual filter to fill this. You can choose to get the user id from url and then select all products created by that user.

Filtering by category is exactly as done on the page above.


Validate all instances of a field programmatically What is the best way(hook) to validate all instances of a field programmatically? I have a lot of content types having the same fields like field_phone. I want to programmatically validate field_phone everywhere it is used.

You could implement hook_field_validate and check if its the correct instance. Doesnt work if the field is not defined by the module.

One way to build that would use hook_form_alter and add element_validator if the field exists on the form.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
   if (isset($form['field_phone'])) {
      $form['field_phone']['#element_validate'][] = 'mymodule_somevalidator';
    }
 }

function mymodule_somevalidator($element, &$form_state) {
  if (!empty($element['#value']) && !is_numeric(parse_size($element['#value'])) {
    form_error($element, t('The "!name" must be x', array('!name' => t($element['title']))));
  }
}


How to create template suggestion for image like IMAGE--BLOCK-TYPE or IMAGE--FIELD-TYPE I'm struggling to make template suggestions like IMAGE--BLOCK-TYPE or IMAGE--FIELD-TYPE.
I have three different block types(image1, image2, image3) with one image field(field_image_1, field_image_2 and field_image_3).
And I don't know how to get suggestion like
image--block_image1.html.twig
image--block_image2.html.twig
image--block_image3.html.twig

or
image--field_image_1.html.twig
image--field_image_2.html.twig
image--field_image_3.html.twig

Is there any way to pass variable between the two hooks below?
  function full_nature_theme_suggestions_block_alter(array &$suggestions, array $variables) {

    global $block_id;

    $block_id = $variables['elements']['#id'];

  }

and
  function full_nature_theme_suggestions_image_alter(array &$suggestions, array $variables) {

    $suggestions[] = 'image__'.$block_id;

  }

Please help!

Solution is here
https://www.drupal.org/forum/support/theme-development/2021-02-23/how-to-create-template-suggestion-for-image-like-image#comment-14017195
It is alternative solution but it works with this module
https://www.drupal.org/project/image_class


Drupal 7 - Create a custom template that can be assigned to different pages I want to have a custom template for pages. WordPress has template selection feature for Pages or Posts. Is that possible for Drupal?

See here Drupal 7 Theme Hook Suggestions

For nodes You can use

    node--[type|nodeid].tpl.php
    base template: node.tpl.php
    Theme hook suggestions are made based on these factors,
listed from the most specific template to the least.
Drupal will use the most specific template it finds:

    node--nodeid.tpl.php
    node--type.tpl.php
    node.tpl.php

Also Drupal 6 Template Suggestions

To use same tpl for multiple pages you need to use theme_preprocess_node
Like

function theme_preprocess_node(&$vars, $hook) {
  $node = $vars['node'];
  if(in_array($node->nid), $myuids)
   $vars['template_file'] = 'your_template_file';
}


How to pre-populate multiple "field collection" fields in node form I'm building a multistep node add form where you upload a zip of files on page 1, let the module read file names into an array when the uploader presses the "next" button, and then allows the uploader to enter some meta info for each file on page 2. I have set up the field collection "field_files" to hold info for each file.

However, I can't seem to figure out how to generate the field collection form code for page 2. I would like it to be pre-populated with one field collection entry for each file. I've been reading module source code and huge var_dumps all day without getting anywhere. Does anyone know if this is even possible, and if it is, what would be the best way to do it?

After hours of debugging I found a good working solution to pre populate fields in field collections. (see Drupal forum)

So whats the plan?

  Manually generate a node-add form for the desired bundle.
  Change the form state of the generated form and set the desired number of fields you want to pre-populate.
  Rebuild the node-add form with the new form state values.
  Use hook_form_alter() to pre-populate values.

Ok. So lets assume we have a bundle called bundle_with_unlimited_fc which belongs to the node entity type. Furthermore all our custom code will reside in our module named my_module.

We can use hook_menu_alter() to define a new page callback. Everytime a new bundle_with_unlimited_fc is added Drupal will call now this function.

function my_module_menu_alter(&$items) {
  $items['node/add/bundle_with_unlimited_fc']['page callback'] = 'my_module_build_form';
}

Now definde our form builder function. Notice the function argument which comes from the Drupal implementation of our altered menu item.

function my_module_build_form($type) {
  // get the standard node form;
  // we cannot get it from drupal_get_form() because we need the form_state reference,
  // so we copy a bit of code from node_add() and drupal_get_form()
  global $user;
  $form_id = 'bundle_with_unlimited_fc_node_form';
  $form_state = array();
  $form_state['build_info']['args'][] = (object) array(
    'uid' => $user->uid,
    'name' => (isset($user->name) ? $user->name : ''),
    'type' => $type,
    'language' => LANGUAGE_NONE
  );
  $form = drupal_build_form($form_id, $form_state);

  // we now have exactly the form which node_add() is returning BUT
  // we also have a reference of the form state array ready to alter;

  // how many items do we want?
  $num_items = 5;
  // this is exactly what the ajax request for the add more button does
  $form_state['field']['--machine-name-of-field--'][LANGUAGE_NONE]['items_count'] = $num_items;

  // now this is important!! set a flag inside the form state so that the hook_form_alter() function
  // is able to know when it should pre-populate (remember: hook_form_alter() will be called twice
  // during this process)
  $form_state['my_module_prepopulate'] = TRUE;

  // reset the html ids so that our new rebuilted form will get nice ids and not form_id--2
  drupal_static_reset('drupal_html_id');

  // rebuild the form and return it;
  // through drupal_rebuild_form() hook_form_alter() will be called again - this time with our
  // prepopulate flag and 5 empty form elements ready to prefill
  return drupal_rebuild_form($form_state['build_info']['form_id'], $form_state, $form);
}

Thats nearly all there is. Just setup your hook_form_alter() and you will be ready.

// hook_form_FORM-ID_alter().
function my_module_form_bundle_with_unlimited_fc_node_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form_state['my_module_prepopulate']) && $form_state['my_module_prepopulate']) {
    $delta = 0;
    $max_delta = $form['--machine-name-of-field--'][LANGUAGE_NONE]['#max_delta'];
    while ($delta <= $max_delta) {
      // prepopulate whatever you like with help of #default_value'
      $form['--machine-name-of-field--'][LANGUAGE_NONE][$delta]['#default_value'] = 'Value to show';

      $delta++;
    }
  }
}

So thats it basically. Hope that this solution will help some people to save time...


Drupal 7 - Webform 3 - How do you expose form results to Views Easily? What is a good module to use to expose Webform 3.x results to views? I want to create a views page with links to each form submission so search engine spiders can crawl and index user submitted questions.

If you want to make a page with links to each webform submission, you can just use Views itself; you don't need an extra module.  Add a new view.  Choose show Content of type webform.  Check the box for Create a page.  As the display format, I would recommend choosing the format you want and using fields; this will easily allow you to add links to the forms.

To be sure the search engines (Google, Bing, etc.) index your content, though, I wouldn't use this approach.  I would use the XML Sitemap module.


"syntax error, unexpected end of file" Upon enabling modules I'm getting a syntax error when enabling modules.  This is happening intermittently and it isn't specific to any module in particular, which is making it impossible for me to track down.  Here is the error I'm receiving today:

  Parse error: syntax error, unexpected end of file in sites/all/modules/contrib/headerimage/headerimage.module on line 821

Line 821 is the very last line of the file, and the syntax looks fine to me.  When I get a similar error when enabling modules, it's always complaining about the last line.  There are never any missing brackets.  I've disabled any custom modules I wrote thinking that it could be my code causing this, but I've had no success.

I was wondering if anyone has run into this, if they have any suggestions, or possibly a method to troubleshoot this.

-- EDIT --

I was able to resolve the syntax errors for this particular module (headerimage).  I had to delete the very last line in two of the files and re-add them manually.  They were closing brackets "}".

I'm not convinced that this is the correct fix.  Maybe it's some kind of encoding issue?  Any thoughts?

I figured out what this was. It wasn't necessarily related to Drupal or PHP syntax, but the answer might save someone else some stress.

I had VMWare Fusion on my Mac running a Linux VM with Apache/MySQL/PHP server.  The webroot for Apache was a shared directory on my host machine which contained my Drupal install. I did this so I can have the benefit of a Linux web server while being able to edit my code locally on my host.

This works when serving up the site, but whenever I used Drush on the VM to install a module, there was always a hidden line appended to the module's files that Vi didn't pick up, which is why the syntax error was always on the last line. I'm assuming it had to do with the hgfs filesystem used for sharing between my host and the VM.

Once I removed the VM sharing and modified everything on the VM itself, all of my problems went away. Downloading modules with Drush no longer produces these syntax errors.

Here is a related thread on the Drush issue queue where people are having similar issues.

https://drupal.org/node/1948962

Thanks to those who gave their feedback.
--richard


Retrive specific deleted nodes and re-import Some nodes (from two different CTs) have been deleted accidentally and there is no way to restore them.

The question: is it possible to retrieve and import these very specific deleted nodes from our backups without making a full database restore, and having the reassembled nodes back to the UI, is there any method/technique that will work ?

One of our CTs consists of many many fields (~80) of any possible type image, link, entity/taxonomy reference, integer, text, file and Boolean.

I have already looked at the Node export but it depends on the uuid module and I don't have that installed.

We had this same problem on one of our sites and the best solution we could come up with was to use Node Export as you mentioned. Like you, we didn't have it or UUID installed at that time, but we installed them just for this purpose, and it worked fine.

The only catch is you need to be able to load the backed-up database into a functioning site (we did it on our test server) before you can export the missing nodes.


Only show field type content added by user On my website I allow companies to add jobs, I allow a user to create one or more companies. When the user goes to add a job I have a drop down which lists all of the companies on the site, I want this drop down to only list the companies added by the user so they can choose which company they want to attach to the job. I can't find a way to do this via the manage fields screen. Below is a screenshot of my manage fields screen. Any help would be much appreciated!

I suggest you use views entity reference this link is good tutorial about it .

So first create a views that show the current user company items ( the companies that the author (creator) of them is current user)  then add "Entity reference" display to it , then in your field settings in "Entity Selection" instead simple mode use "Views :Filter by entity reference" Then select your created views entity reference then enjoy it ;)


Conditional markup field display I have content type with a term reference field.  Let's call it 'Color'.  I want the content type to display markup depending on which term has been selected in the term reference field.  For example, if 'Color' is Red, then the markup field will display 'Red is the color of fire'.  If 'Color' is Purple, the markup field will display 'Purple is the color of royalty'.

Any ideas?

Thanks

You need to implement hook_preprocess_HOOK(&$variables), and add processing there, like this:

<?php

function MYTHEME_preprocess_node(&$variables) {
    // Check if field tid (term id) is filled up
    if (isset($variables->field_term_color[LANGUAGE_NONE][0]['tid'])) {
        $color = $variables->field_term_color[LANGUAGE_NONE][0]['tid'];

        $text = '';
        // You need to look up tid of each color
      switch ($color) {
        case 123:
            $text = 'Red is the color of fire.'
            break;
      }

      // Assign value to markup (text) node field
      $variables->field_markup_field[LANGUAGE_NONE][0]['value'] = $text;
    }
}

?>

You should place the right field names instead of the ones I use, of course.


In Drupal 7, what events are logged? I'm looking for a list of the events that Drupal 7 logs via watchdog. The question I'm trying to answer for a colleague is this:

"What logging Drupal is capable of, specifically related to security, performance, and metrics?"

I realize that I can log whatever I like but I'm looking for the default list. Googling hasn't helped.

Thanks very much.

If you have a look through the list of Drupal core functions that call watchdog(), you can get a good idea of the events that get logged.

http://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/calls/watchdog/7


How do I code to take action when a VBO (bulk action) is finished? I've recently coded a few Drupal\x\Plugin\Action classes that respond nicely to my VBO (now bulk actions?) in Drupal 8.  Now I'd like to implement a hook, or whatever is required, to take action when all the entities in a selected action have been processed...essentially a VBO post-process hook like we had with hook_views_bulk_operations_finish in Drupal 6.  Where and how can I implement that?

I see no obvious hook in D8 to do this, and unfortunately, I've been unable to get Rules to work in D8 (still really confused by Rules and Actions configuration) so I really don't want to go down that path if I don't have to, yet.

This is how I tackled this scenario in D7.

In my custom VBO code I did a variable_set() and then I use hook_views_pre_render (note that the D8 hook params changed, so don't copy the hook from my code below) and did a variable_get(), if it was not empty, then do your action.

/**
 * Implements hook_views_pre_render().
 */

function bulk_mail_hauliers_auto_emailing_views_pre_render(&$view) {
// check the view name
if ($view->name == 'hauliers_auto_emailing') {

    $store_all_in_one_en = variable_get('bulk_mail_hauliers_auto_emailing_all_in_one_en', 0);

    // check that variable_get is not empty, which means VBO ran.
    if ($store_all_in_one_en != 0) {

      // CUSTOM ACTION GOES HERE

      // delete the variable
      variable_del('bulk_mail_hauliers_auto_emailing_all_in_one_en');

    }

}

So you can basically do this in D8, except use the D8 equivalent of variable_set,get,del.


Get an image with style url from an URI in twig So thanks to 4k4 I finally managed to get my original image URI in a field template via

item.content['#item'].entity.uri.value

and with

{{ file_url(item.content['#item'].entity.uri.value) }}

I would get the url of the original file.

I have the image style information via

item.content['#item']['#image-style']

that 'medium' is requested

A PHP solution is already available here, but how do I do this in TWIG?

There are some attempts on creating a filter for 8.1 here - but that doesn't help me currently.

You could put the php code in the preprocess function of the field template. You have all information you need in your question.

But then you would do coding, that is already in drupal. If you have #image-style set in the image render element, then the image field should be configured for the preprocess functions that come later in the image-formatter and image-style templates to put the right src attribute in the variables for image-style.html.twig. So you can use the code that is already there by overriding this template.

See the code in /core/module/image/image.module:

function template_preprocess_image_style(&$variables) {
  $style = ImageStyle::load($variables['style_name']);

  // Determine the dimensions of the styled image.
  $dimensions = array(
    'width' => $variables['width'],
    'height' => $variables['height'],
  );

  $style->transformDimensions($dimensions, $variables['uri']);

  $variables['image'] = array(
    '#theme' => 'image',
    '#width' => $dimensions['width'],
    '#height' => $dimensions['height'],
    '#attributes' => $variables['attributes'],
    '#uri' => $style->buildUrl($variables['uri']),
    '#style_name' => $variables['style_name'],
  );


How to hide views UI reaching number of limits of searches I'm developing a D8 site. I am using a custom views plugin to query data from a remote api by searching a business ID.

My scenario: User is only allowed to enter 3 attempts of business ID in a search view. If 3 attempts fails, I want to hide the views UI from the page for 24 hours. What's my purpose? To give difficulty for others to guess my business ID.

This is a duplicate question with: How to use Rules to limit the number of searches to pull data from a remote API, but on another perspective.

I wasn't able to implement it using Rules, and I'm guessing if we can do it on front-end coding. Does anyone have an idea to implement this?

You can Set a configuration variable for each user (it's equal variables on drupal 7 ) and for each search increase it,reset it each day,But another and simple method is  implement it by cookie , create a cookie for user, set expire to 24 hours, and every time user search, first check it's cookie and if not do it more that three times  show results for him/her else  there is nothing to him/her.I think cookie solution is good for you.


How do you get Product Variation Type fields and display modes to show up when displaying Products in a View? I've created a Product Variation Type for all my products, all of which have the following custom fields: Display Title, Subtitle, and Top Rated Product? (boolean checkbox):

When setting up a View to display my Products, I am unable to access any of these fields, regardless of whether I choose "Fields" or "Content" under "Format > Show:". Nothing shows up:

I also can't access any of the display modes I created for Products — not even the default "Cart" display mode shows up here:

Am I missing something that's required to get this working properly? I can only choose "Fields", "Product", or "Search Results", and like I said, even when I choose "Fields", I can't find any of the custom fields for my Products.

It turns out that I had to add a relationship to Product Variation Type in order for those fields to show up. Hope this helps others!


ShareThis in header rather than content type? I am adding Drupal ShareThis to a header mini-panels, but the buttons are not displayed. Firebug tells me that the corresponding code is not there at all. How can I display ShareThis buttons outside of content types?

Please try the following:

Go to menu Structure>Blocks.
find the ShareThis block.
set the block region settings for the theme you are using
go to block configuration and make sure the block is visible for all required pages, content types, roles, users
go to menu Configuration>Web Services>ShareThis
go to 'Advanced' section
find 'Location' settings
select 'Block' to select the ShareThis widget should appear as a block and not in a node content.


Create a Taxonomy Archive Block Hello i was hoping to create a block to attach to the taxonomy/term/* page but i am running into problems with the date arguement working with the term argument. I have just cloned the archive view and disabled the taxonomy view, added the arguments but to no avail.

Has anyone ever achieved this before with D^ and Views 3?

thanks

http://www.webbykat.com/2012/02/creating-monthly-archive-block-drupal-7-views While not taxonomy should work. Change the content type from node to taxonomy and as you create it it will be archived. You may need to ad a date entity to the taxonomy and have rules or trigger put in a creation date since I don't believe they are creation date stamped.


Manual crop not working in Chrome Is anyone using manualcrop https://drupal.org/project/manualcrop?
It works fine in Firefox but doesn't work in Chrome.

Using Drupal 7.

Thanks!

There's an issue queue going on drupal.org for this - https://drupal.org/node/2093533

It looks like the module maintainer may have fixed the chrome issue with the latest dev version


What methods are available to assign a TPL to a specific url for Drupal 7 theming? Currently I have a custom javascript libary that is being loaded on all pages of the site as i hardcoded it into the html.tpl.php file. I konw you can target specific nodes or node types via the tpl filename format, but what if I wanted more control of where this tpl is activated? Is there some type of regex formating that I can use for html.tpl.php?

What I want to be able to do is load my custom js library on all pages except for a specific content type and a few views urls. How can this be done the most efficient way?

Unset the JS or CSS assets on page build with either hook page build or hook page process and drupal add js.

Alternatively you can use hook theme to define custom tpl files on custom business logic (such as url paths).

Im on my phone, unable to gives more info or examples until at pc.


How to build an Email Diggest using Rules I am building a Website using Drupal 7. This website contains events, event-comments and event-registrations (=Registrations module):

Event

Event Comments
Event Registration

Now I need to inform users by email when:

New events are created
Existing events are changed/updated
Events are deleted
Event Comments where added
Somebody register for an event
Somebody unregistered of an event

I found the Rules module can trigger actions on these events and conditions.

BUT: I need to generate a digest/newletter with the above information once all day or half a day etc. so users don't get too much emails ;-)

Advanced (but optional) features:

If a user un-register from an event don't send him any more updates on this particular event.
Users can set their digest/newsletter interval in their profile. eg. once a day, once an hour, etc.
Maybe other content-types then events will be added to the digest system later.

Questions:

How to I best build such a digest/newletter email using Rules? What additional modules can be integrated to Rules to address this?
Can Rules-Scheduler by of any help for this?
Is there another email-module that can to this out of the box without Rules?

You may want to consider Notifications or Subscriptions. Both modules offer either immediate or digest notifications for content updates. Be aware that Notifications currently requires PHP 5.3.


How can I redirect users on login with PHP? I'm trying to redirect users with certain roles to different pages on login.  Sample code is below:

function MYMODULE_user_login(&$edit, $account) {
  // Allow users to reset their passwords
  if (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset') {
    // Admin
    if (in_array('administrator', $account->roles)) {
      $redirect = 'admin/hud';
    }
    $edit['redirect'] = $redirect;
    dpm($edit);
    dpm($redirect);
  }
}

This is based on drupal.org login hook documentation about "How to redirect users after login in drupal?" and the answer to "Custom redirect on custom page for admin user".

The problem is that when I actually log in with a user having the given role, I am redirected to /user, not my custom path.  The results for dpm() for $redirect and $edit->redirect show the path specified in my code, so why am I not getting redirected there?

I had this working in Rules, where there is a Force redirect checkbox.  But I am trying to move the code out of rules because it relies on a lot of custom PHP to check various conditions.

$edit['redirect'] = $redirect; doesn't stop other operations being executed I think.. The only thing I can think is to stop them with drupal_goto, but you should check you won't break anything else or not:

function MYMODULE_user_login(&$edit, $account) {
  // Allow users to reset their passwords
  if (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset') {
    // Under 18
    if (in_array('administrator', $account->roles)) {
      $redirect = 'admin/hud';
    }

    drupal_goto($redirect);
  }
}


Is it possible to add second horizontal Menu below Main Menu? I use "user menu" on top, for user related links.
I use "main menu", in reaching my main contents of site.

I need one more horizontal menu below the "main menu".
So second priority links will be there.
Can it be possible?

(I'm not interested with drop down menus. "Main Menu" and "Second Horizontal Menu" will be independent of each other)

Thank you very much for your help.

Go to /admin/structure/menu/add and add a new menu
Go to /admin/structure/block and place the new menu block in the region of your choosing.


batch api for large batches After a form submit, can I create multiple batches based on the maximum table size for the serialized batch string and how can this be done?

I am using a batch process to pass users to an external site using their API.

For each user I set $batch['operations'][] = array('process_funcion', array(LIST OF VARIABLES));

The batch processing works for upto 5000 users; anything over that I get the following error:

  Access denied
  You are not authorized to access this page.

I thought this had to do with max_packet size, but I am not to sure of that anymore.

The batch is being initiated after a form is being processed.

Do you have any ideas on how I can process 5000 users at a time, or why I am getting this error?

I think that the insert to the batch table is to big, so I am trying to split this into separate batches like this.

$contactCount = 1;
foreach ($contacts as $contact) {
  $batch['operations'][] = array('_contact_add_batch', array($module, $acc_id, $Group_ID, $verb,$contact));
  //Due to max_packet_size restrictions, need to set multiple batches
  if (($contactCount % 2000) == 0){
    batch_set($batch);
  }
  $contactCount++;
}
// For the last set of batches, in the event that there is not 2000, lets add them also.
if (!empty($batch['operations'])) {
  batch_set($batch);
}

I am still getting the Access Denied error.

Batch API in Drupal 6 serializes everything into one row, causing the problem you've seen.
You need to do manually what Batch API does for you automatically in Drupal 7: use a queue.
The Drupal Queue module is a Drupal 6 backport of the Queue API that is in core for Drupal 7.

Basically, queue the items you want to process, and then only pass the queue ID to Batch API.
Batch API then fetches the queue and processes the queue part by part until it's done.
See batch_example_batch_2 from the Examples project for reference.

The Examples project also has an example module for queue usage, see:
http://drupalcode.org/project/examples.git/tree/refs/heads/7.x-1.x:/queue_example


Rendering form manually When making my ticket-system I want managers to be able to reply to tickets when viewing the ticket. On the page to view any ticket I load my form. Because I want it to be a bit more fancier than just the default 'element under element' style I render each item by item manually.

<?php print drupal_render($form['open']); ?>

Now the problem is, my form doens't work. Clicking on my rendered submit doesn't perform any action.

My guess is that rendering each item manually doesn't include the 'form container'. How should I include is? Or is my style of working completely wrong?

The best way to implement custom rendering of a form would be to use a custom theme hook for the form:

/**
 * Builder function for the ticket form.
 */
function MODULE_ticket_form($form, $form_state) {
  // Build the $form array here...

  // Let the theme API knows that this form use it own theme hook.
  $form['#theme'] = 'ticket_form';
  return $form;
}

/**
 * Implements hook_theme().
 */
function MODULE_theme() {
  return array(
    // Custom theme hook for the ticket form.
    'ticket_form' => array(
      'render element' => 'form',
    ),
  );
}

/**
 * Default implementation for the ticket_form theme hook.
 */
function theme_ticket_form($variables) {
  $form =& $variables['form'];

  //Custom rendering of forms elements goes here...
  $output = ...;

  // Render every other elements (incl. hidden system ones).
  $output .= drupal_render_children($form);
  return $output;
}

Instead of using only a theme function, you can also use a template file. The theme function can also return a render array instead of a string.


Showing user image for custom comments created in a view I am using a Drupal view for displaying comments.

I have the show: in the format field set to comments.
Therefore I won't be able to add extra fields in the field's section.

I have a custom URL where I show the contents of a node along with its comments and a comment box which I have custom coded.

How can I add a user image along with my comments?

Try adding a "Relationship" to the comment author, and then add the user picture from the updated field list.


How to change "to" to "-" while displaying start and end date in views? When using views to display start and end date by default it adds "to" text in between two dates, I was wondering what is the appropriate way to convert "to" to "-" or anything else.

Thanks

My answers assume I have a field called "field_event_date" which shows as Content: Event Date in my view.

Answer #1 - Use View Template

Under the Advanced Section of the view, under the Other section, open Theme Information
Copy the filename of the last theme option for Field Content: Event Date, in my case it will be views-view-field--VIEWMACHINENAME--BLOCKMACHINENAME--field-event-date.tpl.php
Copy the following into it:

<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>

<?php print date("Y-m-d H:i:s", strtotime($row->field_field_event_date[0]["raw"]["value"])); ?>
 -
<?php print date("Y-m-d H:i:s", strtotime($row->field_field_event_date[0]["raw"]["value2"])); ?>

This will output something like 2014-08-09 20:15:00 -
2014-08-12 20:15:00, format using the date() format string.

Answer #2 - Use View Fields

Under Fields, add Content: Event Date and set the Display to "Start Date Only"
Under Fields, add Global: Custom Text and set Text to  -
Under Fields, add Content: Event Date and set the Display to "End Date Only"
Under Field Settings, Set the three fields above as Inline.

This will output something like Sunday, December 1, 2013 - 12:00 - Sunday, December 1, 2013 - 12:00, based on the format you have chosen.


Adding links to EntityForms on submission confirmation page I'm working on a site that has a series of EntityForms I'd like to guide users through. After filling out the initial form, I want the submissions confirmation to recommend subsequent forms based on some of the values in the submission. I figure I can do this with a custom form submission handler, but I was wondering if it would also be possible to do this with Rules. I can make a Rule trigger on EntityForm values, but I don't know what kind of actions to include (I haven't done much with Rules yet).

Any thoughts on using Rules here, or any other approaches to this problem?

One rules action you could use would be the System > Show a message on the site where you could use replacement patterns to build your recommended links to other forms. This way users would always see the message regardless of the initial entityform redirection page. (This is actually a very handy concept and I will file it away for future use :)

Note: in order to get the replacement patterns you need, you may need to add conditions to your rule in order to make the right data available to the rule.


Creating breadcrumbs based on content type relationships Currently I have 3 different content types: Program, Chapter, Item. A program contains multiple chapters and a chapter contains multiple items. These are related to one another using node reference field types.

On the item page I would like to have a breadcrumb listing: Program --> Chapter that is related to that specific item node.

I've looked into Custom Breadcrumbs and Page Breadcrumbs, but can't seem to figure out how to pull in the chapter and program that it is related to.

For the time being I was able to figure it out by adding node reference fields to each of the content types. Then referencing my items to the chapters. I then found the Corresponding Entity Reference Module and used that to link them up. Using Custom Breadcrumbs I could use the reference tokens to create my breadcrumb.

Only downside is that I had to go into each item node. Took some time!


How to change value of a field in hook_node_view In hook_node_view() I want to rewrite some fields' values. The $node parameter is not referenced, so how can I rewrite a value?

Take a look at the API documentation for hook_node_view, specifically the comments at the end of the page -> Has anyone been able to successfully modify a node object?. There's talk of using hook_node_load as a solution as well as many of the hooks that are field specific. Note the comments at the bottom of the hook_node_load API page that explains why $nodes is not called by reference but is still changed when changes are made to the variable within the hook re: OOP -> http://php.net/manual/en/language.oop5.references.php.


Get "Raw" views data (with no or little markup) One thing i hate about views is this bunch of markup and nesting it uses to render the data on a page.

What i usually do to remedy this problem is iterate through the content variable and trim all tags so i can them display it as i wish. I know this kind of a dirty shortcut and i was wondering if there was a better way to do so.

Can' t views only output the raw data from the DB without adding all that markup to it ?

Are you using Views 6.x-3.x or 7.x-3.x? If so, you can do a ton of the grunt work of stripping out views' default markup by adjusting fields' 'Style settings'. If you're using an older version of Views, Semantic Views does just about the same thing. One gotcha: If you don't want the default  wrapper around each field, you need to check the 'configure the field and label wrapper' option and set it to 'None' - that trips me up sometimes.

To adjust the other bits of markup around, for example, the entire view, or each row, you can copy the views template files (in the views/theme folder) into your theme's folder, and modify them to your heart's content.

The reason Views creates all this extraneous markup is that it is trying to be all things for everyone. I find, a lot of times, that it's easiest (and barely helps performance or page load times) to just go with the default markup, unless I'm trying to do some advanced theming. There's a class for just about everything!

On another note – if you're trying to return just some data, in a format like JSON or XML or something similar, you'll want to use a different display type for views besides one of the standard 'Unformatted fields' or 'list' types...


Password strength with password type field on registration On my site, I have 10 different registration forms it means altered register form 10+ times and added different field on different scenarios. So on another new registration form, I have to remove confirm password field as it was required according to design so I did this way.

function HOOK_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'user_register_form':
     $form['account']['pass']['#type'] = 'password';
    break;
  }
}

So, as core's functionality we have password strength with the confirm_password field on registration and by changing confirm_password field type to password it also removes password strength that I really need with password field.

Is there any way to do that?

You can do this with jQuery, something like this should work.

$(document).ready(function () {
  $('.password-field').blur(function () {
    $('.password-comfirm').val($(this).val());
    $('.password-comfirm').hide();
  });
});


if i am on a node page how can i get one of the taxonomy terms for that node? In drupal 8, if I am on a certain page, how can I get the taxonomy terms for one particular taxonomy that that node has ?  I want to do this in a custom module

You should be able to access it via its field:

$node->field_taxonomy->value


Drupal ignoring changes to settings.php I made a copy of one of my drupal sites and I'm attempting to set it up to use a different database but for some reason it's ignoring changes to my settings.php file. My settings.php file is in sites/default/settings.php and contains the following

$databases['default']['default'] = array (
        'database' => 'my_db_database',
        'username' => 'my_db_user',
        'password' => 'my_db_password',
        'host' => 'my_db_host',
        'port' => '3306',
        'driver' => 'mysql',
        'prefix' => '',
        'collation' => 'utf8mb4_general_ci',
);

However the changes I made to it don't seem to take. It's still using the old database. As a test I even put in incorrect information and tried commenting everything out to see if I can break it, but there was no effect. I also checked to make sure there was no local.settings.php file.

Is there something that needs to be done to reload the settings.php file. If not is there a way to see what settings.php file is being used in case there's another file overriding it?

UPDATE: Turns out the issue was a dummy mistake on my part. The domain was pointing to the wrong server. However I'm not closing this question because I believe these answers could be helpful to others in similar situations.

Check with including namespace.  Also, check if any other code override configuration or do you enabled settings.local.php. Add this code to the bottom of settings.php

 $databases['default']['default'] = array (
  'database' => 'my_db_database',
  'username' => 'my_db_user',
  'password' => 'my_db_password',
  'prefix' => '',
  'host' => 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);


Can Drupal site logout user when he change IP Address? Can Drupal site logout user when he change IP Address or ask user to confirm password again?

I need to implement follow requirements:

Log source IP address changes during application sessions.
Notify the user of potentially suspicious activity.
When IP address changed, ask user to confirm password again.

I'm not aware of any contrib module providing all these features out-of-the-box.

If you are on Drupal 7, you might want to give the IP Address Manager module a try, which provides user-based IP address logging and can be extended programmatically with your own module.

For Drupal 8 you may have to create it from the scratch. Which shouldn't be too hard, if you have appropriate knowledge of Drupal 8 programming.

Btw., I also strongly suggest adding another feature to your requirements: Save the previous IP into the active session (cookie) and check, whether the user just switched the IP during the session (e.g. by means of VPNs), but is still using the same device/browser. - I always find it quite annoying and a bad user experience getting captchas/password dialogs when trying to access sites securely with switching IP addresses. (Which I need to when working from within China. ;)


Redirect loop served from cache My Drupal 8 site occasionally (maybe once a week) gets a redirect loop for an url. The redirect sends a 301 Moved Permanently for that url to the exact same url; not even a to and fro redirect loop. Clearing the Drupal cache will fix the problem.
It is not always the same url - it seems pretty random.

I'm including the full anonymized http response:

HTTP/1.1 301 Moved Permanently
Server: nginx
Date: Tue, 13 Jun 2017 11:41:56 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
X-Powered-By: PHP/7.1.5
Cache-Control: must-revalidate, no-cache, private
X-Drupal-Route-Normalizer: 1
X-UA-Compatible: IE=edge
Content-language: nl
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Expires: Sun, 19 Nov 1978 05:00:00 GMT
X-Generator: Drupal 8 (https://www.drupal.org)
X-Drupal-Cache: HIT
Location: http://www.domain.ext/lang/parts/of/url
X-Powered-By: PleskLin
MS-Author-Via: DAV
Content-Length: 488

<!DOCTYPE html>

        <meta charset="UTF-8" />
        <meta http-equiv="refresh" content="1;url=http://www.domain.ext/lang/parts/of/url" />

        <title>Redirecting to http://www.domain.ext/lang/parts/of/url</title>

        Redirecting to http://www.domain.ext/lang/parts/of/url.

X-Drupal-Route-Normalizer: 1

That's either the redirect module or the corresponding core patch, I guess the first.

There have been a bunch of bugs in the past about this but it should work now if you update to the latest version.

This for example someteimes happened with different url query parameters, or a trailing ?, e.g. "some/url?", redirect.module redirected that to /some/url but the page cache in Drupal core actually cached it for a normalized URL without ?, so it cached a redirect to /some/url as /some/url, and then you have your redirect loop.

If you can still reproduce with the latest redirect version, then open a bug report. Also make sure that you are not using a Drupal 7-style configuration for nginx (that e.g. adds a ?q=path qery parameter)


Is there a way to make a unique view template for a specific type of view? I needed to edit the views-view-unformatted.tpl.php for a specific view, however I'd rather it not apply to every view. Is there a possible way to make a unique view template to select from? Rather than rewriting every view that uses views-view-unformatted?

Yes it is. Open the Views Admin UI and in Theme Information there is a list of available template files

For example in my website it is:

You can use any of them.


Exposed filters with dropdown selections I have a project where I've created a View with some basic information, showing for example Year, Manufacturer, Product Type. They are all custom text fields. I can expose a filter on them which lets me manually enter in a search, for example, 2008 for year and it correctly shows me all the entries for 2008.

Is there any way to have these fields available as a dropdown selection based on the content saved within each node, eg so that the Year field shows 2001, 2002, 2003 ..... 2012 etc, or Product Type shows "Table, Chair, Lamp etc" that the user can choose from? I'm fairly new to using Views and struggling to find an answer.

I'm using Drupal 7 and Views 3.3.

The problem here is that the fields are custom text fields. If the "product type" field was of the type "List (text)" instead it would be a drop down in Views when exposed.

Maybe the product type would be good to have as taxonomy terms instead? Then product types could easy be added to the vocabulary as the site grows. The field in your content type would then be a "Term reference" to the Taxonomy vocabulary product type. If the product types rarely or never change you could stick with "List (text)"

I would probably make the field year into a date field or taxomomy, or list (integer).

I hope you see where I am trying to go here, the fields needs to be of the correct type for Views to be able to interpret the fields correctly and "automatically" give you dropdowns when the filters are exposed etc.


Product Reference inside a Product Reference? In my attempt to solve a "variation can update second variation" issue, I am wondering if a Product reference can go inside another Product Reference?

So that the 'Variation' itself has a product reference inline form to another type of variation? ( I have tried and nothing shows up).

The idea is that loading 1 variation will then load the referenced product variations therein and combine the 2 to create the final price.

(This is a case where the 2nd variations price is based on what is selected in the 1st variation.)

I figured this out by using taxonomy terms (categories in commerce kickstart), and then yes, indeed, make a product for each combination. (ive heard bulk product creation can do this, and incase you are dealing with a customer input size (how many inches long do you want it), then check out custom line items and Pricing rules.

Thread on drupal commerce > http://www.drupalcommerce.org/questions/7894/adjust-variation-price-based-next-variation#comment-7566


Omega theme conflicts with CSS of Seven administration theme, how to resolve? Not sure exactly where my problem stems from but here goes: I am developing a site with an Omega4 subtheme. Something in the css rules is conflicting with the CSS for the Div: Views-ajax-popup and overwriting the default white back ground to none. This makes the UI visually hard to use, and while I can get by with highlighting the text, but my other site users are not so adept.

The issue is I have no idea what's causing the conflict, or where to address it. In chrome inspector, setting the background to white corrects what I want. The css for the body seems to be the issue, it's getting it's styles Media=screen, and I can see that the default CSS is white, but it being overwritten but again no idea from where.

So, what's causing my css conflict with the admin theme and how do I fix it?

When Drupal loads the Seven theme for admin, it doesn't load files from any other theme. Same goes vice-versa. So it's unlikely either theme can be to blame, or even involved.

There's no way to guess from here what styles are overwriting others unfortunately, you'll just need to dig further with dev tools until you find the culprit.

Methodically disabling contrib/custom modules and testing the results each time is a good idea if you can't see any where else to look in the dev tools, you can find or at least rule out a culprit that way.

You could also search the files for those modules for instances of "views-ajax-popup", maybe something you have installed is specifically targeting it through CSS or javascript.


Html mail gets broken by new lines I am using the Mail system and the Swift mailer* modules to send HTML emails. I then implemented a custom module to send HTML newsletters to users, and I noticed the emails didn't look as expected: Many styles kept broking randomly.

After digging, I discovered the problem was with the string of email randomly being broken by new lines: If a new line came in a critical position in the string, the whole mail would be broken. I needed to know where these strange new lines were coming from.

It turned out I am not doing anything to string expect this.

$body = 'some html code without new lines';
$body .= 'some more html code without new lines';
$body .= 'some more and some more html code without new lines';

$params['body'] = Markup::create($body);
$language = $recipient['lang'];
$to = $recipient['mail'];
$params['to'] = $to;
$result = $mailManager->mail('custom_newsletter_mail', 'newsletter', $to, $language, $params, $from, $send_bool);

I don't know what Markup::create($body) does, so I tried removing it. The email was delivered with no new lines, but the HTML was not rendered.

In mail system configuration, I set swiftmailer as FORMATTER and default PHP mailer as SENDER.

This is the custom module's .module file.

function custom_newsletter_mail_mail($key, &$message, $params) {
  $message['body'] = [];
  $message['subject'] = [];
  $message['format'] = 'text/html';
  $message['subject'] = $params['title'];
  $message['body'][] = $params['body'];
  $message['headers'] = array(
    'content-type' => 'text/html',
    'charset' => 'UTF-8',
    'format' => 'flowed',
    'delsp' => 'yes',
    'from' => $params['from']
  );
}

I found out that my testing environment send emails with no new lines (Email looks as expected), while my production environment doesn't. I double checked every setting; both are identical as far as I can tell.

I tried using mime mail instead of swift mailer and it WORKED!! there is no newlines or spaces (The HTML mail actually looks good), BUT mime mail only reaches live mails. It doesn't work with yahoo or gmail for some reason.

I need to fix this. I need to remove those annoying new lines in the email body, which I feel it's a swift mailer issue.

You cannot send email without line breaks.

The SMTP standard requires that lines be limited to 1000 characters. 998 really because the line must end with "\r\n".

If you successfully avoid having line breaks inserted for you, what will happen is that many email servers on the Internet will reject your email. Some will accept it, because they decided to ignore the standards. Guess who does that.

Many servers will not.

The correct answer to this problem is to create HTML email that has line breaks. This is really easy to do. Pick a few elements that occur fairly often, like </tr> if you use tables, and CSS rule end braces, and put a newline after it.

Reviewing your HTML will also help you avoid very stupid looking HTML text, if you care. I was just viewing source on a newsletter email from TweakTown where they first include a bunch of CSS rules at the top. Then every single table row repeats the same CSS as inline styles. Really. Why? No wonder their lines are more than 1,000 characters long.

So, are people intentionally creating HTML with no line breaks to save space? Because if so, CSS rule spam is the opposite of saving space.


Embed and display PDF viewer I'm looking for a solution to display some of my PDF files with a viewer.

I found many solutions for Drupal 7 but not yet for Drupal 8.

Is there any module or open source solution to display PDFs in a Viewer ?

You can use the Embedded Google Docs Viewer module for that

  Drupal 8

  This module provides a formatter for the File field type. This
  formatter presents the file as a fully rendered object within a web
  page - i.e. it displays the contents of the file as appropriate to its
  filetype (Adobe Acrobat .pdf, Microsoft Word .doc/.docx, Microsoft
  Excel .xls/.xlsx, Microsoft Powerpoint .ppt/.pptx), using the Google
  Docs embedded rendering engine.

There are some other modules but those are in Dev version. Have a look at the Comparison of PDF viewer modules


Link to a large image In D7 Commerce module, I've created a product_display content type.
With this content type, it is possible to create nodes from product entities that come from my store.
In these nodes, the images are shown but I can't figure out how to link them to a large image when hovered or clicked on.

I guess this has to be done through a basic D7 configuration.

Assuming these are normal image fields, you can go to Structure > Content types, then select manage display for your product node type.

There, click on the settings button on the right side of your image field. A settings form should be expanded now, where you can configure in which image style you want them to show up and to what they should link. If you choose link to file, clicking on it will link directly to the original file (only).

An alternative is provided by the Colorbox module, which allows to display the images in a popup-like overlay. The same settings form should have more options to choose from once you installed that module.


Commerce 2 Add to cart with quantity field and Product Picture I have added an image field in product variation type. Add few products to my store. Now when I am going to product detail page to add the product in cart it just shows the add to cart button without any quantity field. Also not showing Image of the product.

I tried to change the formatter to Rendered Entity, but it then only showing the picture  and price but not the add to cart button. Rendered Entity was using default view mode. So I created additional view mode through manage display of product variation type but that also didn't provide any option to show the add to cart button.

What I want is to display the product variation picture + Price + SKU + Add to Cart button with quantity field.

Please guide me how to achieve this.

Please check your order item type e.g. admin/commerce/config/order-item-types/default/edit/form-display/variation_cart_form (default type)

Needed view mode is variation cart form. There is quantity field.

Also check this default view mode for your product variation type /admin/commerce/config/product-variation-types/default/edit/display

There is add to cart button.


Merge Rows and Views PDF integration I've got a view that outputs a pdf business card for every student with all the classes he attends.
Someting like this:

2014
Name Surname
class1, class2, class3

To associate students and classes I use a Session content type with fields: year, entity referenced student and entity referenced class (Students and Classes are separated content types as well).

Because I need to control the exact position of every field on the final pdf, I use views PDF.
To achieve that some kind of "GROUP_CONCAT" on classes I succesfully used Merge Rows module.

My query is ok. If I try it on page display everything is all right, but when I try to make a PDF display using views PDF it shows just one value, not the entire comma separated string of classes.
I've tried many combinations of merge rows settings, played with custom html output of fields, but it seems that Merge Rows doesn't work on PDF display.
Any idea to make this work?

As suggested for invoices in the paragraph "Append and Include other Views" from views PDF documentation, I also tried to split the view into two separate views: the main and the secondary view of classes included as a field but with no success. The classes view doesn't filter content using the contextual filters passed by the main view. Removing contextual filter, I can see classes under student name, but all of them. And the query is really slow...

Another solution could be to rewrite the SQL using GROUP_CONCAT (I use MySQL)... But how?

What should I do?

Thanx in advance

Finally I solved applying this patch to views in order to get GROUP_CONCAT as an aggregate function in views UI and uninstalled views_merge_rows.
I think this is a better solution from a sql query performance point of view: views_merge_rows simply changes how data appear. Probably I was wrong in configuring something in it but I won't investigate any more.

Thanx all for reading...  ;-)


js-header and js-footer are not loading drupal 8 portfolio-library:
  version: 1.1
  css:
    theme:
      assets/css/main.css: {}
      #assets/css/font-awesome.min.css: {}
      assets/css/ie9.css: {IE: 'lte IE 9'}
      assets/css/ie8.css: {IE: 'lte IE 8'}

  js-header:
    header: true
    js:
      assets/js/ie/html5shiv.js: {IE: 'lte IE 8'}

  js-footer:
    js:
      assets/js/skel.min.js: {}
      assets/js/ie/respond.min.js: {IE: 'lte IE 8'}
      assets/js/main.js: {}

  dependencies:
    - core/jquery

This is my library file but my js files are not included in my theme can anyone please let me know what is going wrong.

You may be over-complicating this. HTML5 shiv is already in core, so you can just depend on it without any extra work. There's no js-header or js-footer keys, just use js as normal:

portfolio-library:
  version: 1.1
  css:
    theme:
      assets/css/main.css: {}
      #assets/css/font-awesome.min.css: {}
      assets/css/ie9.css: {IE: 'lte IE 9'}
      assets/css/ie8.css: {IE: 'lte IE 8'}

  js:
    assets/js/skel.min.js: {}
    assets/js/ie/respond.min.js: {IE: 'lte IE 8'}
    assets/js/main.js: {}

  dependencies:
    - core/jquery
    - core/html5shiv

If you need your own version for whatever reason, declare the shiv separately:

html5shiv:
  header: true
  js:
    assets/js/ie/html5shiv.js: {IE: 'lte IE 8'}

and depend on it:

portfolio-library:
  ...
  dependencies:
    - core/jquery
    - mytheme/html5shiv


How to get notifications for unpublished content? I want to achieve that user can view the unpublished content once they have logged in .

Unpublished content should be displayed as a notification like Topic(1).

How to achieve this ? Is there solution to achieve this?

Part 1 - Notifications
Have a look at the Menu Badges module to add such notifications to any menu item and/or menu tab of your choice.
Here are some details about it (from its project page):

Provides a method for adding iOS-style badges to menu items. (see screenshot)

Adding Badges to Menus
Once enabled, go to Administration > Structure > Menus, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.
Adding Badges to Tabs
For adding badges to menu tabs, there is a tab under Administration > Structure > Menus called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.
Badge Types
The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, you basically reduce the solution for any type of notification to something like "Just create an appropriate view of it".
Video tutorials:

Defining Menu Badges with Views in Drupal, from the module maintainer, which shows how to use it for a custom view with a menu tab "unpublished content" within admin/content.
Drupal 7 Menu Badges Module.

Part 2 - View unpublished content
You may want/have to combine this also with using the view_unpublished module. Some details from its project page:

This module allows you to grant access for specific user roles to view unpublished nodes of a specific type. Access control is quite granular in this regard.


How do you hook into a path being created via pathauto? I can't seem to make hook_pathauto_alias_alter() get called in my custom module, in either 1.x or 2.x. I'm not certain, but I'm not clear if this hook is even in pathauto 1.x.

I am trying to hook into a Pathauto alias right before it's saved, so I can make some changes to the path (remove certain words). How do you do this? Is there another method besides a hook in the Pathauto module?

I have a module that let's the user enter in a list of words they want to filter from nodes; I would prefer not to enter it in two places.

The UI has this built in as it happens, if you visit http://mysite.com/admin/build/path/pathauto and look in the "General Settings" fieldset you'll find a textbox containing a list of strings to remove from aliases:

hook_pathauto_alias_alter is definitely the right way to do it; it's available in both the 1.x and 2.x branches. Have you run any debug code to see if the hook is actually being called? And did you clear the caches? Hook implementations are cached (in Drupal 7 anyway; I can't remember if they are in Drupal 6 or not).

In case you're still wondering most modules that declare hooks come with a MODULENAME.api.php file which lists those hooks and how to use them. In the case of pathauto the file and hook function declarations are there, but sadly there's no documentation.


How to remove selected topics from aggregator feed? In my Drupal feed aggregator generating a separate website feed into my website. However, my client dislike some topics on that feed therefore, is it possible to remove selected topic from that feed ?

Probably you must implement hook_aggregator_fetch for this job.


Installing live drupal website in local I am trying to install my live drupal (version 8) website in localhost. I have downloaded the files and folders. I have imported the database. And updated settings.php file.

But when I try to log in, after entering username and password, the page redirects to core/install.php and I get this message - "Drupal already installed".

what does this mean? How can I resolve this?

This error message is shown when you try to install Drupal, but the Drupal install script detects that there is already a populated (i.e. not empty) database present in the database pointed to by settings.php.

Here is how you set up an empty database to hold Drupal (provided the database is named "drupal").

$ mysql -u root -p
Password:
mysql> DROP DATEBASE drupal;
mysql> CREATE DATABASE drupal;
mysql> GRANT USAGE ON *.* TO drupal@localhost IDENTIFIED BY 'password';
mysql> GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, INDEX, ALTER,
    -> LOCK TABLES, CREATE TEMPORARY TABLES ON drupal.* TO drupal@localhost
    -> IDENTIFIED BY 'password';
mysql> quit
Bye
$

This will create an empty database named "drupal", belonging to a database user named "drupal", with the passord "password". (Choose a more obscure password than "password".)

Then delete settings.php and copy default.settings.php to settings.php.  Do not edit it. Make sure the directory where settings.php lives and settings.php itself is writable by the web server.  That will make the install script create a new settings.php with the correct values during the install.

After doing all this: Start again installing Drupal.

After installation is complete, change the permissions for settings.php and its directory back to safe values.  Check that there are no warnings in the Drupal status report.


Is it possible to hardcode views as part of the custom module to avoid `config/sync`? I've exported views into the custom module using Drupal Console and config:export:view command, so they exist as part of the module in modules/custom/my_module/config/install (YAML files).

After I've enabled the newly created custom module, the views are imported on install as expected.

However when I'm trying to to do config import (drush config-import), Configuration Manager wants to remove the views. Respectively, when I want to export (drush config-export), it asks to create them in ../config/sync (despite they're already existing in the module it-self).

What I'm looking is, the ability to hardcode the views into custom module, so they won't be part of ../config/sync anymore, so config import won't affect or remove them. In other words, I'm looking for locking down mechanism to avoid accidental removal during config import on the production (something similar to hook_views_default_views in D7), where views are hardcoded as part of the code.

Yes that's right the config export will recreate them for its config sync handling. The /module/config/install is exactly that, just for install time. The config syncing would become a big mess of overlaps if every module could define different elements to handle syncing themselves. Is it such a problem that config sync has them? As that can be your master of that the view should contain. So think of it as: The module sets up the default upon install and Drupal's config sync will make a copy so that's now the master and won't get removed unless you remove it through the UI and then do a config export.

If people are paying attention it should hopefully be unlikely someone would delete a view from the UI, do a config export and do an import on live without realising they've messed up. But just in case have you thought about adding your config sync directory into GIT? So that if someone does say delete a view through the UI and do an export you'd be able to revert


Creating a content type that merges fields with its assigned area within the body I have a requirement to build a content type that has a number of fields and also the body section which is where the html goes.  When new content is added using this new content type the user would enter information for all the fields (like city, state, zip, etc) and at the point of saving the content that is created is a combination of what was already inside the body section plus the fields values would go in their assigned areas within the body section.
What possible ways could this be implemented?
Any recommendations for modules that do the above?

I think it sounds like you want to write a node template. http://api.drupal.org/api/drupal/modules%21node%21node.tpl.php/7

Basically you are going to create a template file called node--content-type-name.tpl.php and in that template you have access to the $node object which contains fields. Then write your html and use the values from $node.


Debuging OG access field I have few roles in OG groups: Visitor, Reviewer, Member, ...

Visitor and Reviewer are added roles with (at the moment) exactly the same settings. Unfortunately somehow Visitor is inheriting Member's access rights while Reviewer is not.

I checked everything and all looks fine. I tried hacking OG code (I switched off the default role inheritance), checked og_role_permission table and all looks fine. But still whenever I give some rights to the Member role, Visitor user is somehow inheriting them while Reviewer is not.

My website is making use of OG roles everywhere. I have context, rules, custom code depending on it. And while everything works fine, field_access is behaving strange.

Do you guys have any idea how can I go on with debugging this issue? Is there a place in node_access module where I could put some debug code informing me what is going on?

UPDATE

I switched off all the custom code, changed drupal core to older version, made sure that access settings for Visitor OG role are exactly the same as Reviewer's.

I rebuilded cache, rebuilded access rights, changed browsers, went through code in OG and data stored in the db.

Still users with Visitor OG-role inherit rights from Member OG-role, while Reviewer does not. This bug is killing me.

Unfortunately I have to surrender. There is a bug somewhere in the og module but I can not track it down. What happens is that the default group membership role can not be changed. Changing the definition of OG_AUTHENTICATED_ROLE in the og.module does nothing. Because of that all the access rights given to the "member" role are being inherited by all the other roles and so they can not be weaker.

My solution will have to be creation of new members role - "full_member" where I will be able to define roles of that member. I will also remove all permissions from the "member" role. The problem is that I will have to redo all the rules, contexts, pages, blocks, custom code and so on. Few days of boring work and debugging.


Using "Security Review" gives file permission errors, how to fix them? I've searched the drupal docs and all over the internet, but I don't find a concrete answer regarding what file permissions the drupal directory should have.

I've been redirected to this page: http://drupal.org/node/244924

On almost every search, but this page doesn't actually tell me what each file's permission should be. I'm trying to pass "Security Review's" permission test, but it literally says ALL my files have wrong permissions.

I know its a very specific question, but can anyone give me a specific CHMOD number for each directory and files in the directories?? I've spent a good portion of the day looking for this with no success..

If your webserver user is the same as your account user that you use to login and update the files, then the files should be 440 and folders 550. However, this will make it hard to edit or update the code of the site as you will have to change the permissions back to 755/644 before doing the update.

Note, also, that using anything other than 0 as the final digit in the three is likely the wrong value on a shared server where you do not know/trust every user of the server.

The security review test is about "defense in depth" that prevents a poorly coded file-upload tool from becoming a way to overwrite executable files in Drupal's installation. Sometimes it's OK to ignore some of the reviews from security_review module.


How to get views machine name in `block--views-block-html.twig` file? I've create views as block. Then i tried to theme my views block by altering block--views-block-html.twig file. I've struggled to get views machine name in this file. I need views machine name for some reason. So any other solutions to get views machine name?

Views machine name would be: /admin/structure/views/view/frontpage.

You can edit/change the view name on right corner: Edit view name / description.

You can override the template name using below.

[base template name]--[view machine name]--[view display id].html.twig
[base template name]--[view machine name]--[view display type].html.twig

So this would be:

views-view--frontpage--page.html.twig

or:

views-view--frontpage--block.html.twig

There is no theme information is displayed with D8 views as D7 views was having the those information.

Please refer the reference page.