How to decrease the width of the sidebar for a specific page? Is it possible to decrease the width of my right sidebar for any specific page only? If so, please shed some light on that.

I have created a basic page whose node id is 56. In that page I want my right sidebar region to occupy less width than it normally does. This can be done through CSS but I want to know if there is a way to do that through Drupal, either with coding or without it.

You could use drupal_add_css() to conditionally include a custom CSS file on particular pages.

You could also add a custom template in your themes templates folder. If you clear caches after including it, it will automatically be included as long as it follows the Drupal template naming conventions.


What is the best way to preprocess fields with Display Suite I'm using Display Suite with Drupal Commerce, and I need to pre-process some fields in my product display.  I need to change some values based on some conditions, and need to wrap a few fields in some markup.  Should I write a hook to pre-process and change the values, and use a template to wrap the fields in markup?  If so, which template file would I use, because DS comes with a few templates.

You can customize your field at theme level by using TEMPLATE_preprocess_field() function at template.php

You can get get some field value by node object or by fetching field values itself. You can do something like this to get fields value by node object --

function MYTHEME_preprocess_field(&$vars) { //Replace your theme name MYTHEME here.
  if ($node = menu_get_object()){
    if($node->type == 'PRODUCT_DISPLAY'){//Use your product display name here.
      $vars['node'] = $node;
      $product_id = $node->FIELD_PRODUCT_REFERENCE[LANGUAGE_NONE][0]['product_id'];//Use your product ref field name here.
      $product = commerce_product_load($product_id);
      $manufacturer = $product->FIELD_PRODUCT_MANUFACTURER[LANGUAGE_NONE][0]['value'];//Use your field name of product type here.
      $final_body_label = "Description by ".$manufacturer;

      //Set body label for node from here itself.
      $node->content['body']['#label_display'] = $final_body_label;

      //Or set a variable to use it further.
      $$vars['manufacturer_description'] = $final_body_label;
  }
}

Further you can use your default template for node or page if it fulfils what you want or you can make separate TPL for fields too, which will be named like field--field_image.tpl.php, where field_image is field name of your content or product.

You will get default field.tpl in $base_path/modules/field/theme.


Get only Taxonomy from $content array I need to get the taxonomy from the $content array to print in the node template.  How can I do it? I tried with $content['taxonomy']. Where can I get a guide with all params in $content array?

$content contains the renderable elements of your node (see documentation on node.tpl.php). This contains the node body, links, and other custom fields you've added to your node type. As Andrew suggested, the drupal_render() function can print individual fields or all fields (render($content)).


Profile2_path form_alter - Anonymous user form - access denied problem I have created a custom profile type and given it a unique registration path using profile2 registration path. I am attempting to form alter the custom fields but I cant seem to find a way to view the from as admin in order to view the form array.

Whenever I go to the custom path of offers/register as admin I get an 'access denied'. How can I view this form that is for anonymous users whilst logged in as admin so that I can kpr($form);?

Thanks in advanced.

I set devel module permissions of 'Access developer information' to anonymous user .
Make sure to disable this module on a production site.


Unsupported Operand Types theme_image_style I'm using the following code to generate a thumbnail and it's URI. The URI works on its own (though it 404's) but whenever I add theme_image_style function it gives a fatal error: "Unsupported operand types in /theme.inc on line 1088"

$image_fields_src = array_column($image_fields, 'uri' );

// thumbnail uri
$thumburi = image_style_path('thumbnail', $image_fields_src[0]);
// generate thumbnail
$thumbnail = theme_image_style('thumbnail', $thumburi );

According to theme_image_style page you tried wrong parameters,

as an example, your code should be something like the following snippet

$variables = array(
        'style_name' => 'thumbnail',
        'path' => $image_fields[LANGUAGE_NONE][0]['uri'],
        'width' => $image_fields[LANGUAGE_NONE][0]['width'],
        'height' => $image_fields[LANGUAGE_NONE][0]['height']
);
$thumbnail_image = theme_image_style($variables);

and in short

$thumbnail_image = theme('image_style', array(
        'style_name' => 'thumbnail',
        'path' => $image_fields[LANGUAGE_NONE][0]['uri'],
));


Mail is sending after running the cron I have created a rule to trigger an email in user profile. But I could see the email after running cron only or else I could not see email in my inbox. Why is this? Can any one help in this please? I want to send an email automatically on particular date even though if I don't run the cron.

Can anyone help me? You will be appreciated.

By programming theory anything is related to action, when anyone do any action then he get any result or response, in your theory I can not able to understand the action.

But I would like to suggest you by default every trigger works when cron runs, if you want to send mail without cron then set trigger on any action.

Enjoy!


Add animation/fade to modal/dialogue box (without using the bootstrap) The current state of a modal/dialog opening in Drupal 8 (and 7 for that matter) is pretty clunky from a user experience perspect. Leveraging some type of animation/fade would really enhance the elegance + cohesiveness of the modal. I notice bootstrap allows a "fade" class on the modal, which gives it a fade effect (I assume). Is there a way to add this type (or any type) of animation to a Drupal 8 modal without needing bootstrap? Am I missing something simple?

Edit:
Thanks for quick replies and patience with a newbie. So I'm opening a node/add form into a modal with a link like so..

Add Article

I'd like the modal to open/close with a fade effect (or slide in, etc).
Is there a way to leverage JS, CSS or Drupal itself to create this animation?

Is there a better solution all together to displaying a node/add form in a popup/lightbox type element with ajax?

Thank you!

What do you need the modal to do? I often use animated modals for my Drupal projects - http://joaopereirawd.github.io/animatedModal.js/

It seems to work pretty well for menus and forms in my experience.

It uses animate.css ( https://daneden.github.io/animate.css/ ) which you can use also to create some nice transitional effects.


How do I create content of the day/week/month? I have a (growing) number of articles. I want to display one on the homepage as article of the week, although that week will probably be a day in the beginning and a month later on. I also want a specific editor be able to choose which of those articles will be the chosen one for a given time period. There will only be one chosen article for any given time. What is the best way to do this (preferably without programming)?

I first thought of creating a vocabulary (with a date field and an entity reference to an article field) for this where the editor can simply add days/weeks/months as they come and select from the articles. The bad part here is that the name field is required and I cannot ui wise set it to take the name from the actual date field.

Making it then a custom content type instead would probably work, but seems overkill.

Adding an article of the timeperiod date field to the article content type would also seem to encapsulate all the necessary information, but how do I expose this to the editor?

I want the editor to see a list of the coming say 20 months and assign to each an article on the same page (a single save operation from the editor's point of view). I also want the editor to be able to override that for specific shorter time periods.

I'm using Drupal 7.

Using the Flag module seems like a no brainer to me to get this to work: introduce a global flag that is allowed to be used by your editors to flag relevant articles. Since Flags are fieldable, you could add extra field(s) to such flags to let the flagging user indicate an appropriate start date and end date.

With the above in place, you've reduced your question to creating an appropriate view (using Views) which shows the flagged article(s) for which their flag fields (start / end dates) have appropriate values as compared to the current date.

This solution is "without programming" (as in your question) ...

Ps: I'm assuming this is about D7.


Splitting existing feature into several smaller. Safe? I have this really big feature where all CT, fields, views etc are exported. As far as I understand it makes sense to make it into smaller features, more context specific, like features_views, features_fields, features_CT etc.

The big feature is already enabled in production, is it safe to disable it and enable the other 3? Which approach should I follow?

Direct Answer
If you take the appropriate precautions, and test locally first, it should be safe to break up the feature.
Background
If you want to split the big feature up, you need to make ensure that disabling the features does not affect the configuration of your site. Then you can disable the feature and use features to carve up the config differently and export as smaller component features.
I understand your point that one big feature is not that useful, as the individual components are not then transferable via features to other sites (or from dev to production), which is one of the uses of features.
I agree with letharion that it makes much more sense to divide your features along the lines of functionality (eg blog, gallery) rather than along modular lines (eg views, fields) otherwise all of your features will be interconnected anyway, in that disabling one will break dependent functionailty on the site. For example if I export a content type in one feature, and a view using that content type in another, then I would have to declare that the views feature is dependent on the content type feature. Functional features are also easier to document sensibly in version control.
Method
I have taken solution from my own previous comment on d.o
You can use the Features Tools module to disable a module while leaving functionality in place. You can then re-export your config as smaller features.

First BACKUP YOUR DATABASE
backup your feature (files) if you would like to use it again.
Install Features Tools, go to the 'recreate' page for a feature, uncheck all of the features components
Now click on the 'Safe autocreate' button to recreate and replace the feature with an empty version.

You can now disable the module without affecting your site configuration.
These instructions are for D7, if you are using D6 there is an extra step.
See ftools project for more complete documentation.
http://drupal.org/project/ftools
PS - unchecking all the boxes in the features ui is much quicker if you install a browser plugin like check all first.


Remove uploaded files before the 6 hours cron? I have a custom Content Entity in wich definition there is a 'file' field.
The file widget works fine.
The 'Browse' button allows to select a file and uploads it to the proper server directory and the 'file_managed' and 'file_usage' tables are updated accordingly.
If I delete the entity, 'file_usage' record is deleted and in 'file_managed' table, the record has its status field set to '0'.
What I understood is that cron job removes all files in the directory with status = '0' after 6 hours.
My question is: how to have the file removed just after the submission of the delete form?

file_cron() contains the code that delete managed files. To adapt it to delete those files with their status set to 0, this is what I would use.

$file_storage = \Drupal::entityTypeManager()->getStorage('file');
$fids = Drupal::entityQuery('file')->condition('status', 0)->execute();
$files = $file_storage->loadMultiple($fids);

foreach ($files as $file) {
  $references = \Drupal::service('file.usage')->listUsage($file);
  if (empty($references) && file_exists($file->getFileUri())) {
    $file->delete();
  }
}

This code returns you all the files matching those conditions. You can also use the following code to get them in batches of 100 per time.

$file_storage = \Drupal::entityTypeManager()->getStorage('file');
$fids = Drupal::entityQuery('file')->condition('status', 0)->range(0, 100)->execute();
$files = $file_storage->loadMultiple($fids);

foreach ($files as $file) {
  $references = \Drupal::service('file.usage')->listUsage($file);
  if (empty($references) && file_exists($file->getFileUri())) {
    $file->delete();
  }
}

I didn't check, but it is probable you can also filter the returned file entities by the bundle using them.


Change module settings stored in an array with drush I would like to configure a module (addtoany) settings with drush. This is the variable:

addtoany_nodetypes: Array
(
    [about_us] => about_us
    [contact] => contact
    [page] => page
    [legal] => 0
    [webform] => 0
)

So that, for instance:

[page] => page
[legal] => 0

becomes

[page] => 0
[legal] => legal

But I am rather new at drush and I am at a complete loss. Thanks for your time.

Drush does not have any mechanism to convert commandline arguments into php arrays for the variable-set command; however, it is easy to write short php snippets using the php-eval command ('ev' for short).

For example, if you have set up a site alias for your site called "@site":

$ drush @site ev 'variable_set("addtoany_nodetypes", array("about_us" => "about_us", "contact" => "contact", "page" => "page", "legal" => 0, "webform" => 0));'
$ drush @site vget addtoany_nodetypes
addtoany_nodetypes: Array
(
    [about_us] => about_us
    [contact] => contact
    [page] => page
    [legal] => 0
    [webform] => 0
)
$ drush @site ev '$v = variable_get("addtoany_nodetypes", array()); $v["page"] = 0; $v["legal"] = "legal"; variable_set("addtoany_nodetypes", $v);'
$ drush @site vget addtoany_nodetypes
addtoany_nodetypes: Array
(
    [about_us] => about_us
    [contact] => contact
    [page] => 0
    [legal] => legal
    [webform] => 0
)

If you are not using a site alias, then cd to the Drupal root of your site (or cd to the sites folder that contains settings.php if using a multisite) and remove the "@site" from the examples above.


Display a block when a view doesn't return any result On node/48, the page is composed from a text and a view. I would like to display a block when the view does not return any result.

How can I achieve this?

You can call your block inside "No results behavior", using a "Global: Text area" and the "PHP" Text format.
But you won't be able to display it where you want, it will have to be at the same place as the view.


Generate Install Scripts from current Nodes, Views, Fields in Drupal I have theme with custom content types, views, etc. and i would like to package into a custom module so it can be easy installed in another Drupal instance via MODULE_install().

Currently, Module_install() looks something like this:

function MODULE_install(){
    $t = get_t();
    foreach (_jobs_installed_fields() as $field) {
        field_create_field($field);
        drupal_set_message($t('Field type: '.$field['field_name'] . ' created'));
    }

    foreach (_jobs_installed_field_instances() as $field) {
        field_create_instance($field);
        drupal_set_message($t('Field instance: '.$field['label'].' initiated and added to User Profile'));
    }

    drupal_set_message($t('Finished adding fields to User profile'));
}

function _jobs_installed_fields() {
    return array(
        'field_name' => array(
           ...
        ),
        'field_name2' => array(
           ...
        ),
     );
}

function _jobs_installed_field_instances() {
    return array(
        'field_name' => array(
           ...
        ),
        'field_name2' => array(
           ...
        ),
     );
}

The content of _jobs_installed_field_instances and _jobs_installed_fields functions is generated via PHP Execute Script Dev module block from the current instance content and then copy/paste in the install script.

$entity_type = 'user';
$field_name = 'field_name';
$bundle_name = 'user';

$info_config = field_info_field($field_name);
$info_instance = field_info_instance($entity_type, $field_name, $bundle_name);
unset($info_config['id']);
unset($info_instance['id'], $info_instance['field_id']);
include_once DRUPAL_ROOT . '/includes/utility.inc';
$output = "field_create_field(" . drupal_var_export($info_config) . ");\n";
$output .= "field_create_instance(" . drupal_var_export($info_instance) . ");";
drupal_set_message("<textarea rows=30 style=\"width: 100%;\">" . $output . '</textarea>')

This can be lot of work for larger Themes and i cannot rerun it later once the change is introduced. I was thinking creating some Php scripts that would generate me the install script from the current nodes, views, etc so i can rerun as like in future. Is there anything like this already available? What would be your approach to this problem? Thank you

Looks like Features module is what you really want:

The features module enables the capture and management of features in Drupal. A feature is a collection of Drupal entities which taken together satisfy a certain use-case.
Features provides a UI and API for taking different site building components from modules with exportables and bundling them together in a single feature module. A feature module is like any other Drupal module except that it declares its components (e.g. views, contexts, CCK fields, etc.) in its .info file so that it can be checked, updated, or reverted programmatically.

With addition of UUID Features Integration:

The UUID Features Integration module provides a mechanism for exporting content (nodes, taxonomy, fields) into a features module. What's that you say? You thought features was only for configuration? This module is meant to be used in the cases where certain pieces of content straddle the line between pure content and configuration.

Of course you will probably only use a subset of it's capabilities, but it should cover all your needs with content types, nodes, and views definitions.


Drupal Ubercart Merchant ID and Key are incorrect? When I checkout in Ubercart the merchant key and merchant id are incorrect. In my configuration they are correct, but when the login credentials are displayed during checkout, they are jumbled.

I am using the uc_domain module to manage different payment gateways per domain. My original domain is working correctly, but my new domain, as seen in the image, is not working correctly.

The main error that I am getting is this:

  DOMDocument::loadXML() [function.DOMDocument-loadXML]: error parsing
  attribute name in Entity, line: 1 in
  .../ubercart/payment/uc_cybersource/uc_cybersource.soap.inc on line
  31.

Screenshot:
 http://yfrog.com/gzv1tpp

To fix this issue I made sure that the proper soap packages were installed.
Then I went on to create new credit card encryption keys for each domain. Right now I am waiting on SSL certs so that Drupal can generate new credit card encryption keys for each domain. I hope it works!


How to know that the user has completed a quiz? Is there any function to pass the user id and the quiz node id and get true or false if the user has completed the quiz?

Or I have to write sql query for this?


user_load_by_mail is not working I created custom module, and the module uses the mymodule_boot function. Inside that function I wrote user_load_by_mail to check the user is exists or not. But it is not working and I am not able to access site. It throws http error 500.

You cannot call user_load_by_mail function in hook_boot because this hook is called before the theme, modules, or most include files are loaded into memory. It happens while Drupal is still in bootstrap mode.

To get this function work you need to add this code before calling user_load_by_mail function:

drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);


Devel output on hooks called during cron run I'm implementing a hook that is called if certain conditions are met during a cron run.

(Specifically hook_bounce_mails_blocked($mails) from the Bounce module)

The hook is triggered, but any output from dpm() functions is never shown. I do see output from var_dump() after cron finishes.

Is this normal behaviour? Is there a way to get devel output shown once cron finishes?

You should use the function dd() to log something during cron.
Here is the doc: https://api.drupal.org/api/devel/devel.module/function/dd/7
It will log the output to a file, which later you can investigate. I think you must have private file path set.
you could use something like this, But be careful about XSS!
$export = var_export($var, TRUE) // TRUE will cause var_export to return the output not print it.
$export = nl2br($export); // Convert new lines to
 tag for display in HTML
$export = strreplace(' ', '&nbsp;'); // Again convert whitespace to HTML specific chatacter
watchdog('my_debug', $export); // That's it!

or even easier:
but again be careful about CSSF and XSS
watchdog('my_debug', '
' . var_export($variable) . '
');

dd is the safe drupal way to go.

Update
From comments so you wont miss:

... better than dd() is ddl(), from the drupal_debug_log module that enhances > the devel module... –  DrCord

Important point to developers.
If you search drupal.org modules there are many more to  make development easier. After you found and used them, it would sound impossible to go without them (devel_themer to name one). An example search.


Add wrapper to Views Rest JSON Output I am rebuilding an API in Drupal. The structure of the JSON must remain the same.

I am using Views and Draggable Views so the user can order items on an overview page. I Enabled the view for exporting REST JSON.

The response JSON must have a structure like this

{
  items: [{...},{...}]
}

But currently views output is like this

{[{...},{...}]}

I already managed to get my desired output without views and a special export controller but unfortunately, I need draggable views in additions to views.
I also managed to create nested structures with Entity Normalizers inside an item but I want the whole output of the view is wrapped in "items".
Any help would be appreciated.

You can write a views style plugin to get through this fast. Here is an example of that, which adds an outer wrapper of results plus a totalCount item:

<?php

namespace Drupal\mymodule\Plugin\views\style;

use Drupal\rest\Plugin\views\style\Serializer;

/**
 * The style plugin for serialized output formats.
 *
 * @ingroup views_style_plugins
 *
 * @ViewsStyle(
 *   id = "serializer_count",
 *   title = @Translation("Serializer with Count"),
 *   help = @Translation("Serializes views row data using the Serializer component and adds a count."),
 *   display_types = {"data"}
 * )
 */
class SerializerCount extends Serializer {

  /**
   * {@inheritdoc}
   */
  public function render() {
    $rows = [];

    if (isset($this->view->pager)) {
      $count = $this->view->pager->getTotalItems();
    }
    else {
      $count = 0;
    }

    // If the Data Entity row plugin is used, this will be an array of entities
    // which will pass through Serializer to one of the registered Normalizers,
    // which will transform it to arrays/scalars. If the Data field row plugin
    // is used, $rows will not contain objects and will pass directly to the
    // Encoder.
    foreach ($this->view->result as $row_index => $row) {
      $this->view->row_index = $row_index;
      $rows[$row_index] = $this->view->rowPlugin->render($row);
    }

    unset($this->view->row_index);

    // Get the content type configured in the display or fallback to the
    // default.
    if ((empty($this->view->live_preview))) {
      $content_type = $this->displayHandler->getContentType();
    }
    else {
      $content_type = !empty($this->options['formats']) ? reset($this->options['formats']) : 'json';
    }

    return $this->serializer->serialize(['results' => ['items' => $rows, 'totalCount' => (int) $count]], $content_type, ['views_style_plugin' => $this]);
  }

}

Then clear cache, and change the plugin for the View under "Style".

So in your case, the final line would look like:

return $this->serializer->serialize(['items' => $rows], $content_type, ['views_style_plugin' => $this]);


Fatal error message after installng drupal I get this error message when uploading the site on the server. I really need help.

  Fatal error: require_once(): Failed opening required '/home/mydomain/public_html/includes/drupal/includes/database/select.inc' (include_path='.:/usr/local/share/pear') in /home/mydomain/public_html/includes/bootstrap.inc on line 3160

This error say that can not  the specified file '/home/mydomain/public_html/includes/drupal/includes/database/select.inc' , It may happened by 2 reason , one permission and another reason ( with more probability ) The file not exist, please make sure that the file exist or have permission .


How to calculate difference between two dates using Global PHP field? I have a global PHP field provided by views php module. I tried two functions to calculate the date difference, date_diff() and $fieldDate->difference() but it always gives me an ajax error.
I think it causes by date format of the date field but I don't know how to fix it. What is right here?

$today=date("m/d/Y");
$load = $data->field_field_date_loading[0]['raw']['value'];
$diff=date_diff($load,$today);
echo $diff->format("%R%a days");

or

$today=date("m/d/Y");
$load = $data->field_field_date_loading[0]['raw']['value'];
$diff = $load->difference($today, 'days');
echo $diff;

The function date() is a formatting function, if you want to use date_diff() your code needs to be something like:

$today = new DateTime();
$load = new DateTime($data->field_field_date_loading[0]['raw']['value']);
$diff = date_diff($load, $today);


How do you wrap a link around the block header text with Drupal? (sorry if i'm redundant) What's the easiest way to wrap a link to the header of any block title text?

I know a workaround would be to just not include a title and add it in the content; but that's not the most convenient at times.

I f I understand that your question is How to make block title a link? You can use this module http://drupal.org/project/block_titlelink


Basic Page - Associated Image Field I created an Image Field for the Basic Page Content Type.

I want to control the output of this image to use as a banner with a caption on top. Is there a function to render out a field specific to the page,

such as <?php print render($page['my_image_field']); ?>.

I wan't to style this separately from the body content.

You can do this within a tpl file specific to your content type. In this case it sounds like it'd be node--page.tpl.php

All the drupal 7 template naming suggestions are available at - https://drupal.org/node/1089656

Just make sure you have a regular node.tpl.php file in your theme before creating the new one.

From there this thread tells you how to go about printing your field elsewhere (specific to drupal 7)- https://drupal.org/node/1059636

Specific to your question:

<?php
hide($content['field_my_image_field']);
print render($content);
?>

then wherever you want your image to appear at use

<?php
print render($content['field_my_image_field']);
?>


Where to start on fixing a locations module not accurately displaying on a gmap with views I have been having problems with my locations module displaying points on a gmap using views. I have a profile 2 profile that has a locations field on it to store locations. I collect that data using a views to display it on a gmap. But this all works.

The problem I am having is the location points are in most cases not at all accurate or do not show at all. I have a list of 92 countries that are not working correctly. Some smaller countries I could care less about but ones like Barbados and Finland are not working.

I cannot figure out how to start on fixing this issue. It may be a locations.xx.inc problem, or a geocoding problem or a gmap problem. I do not know where to start.

Any suggestions?

Thanks,
Greg

As we can see, pin is rendered at the good coordinates. So the bug is in the Country to coordinates relationship data. You need to look in your database and find a table with this data. Probably, to avoid name collisions, table will be prefixed with module name.

When you have it, just update it with coordinates of capital cities, for example from Wikipedia.


Check if viewing teaser in hook_node_access Is there a simple way that I can forcibly allow everybody to view all teasers no matter what, overriding any other permissions set by Content Access, etc.

I was thinking something like this:

function mymodule_node_access($node, $op, $account) {
  if( $op == 'view' && ... viewing teaser ) {
    return NODE_ACCESS_ALLOW;
  }
  return NODE_ACCESS_IGNORE;
}

and then I would set the module weight really high. But I'm not sure how to check if viewing teaser. I would also need Views to respect the access I'm granting.

This is not possible in hook_node_access, Drupal does not allow for this so easily. Instead, you could use module Premium Content (https://drupal.org/project/premium_content) and do this in configuration.

Btw., this question has already been answered:
Show teasers to anonymous visitors but not allow access to the body/node


Finding out if panelizer displays are in use Does Drupal keep track of exactly where panelizer display(s) are in use? Basically, I would like to identify all pages across content types that use a particular display.

Is this information stored? Is there a way to get it programmatically or via the UI?

This info is not saved in the theme registry, and it's not really available per page or per node. However, it is stored per configured Panels display. Many don't have a title but since I'm using Panelizer, they do have a Panels display ID. Here's a query that returns those:

select did, title from panels_display where layout = 'mytemplate';

Entity IDs correspond to DIDs in the panelizer_entity table. Once you have queried for the DID you can query for the entity ID using the DID, like so:

select entity_id from panelizer_entity where did = 1234;

Where you replace '1234' with the DID you got from the previous query.

I have to do that second one for each DID that the first one returns in order to find all entities using mytemplate.


Do I still need to add verifications if the site has been verified through Google Analytics? I'm working my way through the items in the SEO Checklist module.  One of them is the Site Verification module. We have already verified our domain name through a Google Analytics account.  Do I still need to add a verification using the Site Verification module, or is it redundant at this point?

It's up to you, of course. from the module's page:

  This module is useful for the following search engine verifications:

  Google Webmaster Tools
  Google Apps
  Bing Webmaster Central (formerly Live Search)
  Yahoo! Site Explorer
  Yandex.ru
  Any search engine or web service that uses META tags or file upload to verify that you are the owner of a site.

You are the one to know if you will need or want assistance with verification against above tools.


drupal 7: my hook module make my site slow? I create my own hooks module, in a simple frame (to test it) to change  in exposed filter of view to 'All' , but when I enable this module, it's work fine but make my site slow .. and just when I disable it , my site back to fast, what is my mistake?

myhooks.info

name = my hooks module
description = hooks website module.
package = myhooks
core = 7.x

myhooks.module

function myhooks_form_views_exposed_form_alter(&$form, $form_state, $form_id) {
  if($form_id == 'views_exposed_form') {
    $form['name_list']['#options']['All'] = 'All';
  }
}

I see two possible reasons:

You pass form state by value. It should be passed by reference. It is a really, really big array, so copying it when there is no need to may eat up quite a lot of memory, slowing down everything.
You alter $form['name_list']['#options'] in all views exposed forms. But probably most of these forms does not have name_list element at all. So what you do can generate array items that are bad from form api point of view, slowing down form processing, and generate warnings. Server will not show you warnings, but it will save them to error logs, and writing to disk is slow.


Issues with a trigger module ("beep"). Module is not updating or changing labels in the hook_action_Info() hook i'm learning Drupal and was going through this text book to do so: "Pro Drupal 7 Development by  Todd Tomlinson".

Chapter 3 of the book teaches readers about hooks actions and triggers.  It does this by taking you through the steps of creating a module called beep that involves making a function that implements hook_action_info() to write the word Beep! to log when an event takes place.

The issue I am having is that I can enable the module in the module page and once I do it works and i see the label 'Beep annoyingly' as a selectable option but when I change the label to something else like 'Beep elegantly' it doesn't change.  Nothing is updating and it just stays as Beep annoyingly every time.  Am I missing something?  I've cleared the caches and everything too. I was thinking it might be a simple PHP syntax error but i cannot find it and have been struggling over this for some time now.

I've provided the code below. You should be able to make a module yourself with this. I'd provide the files themselves but I don't see a way to do that in this forum. Can anyone else get the labels to change? If your awesome enough to try this. make sure you have the triggers module enabled first. Thanks!

For the beep.module file:

<?php
/**
 * @file
 * Provide a simulated beep.
 */
function beep_beep() {
  watchdog('beep','Beep!');
 }
/**
 *Implementation of hook_action_info().
 */
function beep_action_info() {
  return array(
    'beep_beep_action' => array(
      'type' => 'system',
      'label' => t('Beep annoyingly'),
      'configurable' => FALSE,
      'triggers' => array('node_view', 'node_insert', 'node_update', 'node_delete'),
    ),
  );
}
/**
 * Simulate a beep. A Drupal action.
 */
function beep_beep_action() {
  beep_beep();
}

HERE IS THE CODE FOR THE beep.info FILE.

name = Beep
description = "Simulates a system beep."
package = Pro Drupal Development
core = 7.x
files[] = beep.module

The thing is that the system registers an action with the system name beep_beep_action and probably stores that in a cache. That way it's easier and faster to access the right function in your files. I've however not found that cache, nor a way to clear it.

There are three things you can do:

Accept that all others who install your module will see it right.
Rename beep_beep_action and beep_beep_action() to something else and you will register a fresh action.
Open the database and find and remove the stored action. (But only if you know what you are doing.)

I'd go for the second approach.


How to translate my drupal site in other language. My drupal site is in default English language and I have added Spanish and German languages using Internationalization and Locale Modules. When I switch to other language using Language Switcher block placed in header of my site, It translated Drupal Interface like admin menu and other core displays, but does not translate nodes or module pages which I have added. I have used t() function to display page contents or titles and its not translating them using t function.

The code for the page which I have added is as:

function MY_MODULE_menu() {
     $items['fee/per'] = array(
    'title callback' => 'attendance_og_get_title',
    'title arguments' => array('calendar'),
    'description' => t('Shows attendance percentage recorded per day for a group in a calendar.'),
    'page callback' => 'attendance_og_calendar_page',
    'file' => 'fee_management.pages.inc'
  );

    return $items;
}

function attendance_og_get_title($c) {
    return t('!entity_type Attendance Report (Aggregated)',  array('!entity_type' => ucfirst('Some Name ' . $c)));
}

File fee_managemen.pages.inc.

 function attendance_og_calendar_page($entity_type, $etid) {
       return array(
        '#prefix' => '
' .
        t('This view shows the percentage attendance recorded per attendance day in this group. An attendance day is a calendar day in which attendance was taken.') . '
',
        '#markup' => '
' . t('Loading.. I am loading here') . '

',
      );
}

Please help me to get this working.

As your module is not hosted on drupal.org, the strings it uses are not available on localize.drupal.org, where they can be translated in any language available there.

As such, you need to enable the Locale module, and translate the strings on your site.

With Drupal 7, you visit the page at admin/config/regional/translate/translate, and you get a list of untranslated strings you can translate.

In Drupal 6, a similar page is available on admin/build/translate/search.


Why cannot I install this module? I installed Drupal 8 distribution in Acquia Drupal. I am trying to install the Panels module after downloading the archive file from drupal.org.

I am not able to select the Panels module to install it.
Is there any other additional module to install, apart from the Layout Discovery module?

If you go through the panels module README file. It clearly says the below:

dependencies:
  - ctools
  - layout_discovery
  - drupal:system (>= 8.3.x)
test_dependencies:
  - page_manager

Make sure you have the above modules pre-installed for Panels.

For further help you can follow here: https://www.ostraining.com/blog/drupal/panels-drupal-8/

Else, revert back for further help.


What happens with modules and themes when I rebuild the cache? Just for learning, this document explains me in a "ballpark" way how cache rebuild works, but I want to know more about "Updates the system with latest information about extensions (modules and themes)."

What happens with modules and themes when I rebuild the cache?

To create a page Drupal needs to make several database queries. This can slow down websites with a lot of traffic. To make websites faster Drupal stores web pages in a cache.

Before Drupal 8, the common mantra was drush cc all (i.e. drush clear-cache). Now, in Drupal 8, it's drush cache-rebuild OR drush cr.

Caching is widespread in Drupal and creates many interdependencies. Improperly or incomplete cache flushing operations can cause the site to fatal error. In order to guarantee that old data is properly flushed and the site stays up and running,  drush cache-rebuild both rebuilds or re-bootstraps the Drupal site in    addition to clearing the cache

In-short, Drush's cache-rebuild command does the following:

Clears the APC cache
Bootstraps Drupal
Calls drupal_rebuild()
Clears the Drush cache (to maintain consistency with Drupal 7's drush cache-clear command)

If you would like to dig more into this check out https://github.com/drush-ops/drush/blob/659f67712adab143a2c921f9f23828782e414e8d/commands/core/cache.drush.inc#L263 at the end of the file, look at function drush_cache_rebuild().

Thanks!


Lose ability to use node load with an argument in ajax form submit I have a basic form like this, that is literally just a submit button:

function mymodule_form($form, &$form_state) {
    $form = array();

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#ajax' => array(
            'callback' => 'mymodule_form',
        ),
    );

    return $form;
}

The form uses Drupal's built in #ajax feature, and calls back to itself because nothing is supposed to change after the submit button is clicked.

I also have this form submit function that submits that form:

function mymodule_form_submit(&$form, &$form_state) {
    $node = node_load(arg(1));

    $query = db_merge('mydatabase')
    ->key(array('nid' => $node->nid))
    ->fields(array(
        'nid' => $node->nid,
        'column1' => 'value1',
    ))
    ->execute();
}

This form submit should, in theory, add the current nodes ID to the 'nid' column of mydatabase, and 'value1' to the 'column1' column. The form submit correctly adds 'value1' to my 'column1', however it adds NULL to my 'nid' column every time. But ONLY when ajax is enabled on the form. When ajax is disabled, it correctly submits the node ID. Which leads me to believe there is either an issue with using node_load in an ajax form submit, or using arg(1) in an ajax form submit.

Any advice would be appreciated.

I ended up finding a solution to this. Essentially, instead of trying to load the arg(1) inside the mymodule_form_submit (because apparently you can't do that when the submit is triggered via ajax), I instead passed the node ID to the form submit through a hidden form field. See below:

function mymodule_form($form, &$form_state) {
    $form = array();

    $form['node'] = array(
        '#type' => 'hidden',
        '#value' => arg(1),
    );

    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Submit'),
        '#ajax' => array(
            'callback' => 'mymodule_form',
        ),
    );

    return $form;
}

function mymodule_form_submit(&$form, &$form_state) {
    $node = node_load($form['node']['#value']);

    $query = db_merge('mydatabase')
    ->key(array('nid' => $node->nid))
    ->fields(array(
        'nid' => $node->nid,
        'column1' => 'value1',
    ))
    ->execute();
}

And now it works just fine.


Drupal 8 allow only listed languages Is there a way on Drupal 8 to remove "Not specified" and "Not applicable" languages from list and to display only listed Languages?

Go to Manage form display of a content type and click on settings cog on right corner of Language field. There you will see a checkbox Include locked languages such as Not specified and Not applicable uncheck it to remove options like Not specified and Not applicable.


discount coupon has applied on complete order not specific product in the order commence ( commence discount ).coupon code is applicable  only one product.  but As per attached image coupon has redeemed price on  all product in the cart.i am explaining in details here.There are two product with name
1.Preventing Sexual Harassment at the Workplace - Certificate Programme with original price ₹3,596.00
2.Intellectual Property: Law and Management - Certificate Programme with original price ₹3,596.00

i have applied 20 % coupon only first product it should be redeemed -₹899.00 but it has redeemed -₹1,798.00 rather than ₹899.00 it means it is redeeming same amount on another product also however i have not applied coupon on 2nd product.

HELP WOULD BE GREAT APPRICATED

In admin/commerce/discounts/manage/ choose discount type to product discount and add the product(SKU) for which you want to apply discount and save the discount form.

For adding description you can add it in form_alter()

/**
 * Implements hook_form_alter().
 */
function my_module_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'commerce_checkout_form_checkout' ) {
    $form['commerce_coupon']['#description'] = t('Enter the coupon code <strong>***100</strong> to avail discount');
  }
}

Hope it works.


Set xdebug.max_nesting_level to higher value On my Drupal 8 installation, I am getting this Requirement Problem:

Xdebug settings
   xdebug.max_nesting_level is set to 100.
   Set xdebug.max_nesting_level=256 in your PHP configuration as some pages in your Drupal site will not work when this setting is too low.

On my server, I tried setting it under /opt/app-root/etc/php.ini.template but doesn't work.

Can this be done on the settings.php or .htaccess?

Since xdebug.max_nesting_level is not available/cannot be found in my php.ini file.

What I did is adding this line to .htaccess from Drupal directory and this solves my issue.

php_value xdebug.max_nesting_level 256


Field for publication status I already browsed several posts but did not find an answer. I want to be able to make a list view that shows all my articles. Additionally the articles' teasers should show if the article has been published or not yet.

My Problem: The publication status doesnt exist as a field, so I cant add it to the lists' teasers. How can I achieve this ?

Thanks in advance,

Martin

Views has a field:

  Content: Published
  Whether or not the content is published.

You should be able to add that to your Field based View to show the published status.


Blocking JS from being executed more than once JS lines of code are often executed more than once.
How can this ( annoying ) behaviour be blocked?

    (function ($, Drupal) {
  'use strict';

  Drupal.behaviors.recherche = {
    attach: function (context) {

      var filters = $('.block-facets-ajax');
      filters.wrapAll('

');
...........

what's expected:

what's happening:

EDIT: trying to apply the doc given in comments, unsuccesfully

Drupal.behaviors.recherche = {
    attach: function (context) {

      var filters = $('.block-facets-ajax',context);
      filters.once('behave').each(function () {
        $(this).wrapAll('

');
      });

EDIT2 : dependancies added to the library.
        It is not working as it is not entering the .each :

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

      console.log('this is logged');
      $('.block-facets-ajax', context).once('myModuleBehavior').each(function () {
        console.log('this is not logged');
        // Apply the myModuleBehavior effect to the elements only once.
        $(this).wrap('

');
      });

    }
  };
})(jQuery, Drupal);

EDITED 3 :
if i remove context in the selector then .each is executed but instead of wrapping all elt together it 's wrapping each element individually.
This is the case no matter i use wrapAll or wrap method.

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

      $('.block-facets-ajax').once('myModuleBehavior').each(function () {
          $(this).wrap('

');
      });

    }
  };
})(jQuery, Drupal);

what i am trying to achieve :

what's the outcome:

I adjusted your code to match the one from the docs.

MYMODULE/js/myscripts.js:

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

      $('.block-facets-ajax', context).once('myModuleBehavior').each(function () {
        // Apply the myModuleBehavior effect to the elements only once.
        $(this).wrapAll('

');
      });

    }
  };
})(jQuery, Drupal);

To get that working properly you also need to require core/jquery.once for this script.

MYMODULE.libraries.yml:

myscripts:
  version: VERSION
  js:
    js/myscripts.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once


Let local drush call remote drush with `bash` or `sh` I am trying to get database syncing with drush going. I installed drush on my webserver, but I only have the permission to run it with bash or sh before drush. (So with ./drush I get permission denied)

It seems that my local drush calls the remote drush without bash or sh, so I get permission denied when I try drush status for my @bla.remote.

Is there a way to tell drush to use these commands or can you think of another way to bypass this problem?

Could I write an alias somewhere into drush?

You will need to do something like this:

$aliases['myremotesite'] = array (
  'remote-host' => 'isp.example.com',
  'remote-user' => 'www-admin',
  'root' => '/srv/www/example.com/drupal',
  'uri' => 'http://example.com',
  'path-aliases' => array(
    '%drush-script' => '/home/www-admin/bin/my-drush',
  ),
);

Customize URIs, paths and sitenames to suit.  Then, create a 'bin' directory in your $HOME (if you don't already have one), and make yourself a 'my-drush' script like this:

#!/bin/bash

bash drush $@

Once we commit https://github.com/drush-ops/drush/pull/1595, you will be able to simplify the above by copying the drush.wrapper script to your remote site's Drupal root, and prefixing its call to the Drush launcher with bash.  That PR is close, but it's also Drush 8 only, so you might prefer making your own my-drush script, as shown above.


Combine Multiple Content Types and View I have need to create a page with following information.
Personal Information,
Address and
Contract Information.

One Personal Information will have multiple address and multiple Contract information. I am thinking of creating three content types. The personal information page will have add address and add contract buttons which will popup the respective content type. When the address or contract popup is closed then control is passed to the Personal Information page, here I should be able to view the contact and address information just added in tabular format. I thought it may be a view.

My question is, Is it possible to achieve this kind of work in Drupal 7? If yes how can I do it. It will be nice to have some information so that I can look into the right direction. Some example sites would be help full.

Thanks

Instead of creating new content types. You can create fields and use FieldCollection module to group as many field as you like.

and show (Display) it using FieldCollection Views module.

Find demo here,

FieldCollection Demo

FieldCollection Views  Demo


Get the value of one field from another in the same form I have a form with multiple fields. How can I get the value of field B  from within the formElement method of my widget class for field A?

The formElement method in your widget class should include $form_state as one of its arguments. The value of all the fields in your form should be available in the $form_state object:

example: $form_state->getValue('field_b');


Render a Views row ID using NID (Node ID) I can easily add NID (Node ID) as a field in my view and then render it as a class for the Views Row using replacement patterns for the row class of an unformatted typical view. (See screen capture).

However, I'd like to render the NID as an ID for each row for use for some special theming I am doing. If I use devel themer, I see my template is views-view-unformatted.tpl.php so I can of course copy this template into my theme's template folder with a custom name specific to my view and then theme it.

The relevant line of code in the template that renders the row class is:

  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>

If I change it to:

<div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>
    id="<?php print $fields['nid']->content ?>">

...However, this does not work as I don't think fields are available at this level in the views row.

So essentially right now my rendered output is:

... when I'd like it to be

My question, is there a way to just render the associated NID where I want it as an id other then the method I am trying to use?

In most Views templates, the entire $view object is available.  So, assuming you have a nid field in the row, you should be able to access it with something like this:

$view->result[$id]->nid

so, give

id="my-nid-is-<?php print $view->result[$id]->nid; ?>">

a try in your template.

If this doesn't work exactly, a print_r($view->result); up at the top of the template will give you a gander at what you have to work with.


Query between 2 tables I want the date for the last login for a defined role, but I have a problem with my query with drupal 7.

I have the good answer in phpmyadmin with this query :

SELECT login FROM `users` AS u, `users_roles` AS r
WHERE u.uid = r.uid
AND r.rid = 3
ORDER BY login DESC LIMIT 1

But an error with Drupal7... I tried this code :s :

$query = db_select('users','u')
 ->join('users_roles','r','r.uid = u.uid')
 ->fields('u',array('uid'))
 ->fields('r',array('rid'))
 ->condition('r.rid', '3', '=')
 ->orderBy('login', 'DESC')
 ->range(0,1);
$res = $query->execute();

Thanks

Edit : Thank for your answer Clive , this code works :

$query = db_select('users','u');
$query->join('users_roles','r','r.uid = u.uid');
$query->fields('u',array('login'))
 ->condition('r.rid', '3', '=')
 ->orderBy('login', 'ASC')
 ->range(0,1);

$res = $query->execute();
return $res->fetchField();

SelectQuery::join() returns the alias created, not the query object, so it can't be chained. This should work

$query = db_select('users','u')
 ->fields('u',array('uid'))
 ->fields('r',array('rid'))
 ->condition('r.rid', '3', '=')
 ->orderBy('login', 'DESC')
 ->range(0,1);

$query->join('users_roles','r','r.uid = u.uid');
$res = $query->execute();


Is it a way to get know if more than one user edit the same node? I'm looking for the way to inform site editors if the other editor is trying to edit the same node. In other words I need functionality that is similar to the Checkout module. But it is no longer maintained and I don't like to lock anything, just show a popup message.

Do you think that it is possible? I didn't find any hooks in Drupal API that could do that.

And the last thing - this is Drupal 6

This is already built-in in Drupal 6 (and 7), in the function node_validate.

The relevant piece of code is reproduced below:

if (isset($node->nid) && (node_last_changed($node->nid) > $node->changed)) {
  form_set_error('changed', t('This content has been modified by another user, changes cannot be saved.'));
}

It doesn't lock anything, but it shows the second editor a message, and prevents the second editor from saving and thereby overwriting what the first has done.

The second editor can then copy-paste his/her efforts to Notepad or other temporary buffer, reload a fresh version of the node (i.e. a version that contains the first editor edits), add his stuff again, and save.


setting up drush AFTER drupal multisite installed new to drupal and even newer to drush. godaddy shared hosting, I manually setup drupal 8.x multisite where one site is the host account and the rest are subdomains to it. (I didn't use the cpanel install wizard)

I just ssh'd in and setup drush but now I don't understand how to configure it to see all my sites. all the info I've seen relates to setting up drupal using drush, not configuring drush with an existing installation, especially multisite.

do I need to create aliases? any help is appreciated. thanks!

Drush does not need configuration, as long as you run commands from the relevant site folder such as www-root/drupal-core/sites/mysite it will work.

Do check that your version of drush is compatible with Drupal 8 though.


Migrate DBTNG query with JOIN and IN I'm attempting to write DBTNG query for a Migrate v2 class (D6), and I can't quite get a WHERE clause using IN to work.  Here's the query I need:

select ngeuu.user_name, ngeu.email_address1
from nge_users ngeu inner join nge_user_to_group_tbl ngeutg on ngeu.user_id = ngeutg.user_id
where ngeutg.usergroup_id IN (16, 5608, 48, 34, 22, 26, 24, 18, 28, 20, 14, 12, 6879, 36);

This query returns the appropriate amount of rows.  The way I have the query written in my Migrate class is:

$query = db_select('nge_users', 'ngeu');
$query->innerJoin('nge_user_to_group_tbl', 'ngeutg', 'ngeu.user_id=ngeutg.user_id');
$query->fields('ngeu', array('user_name', 'email_address1'))
$query->condition('ngeutg.user_id', array(16, 5608, 48, 34, 22, 26, 24, 18, 28, 20, 14, 12, 6879, 36), 'IN');
$query->duplicate();

but I start getting duplicate rows after 4 records, even though the query by itself doesn't return any.  How do I need to change this to make it correct?

Thanks.

Your original conditions looks in usergroup_id, while the D7 versions checks user_id?

Also, there is no duplicate() method, only distinct().

You can use something like dpm((string)$query) to debug the generated query, and dpm($query->getArguments) to get the arguments passed to it.


How can I edit the html of the title of my node page I have a content-type "foo" and some nodes with that type. Now, if you go to one of the node pages, e.g. /node/22, you see the node title as the page title.

I can edit the html of the whole page using node--foo.tpl.php but I can't edit the title/titles html.

How can I change the html of the title div on such a page for a specific content-type?

Depending on your current theme, the title may be found in the node.tpl.php, the page.tpl.php (usually this one) or html.tpl.php. Enable theme debugging to toggle theme debug comments. That way, you see which templates control which portions of the page.

Add the following to settings.php and refresh a couple of times (clear cache if it becomes stubborn). Then inspect the page.

$conf['theme_debug'] = true;

With theme debugging on, you'll also see the progression of template name suggestions in the comments, with the top most/most specific/longest name being selected first.

You can also add to this list by altering the theme_hook_suggestions property in the variables argument of the appropriate hook_preprocess_ hook. If I remember correctly, there's no suggestion content type suggestion for templates. If so, you'll have to add one.


Adding Google Map via iframe with CKeditor in an article I want to add to the body of a Drupal node (in my case the default article), the google iframe to embed one map

<iframe src="https://www.google.com/maps/embed?pb=!1m14!1m12!1m3! ... </iframe>

I use Drupal 7.26, CKEditor as Wisywig editor with the "Standard Package", and everything is working fine.

What I tried after reading many articles:

I set the node to Full Html (of course)
I unchecked "Limit allowed HTML tags" in /admin/config/content/formats/full_html
I put "Use custom formatting options"  to yes in the "Cleanup and Output" section of admin/config/content/ckeditor/edit/Full
... few combination of the above.

What it happens: I edit the article, I insert the html source in the body. I untoggle the source button, everything is disappeared (I go back to source and nothing left).

Note: I don't want to use OpenLayers, I don't want to install modules such Iframe, or SimpleMap, because I just need this map once. It should be working, but my html is still filtered for some reason.

Please see dev.ckeditor.com/ticket/11688 for more details.

  If you are using latest CKEditor for Drupal module then please go to Modules->CKEditor->Configure and edit your profiles. Each of them has ADVANCED CONTENT FILTER setting which can be disabled/enabled or extended.

NOTE: durring checking it has turned out that relase version for drupal OS module hasn't been updated thus you can't see this setting. For now please use development release which has this feature and is fully stable.


Taxonomy View and Paths I have a view set up to display all my taxonomy nodes for "Classified Categories" Vocabulary, in the view I have set up the path to be /Dogs however when it lists the terms they are all linked to /Dogs/(term) and this will then display nothing, but if I change the path from /Dogs/ to /Classified-Categories/(term) it will show.

I've had a look at setting up patterns for my URLs but seem to have no joy. Further on this the terms with spaces are linked with %20 in and will not show even in the changed format; only when I replace the %20 with - will they show.

I'm pretty stuck on getting this to work especially being a Drupal newbie.

This is a screenshot from my current configuration of my view.

Both "Link this field to its taxonomy term page" and "Convert spaces in term names to hyphens" are ticked.**

remove the filter and only add the contextual filter with taxonomy term id.
also change path to /Dog/%.


Installing the Media Module + WYSIWYG Module on Acquia Cloud I'm trying to get the Media module (and it's dependent WYSIWYG module) working on an Acquia Cloud environment. Normally, this isn't too bad locally but Acquia has a strange file structure that is giving me some headaches.

I have installed and activated both WYSIWYG along with Media but neither are working correctly. WYSIWYG needs CKEditor to work and wants it to be included in sites/all/libraries (outside of the normal modules folder). Acquia doesnt give you access to add in libraries like that.

Media isn't showing the library when a user accesses a content-type with an image field that use's Media's 'Media file selector' widget.

Im guessing a lot of this is due to path problems, but the only documentation Acquia has about their file structure is here (and this mostly pertains to the files folder - not core + contrib paths):
https://docs.acquia.com/cloud/files

So my question is two fold:

How do you get CKEditor into an Acquia Cloud instance with the WYSIWYG module?
Why wouldnt media show its library? Am I leaving another module out maybe? Path issue?

Short answer: turn off livedev in your Acquia Cloud dev environment.

Longer Answer: I was trying to drush my modules and do basic site building in their environment using the livedev option. But they don't let you run mkdir and scp live in their environment via CLI.

Their recommended workflow will have you add your modules/libraries locally, commit via git and then push up to their environment.


Parent theme hook is still being called when overwritten I have a theme called hasta, and created a sub theme to customize certain aspects of it.  One of the things I wanted to do is change the behavior of one of the hooks, hook_element_info_alter.  The hasta theme defines this as hasta_element_info_alter in template.php.

My sub theme is called hasta_sub, and in that template.php I have overwritten this hook as hasta_sub_element_info_alter.

I put some debug statements, and I can see that my new hook hasta_sub_element_info_alter is being called, but the parent theme hook, hasta_element_info_alter, is still being called as well right before this.

Drupal helps says:

  Theme functions are called through theme('[hook]', $var, ...). When a
  sub-theme overrides a theme function, no other version of that theme
  function is called.

So according to this only the sub theme version of that hook should be getting called.  Can anyone please tell me what I am doing wrong?

Thanks!

Yes theme functions when overridden stay overridden in the sub-theme, but this is not a theme function, but rather a hook function used in a theme.

So hook_element_info_alter() whenever it is implemented will run.


How do you remove the search box on the search results page? I'm working on customizing my search results page. By default, the results page contains another instance of the search box at the top. I have the search box in a block at the top of every page, so it's just cluttering things up on the results page. I have already overridden the two template files, but I don't see anything in there that outputs the second search box. How can I remove it?

This is a fun one... The Search box is returned as part of the render array returned by search_view().

I suggest that you make a hook_menu_alter() which replaces the default callback for the search page with your own, which is basically a pass-thru to the core function, but that unsets the search form.  Something like this:

function MYMODULE_menu_alter(&$items) {
  $items['search']['page callback'] = 'MYMODULE_search_view';
}

function MYMODULE_search_view($module = NULL, $keys = '') {
  $build = search_view($module, $keys);
  unset($build['search_form']);
  return $build;
}

Don't forget to clear your cache to pick up the new hook and menu changes.

You may need to add additional paths to the hook_menu_alter() as needed (e.g., if you search users, then you may need to add entries for search/user and search/user/%menu_tail).


How do I add fields and hide them from client? I added fields to a Client profile using Profile2, such as first name and last name. But I added another fields, let's call it "Assigned Consultant".

But the "Assigned Consultant" field...

I don't want it to be available on registration
I don't want it to be available on the Client view user profile page
I don't want it to be available on the Client edit user profile page

I just want the "Assigned Consultant" field to be available to Administrator users.

How can I do that?

Field permissions module would probably be the way. https://drupal.org/project/field_permissions

"The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity."

Check the issue queue though, for example:
https://drupal.org/node/2069281, "Profile2 field is empty after profile is saved"


How to make relation between user term and nodes terms? I'm newbie to Drupal. I'm in a process to restrict the user based on the node taxonomy term, and the user taxonomy term. For the user's I have attached a custom field of type Term Reference. I have a Taxonomy Vocabulary called Company. Inside that vocabulary I have created two terms Tata, Infos.
There are totally 100 nodes, out of these 60 were belongs to Tata and the 40 belongs Infos.

Now these terms would be reflect to the user profile page as radio button. When admin select Tata for particular user, then that user might be able to see only the Tata tagged nodes and vice versa. I have tried tac_lite and content_access module before adding custom fields to user profile page, but not my requirement is getting finished. Is there any way to achieve this!!!

Thanks!!

You can do it by using view :

add field in views
add relationship of user
add expose filter against term id or term name
if you want show on user profile page add contextual filter against user id


Do PHP static variables persist across Batch API batch items processing? Do PHP static variables, which do persist during a normal page request, persist between progressive Batch API runs? What about during non-progressive (command-line) batch execution?  Does &drupal_static come into play in any way?

In my application, I want to take advantage of in-memory caching across batch processes.

Static variables exist per request, so no, they won't persist across separate batch runs.

If you need to cache data across requests in memory just use redis/memcache/etc, there are contrib modules available for each that hook into the core caching stays so you can use a familiar API


Upload multiple Standolane Media Entities (Images) without Reference Field I'd like to Upload Images as Media Entities without referencing them in another Entity. In media/add/image I can upload a single Image. That's fine.
What I'd like to achieve is a Multiple Upload Widget where I can Upload multiple Images and provide default values for all Images (Taxonomy Reference). After creation these Media Entities can be edited further or assigned to other content Entities or just be viewed in Galleries according to their Taxonomy Term.

The Media Bulk Upload module will allow you to upload many images at once.

This is the Drupal 8 module to bulk upload files and create the media
entities automatically for them. It uses DropzoneJS
to quickly upload multiple files.

The bulk uploader will allow you to edit fields on the media item before saving. You'll want to set alt text for each image, and your Taxonomy Term reference.


Editing fields presented in a view I am looking for a module that allows fields to be edited that are presented<,
preferably by a view. Basically what I am trying to acheive is as follows:

I have a content type as Meter Readings
Meter reading prepopulates by entity reference_prepopulate to a parent project
  ie.Building.
Idea is that a building has a meter say Electricity meter that records
  electricity readings(by Meter Readings Content type) that is presented in a view

I want to add meter readings in the view itself and not let the user to go to another screen,

Any  module to do this? Any references would be of great help.

One option is to use the field collection. and field collection views

This would automatically create the add edit and delete links to those who have permission to do so both in views as well as node view. It will popup a nice box to make the changes or add items.

I followed the following steps.

Added a content type called Meter Reading
Added a field collection called Reading with widget embedded made its value as unlimited.
Add a field to the field collection.
Added a content of the type Meter Reading without entering anything in the reading.

Now when you visit the newly created content you would get something like below image.

Here you will notice the add link this and when you click that you would get a popup something like in the below screenshot.

In the popup you can enter the readings.

This is what I get after entering couple of readings.

By the way you can add field collection with in field collection and it would work the same. So in your case instead creating a content type called Meter reading you can create a field collection called meter reading and then add a field collection with in that called readings and with in that add a field called Reading.

So your entire page would look like this


Make Commerce Checkout Form Submit via Ajax I think its a simple question, but I havent find an answer yet.

I want to make the Commerce Checkout Form Submit as an Ajax Form Submit. I have searched for a while but I havent found something useful.

There is a module Asaf which can add Ajax Submit to every Drupal Form, but I havent find the important locations in code.

There is also a Drupal Page AJAX Forms in Drupal 7, so I have tried a form_alter on the
commerce_checkout_form_checkout and added an Ajax Callback, but the page still reloads.

I have written this code in a custom module to test the ajax submit with an own function:

if($form_id == 'commerce_checkout_form_checkout'){
  $form['#ajax'] = array();
  $form['#ajax']['method'] = 'replace';
  $form['#ajax']['effect'] = 'fade';
  $form['#ajax']['callback'] = 'test_function';
}

function test_function(){
  drupal_set_message('test', 'error');
}

But no message is displayed and no ajax call is done.

Perhaps somebody cant put me on the right turn.

EDIT:

So I have learned that i have to add the ['#ajax] to a specific button or submit element, and not to the whole form. The commerce_checkout_form_checkout has a buttons array with the continue button in it, so i have added the functionality to this button array:

Array
(
    [#type] => submit
    [#value] => Kaufen
    [#attributes] => Array
        (
        [class] => Array
            (
                [0] => checkout-continue
            )
    )
[#suffix] =>
[#validate] => Array
    (
        [0] => commerce_checkout_form_validate
        [1] => commerce_stock_checkout_form_validate
    )
[#submit] => Array
    (
        [#ajax] => Array
            (
                [prevent] => click
                [callback] => test_function
            )
    )

)

But if I hit the submit button, the page still reloads and doesnt jump into my 'test_function'.

I see two problems with your code:

#ajax should be set on one of button, checkbox, checkboxes, image button, password, radio, radios, select, submit, tableselect, textarea, text_format, textfield. You are setting it directly on form, not on form submit element, so it cannot work.
You should also set ['#ajax']['prevent'] if your form gets reloaded. In theory:

  Description: A JavaScript event to prevent when 'event' is triggered. Defaults to 'click' for #ajax on #type 'submit', 'button', and 'image_button'.

In practice, it often fails to work as expected and I found it safer to set it explicitly.

In the button's array, be sure your #ajax definition is on the same level  [#type] => submit is. Don't put it under #submit or any other button's sub-array.


programmatically add an existing entity reference autocomplete field in custom form I need to create a custom form and add an entity reference field to it. The field uses autocomplete with a view for entity selection. The field already exists on a node but i also need it in a custom module. Is there a way to add this field in a custom module with MYMODULE_MYFORM_form()?

If you are using the references module's node_reference field, then, in your custom form, you'll want to create a field that uses the node_reference's autocomplete, like so:

$form['referenced_field'] = array(
  '#title' => 'Referenced field title',
  '#description' => t('Referenced field description.'),
  '#type' => 'textfield',
  '#autocomplete_path' => 'node_reference/autocomplete',
  '#required' => TRUE,  // Optional depending on your circumstance.
);

See node_reference.module line 892 for more details on parameters, etc.


Drupal 8 REST - How to export Drupal 8 Main navigation menu with REST service (JSON) I have tried to GET main menu with rest path "/entity/menu/{menu}" but all I get in response JSON is a menu properties as uuid,language,id... without menu structure (links...).

{
  "uuid": "93d5d0a9-a962-4448-af01-c38aa3ebda22"
  "langcode": "en"
  "status": true
  "dependencies": [0]
  "_core": {
    "default_config_hash": "Q2Ra3jfoIVk0f3SjxJX61byRQFVBAbpzYDQOiY-kno8"
  }
  "id": "main"
  "label": "Main navigation"
  "description": "Site section links"
  "locked": true
}

I have also tried to GET menu through block (main menu is also a block) with "/entity/block/{block}" but without luck.

Fatal error:  Call to a member function access() on null in    C:\Apache\work\test\core\modules\rest\src\Plugin\rest\resource\EntityResource.php on line 52

Is it possible to GET whole main menu with it's sub-menus in JSON format?

Thanks in advance.
Danijel

I ended up creating a module that does the basics for getting a menu via rest. I can just put the menus machine name in the URL and it will give me the title, url and weight in JSON format. I uploaded it to github so you can test it out. It is by no means ready for productions web sites. I was just messing around with angular and REST in D8.

Using angular, I would get the menu using the new URL resource after enabling the module and route resource 'entity/restmenu/{menu-name}?_format=hal_json in your case entity/restmenu/main?_format=hal_json

app.controller('MainController', function($scope, $http) {
  $http.defaults.headers.common.Authorization = 'Basic YWRtaW46YWRtaW4=';
  $scope.menuData = $http.get('entity/restmenu/main?_format=hal_json').then(function(response) {
    $scope.menuData = JSON.parse(JSON.parse(response.data));
  });
});

https://github.com/rondog/rest-menu

<?php

/**
 * @file
 * Contains \Drupal\rest_menu\Plugin\rest\resource\rest_menu.
 */

namespace Drupal\rest_menu\Plugin\rest\resource;

use Drupal\Core\Render\HtmlResponse;
use Drupal\Core\Menu;
use Drupal\Core\MenuTreeParameters;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityStorageException;
use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Psr\Log\LoggerInterface;

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "restmenu_resource",
 *   label = @Translation("REST Menu Resource"),
 *   uri_paths = {
 *     "canonical" = "/entity/restmenu/{menu}"
 *   }
 * )
 */
class RESTMenuResource extends ResourceBase {
  /**
   * A current user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a Drupal\rest\Plugin\ResourceBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   A current user instance.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('rest'),
      $container->get('current_user')
    );
  }
  /**
   * Responds to GET requests.
   *
   * Returns a list of bundles for specified entity.
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   *   Throws exception expected.
   */
  public function get($entity) {
    $menu_name = $entity;
    $menu_parameters = \Drupal::menuTree()->getCurrentRouteMenuTreeParameters($menu_name);
    $tree = \Drupal::menuTree()->load($menu_name, $menu_parameters);
    $result = array();

    foreach ($tree as $element) {
      $link = $element->link;
      array_push($result, array(
          'title' => $link->getTitle(),
          'url' => $link->getUrlObject()->getInternalPath(),
          'weight' => $link->getWeight()
        )
      );
    }
    return new ResourceResponse(json_encode($result));
  }
}


Disable caching on a route I have a route with a parameter, e.g. /r/{app_id}. The controller extends ContainerInjectionInterface.  The method either returns a render array or a new TrustedRedirectResponse.

I believe I have a caching problem because subsequent visits to the page will not update even with changing {app_id}.  If I visit from another browser I get the correct response one time.

My controller is, basically, this:

if (!$a) {
  return ['#markup' => 'no'];
}

return new TrustedRedirectResponse($url);

I have tried to disable cache in several ways, to no avail:

addCacheableDependency
putting #cache => ['max-age' => 0] on the render array
\Drupal::service('page_cache_kill_switch')->trigger();
using $response = new Response() and $response->setCache(['max_age' => 0]) and then, from within the conditional, using $response->setContent('blah')

Not having luck with any of the above.

You have to do all together, set cache max-age = 0 for all responses the controller returns and apply the kill switch

public function mycontroller() {

  \Drupal::service('page_cache_kill_switch')->trigger();

  if (!$a) {
    return [
      '#markup' => 'no',
      '#cache' => ['max-age' => 0],
    ];
  }

  return (new TrustedRedirectResponse($url))
    ->addCacheableDependency((new CacheableMetadata())->setCacheMaxAge(0));
}

and then clear the cache one more time.


problem with page count in pressflow & varnish i'm using pressflow &  varnish & cashrouter in my site.
my problem is node counter is not true because google analytic show diffrent count of node.
for example in google analytic show count of node is 12000 but in pressflow show 300 hint.
im using revers proxy.

This module should take care if it for you
http://drupal.org/project/jstats

For other options see the Performance wiki and look (ctrl-f) for Statistics
http://groups.drupal.org/node/187209


Timeout in sites, perhaps related to cron I have been struggling with a timeout error in a couple of Drupal 8 sites, which I have not been able to reproduce. When I deploy them into my colleague's production server (a Mac machine), all the Drupal 8 sites are experiencing a page lock up (the browser waits indefinitely). I have not been able to reproduce the error in my machine (running Debian), neither in testing instances in other servers (e.g. a free Pantheon instance). The only clues I have for the moment are:

The error seems to not occur so often once I disable cron in the Drupal sites. However, if I run cron manually, I have not been able to reproduce it neither.
This only affects Drupal 8 sites. The rest of the sites (Drupal 7 and many others) are not affected at all.
The error disappears rebooting Apache. However, only when I do the following combination: "/opt/local/etc/LaunchDaemons/org.macports.apache2/apache2.wrapper stop" & "/opt/local/etc/LaunchDaemons/org.macports.apache2/apache2.wrapper start"
My colleague suggested me to use "/opt/local/apache2/bin/apachectl graceful" , but in that case, the error does not disappear.

Any ideas on what the issue could be? I am running different versions of Drupal in the sites (8.0.2 and 8.0.5). At https://github.com/CRESS-Surrey/erie_website_code/issues/31#issuecomment-172512374 I have attached as well some captures of the http headers in a successful and unsuccessful request . I am trying to document the issues as well (more information) at that issue and https://github.com/drozas/cecan/issues/23 for the other site.

Thanks a lot!

David

Even if you say its not: This issue is most commonly not only Drupal 8 related. You will find issues for Drupal 7 reporting near the same behaviour. It turns out that cron starts after the expired period with first page request. If this happens, the cron seems to take endless time and seems to interfere with the page request in the same moment. Many experienced users run their crons from Drush manually or combine it with server crons. But generally spoken :

There are 3 possible points to look at and to modify (and you already named some of them), which all can interfere each other or can be responsible for it each at their own allone:

Take a look at your php and apache settings for memory, cache size
and sql query time settings. Cron is a big wave coming. From my
experience a smooth Drupal experience can be only granted by
increasing it over the given amount suggested.
Turn off automatic cron frequence (as you sad, mostly set by 3
hours, set it to -none-) in the admin/config pages, but make sure
that you run cron by yourself manually often enough (thats how I
generally do it). For some reasons and some unclear circumstances
(mostly server related) this is often the only option to prevent
this behaviour.
Make sure that you have turned off all unneeded modules on
production sites. Even if some suggestions say its not related, my
experience is, that turning off help, update, dblog (use syslog
instead) etc. at production sites makes Drupal faster and prevents
such overheats.


How do I get an uploaded image URL or the default for use in a template (code improvement) I have a working preprocess function that allows me to grab an image for use as a background in the page template from a node if the field exists.  It falls back on a default image if supplied, the function looks like this:

<?php
/**
 * Implements hook_preprocess_page() for page.html.twig.
 */
function mymodule_preprocess_page(array &$vars) {

  // Preprocess the hero image if it exists (it should on all nodes).
  if (isset($vars['node']->field_hero)){
    $field_hero = $vars['node']->get('field_hero')->getValue();

    // If a file has been uploaded, get it.
    if (!empty($field_hero)){
      $hero_id = $field_hero[0]['target_id'];
      $file = File::load($hero_id);

    // Otherwise get the default if there is one.
    } else {
      $default_image = $vars['node']->getFields()['field_hero']->getFieldDefinition()->getSetting('default_image');
      $file = Drupal::service('entity.repository')->loadEntityByUuid('file', $default_image['uuid']);
    }

    // If a file has been found (there might not be a default), get its path.
    if ($file){
      $path = $file->getFileUri();
      $vars['hero'] = ImageStyle::load('hero_image')->buildUrl($path);
    }
  }

}

Finding the default file is a convoluted mess of steps that requires loading all of the fields... there has got to be a better way to do this.  Is there?

You don't need to load all the fields, you can just load the image field:

$uuid = $vars['node']->get('field_hero')->getFieldDefinition()->getSetting('default_image')['uuid'];
$file = \Drupal::service('entity.manager')->loadEntityByUuid('file', $uuid);

On a different note, the first line of your code assumes that $vars['node'] exists, which it won't on non-node pages, so you should change it to:

if (isset($vars['node'], $vars['node']->field_hero))


Performance and optimisation when using panels with views and content pane I would like to know if there is a best practice when we use panels with views and content pane?

Some explanation:
I have a layout with multiple blocks (related to the taxonomy etc.) and a main content.

I'm asking myself what is the best way to have the better result in term of performance: I made many content pane for my views (as many as there are blocks, see my picture for a better understanding)

But i don't know if it's very good to do that.

I would like to know if it's not better to do just one content pane and to check or uncheck the fields that i want in each block.

My site i slow so i try to optimize it. I don't know how panels works "behind the scene".

Thanks

The primary thing you should do, is cache as much rendered output as you can. If you cache the generated markup itself, whether you're Views configuration is optimal mostly becomes a non-issue.

Views itself, can be cached with Views content cache, or if you complicated invalidation criteria, with a long timed cache and Cache actions.

More experimental, is a module I've written myself, called Panels cache, which moves the caching one layer higher up, for even better performance, but it requires that the content being cached all comes from the same entity. (I use the module in production, but would still love testing and feedback on the module)

On the actual Views configuration, you should avoid having a single with multiple panes, if you have a lot of overrides. If your displays are significantly different, you waste processing time as builds must build and then alter the display. This however, will be a very small optimization, compared to the caching solutions suggested above.

You can read about more different performance improvements in my answer on How do you improve Drupal performance?


Stop Drupal Commerce automatically adding hyphens before product variations radio button labels Using Drupal Commerce I have created product variations with attributes that correspond to my taxonomies. When I use radio buttons to allow the user to select a specific variation Drupal Commerce adds a hyphen to the start the radio button label. For example my taxonomy term is 'White gold' but the radio button label that is displayed is '-White gold'.

How do I stop these hyphens from being added?

These hyphens are not being added by Drupal Commerce itself, so you'll need to look into what other modules on the site might be interacting with the form.


Permissions defined by fields I have some content that has state field. I would like to permit users with the same state to delete this content.
Can  I implement this in Drupal?
Can I implement it with PHP code?

custom.info

PS. Do not include <?php ?> tags.

; $Id:
name = Custom
description = Custom validate node delete permission
package = Custom
core = 6.x

custom.module

  <?php
    /*
     * file
     */
    function MYMODULE_form_alter(&$form, &$form_state< $form_id){
      switch($form_id){
        case 'node_delete_confirm':
          $form['#validate'][] = 'my_custom_validate';
          break;
      }
    }

    function my_custom_validate($form, &$form_state){
      $nid = $form_state['values']['nid'];
      $node = node_load($nid);
      if(/* conditions */) {
        // some procedure to check fields
        $message = t('You have not any permission to delete this node!');
        form_set_error('nid', $message);
      }
    }
  ?>

Place this files into /sites/all/modules/custom/*.* and activate it on module administration page.
Enjoy.


How to disable a block on a certain view? I want to disable two blocks for a certain view. I have tried
"Show block on specific pages >> All pages except those listed" using the machine name and the view URL with no luck; I tried Drupal Context still no luck. May you please assist?

I have looked at Exclude a block from specific parts of the website with the Context module, but the answers there didn't help.

These are the details for the view I am using.

View name: All albums Front
View machine name: all_albums
View path: /all-albums
Website view URL: http://www.example.com/all-albums
View display name: All Albums

If the view path is /all-albums then try entering all-albums in the block under Show block on specific pages: All pages except those listed, not the full url or the machine name.


Force allowed in hook_node_access Is there a way to force node access to allowed if there is a hook in a different module marking it as forbidden?

I have a custom module where i implement hook_node_access, returning allowed should certain conditions apply, but the result is being override by a contrib module that sets node access to forbidden.

Can i force my result?

The only way i found to fix this was preventing the conflicting hook from running:

function myModule_module_implements_alter(&$implementations, $hook) {

    if ($hook == 'node_access') {

      unset($implementations['conflicting_module']); // Not any more
    }
}

As it contains useful functionality, i'm running it in my own code, should my conditions for allowed not apply:

function myModule_node_access(NodeInterface $node, $op, AccountInterface $account) {

  if ($account->isAuthenticated() and myConditionIsTrue()) {

      return AccessResult::allowed();
  }

  // Run removed hook

  if (function_exists('conflicting_module_node_access')) {

    return conflicting_module_node_access($node, $op, $account);
  }

  return AccessResult::neutral();
}

This is less than ideal and i would prefer an alternative.


Correct way to link to views (to solve multi-domain problem) I have one site (same codebase, same database) that uses two different domains to display two different themes, depending on the content. (This is achieved via the Domain Access module.)

I need to be able to link from one domain to a view on another domain without manually inserting the absolute URL, but I'm not sure how (or even if it's possible).*

I can use l() to link to nodes without any problems. For example, if I'm on first-domain.com and I want to link to second-domain.com/news-story, I would do the following:

<?php print l('News Story', 'node/2213'); ?>

I don't know exactly how it works, but it realises that the news story isn't available on the first domain and automatically creates the absolute link to the second domain.

Creating a link to a view doesn't seem to be so easy. I've made sure the view's Access restrictions is set to Domains (and that only the one domain is selected) but the l() function doesn't seem to look this up.

For example, if I'm on first-domain.com and want to link to a list of all the news stories (which is created by a view) on second-domain.com, doing this:

<?php print l('Latest News Stories', 'news-stories'); ?>

Results in a link like this:

first-domain.com/news-stories

When I really want: second-domain.com/news-stories

Is there any way to solve this? Even if I could look up both domains that have been set via the Domain Access module would work, but I don't know how to do that either. (I've also thought about using Path Redirect, which is better than nothing, but not quite what I'm looking for.)

* Obviously it's possible to put in an absolute URL, but this is far from ideal as the site is currently being developed locally and will eventually be moved to a staging site, and then moved again to production once ready. Remembering to change the absolute links every time would be annoying at best.

Since you obviously are capable of PHP, the best way I can think of is to write a custom wrapper for l(), something like:

function ml($text, $path, int $domain = NULL, array $options = array()) {
  switch ($domain) {
    case 1:
      return l($text, 'http://first-domain.com/'.$path, $options);
      break;
    case 2:
      return l($text, 'http://second-domain.com/'.$path, $options);
      break;
    default:
      return l($text, $path, $options);
      break;
  }
}

That way, the absolute domains only have to be changed in this one central place with each staging step (domains may even be stored in settings.php).


Menu endpoint hangs when access callback returns false I'm trying to add a custom access callback function that checks that a user is a specific user (we only want this one api user to have this specific endpoint. It is set up like so:

function my_module_menu() {
    return array(
        '/api/v1/sample/request' => array(
            'page callback' => 'sample_request',
            'access callback' => 'user_is_api_user',
            'type' => MENU_CALLBACK,
        )
    );
}

function user_is_api_user() {
    watchdog("GLOBALS", "<pre>" . print_r($GLOBALS['user'], true) . "</pre>");
    return $GLOBALS['user']->name == 'api';
}

If my custom user_is_api_user function returns FALSE, the endpoint just hangs instead of sending back a 403 Forbidden (like expected). Instead, it looks it just keeps retrying because my recent logs just repeat the error not authorized and the watchdog log I put in over and over again until I end the request.

If my custom user_is_api_user returns TRUE, it logs the user in fine. Why does it just look and not actually return 403 forbidden when my custom function return false?

To return 403 Forbidden in your callback function, use drupal_access_denied() function something like:

function user_is_api_user() {
  watchdog("GLOBALS", "<pre>" . print_r($GLOBALS['user'], TRUE) . "</pre>");
  if ($GLOBALS['user']->name !== 'api'){
    drupal_access_denied();
  }
}


drupal_html_id() alternative for non-Ajax content? I am looking for a drupal_html_id() function alternative which returns incremented ID's of non-Ajax contents only.

Is this "ajax/non-ajax" distinction feasible in this context or any other way?
If yes, can anyone provide a solution or recommendation?

Here's a simpler version I came up with by altering drupal_html_id() that doesn't pay attention to the $ajax_html_ids. Also note that it produces dashes instead of hyphens:

function foo_html_id($id) {
  $id = strtr(drupal_strtolower($id), array(' ' => '_', '_' => '_', '[' => '_', ']' => ''));
  $id = preg_replace('/[^A-Za-z0-9\-_]/', '', $id);
  $id = preg_replace('/\-+/', '_', $id);

  $seen_ids = &drupal_static(__FUNCTION__);

  if (isset($seen_ids[$id])) {
    $id = $id . '_' . ++$seen_ids[$id];
  }
  else {
    $seen_ids[$id] = 1;
  }

  return $id;
}


Update $form based on $form_state Shouldn't the form generating function get executed every time the form is rendered? Because I need to update some field suffixes based on the $form_state values and I don't know how to do this.

I have something like this:

function xxxx_some_form($form, &$form_state){
  $form["some_field"] = array(
    "#type" => "textfield",
    "#required" => true,
    // bla bla bla
  );
  drupal_set_message("whatever");
  $form["actions"]["do_action"] = array(
    "#type" => "submit",
    "#value" => t("Do action"),
  );
  return $form;
}

When I submit the form, the validation messages are displayed ( Eg: X field is required ) but the message from drupal_set_message("whatever") is not displayed.

Also, no other logic is executed there.

When a form has a validation error, the form is rebuilt from cache, meaning that the form function isn't invoked.

I could move the drupal_set_message call over to a #process or #preprocess function on the form itself or on one of the methods. These should be called again.

If the form is displayed with hook_menu you could also make a callback function which calls drupal_set_message and then fetches the form. There are a lot of ways to get around this.