Why do vertical images flip horizontal after upload? I run into this issue once in a while and I am not sure what it is.  For example I have an image that I get from a non Drupal site or directly from a camera. If I view the image via Preview on my Mac or on a browser from the site it displays vertically. As soon as upload to my Drupal site, it flips horizontally.

To go around this I just open the image on my Mac and just re-save.

I always thought that my computer somehow is rotating the images just for display (based on some logic) but really in the background it is still a horizontal image. But I don't understand why the image displays correctly in the browser from the non Drupal site?

Probably the program looks on your mac to the orientation of the recording itself. Most cameras place information in the photo or it is taken in portrait or landscape. The program that reads the picture can then look at it and put the picture correctly on the screen.


Ctools wizard multistep form: Back button should remember entered data I am building a multistep form using ctools, basically following this approach. Now I want the following behaviour:

user is at step 1
enters data for step 1
clicks continue and gets to step 2
enters data for step 2
clicks back and gets to step 1
sees the data he entered previously (works already)
clicks continue and gets to step 2
sees the data he entered previously (works not yet)

To show the previously entered data after clicking continue, I simply set $form[$name]['#default_value'] with values from $form_state['values'] (with a detour via ctools object cache). So this works already.

The problem is with clicking back: After clicking back, $form_state['values'] does not contain any entered values. So I don't have the values to populate $form[$name]['#default_value'] and this is my current problem.

So I wonder: How can I send entered values with the back button submit?

To get ctools wizard to save values when the user presses the back button, you would have to remove it's '#limit_validation_errors' property that is set by default in ctools_wizard_wrapper(). There is no convenient switch or form_info property to do this so you have to use a form alter hook similar to this:

function test_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form_state['wrapper_callback']) && $form_state['wrapper_callback'] == 'ctools_wizard_wrapper' && $form_state['form_info']['id'] == 'test_wizard') {
    if (isset($form['buttons']['previous'])) {
      unset($form['buttons']['previous']['#limit_validation_errors']);
    }
  }
}


How to make a regular expression case insensitive? I am working on a Drupal Commerce shipping rule and it needs a regular expression to compare postcodes with the buyers address as below;

/^AB37|^AB38|^AB41/

I am finding this code to be case sensitive and I need it to be more relaxed allowing lowercase or mixed.

I have read I need a 'i' flag, but I am unsure how to apply this.

Could somebody please provide me with an example?

The case insensitive usually is adding a "i" char after the delimiter bar, something like this:
/^AB37|^AB38|^AB41/i

but depends of the case it can be changed. In JS, for example is adding a new param (var re = new RegExp(myVar,"ig")) or in php is preg_match("[expression]i", $text, $matches);


Changing the image path after images were uploaded I have created a image field under a custom Content Type and let the file directory setting to default, meaning the files are not uploaded to any sub directory.

As I can see now this is not a suitable situation for me and I would like to save the files in a sub directory. If I change the File Directory setting under the Field Settings will this break the paths of the files uploaded prior?

Thanks

If I change the File Directory setting under the Field Settings will this break the paths of the files uploaded prior?

Yes

As i think you need to go a two step process.

Move the images to the new folder.
Update the existing image path in database.

Before moving with any process keep all the backups.

Refer these links which may help you to move

seeking advice on changing file system path after files have been upload

Moving the files directory


Reset Webform's SQL table indices? I'm using webforms to get some data from users. These results are later used in another php script, and this relies on looping through the data:

for ($i = 1; $i <= count($data); $i++)
    {
        $answers[] = $data[$i]["value"][0];
    }

However, by adding and deleting questions in the webform, the indices look something like this now:

1
2
3
5
8
12

And this gives an error because I use count() to get the number of entries. (count() = 6, but max() = 12). My first idea is to find a way to automatically reset the indices after adding or removing questions. So my indices look like this:

1
2
3
4
5
6

But I honestly have no idea how to go about this. Any ideas?

I might be misunderstanding you but I think you just want a foreach loop:

foreach ($data as $item) {
  $answers[] = $item["value"][0];
}

Or even shorter:

$answers = array_map(function($item) { return $item['value'][0]; }, $data);


Can I expose the signup form through views 2? I am using Signup and Views in Drupal 6 (I can't install Drupal 7), and I created a view that lists all the nodes for which users can signup.
Now I want to enable users to signup for one of these nodes without forcing them to navigate to the node itself, and I need to expose the signup form though Views (perhaps using a PHP field). I've searched for this, but most of the comments are a few years old. Furthermore, I'm rather unfamiliar with PHP.

Can I expose the signup form through views 2? How can I do it?

This is currently a feature request for the Signup module (originally submitted to that module's issue queue 3 days before this StackExchange post). For the latest progress on this feature, see the issue: http://drupal.org/node/1118448 .


Using rules to populate a field with the output of pdfprevew I have a field (public_files) that accepts file uploads to which I have applied the pdfpreview module which provides a field formatter that will provide the generated image for pdf files.  I have another field for cover images.

This setup is working well, and I basically default to the cover image field, and fallback to the pdf preview version of the first file if the cover image hasn't been provided.  A problem arises for a section of the site where I only want to list items that have cover images.  There is a complicated bug in drupal that prevents me from doing the filtering in views to only items that have a cover image or for which the first file is a pdf file.

To alleviate this, what I'd like to do is use rules to automatically populate the cover image field with the generated cover whenever there is a generated cover image, and the cover image field is empty.

Sorry for the long preamble, here is the question:

Is there any way to get at the pdf preview image and populate an image field with it in rules?

From your question, I seem to understand that this is your goal (= quote from your question):

  ... use rules to automatically populate the cover image field with the generated cover whenever there is a generated cover image, and the cover image field is empty.

There seem to be at least 3 ways to achieve that goal, as further detailed below ...

Solution 1

This solution elaborates on one of your comments, which is like so:

  I was thinking at node view, might be a good time just to be sure that the preview had had a chance to be saved. I'd then need a condition to check whether the cover field already has a value and one to see if either there is a pdfpreview available or if the first file in the field is a pdf.

This could indeed work, but the crucial Rules challenge here is that there is no such event like "BEFORE" a node is being viewed. Because the "clue" about what Rules EVent "Content is viewed" actually means, seems to be like so:

The event Content is viewed is what it is: the user has (already) started viewing the content.
The (system) event Drupal is initializing is what you should use instead (possible combined with other Events and/or Actions), if you want to trigger some Rules "Action(s)" BEFORE the user can start viewing (= looking at) the content.

For more details, and a working sample (in Rules 'export format'), refer to
How to specify a Rules event like "Content is 'going to be' viewed"?

My advice: only use this if all other options (solutions) fail. Read on for what IMO is a better solution.

Solution 2

This solution elaborates on one of your comments, which is like so:

  ...  at node create and node update may be a much better time, if pdf preview has had a chance to do what it does by the time those events fire ...

Using this approach, you'll run into another Rules challenge ... I.e what's detailed in issue # 430274, about an event which is a variation of your event here, and somehow explains that "after saving something" actually happens "before saving something". This is not a bug, but simply how the Rules module works.

My advice: using this solution is a kind of risky, because of that above mentioned Rules challenge. Read on for what IMO is a better solution.

Solution 3

A possible compromise to avoid the kind of issues described in Solution 2, is to implement what needs to be done into a Rules Component, so that your original Rule "schedules the execution" (using the Rules Scheduler sub-module) of that Rules component. For example after only a few seconds or minutes if your cron job runs frequent enough (otherwise it'll be next time cron runs). This compromise will ensure that, at the time the Rules component is executed, the entity is for sure saved (so that can't be the reason anymore then why things don't work as expected). Read on for how you can get this to work ...

Step 1 - Create a Rules Component

Have a look at this Rules Component, in Rules export format:

{ "rules_populate_an_output_field_with_an_input_field" : {
    "LABEL" : "Populate an output field with an input field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : { "node_to_update" : { "label" : "Node to be updated", "type" : "node" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node-to-update" ], "field" : "field_image" } },
      { "NOT data_is_empty" : { "data" : [ "node-to-update:field-image" ] } },
      { "entity_has_field" : { "entity" : [ "node-to-update" ], "field" : "field_cover_image" } },
      { "data_is_empty" : { "data" : [ "node-to-update:field-cover-image" ] } }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "node-to-update:field-cover-image" ],
          "value" : [ "node-to-update:field-image" ]
        }
      },
      { "entity_save" : { "data" : [ "node-to-update" ], "immediate" : "1" } }
    ]
  }
}

This Rules Component used a "node" (the node to be updated) as a parameter.

This is what the Rules Conditions in the above Rules Component are about:

It uses a parameter "Node to be updated".
It processes the fields with machine names field_cover_image and  field_image (adapt the machine names to fit your own field names, prior to trying to import this Rules Component in your own site).
It has a rules condition "Entity has field" (twice) to make those fields available for subsequent processing.
It has a Rules Condition for each of both fields to check that their initial value (before the Rules Component's actions will be triggered), to match your requirement like "... populate the cover image field with the generated cover whenever there is a generated cover image, and the cover image field is empty...".

This is what the Rules Actions in the above Rules Component do:

Set the value of field field_cover_image equal to the value of field  field_image.
Save the node (to ensure the updated value actually gets saved ...).

Step 2 - Create a Rule to schedule the Rules Component

This one is pretty easy, here is a rule (in Rules export format) that will "schedule" the execution of the Rules Component from the previous step:

{ "rules_schedule_image_population" : {
    "LABEL" : "Schedule image population",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "rules_scheduler" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_cover_image" } }
    ],
    "DO" : [
      { "schedule" : {
          "component" : "rules_populate_an_output_field_with_an_input_field",
          "date" : "+1 min",
          "identifier" : "Schedule-image-population-[node:nid]",
          "param_node_to_update" : [ "node" ]
        }
      }
    ]
  }
}

The rule uses as Rules Event "After creating a new node", or "After updating an existing node".

To avoid wasting resources, we only want to trigger the Rules Action for nodes that do have that field_cover_image field we want to populate (hence the Rules Condition).

And all this rule has to do (as Rules Action), is to schedule the execution of the Rules Component from the previous step. Adapt the delay to fit your needs (I've set it to just 1 min).

My advice: go for solution 3 (tested in my own setup, works like a charm ...)

Easy, no?


How can I create multiple cropped Media images without re-uploading them? Solutions that I've found allow to crop Media, type Image when I've uploaded an image, but the media entity is not yet created (on the "Add media" page).

I need to upload a large full image once (and use it in full format on some nodes), and then crop it differently when I select it in different content types (to display small "zoomed" parts of the full image). So I need a manual crop to appear when I select a Media of type Image from a Media library. It can appear in Entity browser or on the node page.

Other solution is that I can create cropped images in advance being in my media library (/admin/content/media) or when adding a media (/media/add/image). The idea is that I do not want to reupload the image and add new title and alt.

Is this possible?

Solution:

Install Crop API and Image Widget Crop modules
Configure Image Widget Crop as explained in the tutorial, for Image field situated in Structure > Media types > Image. The image style for this Image field should contain no effects.
There where you want to use cropped image, select the style for it (in content type, for example) that contain "Manual crop" effect and, if you need, "Crop and Scale effect" (to display square thumbnails in listings, for example).
There where you want to use full umage, select the style for it that contain no "Manual crop" effect.

How to use images:

Upload a large full image, crop manually the interesting part
Use the same image there where you need it cropped and there where you need it full. It will be displayed differently on front.

Note: if you try to clone the Image entity (for example with Entity Clone module), it will not help because the clone Image entity and the original Image entity will apply the same crop.


How to avoid invoking the same module every time when I have to call a function of that module in Drupal 7? When there is a need to call a function inside a module, some of you say- it is good to use module_invoke() inside the template pages to call the function(it looks great-since I can pass arguments too).

Using Drupal 7. So for the first time, it is okay. Even for the second time, it makes a bit extra effort in the code, but somehow I can manage it.

Now it is invoking again and again, the same module. Say if the module is block, and the function is hook_block_view()- I doubt, it could affect the Drupal site performance(the time for loading the page contents), what do you think?
Is there a solution for this problem?

<?php
  $header_block = module_invoke('block', 'block_view', '2');
  print drupal_render($header_block);
  $news_block = module_invoke('block', 'block_view', '3');
  print drupal_render($news_block);
  ...
  ...
  $footer_block = module_invoke('block', 'block_view', '12');
  print drupal_render($footer_block);
?>

Is it a good idea to use the module_invoke() every time when I have to call hook_block_view() with different arguments?
Is there any other function that can be used for calling the same function or any other function in the module after one- module_invoke()?
Is there any other way of doing thing?

You're calling the same function over and over, that's true. But the parameters are different, so from a pure programming point of view, the processing could be completely different. I don't see another option to approach this.

Is it a good idea to use the module_invoke() every time when I have to call hook_block_view() with different arguments?
Yes
Is there any other function that can be used for calling the same function or any other function in the module after one- module_invoke()? Not that I'm aware of
Is there any other way of doing thing? I don't think so

More specifc, some functions allow passing an array of arguments instead of one. Eg node_load_multiple allows to pass 1 nid or whole list of nids. But hook_block_views doesn't allow this.


Which is the leading facebook module for Drupal 7 a complete site integration? There are 3 main FB integration modules for Drupal 7;

FB
FBconnect
FBoauth

There are tons of discussion threads around the net and drupal.org describing the pros and cons of each module. From all these threads, this is what I've gathered. If all you want is FB login capabilities for your users. Then FBoauth is your best bet. FBconnect does a few of the 'other' features pretty well but requires some bug fixes to be stable. FB is great if you want APP integration for your site. But my question is;

If you wanted your site to do;

User Registration
Content Posting to Wall Stream
Comment Stream
Friend Inviting

Which is the best module to be able to have those features built into your drupal site?

You need FB. It offers all what you need.

I've been in the same dilemma and went with that one.

I suggest to try all of them and see for yourself though. Don't waste time with modules which offer third party integration - they rely on registration on those websites and usually paying a fee to them. I think it's silly registering and paying for a third party service in order to use another (free) third party service.


How do I know if a link has the "active" class? I've added a custom twig template for links--language-block.html.twig.

Inside of it, I want to render additional HTML when the current item is active. But I can't figure out how to check when the current item is active.

{% if links -%}
  {%- if attributes.hasClass('inline') -%}

  {%- else -%}

  {%- endif -%}
    {%- for key, item in links -%}

      {% if item.attributes.hasClass('is-active') %} << this is always false

foobar

      {%- endif -%}

        {%- if item.link -%}
          {{ item.link }}

          {# Deutsch  #}
        {%- elseif item.text_attributes -%}
          {{ item.text }}
        {%- else -%}
          {{ item.text }}
        {%- endif -%}

    {%- endfor -%}

{%- endif %}

How can I check if the link as the active class?

In some cases, the active state is not set by design due potential problems with caching. This behavior is documented in this change record.

  Setting the active class is now an opt-in feature:

  l() and LinkGenerator::generate() now have a set_active_class option that defaults to FALSE
  theme_links() now accepts a set_active_class key that defaults to FALSE
  Those links that you'd expect to get the active class set, do get it: menu links, language switching links …

  The output of l(), LinkGenerator::generate() and theme_links() no longer contains the active class, even if you do opt in. Instead, they get a data-drupal-link-system-path attribute, and if there's a GET query, they also get a data-drupal-link-query attribute…

In those cases, where it is not set on server side, you can take a look at core/misc/active-link.js to get an idea how to manipulate the active state on client side.


Can entity references have "types" like links in Jira? Suppose I have a node that represents a task, or a to-do item:

Node 1: Instructions for building a drivable car

I want to link this node to another node, such as a sub-task of the original node:

Node 2: Instructions for assembling an engine (Sub-task of Node 1)

Now suppose I have another node that is caused by one of my original nodes, but is not a sub-task of it.

Node 3: How to obtain a driver license (required by Node 1)

The entity reference from Nodes 2 to 1 is of type sub-task while the link from 3 to 1 is of type required by (or maybe related to, whatever).
When viewing Node 1, it might be helpful to display a view of referenced nodes, but rather than just showing the nodes, it would be useful to show the relationship type as well:
Items related to "Instructions for building a drivable car":

| Link Type      | Node                                  |
|--------------------------------------------------------|
| Parent Task of | Instructions for assembling an engine |
| Requires       | Getting a driver license              |

Applications such as Jira handle this via link types. Is functionality like this available within the Drupal ecosystem? Alternatively, what would be a logical way of implementing such functionality?

In Drupal 7, this is possible with the Relation module.
Relations are entities.
So instead of creating entity references to link nodes, when using the Relation module, you create Relation entities, and these Relation entities can contain entity references to two or more entity references to connect them via a "type".  In the case of the Relation module, this is an entity type.
Also, because relations are entities, you can add fields to them.  And the module provides Views integration and other useful features.
Unfortunately, the port of Relation to Drupal 8 has been abandoned and the maintainers now recommend using the features of core itself-- this is possible, but it's a lot more work than what Relation provided out of the box.
Creating a similar config to Relation module in D8

Make each "type" its own entity type.
Add entity reference fields to each type and set them appropriately.
Customize your Views accordingly.


jQuery not Loading for "Anonymous" Users For Drupal 7, a jQuery will not load for "anonymous" users on any template pages. But when I log in as an administrator it loads. It's similar to this issue: http://drupal.org/node/802432, but nothing I tried has worked. The only way I could get the jQuery to load was by giving the user access to the administration menu, which I do not want to do.

I have the following code in the preprocess_node function of the template.php file.

if ($variables['view_mode'] == 'full') {
$node =& $variables['node'];
if ($node->type == 'page') {
  $path = drupal_get_path('theme', 'responsive');
   drupal_add_js($path . '/js/jquery.snap.js', array('type' => 'file', 'scope'
   => 'header'));
   drupal_add_js($path . '/js/jquery.snap2.js', array('type' => 'file', 'scope'
   =>'header'));
  }
}

Here is the original JS code

<script type="text/javascript">
document.write(unescape("%3Cscript src='"
+((document.location.protocol=="https:")?"https://snapabug.appspot.com":
"http: //www.snapengage.com") + "/snapabug.js' type='text/javascript
'%3E%3C /script%3E"));
</script>
<script type="text/javascript">
SnapABug.addButton("77777-7777","0","50%", true);
</script>

I put the code in two separate JS files (couldn't get it to work in a single file)

jquery.snap.js

(function($) {
document.write(unescape("%3Cscript src='"
+  ((document.location.protocol=="https:")?"https://snapabug.appspot.com":
"http: //www.snapengage.com") + "/snapabug.js' type='text/javascript
'%3E%3C /script%3E"));
})(jQuery);

jquery.snap2.js

(function($) {
SnapABug.addButton("77777-7777","0","50%", true);
})(jQuery);

When I look at the HTML source I see an error for jquery.snap2.js: "Uncaught Reference Error: SnapBug is not defined." The result is the snapabug.js is not loading. This error does not occur on the administrative side and the snapabug.js does load.

Drupal does not load jQuery if there are no dependency on it.

When drupal_add_js() is used once any where, Drupal includes jQuery automatically.

In case of user session, admin menu and overlay are dependent on jQuery so it is added automatically. So i advise you to try your drupal_add_js() code in hook_init just for try. I am not confirmed if it does not have any effect if it is called in hook_preprocess.

Please also check if you hook_node_preprocess is working at all?


Adding external databases to settings.php using prefix As per the comments in settings.php:

/*
 * You can also use a reference to a schema/database as a prefix. This maybe
 * useful if your Drupal installation exists in a schema that is not the default
 * or you want to access several databases from the same code base at the same
 * time.
 * Example:
 * @code
 *   'prefix' => array(
 *     'default'   => 'main.',
 *     'users'     => 'shared.',
 *     'sessions'  => 'shared.',
 *     'role'      => 'shared.',
 *     'authmap'   => 'shared.',
 *   );
 * @endcode
 */

So if my current simple default looks like:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'dev',
      'username' => 'dev',
      'password' => 'dev',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => false,
    ),
  ),
);

How would I add two tables (table1 and table2) on another database (dev1) on localhost so that they are available to drupal?

If they're on the same mysql host (and you've got the appropriate permissions) you can access the tables by simply prefixing them with the schema name: otherdatabasename.tablename. You can even run queries joining across the two databases.

If they're on a different server you'll need to add a separate connection and specify it as part of the query by using the $options['target'] setting.


How can I correct a word on the CKEditor field? When editing a text area in Drupal 8, right clicking a highlighted spelling error doesn't produce a context menu option to correct the misspelled word. How can I correct the word on the CKEditor field?

According to AdamPS in Enable browsers' (native) spell checker in CKEditor

  2) If you browser supports spelling suggestions, the way to access
  them in Drupal is slightly different. When you are in an edit area,
  then the normal browser context menu may be replaced by the editing
  context menu. However you can access the browser menu by clicking
  Control. [But on a Mac it is potentially command and on a tablet
  ....??]

You need to hold down CTRL before right clicking. (which worked for me on Windows OS)

An alternative would be to install the SpellCheckAsYouType(SCAYT) plugin for CKEDITOR

  Note: You have to build a custom module to install CKeditor plugins in
  D8.


Contextual filters and node types I have a block that is displaying related content to the node being viewed. Currently it's displaying node titles for three content types : hotel, tour operator and transport.
I would like it to display only content type that is similar to the content of the node currently viewed and filter out the two other content types.

I have been trying to set this up using contextual filers in views but I can't get it to work.

Is it something that can be done using contextual filters without writing any code ? Or do I need to write some php (I can't) to get this to do what I need.

Thanks

It might be possible to add a conditional filter on the node type and then add custom PHP code to get the default value based on the currently viewed node. The code to do this should look like this: (should work both in D6 and D7):

if ($node = menu_get_object()) {
  return $node->type;
}

It would be cleaner to do that in a views handler, that is however quite a bit more complicated to set up than pasting the above code in the textfield in the views UI.


How to find out if a Rule is successfully executed or not? I am using Drupal7. I have created a custom event for a rule using hook_rules_event_info(). I have added a Rules Action for the Rules Event "Flag a node".

When I invoke the Rules Event in code, using rules_invoke_event(), I have to know whether the Rules Action is executed successfully or not.

How can I identify if the Rules Action fails and handle the failure situation gracefully? Primarily I need to know how to identify whether the rule is successfully executed or not?

Try enabling debugging in rules->settings.
Hope this will help you in finding the execution of action


Removing field wrapper in a form I would like to theme a form, and the div wrapping my text input element prevents me from doing what i want. So i got this right now :

<div class="form-item form-type-textfield form-item-email">
 <input type="text" id="edit-email" name="email" value="mail@msn.com" size="20" maxlength="128" class="form-text required">
</div>
</div>

I would like to have this :

 <input type="text" id="edit-email" name="email" value="mail@msn.com" size="20" maxlength="128" class="form-text required">

You can set #theme_wrappers of the element to empty array so the element will not have any wrapper at all.

$form['email']['#theme_wrappers'] = array();


Drupal 8 - How to add link & display in twig template I have file in src/Form/TestForm.php.

I would like to add link of Forgot password in buildForm function & want to display in twig template file.

How to achieve this?

You should add the link in the form builder, something like the following example:.

$forgot_password_link = \Drupal\Core\Link::createFromRoute($this->t('Password link'), 'user.pass')->toRenderable();
$form['forgot_password_link'] = [
  '#markup' => render($forgot_password_link),
];


Cached "Page not found" for anonymous users My site's drupal version is 6.19. There are always logs like the following.

the recent log entries shows

type: page not found
location:http://www.example.com/display.html
referrer:
  message: 500.shtml
  severity: warning
  hostname: 95.64.11.29 or others (maybe search engine robot IP)

The URL and the content is right, but when the anonymous user accesses it, it returns the "Page not found" page. Anonymous users have the permissions to access content.

The cache_page table contains the following header for http://www.example.com/display.html:

Content-Type: text/html; charset=utf-8 HTTP/1.1 404 Not Found

Why is the page being cached as "404 Not Found", when it actually exists?

When I access http://www.example.com/display.html as an anonymous user, the site shows "page not found"; when I clear the cache, anonymous users can access the page.
How can I correct the cached content generated by search engine bots?

Is the page actually handled by Drupal or is it a static .html file?
It looks like a file that shouldn't be handled by Drupal, the 500 error
http://www.checkupdown.com/status/E500.html indicates a fatal server error.

If it is handled by Drupal can you change the url to one without the .html & see if that works with caching. You could use the global_redirect module to forward the .html addresses, once you figure out why it's failing.

If it is a flat file you may need to change the .htaccess or settings.php file to allow the .html to be processed by the webserver without bootstrapping Drupal.

There is a massive thread about this issue on Drupal.org http://drupal.org/node/76824#comment-3299738 You may find an answer in there.

PS
If this is served on a shared host you may want to contact your provider, they can have some strange setups & can fix quickly if you explain clearly what is happening.


Entity reference field dependent on entity reference in referenced entity of another entity reference field I have a content type 'order' with 2 entity reference fields. One is a reference to another content type 'brand' and the other is a reference to a taxonomy term 'categories'.

Now the content type 'brand' has an entity reference field aswell, containing a selection of taxonomy term 'categories'.

When creating a new 'order' I can select a 'brand'. Now the second field with the 'categories' should only show taxonomy terms available (selected) for the selected 'brand'.

I have tried to achieve this with the second entity reference field (categories) to use a view.

In this view I configured the following:

Relations:
- Content using field_categories
- Content referenced from field_brand

This worked when I had only 1 brand, since this brand was not connected to all categories. But now with multiple brands, the view just returns all the terms used in ALL brands.

Any idea how to achieve what I try? Any help is very appreciated. Thank you!

This isn't easily possible at the moment with the standard widget/autocomplete API as it has no context from where it is referenced.

To get something like that, you need a custom widget, one that supports to pass an argument to the views query based on your current node and then you need to connect it with your other field so that setting/changing a value there sends an ajax request to update your other widget, which then needs to get that value and pass it along to the views selection plugin.

Some related core issues:
* https://www.drupal.org/node/2776571
* https://www.drupal.org/node/2280479


How can I make a View that shows the number of nodes attached to per taxonomy term? I want to list taxonomy terms to see how many nodes are attached to each term.

I made a taxonomy View but can't find a field for the number of the nodes attached to per taxonomy term.

There is no this kind of field by defualt and maybe Views PHP or Views Custom Field are the way to go ??

This may help get you started. What you want to do can be accomplished by creating a views entity with a taxonomy argument that returns 'display summary when argument not found.'  In that setting as well is an option to display the number of nodes, (339) for example, that have that term attached to them.

http://drupal.org/node/301485#comment-1065230

Check out that link and post back with questions.


Two domains pointed at the same site, can't log in to one of them A client has two domain names, a .ca and a .com, that both point to the same D7 site (same codebase, same database, no custom sites folder for either of them, so it's not a multisites situation; the Apache document root path is simply the same for both sites). Everything works fine except that nobody can log in to the .com version. There is no "unrecognized username or password" or other error generated, it just doesn't log them in. (Incorrect passwords do generate the error message.) Checking the log messages, I see that it opened and then immediately closed a session.

Changing cookie settings is not a viable approach here, because it's different top-level domains, not different subdomains.

One possible solution is to redirect one domain to the other instead of running them "in parallel" (I'm aware of the methods, pros and cons of this approach), but I'm interested in why this is and what else can be done about it.

I had this issue before. It is related to the cookie setting, try doing this:

<?php
if (isset($_SERVER['HTTP_HOST']) && substr_count($_SERVER['HTTP_HOST'], 'parentdomain.com') > 0) {
$cookie_domain = '.parentdomain.com';
}
?>


How to remove overlay hashtag and trailing menu from the parent overlay Lets say for example we have activated contextual links & overlay modules and when clicking the edit button for the node, which is all the way bottom of the page, it open on overlay. Now when we look at the address bar the link now looks something like this http://localhost:8888/node#overlay=node/25/edit%3Fdestination%3Dnode

The problem with overlay is that it pushes the parent overlay to scroll all the way to the top and when I decide to "cancel" editing I have to scroll all the way to bottom again just to reach the node teaser. So I need to remove the this part from the link above #overlay=node/25/edit%3Fdestination%3Dnode

Now I guess it is being caused by jquery bbq feature. And looking into overlay module and her js files I find it very scary and dont know how to avoid this.

I need some help on where to look into this for starters like me.

If you remove the "#overlay=node/25/edit%3Fdestination%3Dnode" part from the module, you disable the overlay for that page.

if that is what you want to do, then you need to implement hook_admin_paths_alter() in a module, using code similar to the following one (change "mymodule" with the effective short name of the module):

function mymodule_admin_paths_alter(&$paths) {
  $paths['node/*/edit'] = FALSE;
}

The result returned from hook_admin_paths() is used from the Overlay module to decide when a page is rendered in an overlay. The implementation of that hook done by the Node module is the following one:

function node_admin_paths() {
  if (variable_get('node_admin_theme')) {
    $paths = array(
      'node/*/edit' => TRUE,
      'node/*/delete' => TRUE,
      'node/*/revisions' => TRUE,
      'node/*/revisions/*/revert' => TRUE,
      'node/*/revisions/*/delete' => TRUE,
      'node/add' => TRUE,
      'node/add/*' => TRUE,
    );
    return $paths;
  }
}

The module that implements the hook I reported in the first code snippet should be enabled when the  Overlay module is enabled; alternatively, that hook implementation should check if the Overlay module is enabled.

function mymodule_admin_paths_alter(&$paths) {
  if (module_exists("overlay")) {
    $paths['node/*/edit'] = FALSE;
  }
}

The information returned from hook_admin_paths() could be used from another module to render those pages in a different way, such as using an administrative theme; if the purpose is just to avoid the overlay is used to render that page, then the module should change the information returned by hook_admin_paths() only when the Overlay module is enabled.


How to create a custom content type with a quiz field? I'm pretty much new to Drupal 8, is there a way of creating a custom content type with a quiz field?

You can use the Field Quiz module. It already has an alpha version for Drupal 8.

According to the module description,

  This module provides a simple field that can be used as a simple quiz
  or multiple choice questions. It provides a field with a textfield and
  a checkbox / radio selection combined. If added to any entity
  (node/content type, user, taxonomy term, ...) the editor of the entity
  can enter multiple answers in the textfields and determine which
  answers are correct.

  This module is for everybody who does not want to use the whole
  complex system of the quiz module, but just a simple field for
  multiple choice questions.


news site for a complete beginner I'm a programmer with medium skills in Java-C# with few knowledge about web development. Now I want to create a news site for our corporation.

I searched a bit and found that Drupal is a good tool to create a news site but I don't know if I can do this or not.
Currently I know nothing about PHP and Drupal.

So my questions are

Is it possible to create, manage and maintain a small news site using Drupal without (or with few) PHP skills?
If Drupal is not a good choice, what other options I have?

Yes, Drupal is a good choice to get started.. You can create and maintain site without PHP knowledge using Drupal since your requirements is very simple and can be achieved using out of the box Drupal.

You can try using OpenPublish Distro..

  OpenPublish is a packaged distribution designed for the online news
  industry. It is ideal for the implementation of a variety of media
  outlets sites including magazines, newspapers, journals, trade
  publications, broadcast, wire service, multimedia sites and membership
  publications. OpenPublish is built for flexibility, customization, and
  extension -- a powerful CMS to help publishers focus on their content.


Where should I put a modified version of l() function? I want to customize l() function, which is part of Drupal 7 core and it is located in the common.inc file.

Where should I put such a function?

Modifying l() function or putting a new function in the common.inc would be considered hacking the core.

You should put it in your custom module. I think it's anyway good development practice to have a custom module in every project you develop.

What I do usually, is that I create MY_MODULE.helpers.inc file, and include it at the top of the .module file.

Here's an example of .module file:

// Get helper functions.
require_once dirname(__FILE__) . '/MY_MODULE.helpers.inc';

This way, if your module is enabled, the function will become available to other modules or your theme, and your .module file is cleaner because it doesn't include the helper functions.

You can see my Drupal 7 Boilerplate and specifically the boilerplate.helpers.inc file on Github.


How to specify multiple submit handlers for multiple forms I am implementing hook_forms in my custom module and I don't know how to have multiple form submit handlers.

Here is my custom form function:

function data_retrieval_main_form()
{
    $form ['field2'] = array(
        '#type' => 'textfield',
        '#title' => t('Name'),
        '#default_value' => $name,
        '#maxlength' => 127,
    );

    $form ['field3'] = array(
        '#type' => 'textfield',
        '#title' => t('Age'),
        '#default_value' => $age,
        '#maxlength' => 127,
    );

    $form['fileupload'] = array(
        '#title' => t('Choose Image'),
        '#type' => 'file',
    );

    $form ['submit_field'] = array(
        '#type' => 'submit',
        '#default_value' => 'Submit',
    );

    return $form;
}

Here I am implementing hook_forms:

 function hook_forms($form_id, $args) {

      $forms ['mymodule_first_form'] = array(
        'callback' => 'data_retrieval_main_form',
      );

      $forms ['mymodule_second_form'] = array(
        'callback' => 'mymodule_main_form',
        'callback arguments' => array('some parameter'),
      );

      return $forms;
    }

Now I previously had a single form using hook_form and the handler was simply like this:

function data_retrieval_form_submit($form_id, &$form_state)
{
// validation and submission of form
}

But now that I have multiple forms, how do I have multiple submit handlers for the forms, is there a way in Drupal that checks which form is being submitted?

You can specify a submit handler for each of your forms. Examples:

Override default handler with custom handler (new array):

$form['#submit'] = array('data_retrieval_form_submit');

Run custom handler after default (append to array):

$form['#submit'][] = 'data_retrieval_form_submit';

Run custom handler before default (prepend array):

array_unshift($form['#submit'], 'data_retrieval_form_submit');

You can add it to the $form array in a custom form builder function, or alter an existing form via hook_form_alter.


Google web font imports breaking with advagg I'm trying to pass Google Page Insights, and they keep saying we have render blocking CSS.  When I try and inline the CSS, it breaks my fonts I'm importing from Google Fonts.  I've tried a million combinations, but the inline is the culprit for some reason.

Here is the CSS code from one of the aggregated files:

@import url("http://fonts.googleapis.com/css?family=Pontano+Sans");@import url("http://fonts.googleapis.com/css?family=Roboto");

I tried it with and without quotes.

For the time being, to keep my client happy, I moved the $styles variable below in my html.tpl.php template, right before the close of the body.  It works fine, but there is a nasty flicker on the page load before the CSS loads, so inlining makes the most sense to me.

I use Omega 4 and use @import in my SASS.

You'll want to follow this issue https://www.drupal.org/node/2396609 Inline critical css

I'm guessing you're using the "Inline CSS on specific pages" setting on the AdvAgg: Modifications page. If the imports and not working correctly when everything is inlined, please open up a bug report explaining this with a good way for me to reproduce the issue locally.

Also noted that you can use the Adjust CSS location and execution setting to load the css async without having to mess with the tpl file.


How to make a link between Drupal and my ownCloud server? I want my documents uploaded from Drupal to be directly stored on my ownCloud server. Drupal server and ownCloud are both installed in the same machine.

Do you know how to do this type of action?

As a first step you would need to share users between owncloud and drupal.

I found this github project that appears to allow your owncloud installation to use the users from the drupal database.

Anything beyond this point requires some coding.

Assuming that the above worked and you have the user shared between the two platforms, then I expect you would need to write a drupal module with that used the owncloud API to submit a file from a drupal form. You would also need to use the owncloud api to return a list of files associated with a user.

This would be a very crude implementation, which bypassed all of drupal's file handling functionality, and relied on your own code for every interaction with owncloud (I can't find an existing module). A more advanced module would aim to use owncloud as a backend for the file system, in which case you might want to look at the patterns used in the Droogle or dropbox modules and adapt them to the owncloud api.

Whilst writing this answer I found what looks to be an interesting discussion from drupalcon Austin entitled Collaborative Spaces: Integrating Drupal with Google Drive, Dropbox, and more. Maybe that would be of help.


How could the contextual filter "Content: Nid" return the TNID instead of NID? I am using the contextual filter "Content: Nid" in Views3, and I want it returns the TNID instead of the NID When the filter value is NOT available.

I tried the following code.

$node = node_load($argument);
$argument = $node->tnid;
return $argument;

I also tried the following code.

$node = node_load(arg(1));
$argument = $node->tnid; // bzw. $argument(1) = $node->tnid;
return $argument;

I used that code in Provide default value:PHP Code Field, but nothing worked.

I solved the problem by adding this code to the page.tpl.php.

$imagemenuview = views_get_view('projectimagemenu');
echo $imagemenuview->preview('block', array($node->tnid));

I am still interested in the solution using the contextual filter "Content: Nid" returning the TNID instead of the NID When the filter value is NOT available.

This PHP code should work:

$node = node_load(arg(1));
return (isset($node->tnid) ? $node->tnid : $node->nid);

The better way (without evil eval()) is to provide own plugun of type 'argument default' which will do work. Look at Content ID from URL argument default plugin as an example.


How to hide custom fields on the registration form? I have added a lot of fields in the user profile, and sorted them using Gield Groups module tabs. Аnd now when registering the user, on the register form appears all fields and field groups tabs.

How can I hide all custom field and tabs on registration form and leave only email and one of custom field? Or can I create custom registration module with custom module?

You can configure the registration form in "Manage form display" of the "Account settings":

/admin/config/people/accounts/form-display

Go to the bottom of this page and in "Custom Display Settings" enable the use of custom display settings for the "Register" form.

Then you get a tab "Register" at the top of the page. Here you can configure which fields are displayed.


in drupal 7, views_get_view('VIEWNAME') get a error? I want to embed a view in the tpl.php, so I am using the views_get_view('VIEWNAME') function.Here is what I am doing the tpl.php.

<?php
   $view = views_get_view('MapView');
   print $view->preview('default');
?>

"MapView" is the view's name, I am not sure the argument in the views_get_view is the machine name or human readable name, in fact in my example is using the human readable name, because I can't find the machine name in the drupal view configuration

anyway, I get a error saying "Fatal error: Call to a member function preview() on a non-object", seems like I didn't fetch the view in the correct ?

any idea ?

Even thought the documentation for views_get_view() refers to $name as the name of the view, what the function wants is the machine name of the view.

You should always check the value returned from the function is not NULL, as the function doesn't return any value, if it doesn't find the view with that name.

  ctools_include('export');
  $view = ctools_export_crud_load('views_view', $name);
  if ($view) {
    $view->update();
    return $view->clone_view();
  }

views_embed_view(), for example, uses the following code.

  $view = views_get_view($name);
  if (!$view || !$view->access($display_id)) {
    return;
  }

  return $view->preview($display_id, $args);

You should use similar code, avoiding to call $view->access() if the view should always be visible, independently from the permission the currently logged-in user has. If you need to show the view only when the user has the permission to see it, then you should consider using views_embed_view().


The 'publish on' date must be in the future Is there a way to set the content to be published on future time instead of future date. I get the message "The 'publish on' date must be in the future" when trying to set publish date to today but late at night.

Under

  admin/config/content/scheduler

you can set your date format. What have you set here? Has the date format included time formatting?

The publish time has to be added after the date (that is today).


Is it possible to send a response from a service, but return something else? I have a block that returns a render array. I would also like to set a cookie value as well in this process. Is it possible to set a cookie and also return a render array?

You can still use setcookie/setrawcookie in Drupal, if you are sending a response, you can use Symfony to set one:

$cookie = new Cookie('name', 'value', $expire, '/', 'domain', TRUE, TRUE, TRUE);
$response->headers->setCookie($cookie);

vs

setrawcookie('name', 'value', $expire, '/', 'domain', TRUE, TRUE);

Note that the internal Drupal function that writes a cookie adds a prefix that you probably don't want.


comment count statistic Hi I'm Drupal beginner.

I'm trying to make a view which shows most commented content today, this week, this month, total in Drupal 6.

I only found the total comment count field.

Please help me.

I believe that the total comments is the right field.  You'll have to make different views to show all content from today, this week, this month....THEN sort the view by most comments (so that the highest is first), then restrict your view to show 1 item, and VOILA! (should work)


trying to dynamically change drupal commerce order I am trying to create a pane on the drupal commerce checkout page which will will give the user some options to change which product is in the cart. I want this done with ajax, without leaving the checkout page.

This is the code I have written so far:

  global $user;
  $product_id = 3;
  $order_id = commerce_cart_order_id($user->uid);
  commerce_order_delete($order_id); //delete the present order
  $newOrder = commerce_order_new($user->uid); //and create a new one
  commerce_order_save($newOrder);   //NEED?
  $product = commerce_product_load($product_id);
  $lineItem = commerce_product_line_item_new($product, 1, $newOrder->order_id);
  commerce_line_item_save($lineItem); //NEED?

  // Add the line item to the order using fago's rockin' wrapper.
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  $order_wrapper->commerce_line_items[] = $line_item;

  // Save the order again to update its line item reference field.
  commerce_order_save($newOrder);
  commerce_cart_order_refresh($newOrder);

  return $form;

However, this code gives me an ajax error

  Failed to load resource: the server responded with a status of 500 (Internal Server Error) http://example.com/system/ajax

Am I making a code error? A Commerce error?

Going out on a limb a bit...

There's no function called commerce_new_order, you probably mean commerce_order_new()

Same thing with commerce_load_product() and commerce_product_load()


Region on specific page Is it possible to set a region on a specific page? I've created a page and I only want it to display it there and not elsewhere.

Create View Block.

Go to Home » Administration » Structure » View

Add New View.

Create a Block with View (Not Create a Page)

Then, Select that block on the specific page.

If you have created that page with Panels or Node Template (By Adding New Variant)
You can set View Rule.

Add Visibility Rule in View Block

Select String: URL Path as an Option

Then, set path to your page where you wanted to display your block.

I hope this will help you..


Database updates failing I sort of inherited a Drupal 8 site which has lately generated a problem causing 500 error when e.g. trying to modify menus. I haven't myself updated the Drupal (just got it, it is currently on version 8.7.5).
I checked what is the status of database and found out there's about two dozens updates needed. So, I though, maybe drush updb would cure the problem. Well, it still might, except that the first update fails and so the others never ever get even tried. The significant lines are as below

[notice] Update started: feeds_update_8001
[error]  Missing bundle entity, entity type node_type, entity id migrate_example_beer.
[error]  Update failed: feeds_update_8001
[error]  Update aborted by: feeds_update_8001
[error]  Finished performing updates.

How to overcome that? There is no table named migrate_example_beer (though a few others including that part do).
Is it possible somehow to skip the first update, or anyone has any ideas how to cure that one error?

I finally got through this. In config table in the database there was (probably just from some test long ago) a reference to that example.

Deleting that line made the updates to go through.

Now checking if it solved my actual problem...

Thanks for the help

hank


Multiple taxonomies in single field Is there a module that allows you to combine two taxonomies?

Lets say I have the two simple taxonomies listed below.

Award:

gold
silver
bronze

Year:

2012
2011
2010

Is there a module that allows me to add different deltas like "Gold+2012" and "Silver+2010" to the same field?

You can try the Computed Field module.

  Computed Field is a very powerful CCK field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. […] You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views.


Remove the ability to import previous imported file I'm guessing someone must have done this before but I can't find a module for it.

In Feeds the last file you imported can be seen by name on the left hand side.  Next to the 'Browse' box.

If the user doesn't browse for a file then the File shown in that box is imported when clicking on the 'submit' button.  What I'd like to do is to leave this file being shown as the last import but I don't want it to be imported if no file has been selected.

Has anyone done this or something similar .

you can simplely remove it by using hook_form_alter

don't forget replace  form_id and yourmodulename with yours  in following code

function yourmodulename_form_alter(&$form,$form_state,$form_id){
    if($form_id=='feeds_import_form' ){
    unset($form['feeds']["FeedsFileFetcher"]['upload']['#file_info']);
}
}

update
in this section we prevent user to resubmit the old file,this mean if user push import button without browsed new file we prevent him to remport

function mymodule_form_alter(&$form,$form_state,$form_id){
    if($form_id=='feeds_import_form' ){
      $form['#validate'][] = 'mymodule_prevent_import_validate';
}
}

function mymodule_prevent_import_validate($form,$form_state){
    if(!isset($form_state['values']['feeds']["FeedsFileFetcher"]['file'])){
            form_set_error('upload', t('Not new file uploaded'));
            return false;
    }
}


How do I add embedded YouTube videos in a field? I would like to have a field for adding YouTube videos; however, I do not want to use the Media module because it is very buggy at this point. Is there any alternative for Drupal 7?

Just use the Video Filter module, here is a quote from its project page:

This is a highly flexible and easily extendable filter module to embed any type of video in your site using a simple token. Other modules can add video sites/formats (called codecs) using an easy plugin architecture.
With WYSIWYG installed, you can use the Video Filter button to easily add videos in a rich text editor.


Which is better approach "taxonomy_get_term" or using SQL to display term name on template file I have a View page with term id in its URL as argument and I have found two ways to display term names on Views template file.

One is using taxonomy_get_term(); the other one is querying the database.

$explode_vocubulary=explode("/",$_GET['q']);
$vocubulery1=$explode_vocubulary[1];
$sqlvoc1="SELECT *  FROM `term_data` WHERE `tid` =".$vocubulery1;
$rowvoc1=db_query($sqlvoc1);
while($resultvoc1=db_fetch_object($rowvoc1)) {
  echo  $resultvoc1->name;
}

I'm not a coder and don't understand the difference very well but it seems that using Drupal API seems to be cleaner. What the difference between these two approaches or which is the better way?

Literally the only difference between you calling taxonomy_get_term() and running the query yourself is that taxonomy_get_term() statically caches and serves term objects that have been loaded previously in the same page load.

You'll only get performance increases, not decreases, if you use the API function so I'd thoroughly recommend using that instead of going directly into the database.

Since you're running an identical query anyway, it's just repetition of code otherwise.

This is the code from taxonomy_get_term(), it should help illustrate the above:

function taxonomy_get_term($tid, $reset = FALSE) {
  static $terms = array();

  if ($reset) {
    $terms = array();
  }

  if (!isset($terms[$tid])) {
    $terms[$tid] = db_fetch_object(db_query('SELECT * FROM {term_data} WHERE tid = %d', $tid));
  }

  return $terms[$tid];
}


Accent caracter encoding I move a Drupal site and DB from old server to new (almost same setting) the site on the new server is running "almost" perfectly, but for the accent caracter encoding... here is the problem.

The site is requesting the file "Québec.jpg" i know for sure I spy it with firebug, and the Québec.jpg is where it should. The only problem is the the photo is not showing properly

If I change the file name for : QuÃ©bec.jpg it work...

I prefer not thinking about all the change i should do, so now the question why it's doing that, and what to change to fix that, file is there, request it ok, but mix-and-match don't append !

Thanks in advance

The contents of your tables are not stored in the encoding that is specified for those columns. So you need to find out how the characters are stored and what the specified encoding is, e.g. using phpMyAdmin. It seems the characters are stored in UTF-8, but the columns are identified as latin1. If I recall correctly I've used this conversion script successfully in the past for a similar situation. Of course, always backup your database before attempting such operations! Or try it on a copy first.

You can also drop all tables and fully reimport the old database, this time choosing the correct character encoding. (It's best to have everything in UTF-8, so if the old database dump is not in UTF-8, you could convert the .sql file first and then import it as UTF-8).


How do I get a module path? I'm creating a module in Drupal 8 and I need to define a relative path to mymodule to pass it on a JavaScript file like this.

$scope.getPlatformIcon = function (_platform) {
     var modulePath = "/modules/mymodule"
     switch (_platform) {
         case "youtube":
         case "twitter":
         case "instagram":
         case "facebook":
             return modulePath+"/img/"+_platform+".png";
     }
     return false;
};

In Drupal 7 I could use the following.

var modulePath = Drupal.settings.mymodule.basePath;

For the Drupal 8 root directory, I could use the following.

drupalSettings.path.baseUrl

I didn't find how to get the module path.

How can I do it with Drupal 8?

To answer the original question (how do I get a module path), and not taking into account the javascript attachment part here is OO friendly solution (without showing the dependency injection itself):

$module_handler = \Drupal::service('module_handler');
$module_path = $module_handler->getModule('my_module')->getPath();

This will give you back the following (of course also depends on how your directory structure looks like)

"modules/custom/my_module"

drupal_get_path is indeed faster to write. However, it calls the same service above statically which makes your code unable to unit test (also not to mention the dependencies of your class are not visible).
Long story short: if you choose to make things Quick&Dirty go for drupal_get_path any other cases use the right service yourself with a proper dependency injection.


Protect site from flooding when user login is attacked by brute force I've been experiencing issues with bots trying to force their way into the website I manage. It seems to be a daily occurrence the the flood system is being triggered (I'm on D7).

I'm happy the the flood system is doing it's job and stopping the attacks, but the problem is the bots are using private IPs, so when the flood is triggered it just locks everyone out.

I would like to find out if there is a way to limit the amount of bots that are getting through to the actual login verification. I tried throwing hidden captcha on to the login form, which does an ok job of it, but even when it suspects a bot, it doesn't't stop the login verification, so the flood system still gets triggered. Does anyone know of anything I can put in front of that process to limit the amount of bots getting though? The less intrusive, obviously the better.

The type malicious bots you describe can connect through open proxies all over the world (typically without permission), each having different IP addresses. They can also use trojans and viruses on hijacked client computers/servers to do their work.  In other words, Drupal's built-in flood control system, that uses IP-addresses for blocking, is no good for dealing with this type of attack.  If the flood system causes problems for you ("locks everyone out"), you need to reconfigure it or turn it off.

You can do this by adding one or both of the following pair of configuration settings to your site's settings.php file:

// Set per-IP failed login attempt limit to max and window to 5 seconds
$conf['user_failed_login_ip_limit'] = PHP_INT_MAX;
$conf['user_failed_login_ip_window'] = 5;

// Set per-user failed login attempt limit to max and window to 5 seconds
$conf['user_failed_login_user_limit'] = PHP_INT_MAX;
$conf['user_failed_login_user_window'] = 5;

In that way, no-one will be locked out.

Instead of using the built-in flood control in Drupal, try using Apache ModSecurity to limit bots access to your server, filtering on content (POST requests), instead of IP-address.

From its documentation on HTTP Traffic Logging:

  Web servers are typically well-equipped to log traffic in a form
  useful for marketing analyses, but fall short logging traffic to web
  applications. In particular, most are not capable of logging the
  request bodies. Your adversaries know this, and that is why most
  attacks are now carried out via POST requests, rendering your systems
  blind. ModSecurity makes full HTTP transaction logging possible,
  allowing complete requests and responses to be logged. Its logging
  facilities also allow fine-grained decisions to be made about exactly
  what is logged and when, ensuring only the relevant data is recorded.

First discover the pattern in the POST requests the bots make, and use Apache to block them.


drupal commerce rule to skip duplicate sku in cart I have a site and i am using drupal commerce module. i want to set a rule which will prevent the user to add a product twice in the cart. suppose a user add a product A and after that if he add the same product in the same cart than the system should generate a message that the same product is already added in your cart you can add another product.

I tried to create a rule but it works on the total quantity of cart not on total quantity of same product in the cart. please help

Thanks

You can use unique field , autosku and tokens module

using that module set the name of sku using tokens
While generating sku use tokens

the parameters which u know differentiates 2 products should be used in tokens

Like if quantity and size is the parameter which differentiates your 2 products and defines two products as unique
then
using tokens(for e.g.) [product:qty] and [product:size]
set the sku title
and using unique field set the sku as required and unique field

You can try the following function to edit the quantity :
you can set cart quantity for a single item to be default value 1.
hook_commerce_cart_line_item_refresh($line_item, $order_wrapper)

  Allows modules to perform additional processing to refresh an
  individual line item on a shopping cart order.

  Prior to this hook being invoked, product line items will have already
  had their sell prices refreshed via the creation of a new line item
  for the same product being passed through Rules for calculation.

  Parameters

  $line_item: A line item object that should be updated as necessary for
  the refresh.

  $order_wrapper: An EntityMetadataWrapper for the order the line item
  is attached to.


How to display the trimmed value and the full value of a field in a same node I have a content type with a text field that i want to render trimmed and full in the same node.

I've set my field to "trimmed" and rendered it in my node.tpl.php using
<?php print render($content['field_image_desc']); ?>

Now i need to render the same field but not trimmed (to display it in an overlay div).

Thanks for helping...

i answer myself:

inside node.tpl.php, this is rendering a trimmed version of my field

<?php
     print render(field_view_field('node', $node, 'field_myfieldname', array(
        'label'=>'hidden',
        'type' => 'text_summary_or_trimmed',
        'settings'=>array('trim_length' => 30),
    )));
?>

and then i render my 'default' format field like always

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


What is best for setting up the vocabulary for ubercart products? I'm setting up an Ubercart store on drupal 7.

I've created a new product class "tire" and I'm adding custom fields to the "tire" content type.  Some of these fields such as brand and speed rating should to pull their values from a vocabulary.

What is best for setting up the vocabulary?

Option 1)
Tires -> Type -> All-Season, Winter, etc...
Brand -> Good Year, Dunlop, etc...
Speed Rating -> S, T, H, etc...

Option 2)
Tires -> Type -> All-Season, Winter, etc...
Tire Properties -> Brand -> Good Year, Dunlop, etc...
Tire Properties -> Speed Rating -> S, T, H, etc...

Option 3)
Tires -> Type       -> All-Season, Winter, etc...
Tires -> Properties -> Brand        -> Good Year, Dunlop, etc...
Tires -> Properties -> Speed Rating -> S, T, H, etc...

I've started with option 3 already, but I've noticed that when I go to add a new tire the drop-downs are allowing values from the entire vocabulary, not just a specific child-node such as everything below "brand".

I'm not really sure what the best-practice is for setting vocabularies for custom fields using the CCK module.

The way your describing it cannot be used as a vocabulary taxonomy as each term is related to one another. What your describing is a type of content. Since each tire has an attribute of:

type
brand
speed rating

Your vocabulary should be those 3 separate ones, with each appropriate term under them. From there you would create a product in ubercart and those would be the 3 ATTRIBUTES and you would then add OPTIONS to those attributes. Ubercart's architecture isn't very appropriate for your type of setup last i tried. Technically you are only creating 1 product in ubercart and have 3 attributes for it with a bunch of options.

My suggestion would be to use Drupal Commerce as it would work perfectly for you as it will represent each product properly. Each unique tire will be represented as a product item. It will be alot of them as you have 3 attributes for each.


Comment count for different language I have a blog section on a bilingual page that I'm working on and I'd like to show the total number of comments below each teaser. Not to confuse users, the total should be total number of comments for the language that user is in. So, let's say if I have Spanish and English version of the website. If the user is on English, it should only show total number of comments in English not the grand total. Likewise, if the user is on Spanish, it should only show total number of comments in Spanish. Right now, it shows grand total and confuses users. How do I resolve this issue? Any help would be appreciated.

Drupal 7.x

This is untested but you could override the comment_count variable in a template_preprocess_node.

/**
 * Implements template_preprocess_node().
 */
function MYTHEME_preprocess_node(&$variables) {
  // Not sure if you wanted to limit to teasers but here goes.
  if ($variables['view_mode'] == 'teaser') {
    // Get the node object.
    $node = $variables['elements']['#node'];
    // Fetch the language the user is browsing the site in.
    global $language;

    // Query against the database all comments for the node in language the user
    // is browsing the site in.
    $result = db_select('comment', 'c')
      ->fields('c', array('cid', 'language', 'nid'))
      ->condition('language', $language->language, '=')
      ->condition('nid', $node->nid, '=')
      ->execute();
    $comment_count = $result->rowCount();

    // Now we override the comment count from the comment module with our result.
    $variables['comment_count'] = $comment_count;
  }
}

Observe that Views for example fetches $node->comment_count which is set in a node_load by the comment module.

So if you are using Views to display the comment count will still be wrong. One idea could be to add your own hook_node_load and populate $node->comment_count. This needs to be done after the comment module has run it's hook_node_load.

But if you are displaying nodes using the teaser view mode the code above (maybe with some modifications) should work :)

Edit
On second hand it might make more sense to setup a new variable called something like comment_count_active_language instead of overriding comment_count. In theory the comment_count is correct for the node. You are more asking for another count.

Change the example above but setup a new variable.

$variables['comment_count_active_language'] = $comment_count;

Then print that in node.tpl.php instead of $comment_count.


How to add CSS to menu_callback page? I have implemented hook_menu in my module and created a page. Now how to add CSS to this page? I have the below code inside my page_callback function, but still the css is not applied.

$css = "table,tr,th,td {padding: 10 !important; }";
drupal_add_css($css, 'inline');

Any help is appreciated.

Unless you've hacked D6, 'inline' only works with drupal_add_js(), not drupal_add_css().  So, to do what you want, you need to put that line of css in a file and include that file instead.


Lengthy MySQL query being exec I've inherited a Drupal site that is experiencing slow load times and I'm trying to troubleshoot the problem. The site is run on a dedicated box with what should be enough resources.

I ran the Devel module to see the MySQL queries and it's telling me that the following query is being run four times taking a total of 2-3 seconds.

execute SELECT DISTINCT node.nid AS nid, node.title AS node_title,
node_revisions.body AS node_revisions_body,
node_revisions.format AS node_revisions_format, node.sticky AS node_sticky,
node.type AS node_type FROM node node LEFT JOIN node_revisions node_revisions
ON node.vid = node_revisions.vid WHERE node.status = 1 ORDER BY node_sticky DESC

There are almost 400 other queries that are taking over 10 ms, but this one above is by far the longest and that it is being run multiple times, I suspect is causing some of the load problems.

Any suggestions on what is going on here or where to look for more information? All modules and core files are up to date.

You have to work very hard at caching. Particularly if the page is static, then make sure you caching on in  Home → Administer → Site configuration.

If this is not enough investigate 'boost cache' or alternative caching systems. This can takes some work to setup/prime and tune.

Caching most effective way of getting drupal-6 to be performant. What queries drupal makes can't really be beaten as you can't change the logic of Drupal. If the queries aren't being made at all because of caching they won't be slow.

Second thing. You could also make sure that MySQL is using INNODB tables and that you have set innodb_buffer_pool_size to as high a level as you can given memory limitations. Here is a MySQL tuning script that might provides some hints http://www.day32.com/MySQL/.

Third thing is to make sure that only the modules that are in use are installed on the system. Every module has an overhead.


Rules + Button Field: getting entity object to a custom action I am using Rules 7.x-2.2 with the latest version of Button Field (http://drupal.org/project/button_field), Session API (http://drupal.org/project/session_api) and a custom module to store some entity values in a user's session when they click a button.

To clarify, I have an entity type (Commerce product) with an HTML instance of the button field that is supposed to trigger a custom defined rules action, where I want to extract some values from the entity object that the button is associated with.

This is how my Rules action info looks currently in my custom module:

function commerce_custom_box_rules_action_info() {
    return array(
        'commerce_custom_box_add_to_box' => array(
            'group' => t('Commerce Custom Box'),
            'label' => t("Add the product to the user's box"),
            'parameter' => array(
                'entity' => array(
                    'label' => t('Product entity'),
                    'description' => t('The entity the clicked button is attached to.'),
                    'type' => 'entity',
                ),
            ),
        ),
    );
}

And here is how my rule looks:

The problem is, in commerce_custom_box_add_to_box() (the function fired by my custom action), I have tried using dpm() on all of its arguments and none of them contain any entity properties, field values, or anything else that could even be remotely useful. All I get are empty "EntityDrupalWrapper" objects and similar. However, if I replace the action in the rule with "Execute PHP Code", there is an $entity object available there and dpm() reveals that it is in fact populated with all the usual properties.

Naturally I am trying to figure out why that object is there but isn't being received by my custom action. Perhaps I'm thinking about it in the wrong way?

A fresh pair of eyes on this would be hugely appreciated! Happy to provide more info if needed.

It turns out this was caused by the parameter type I used. I set it to "entity", whereas it should be the machine name of the entity type. Changing it to "commerce_product" has fixed the problem.


form_state['values'] generating error undefined index: values I am having a simple form like this. I want to read the ID value in the middle of the form. When I try to get it using $fromvalues = $form_state['values']['id']; it gives the following error:

  Undefined Index: values in templates_form()

function templates_form_add($form, &$form_state, $templates = NULL) {
  $templates = entity_get_controller('templates')->create();
  return templates_form($form, $form_state, $templates);
 }

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

   $form['id'] = array(
     '#title' => t('ID'),
     '#type' => 'textfield',
     '#default_value' => isset($templates->id) ? $templates->id : '',
     '#description' => t('Unique Id'),
     '#required' => TRUE,
     '#maxlength' => 255,
     '#disabled'=> empty($ntemplates->id) ? FALSE : TRUE,
   );

   $fromvalues= $form_state['values'];

   $form['city'] = array(
     '#title' => t('city'),
     '#type' => 'select',
     '#options' => $cities,
     '#default_value' => isset($templates->city) ? $templates->city: '',
     '#required' => TRUE,
     '#maxlength' => 255,
     '#disabled'=> empty($templates->id) ? FALSE : TRUE,

   ),

The error indicates precisely what is going on: during the initial call of templates_form() the $form_state['values'] does not yet exist. This will exist in a future ajax call (if you do ajax) and in validate and submit functions. You better check if it exists first with isset or empty.


How can I show the Sales Report for particular user? I use Drupal 7 and the Drupal Commerce module.

My site has 3 roles defined:

Admin, who can publish and unpublish product of affiliate.
Affiliate, who can add the product in the site.
Learner who can see the show the all product and but the product.

My question is related to a learner buying a product which was added by an affiliate:

When an affiliate checks the sales reports, then the report is null.
But when an admin checks the sales reports, then it displays all functionality in the reports.
And a learner can also check the sales reports.

So how can I solve these issues? Why are affiliate sales reports null?

Attempt to answer the "Why does an affiliate get an empty report?" part of your question (which I believe is part of your question): could it be related to some "permission" you have not granted to an affiliate (yet)?

Here are a few links related to permissions that may be helpful:

Drupal Commerce issue nr 1303194.
What's the explanation for my product permission issue in a Drupal Commerce view? (and/or some of the "related" questions there).


Add a subquery to SELECT'd columns in a dynamic query I have a query I want to run through Drupal 7's DB API as a dynamic query where a subquery needs to be a column of data.

For example:

SELECT a, b, (
  SELECT x, y
    FROM table
    WHERE table.x = 'value') as c
FROM table_2
WHERE table_2.a = 'value_2'

How can I perform this through the Drupal 7's DB API?

You can use db_query()

$result = db_query(
  'SELECT a, b, (
    SELECT x, y
    FROM {table}
    WHERE table.x = :value1) as c
  FROM {table_2} AS table_2
  WHERE table_2.a = :value2',
  array(
    ':value1' => 'value',
    ':value2' => 'value_2',
  )
);


How to display a default value for minute field of Time fieldtype I have a Time component in my webform. When I go to my form I see Hour is selected by default in the Hour field but I see 00 is selected by default in the Minute field.

How I can set Minute as the default value in the Minute field?

As the time component says in its description field, it "accepts a time in any GNU Date Input Format. Strings such as now, +2 hours, and 10:30pm are all valid."

If you want to set the default minute, you can used a formatted string like "1972-09-24T20:02:00,000000-0500" or "10:30pm" in the Default value field.


How do i print image title in custom node for image gallery I use content types for image gallery and write own custom node for image gallery all images are show in custom node by following code but i don't know how to print the image title.

In this code i have given static title 'Circles and Cycles ' and i need dynamically title of every image.

<div id="node-<?php print $node->nid; ?>" class="node-gallery">

    <?php
        $imgcount = count($node->field_gallery_image['und']);
        for ($i = 0; $i < $imgcount; $i++) {
        $image_uri = $node->field_gallery_image['und'][$i]['uri'];
            // url
            $masthead_raw = image_style_url('gallery-thumb', $image_uri);

    ?>

          <a href="<?php print file_create_url($node->field_gallery_image['und'][$i]['uri']); ?>" rel="group-<?php print $node->nid; ?>" class="product-link">

 <img class="image<?php print ($i + 1);?>" src="<?php print $masthead_raw; ?>" />

Circles and Cycles

      <?php
        }?>

Create a view of your content type, then in this view select the fields as your content and then select the title and the image. then every image will have its own title. you can also theme it in any way that you want.

you need to output this view in your node page, so simply in your template.php and in hook_preprocess_node function suggest a theme hook for this content type (for example page--node--gallery.tpl.php) and then in the page--node--gallery.tpl.php output the view using views_embed_view("view_name","display").


How do I use the access arguments? Hel', I don't understand how to use "access argument" with Services Module.

Drupal is used like a server. When I follow specific link some informations about client, user and projects are added. That's work, but everybody can do it. So I want "limit access" : if you are not admin, the access is denied. So I've activated the authentication "Session authentication" and add some code in my custom module :

'create' => [
    'help' => 'Add',
    'callback' => 'custom_api_create_user',
    'access arguments' => array('administer create'),
    'access arguments append' => FALSE,
    'args' => [
        [
            'name' => 'data',
            'type' => 'struct',
            'description' => 'Something',
            'optional' => FALSE,
            'source' => 'data'
        ]
    ],
]

And when I add hook_node_access I get this message : "Access denied for user Lambda", and only the first letter of "access argument" is added to the content.

Someone can explain to me how I can add content and limit access with Services module ?

Do you understand what I want to do ?

(Yes you can see the same post here)

in this case, the first letter is "a" because the access argument is "administer create". If I remove administer the first letter will be "c" from &create". And all fields from user entity get this letter as content :

name : "a"
tel : "a"
mail : "a",
etc.

Actually I just want to know how to say "if you are admin you can add content, if not, you can't". The best way is to use "Session authentication" or "Basic authentication" or "oAuth" ?? Don't know...


Emoji works in a site but not in the other site on the same host I am trying to enable emojis following Multi-byte UTF-8 support in Drupal 7.

I have added the following to the settings.php file.

  'charset' => 'utf8mb4',
  'collation' => 'utf8mb4_general_ci',

I've converted MySQL tables into utf8mb4 format and set the collate to utf8mb4_general_ci.

On the Drupal 8 site emojis work, while on the Drupal 7 I get the following error.

  4 byte UTF-8 for mysql is activated, but not supported on your system. Please turn this off in settings.php, or ensure that all database-related requirements are met.

What am I missing?

Update

When I try to save a node with an emoji I receive the following error.

StatusText: Service unavailable (with message)
ResponseText: PDOException: SQLSTATE[HY000]: General error: 1366 Incorrect string value: &#039;\xF0\x9F\x98\x8A&#039;

First I SUGGEST to take a look at https://www.drupal.org/project/utf8mb4_convert module

try to adding   'charset' => 'utf8mb4',
  'collation' => 'utf8mb4_general_ci', configs to your settings.php file.

after adding it should be something like :

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'databasename',
  'username' => 'username',
  'password' => 'password',
  'host' => 'localhost',
  'charset' => 'utf8mb4',
  'collation' => 'utf8mb4_general_ci',
);

if it does not work for you, probably you need to change MySQL configs. use the following config in your MySQL configuration ( usually my.cnf or my.ini)

# Use UTF8MB4 as the character set
collation-server = utf8mb4_unicode_ci
init-connect='SET NAMES utf8mb4'
character-set-server = utf8mb4

another suggestion:

ALTER DATABASE dbname CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci;
SELECT CONCAT('ALTER TABLE `', TABLE_NAME,'` CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;') AS mySQL
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_SCHEMA= "dbname"
AND TABLE_TYPE="BASE TABLE"

FINAL STEP to make the warning go away and get a clean Status Report:

USE YOURDATABASENAME;INSERT INTO variable SET name='drupal_all_databases_are_utf8mb4', value='b:1;';

my.ini or my.cnf
add:

[mysqld]
innodb_large_prefix=true
innodb_file_format=barracuda
innodb_file_per_table=true

settings.php

  'charset' => 'utf8mb4',
  'collation' => 'utf8mb4_general_ci',


Adding data to node object Is there a hook responsible for generating the node object's data?

I want to add some custom data to specific node objects to help with the functionality of a very complex website.

Can anyone help, please?

hook_node_load() is exactly what you're looking for

Act on arbitrary nodes being loaded from the database.
This hook should be used to add information that is not in the node or node revisions table, not to replace information that is in these tables (which could interfere with the entity cache). For performance reasons, information for all available nodes should be loaded in a single query where possible.

The code example from the docs page is actually very good for your use case so I'll include it here too:
function hook_node_load($nodes, $types) {
  // Decide whether any of $types are relevant to our purposes.
  if (count(array_intersect($types_we_want_to_process, $types))) {
    // Gather our extra data for each of these nodes.
    $result = db_query('SELECT nid, foo FROM {mytable} WHERE nid IN(:nids)', array(':nids' => array_keys($nodes)));
    // Add our extra data to the node objects.
    foreach ($result as $record) {
      $nodes[$record->nid]->foo = $record->foo;
    }
  }
}


Remove XMLRPC to avoid vulnerability exploit How is xmlrpc.php from Drupal core affecting functionality?

Given the fact that a vulnerability was discovered for it, details in this article

is it safe to remove xmlrpc.php file?
Is it bad practice? If so, why?
Is there any way to neutralize this security risk without removing
this file?

is it safe to remove xmlrpc.php file?

Yes, if you're not expecting anyone to use it.

  Is it bad practice? If so, why?

Could be construed as such; any change to core creates an additional step when updating (I'm sure we're all aware of the dangers of 'hacking core' by now, but if not: Never Hack Core).

  Is there any way to neutralize this security risk without removing this file?

Update your core to 7.31, where the vulnerability has been fixed.


How to pre-populate a field with the current users name? I want to pre-populate a form field with the value from another cck field from a different content type. I have been looking into using the prepopulate module and pathauto to get the correct url, but I am not sure that these will work. I am new to drupal and kinda lost in the storm with this problem.

To answer the question posed in the title of this question, you could in a custom module do something along the lines of...

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  global $user;

  if ($form_id=='NODETYPE_node_form') {
     $form['field_FIELD'][0]['#default_value']['value']=$user->name;
  }

  // any other form alters you need

}

where MYMODULE is the name of your custom module, NODETYPE is the content type in question and FIELD is the field name in question without the field_ prefix.  Now, whenever you are editing or creating a content type of NODETYPE, the FIELD in question will have a prefilled default value of the current user's name.

Now, if this is a different form, you'll just need to adjust the $form_id== construct to point to that form, the field in that form, etc, but the rest of the logic should be the same.


Any callback method for migration I have written a migration script that is working but After migrate data I need a method/way to store recent inserted id with some other relevant data in another custom database table.

Can I do with help of any hook or use any plugin.
 This is my yml file.

id: order_billing_address
class: null
field_plugin_method: null
cck_plugin_method: null
migration_tags: null
migration_group: default
label: 'User profile for billing information'
source:
  plugin: csv
  path: pathtocsv/order_billing_address.csv
  header_row_count: 1
  keys:
    - profile_id
process:
  type:
    plugin: default_value
    default_value: 'customer'
  uid: uid
  profile_id: profile_id
  address/country_code: country
  address/administrative_area: state
  address/locality: locality
  address/dependent_locality: locality
  address/postal_code: postal_code
  address/sorting_code: ''
  address/address_line1: street
  address/address_line2: street2
  address/organization: company_name
  address/given_name: first_name
  address/family_name: last_name
destination:
  plugin: 'entity:profile'
migration_dependencies: {  }

In order to do this, I will create a custom module, an event, dispatch it in a  hook_ENTITY_TYPE_insert implementation and subscribe to it so that we can insert the data into different custom table.

https://x-team.com/blog/creating-and-subscribing-to-events/


RSS not appearing in meta tag An RSS-feed on my site doesn't show up in the HTML <head> as it is supposed to, which makes it very difficult to find. Here's my situation:

A view is displaying the latest blog posts.
This view has two displays: a content pane and a feed. The feed is attached to the
content pane.
The content pane is shown on a page using panels and page manager.

The RSS-icon shows up at the bottom of the view, so the feed is definitely there. However, the feed doesn't show up in the the meta-tags, so the browser doesn't discover the feed like it's supposed to. Does anyone know where this goes wrong, and how I can fix it?

I had a similar issue before. As you mentioned, feed auto-discovery works through the link in the  tag (see http://diveintohtml5.info/semantics.html#rel-alternate for more info).

I found that some themes and modules add it in automatically, while others don't. If yours is absent, you can auto-discover the default drupal RSS feed by adding the following to a preprocess function:

$element = array(
  '#tag' => 'link',
  '#attributes' => array(
    'href' => '/rss.xml',
    'rel' => 'alternate',
  ),
);
drupal_add_html_head($element, 'mymodule');

Alternatively, you could just add it into the html.tpl.php file, as mentioned in this post: http://www.webbykat.com/2012/03/adding-feedburner-rss-link-your-theme-drupal-7-omega

Regarding Views, I have found that enabling auto discovery means adding a "Feed" display then turning on the setting at Feed Settings > Attach To > Master, as you did. You can also set it to include other displays to get the RSS icon to display in those views.


View display plugin "entity reference" not using translation UPDATE: This bug was just fixed in Issue
  2174633 and
  Drupal v8.7.9 will no longer have this problem.

For some of my entity reference fields I'm using "Views: Filter by an entity reference views" as reference method. I've configured those views to use the current interface language for rendering (with fallback to default lang).

The interface language selection basically works (in other view blocks, or when previewing in /admin/structure/views), but it does not work when used as source for an entity reference field:

In my admin interface I'm using I've got a paragraph with an ER field using such a view as source. The paragraph always shows the title in default lang
On the frontend I've got a webform select field using the same view as source. The select options are always rendering in default lang.
When using the default reference method I do get translated titles in both use cases.
As stated above, the correct language is used in preview on /admin/structure/views

How can I select the correct language for my view-filtered ER fields?

(Please note that I can not use the interface language as filter criteria, because this would disable the language fallback.)

Comparing TermSelection::getReferenceableEntities and ViewsSelection::getReferenceableEntities it seems like the Views entity reference selection plugin doesn't translate the entity before returning the entity labels. It should work with a core patch adding one line:

/core/modules/views/src/Plugin/EntityReferenceSelection/ViewsSelection.php:

public function getReferenceableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
  $display_name = $this->getConfiguration()['view']['display_name'];
  $arguments = $this->getConfiguration()['view']['arguments'];
  $result = [];
  if ($this->initializeView($match, $match_operator, $limit)) {
    // Get the results.
    $result = $this->view->executeDisplay($display_name, $arguments);
  }

  $return = [];
  if ($result) {
    foreach ($this->view->result as $row) {
      $entity = $row->_entity;
      // add this line to translate the entity
      $entity = \Drupal::service('entity.repository')->getTranslationFromContext($entity);
      $return[$entity->bundle()][$entity->id()] = $entity->label();
    }
  }
  return $return;
}

Edit:

This won't be necessary anymore, when https://www.drupal.org/project/drupal/issues/2174633 is fixed, then resolving the underlying problem, that the selection plugin ignores the views output.


How do I point to a particular installation of simplesamlphp with the simplesamlphp_auth module? I am trying to integrate our company's SSO into our Drupal installation. As a POC to see if it even works, I have a copy of the SimpleSAMLPhp Library located at /foo/bar/simplesamlphp. I configured my apache vhost and the SAML configs and that's all fine for now.

Per the instructions from Acquia on this page, I tried installing the drupal/simplesamlphp_auth module.

composer require drupal/simplesamlphp_auth

This installed the module and as a dependency, installed a second copy of the simplesamlphp library in vendor/simplesamlphp. Now it looks like the module simplesamlphp_auth is using the installation in vendor.

How do I configure this module to use the one I already placed in /foo/bar/simplesamlphp? There doesn't seem to be any options on the page /admin/config/people/simplesamlphp_auth.

I have configuration files that I would like to avoid copying over to the vendor directory after each deployment if possible, since that's not as secure as keeping the configs outside of the project altogether.

EDIT 1

Clarification on the configuration files: I need to define configuration files in /foo/bar/simplesamlphp/config in order for it to work. These configuration files are missing from vendor/simplesamlphp/config and without them the application encounters a fatal error. As stated in the Acquia document above, the library lives outside of vendor/ or docroot/ in their setup.

You can just create a symlink to your temporary SAML folder

ln -s /foo/bar/simplesamlphp ./simplesaml

In settings.php add next line:

$settings['simplesamlphp_dir'] = '/foo/bar/simplesamlphp';

In config.php file in your /simplesamlphp/config library add following settings:

// Load necessary environmental data
$ps = json_decode($_SERVER['PRESSFLOW_SETTINGS'], TRUE);
$host = $_SERVER['HTTP_HOST'];
$db = $ps['databases']['default']['default'];

// Define basic variables
$config = array (
   'baseurlpath' => 'https://'. $host .':443/simplesaml/', // SAML should always connect via 443
   'certdir' => 'cert/',
   'loggingdir' => '/files/private/log/',
   'datadir' => 'data/',
   'tempdir' => '/tmp/simplesaml',
   'store.type' => 'sql',
   'store.sql.dsn' => 'mysql:host='. $db['host'] .';port='. $db['port'] .';dbname='. $db['database'],
   'store.sql.username' => $db['username'],
   'store.sql.password' => $db['password'],
);

Now if you open your-site.com/simplesaml url in the browser, /foo/bar/simplesamlphp library will be used instead of vendor folder.


How can I get $_POST data in a callback? I've implemented hook_menu roughly as follows:

function sample_menu() {
    return array(
        'path/to/things' => array(
            'page callback' => 'callback_function',
            'access arguments' => array('access content'),
            'page arguments' => array(),
            'type' => MENU_CALLBACK
        )
    );
}

I want to be able to post data to this url. So says $_POST is the following array:

array(
    'data1' => 'value1',
    'data2' => 'value2',
)

How can I access $_POST['data1'] and $_POST['data2'] inside the callback? Directly accessing $_POST seems to not work (it's var_dumped as empty).

They access $_POST in the same way other functions do.

Take file_ajax_upload() as example; it contains the following code.

  if (empty($_POST['form_build_id']) || $form_build_id != $_POST['form_build_id']) {
    // Invalid request.
    drupal_set_message(t('An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (@size) that this server supports.', array('@size' => format_size(file_upload_max_size()))), 'error');
    $commands = array();
    $commands[] = ajax_command_replace(NULL, theme('status_messages'));
    return array('#type' => 'ajax', '#commands' => $commands);
  }

The function is a page callback defined in file_menu().

  $items['file/ajax'] = array(
    'page callback' => 'file_ajax_upload',
    'delivery callback' => 'ajax_deliver',
    'access arguments' => array('access content'),
    'theme callback' => 'ajax_base_page_theme',
    'type' => MENU_CALLBACK,
  );