May I use width and height CSS properties on images? CSS architecture (for Drupal 8) says:

  Never apply widths or heights except to elements that natively have these properties (e.g. images).

I use CSS properties like width:100% often with images. It seems much easier to get to than the markup most of the time. Does this guideline mean I should not being doing this? If so, is the only solution overriding a template file to get at the HTML element properties?

What I understand is, it is suggesting opposite to what you are interpreting.

Lets take a look again.

  Never apply widths or heights except to elements that natively have these properties (e.g. images).

So, it is saying that, you can apply the height and width to image freely as the Height and Width are the default property of images. This you can understand as all images has some width and some height. So they are intrinsic property of image.

Now, lets take other proof, why you can apply Height and Width to image. If you see the Drupal's core feature,
Image Style at Admin/Config/Media/Image style, there you can specifiy as many image style as you want with different Width and Height.

Hence this feature allowing the facility to  change the dimensions of same image with different Image styles - AND how this is happening, simply by changing the height and width, So this is the core feature.

Hence, image comes in the category of except in your highlighter following statement.

  Never apply widths or heights except to elements that natively have these properties (e.g. images).

So, you can freely use width and height to Images.


How do I update Drupal 8.2.3 REST configurations for an entity? According to the documentation, I need to update the REST configuration for each entity type. RESTUI seems not to work with 8.2.3, so I figure I'm supposed to update this by hand, for example in rest.resource.entity.node.yml.

I do that, and then I'm stuck. Where does this file go? Does it go in my code somewhere? Am I supposed to import it through Configuration Synchronization (admin/config/development/configuration/single/import)?

I did try to import using Config Synch, but I got the following error, which means nothing to a newbie like me: An entity with this machine name already exists but the import did not specify a UUID.

Sorry if this is already documented somewhere, but I can't find an explanation anywhere for how to update these settings, and they seem pretty important for using the REST services. I'm currently using the Features Module as a workaround but it's kind of an ugly approach for something that seems like it should be simple.

Thanks in advance!

To answer your second question, you'll want to remove the imported configuration from the database and then reimport it with an included UUID - after which you can overwrite the config by re-importing it as many times as you like.

But first, when you upload a config, you should give it a more meaningful ID; rather than 'entity.node', you want something like 'my_config_for_this_thing'.

So in steps:

In your DB, find the config you uploaded (and see note about about the config ID):

select name from config where name like '%entity.node%';

Copy the full name that matches your config.  It will be something like 'migrate_plus.migration.entity.node'.
Delete that row from the database

delete from config where name = '*paste that name here*';

In your yml file, include a uuid. You can generate one locally or using a web tool such as https://www.uuidgenerator.net.  This will look something like

id: some_meaningful_identifier
label: 'A label to describe my config'
status: true
uuid: ac1d69cc-382f-49d2-921e-bb0673fd62ea

Clear your Drupal cache
Then re-import and you should be in better shape.


Drupal SA-CORE-2014-005 - How to tell if my server / sites were compromised? I just updated all my sites using the patch method of resolving the Drupal SA-CORE-2014-005 exploit. I just read reports that just yesterday there is someone from a Russian IP infiltrating drupal sites.

https://www.drupal.org/SA-CORE-2014-005

My main concerns are now:

How do I tell if my sites have been comprised?
What should I search for in my apache access logs to detect if my site was a victim or not?
So far what are these hackers doing to comprised sites?

If you're reading this article and hoping to check a Drupal 7 site more than a month after the exploit landed, your site quite likely already got hacked. Your best bet is to restore a backup from before the attacks commenced and work from there.

There is a FAQ on SA-CORE-2014-005.

  How do I tell if my sites have been compromised?

One way to quickly check if sites are compromised is with the Drupalgeddon drush command.

https://www.drupal.org/project/drupalgeddon

Install to your ~/.drush with drush dl drupalgeddon

Then use drush drupalgeddon-test to test. Drush aliases make this easy and quick.

This tool can confirm an exploited site, but it cannot guarantee your site did not get exploited. There is no "clean bill of health" here unless you upgraded before the attacks started.

Site Audit module includes some of the checks from Drupalgeddon, and gives you a lot more useful input too. I highly recommend it. (EDIT: Now they work together - super nice!)

http://drupal.org/project/site_audit

Security Review doesn't check for Drupalgeddon attacks but is worth having in your toolbelt too.

http://drupal.org/project/security_review

If your site codebase was writeable to the www user , you could additionally check for modified code using the hacked module. This module may not do what you think based on its name alone :)

http://drupal.org/project/hacked

While there is no single certain way to identify all compromised sites, these tools can help you identify the most common indications.

  What should I search for in my apache access logs to detect if my site was a victim or not?

Your access logs will contain a lot of POST requests by now. Unless you had taken the unusual step of logging all post data in advance of the bug, you're unlikely to have the information to tell which of these were malicious.

  So far what are these hackers doing to compromised sites?

Many are reporting that their sites are being patched by the hackers! As an attacker, this makes good sense - you don't want your newly hijacked site whipped out from underneath you by the next attacker :)

Other than that, I'd guess the sites are being used to harvest whatever valuable data is there (maybe grab some creds, maybe lift transaction details after exploiting) and to do boring things like send spam and work as humble botnet slaves. Oh, and further expand the attacker's empire of hijacked Drupal sites. (Sorry, I don't have any hacked sites to observe.)


Views Slideshow, items per slide based on screen resolution I have a Views Slideshow slider with 4 items per slide (see below). I am looking for a way to make it change the items per slide number dynamically when the screen width hits a certain breakpoint -for example 3 items per slide when tablet screen and 2 items per slide when mobile screen. Been trying for few days but without success.

Any ideas are welcome.

Ive done it using detect_mobile class and some tweaking of views_slideshow_cycle.theme.inc, changing the $styles['items_per_slide'] variable based on the device detected. Don't see much of an interest so I won't share the code but if someone is interested please let me know. Cheers ;)


How do I get $entity in hook_form_alter()? hook_add_form() gets $entity_type and $entity as parameters, but hook_form_alter() does not have any of those parameters.

How do I get the entity type and the entity object in hook_form_alter()in Drupal 7?

I think that it should be possible to do something like this.

if ($form_state->getFormObject() instanceof \Drupal\Core\Entity\EntityFormInterface) {
  $entity = $form_state->getFormObject()->getEntity();
  $entity_type = $entity->bundle();
}

UPDATE: In Drupal 7 it should be done like this:

$node = $form['#entity_type']; // E.g this could be, (#node, #user etc.)

Take a look at this site, drupal discussion.


How to use a separate file for IE responsive.css for version 10/11 in Drupal I am setting responsive design for only IE (Internet Explorer) in Drupal 7.
here is my code its for work lower then IE 10 not for IE 10/11

function bootstrap_preprocess_html(&$variables){
  drupal_add_css(path_to_theme() . '/css/ie_10.css',
    array('group' => CSS_THEME,
        'browsers' => array('IE' => 'lte IE 10',
            '!IE' => FALSE),
                 'preprocess' => FALSE)
);
}

I suggest customising a pre-built theme template that has already taken care of that such as Zen or Omega.


2 separate Profile2 Views (one faculty, one staff) I've been able to create a view with the profile2 module (with custom forms)that renders all users on a view. How can I create a separate category of users, say 'faculty' and 'students' and have a view for each? So the faculty view would only show users labeled as faculty.

Thanks!

You could add a field "user type" to the current profile and then add a views filter or views "contextual filter" to only show one type at a time. You may need to add a "relationship" on the profile2.

Alternatively, profile2 lets you specify different types of profiles. So you could make a 'faculty' profile and a 'students' profile.

It really depends on what would work best in your setup.


Can I use Panels context keywords in PHP functions? I'm using the privatemsg module and I would like to display the number of unread messages a user has on his/her profile page.  I attempted to use %user, which is the context keyword for the user currently being viewed.

According to the privatemsg API documentation, the function for this is privatemsg_unread_count().  I tried calling the function like this:

privatemsg_unread_count("%user");

But I get an error: Notice: Trying to get property of non-object in privatemsg_unread_count()

The function takes an account argument, which as far as I can tell (I'm not very skilled in PHP) is an array that stores the values for a given user.  Am I going the wrong way with trying to use the context keywords?

Just call the function without any argument and it will return the unread message count for the current user.


how to add a redirection after password change without modifying Drupal Core? how to add a redirection after user's password change without modifying Drupal Core? (user_profile_form_submit)

You can add your own submit handler to the form using hook_form_alter, and set your redirect here.

Ex:

<?php
function my_module_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'user_profile_form')
  {
    $form['#submit'][] = 'my_module_profile_form_submit';
  }
}

function my_module_profile_form_submit($form, &$form_state)
{
  $form_state['redirect'] = 'some/path';
}
?>


Change list of values dynamically with a click I realize my request is a bit complex, I hope someone can answer.

I have a drupal 7 clean installation. I have a node type called Whole and another one called Piece. A Whole contains one to many Piece: I used the Entity module (with Entity reference) to link entities. The Piece node has a boolean field called selected.

When a user views a Whole node he can see all the Piece elements linked to it.

I need to allow an unlogged user to set the selected field of the piece node to true without leaving the Whole node page. I also need to keep track of the selected Piece elements (maybe in a session variable?). In the end I need to list all the Pieces altered in the session to compose a mail. When the mail is sent the session is cleared.

Is there a module that allows in place edit of node attributes?? I have installed and tried Editable Views, but it doesn't work. Maybe there is a conflict with my drupal version (7.14) which unfortunately I can't change.

You don't need to let anon visitors edit nodes to achieve this, and I wouldn't recommend it. It presents a security issue, and would store the "selected" status as a property of the node (for all visitors).

Rather, you can store the selected nodes in a session or a cookie, using a standalone drupal form. Create a form, like so:

function YOURMODULE_node_store_form($form, &$form_state, $nid) {
  $form_state['nid'] = $nid;
  $dv = (isset($_SESSION['node_store'] && in_array($nid, $_SESSION['node_store']) ? 1 : NULL;
  $form['selected'] = array(
    '#type' => 'checkbox',
    '#title' => 'Include this page in email.',
    '#default_value' => $dv,
  );
  $form['actions']['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );
  return $form;
}

function YOURMODULE_node_store_form_submit($form, $form_state) {
  if($form_state['values']['selected'] && $form_state['nid']) {
    $_SESSION['node_store'][] = $form_state['nid'];
    drupal_set_message('The page will be included in the email.');
  }
}

In the template file for the Piece content type, add the form to the teaser display, like so:

<?php print render(drupal_get_form(MYMODULE_node_store_form, $node->nid);) ?>

To include the stored nodes in the mail, you can retrieve them from the $_SESSION['node_store'] array. Once the email has been sent, you should probably clear the $_SESSION['node_store'] array.

If you DO have to store it to the node, use the node_save function in your submit handler, instead:

function YOURMODULE_node_store_form_submit($form, $form_state) {
  if($form_state['values']['selected'] && $node = node_load($form_state['nid'])) {
    $node->field_selected[$node->language][0]['value'] = 1;
    node_save($node);
    $_SESSION['node_store'][] = $node->nid;
    drupal_set_message('The page will be included in the email.');
  }
}


Search boxes for individuals content types I'm trying to have a search facility for different content types on their term pages.

So I have a view that lists all the terms that link through to a page that lists all the nodes that has that term. On this page I want to have a search box which can be used to search any node within it's content type. Now this is fine if I only needed to search one content type, using the Custom Search module I can tell Drupal to only search one content type.

However I need to do exactly the same as above but for a different content type. What would be the best way of implementing this?

Found an answer in the end if anyone else comes here searching for a solution. Turns out you could do what I wanted with the custom searech module I mentioned in my question. If you go into modules in the admin area there's also a custom search block module that comes with custom search that can be enabled. This gives you the ability to add as many blocks with different confiurations as you please. You then just go into blocks in structure and configure to your hearts content for each block then use those blocks where you want, job done! Just need to work out how to change the template now!


How do I autoload a class with the X Autoload module? I have X Autoload installed and enabled. I'm trying to get a simple example to work. The below setup throws the error:

  Fatal error: Class 'Pet' not found in
  MY-SITE/sites/all/modules/foo/foo.module on line 15

Have I got the directory structure correct for pet.php? I'm finding the docs difficult to follow on the placement and naming of the file that contains the class definitions. I'm trying to follow the PSR-0 standard to begin with. Thanks.

UPDATE: The below has now been corrected as per Clive's answer.

foo.info

name = Foo
core = 7.x
dependencies[] = xautoload (>= 7.x-4.0)

foo.module

<?php

function foo_menu() {
  return array(
    'foo' => array(
      'title' => 'Foo',
      'page callback' => 'foo_page',
      'access callback' => 'user_access',
      'access arguments' => array('access content'),
    ),
  );
}

function foo_page() {
  $output = \Drupal\foo\Pet::dog();
  return array(
    '#type' => 'markup',
    '#markup' => $output,
  );
}

Pet.php (MY-SITE/sites/all/modules/foo/lib/Drupal/foo/Pet.php)

<?php

namespace Drupal\foo;

class Pet {
  public static function dog() {
    return 'Buster';
  }
}

If your file-system is case-sensitive, so is PSR-0. Try changing your class filename to

  MY-SITE/sites/all/modules/foo/lib/Drupal/foo/Pet.php

And make sure you're namespacing your class correctly, e.g.

namespace Drupal\foo;

class Pet {
  ...
}

Lastly, make sure you're referencing the class correctly in your module file. Either

// Top of file.
use Drupal\foo\Pet;

// In a hook or whatever
$dog = Pet::dog();

or

// In a hook
$dog = \Drupal\foo\Pet::dog();


Nginx vs Apache - Are there any actual usage comparisons and statistcs out there? I have a new server to play with, and I am staring at a blank canvas. I can put anything I want on it. While I am comfortable with Apache, I keep hearing how nginx can handle so much more traffic than Apache, by factors of 10, 100, even more. Not only that it's "much much faster."

When I search for articles I can find lots of stuff unrelated to Drupal. Or, when I do come across a Drupal related article it's either 1) someone's configuration file with a quick attempt at explaining how to set it up, or 2) it's someone saying "no, don't use nginx, go with Apache with PHP fcgid" but there is never explanation as of why.

So, when it comes to Drupal, what is the reality here?

As an example, I am looking for something along the lines this 2bits.com article.  Here the author has taken a pretty extensive look at Apache mod_php vs Apache with fcgid, weighing the pros and cons of each, and provided a case study to illustrate the impact in the real world. There is enough information in this article for me to make an educated decision as to which approach would be best for my situation.

While that author compares mod_php to fcgid, I am looking for the same type of comprehensive, real world look at Apache vs Nginx.

Anyone switched to Nginx and been "blown away" by the difference it made compared to Apache? Even for highly optimized environments that are already using APC, Memcache, and aggressive caching like Varnish, when the only variable that changes is replacing Apache with Nginx, does make enough of a difference in and of itself to merit investing in this newer, alternative technology?

The site that will go on this server gets an avg of 2 million PV a month. LAMP stack running Cent OS 6. 4 core CPU with 8 GIGS of ram. Memcached and APC will be part of the mix. Nothing special about the Drupal install - basically vanilla 7 with about 50 modules.

Strictly speaking, this doesn't answer the question you are asking. I'm hoping it's helpful anyway.

Apache/Nginx/Lighttpd/other web server. Does it matter which one I choose? In short, No.

The much much longer answer:

If, and only if, you have a very large percentage of your users being logged in, should you care at all about the performance of your web server. If your users are anonymous, any difference that you can theoretically derive from optimizing at that layers absolute pales compared to making your resources better cacheable. If your css files have proper cache headers on them, the UA won't even ask for them the second time. That matters. If you can cache your pages in Varnish or a similar software solution, then serving that page is a matter of making a hash-lookup, and then returning a large chunk of data directly from RAM. That matters. In both of these scenarios, the HTTP daemon is never even involved, PHP does not get invoked. Drupal does not bootstrap. No large set of modules must be loaded into RAM, no time consuming database queries are executed.

When you perform a full page load, from a cold cache, for a logged in user, on a complex page; a lot of things are going on. Yes, the web server is involved in dealing with the incoming request, setting some headers and passing the response back. But the time that takes, is not even relevant in the context of Drupal running a full bootstrap and outputting its response. There could be hundreds of database queries being executed. Highly complex logic in PHP is evaluated by the parser. Lots of modules are being loaded into RAM. Improving the performance of any of those things, are much more likely to make a serious contribution to performance.

For the sake of argument: Let's say you have spent a lot of time performance optimizing everything else.

You run APC (Or Optimizer+) and the latest and fastest version of PHP.
DB-queries are few.
PHP logic has been reduced.
You cache what you can in Varnish.
You have re-structured your entire site so that you can cache a lot client side, and do lots of heavy lifting in ECMAScript.

If you have a lot of logged in users, and you've dealt with all of the above, then you can probably make a difference but performance tuning, or replacing your web server. However, guess what. Your site is so complex, and the usage patterns of your particular users, is unique. There is no generic answer. You will need to setup all different web servers behind a load balancer, and see how they behave, under your scenario.

The above was an attempt at logically reaching the conclusion that spending time performance optimizing the web server is likely a bad use of time. I would love to have someone pick holes in the above though, I would probably learn something new from it. :)

Some other notes:

During the DrupalCon Copenhagen keynote, PHP creator Rasmus Lerdorf, using Nginx himself, speaking on the topic of Drupal performance, said "People always ask me about web servers ... it really doesn't matter, the web server is pretty much irrelevant". (Roughly at 26:30 in the video)
Facebook has spent countless hours on writing Hiphop, a code base significantly larger than Drupal itself, for accelerating PHP-code by a "measly" 100%. I examined Hiphop with $ wc -l $(find . -type f | grep -v "^\.git" | grep -v "^\.hphp/third_party") | sort -nr | head -n1 and found it to consist of 1.512.481 lines of code. That's an absolutely insane amount of work put in to improving the speed of PHP. I'm guessing that's because the speed of PHP matters greatly to them.
Did I mention that good caching is going to have a much greater effect that tuning the web server?
With the release of Apache 2.4, Jim Jagielski basically claims that Apache 2.4 is faster than event based servers.
I attented Drupal Performance and Scalability with The Dream Team, where just this question came up. All the answers about which to choose, was unrelated to performance. Things like "Which one do you already know how to configure", and "Which one will allow you to build the simplest technology stack", were among the reasons mentioned to pick on over the other. Performance did not enter the picture.


Multi-site sharing content Is it possible to share content/nodes in a drupal multisite environment.

For example:

Content type "Story"

Site 1- Use this content
Site 2- Don't use this content
Site 3- Use this content

It seems the drupal multisite environment suggests using table prefixes for different sites.

I think this is what the domain access module is for.


Hook naming conflicts: what happens? If two modules implementing two separate hooks ended up with functions with the same name, could that cause a conflict or problem?

a.module

/**
 * Implements hook_a_b().
 */
function a_a_b() {}

b.module

/**
 * Implements hook_b().
 */
function b_b() {}

c.module

/**
 * Implements hook_a_b().
 */
function c_a_b() {}

c_a.module

/**
 * Implements hook_b().
 */
function c_a_b() {}

Does the scoping prevent that from causing a problem, even though the functions have the same names?

What happens if two modules declare the same hooks, even though they follow the naming scheme and the hook names contain the module names?

a.module

/**
 * Implements hook_a_b_c().
 */
function a_a_b_c() {}

a_b.module

/**
 * Implements hook_a_b_c().
 */
function a_b_a_b_c() {}

x.module

/**
 * Implements hook_a_b_c().
 *
 * It's not clear which of the two hooks this actually implements.
 */
function x_a_b_c() {}

Hooks are plain PHP functions that follow a specific name schema. As such, the same function name cannot be used from two modules.
Furthermore, Drupal is not able to understand if c_a_b() is the implementation of hook_a_b() done from c.module, or the implementation of hook_b() done from c_a.module.
To answer the question, yes, there would be conflicts and (in the case both the modules are installed) PHP errors.

Use something other than a single underscore for hook namespacing aims to not use a single underscore to separate the module name from the hook name, for example two underscores. Doing so, c__a_b() would be an implementation of hook_a_b() done from c.module, and it would not be confused with c_a__b(), the implementation of hook_b() done from c_a.module.
There is also Module names should not contain an underscore, which would avoid any ambiguity with c_a_b(). As underscores would not be allowed in module machine names, c_a_b() could just be the implementation of hook_a_b() done from c.module. (That feature request is set to closed (won't fix); at the moment, it's not going to be implemented.)

As for two modules invoking the same hook for different purposes and/or with different parameters, that is going to cause conflicts and errors.
The code invoking hooks calls a function basing on its name (<module>_<hook name>) directly passing the arguments to the function. If the arguments don't match the function parameters, PHP will raise an error; if the arguments match the function parameters, there will be other errors, as a hook supposes to be invoked in a specific moment, as described in the hook documentation. Imagine what would happen if a module would invoke hook_user_delete() after a user deleted a node; the modules implementing it would delete the data associated to that account from their database tables, since hook_user_delete() is documented to be invoked before a user account is deleted, not any data associated to the deleted node.

In both the cases, the only solution is naming hooks and modules in a way to avoid conflicts.

As per https://www.drupal.org/project/hook, that URL returns a 403 error because there is an unpublished project. (I can visit the project page because I am a webmaster on Drupal.org.)

The project has been created to avoid somebody would name a project Hook.


Are persistent connections used? How can I find out whether my Drupal 7 site using persistent connection or not? And it's possible to turn it on if it's not?

If the persistent connections is not enabled you can enable it by adding this to settings.php:

ini_set('mysql.allow_persistent', TRUE);

And you just do like this to turn it off:

ini_set('mysql.allow_persistent', TRUE);

To check is persistent connections is enabled go to /admin/reports/status/php, and search for allow_persistent.


How do I pass a checkbox value to a Webform through URL? When I click a webform link, I want one of the checkbox checked. I've set already set up the default value for that checkbox as %get[foo] in Webform.

I tried:

a href="node/34?foo=checked"

a href="node/34?foo=selected"

a href="node/34?foo=1"

a href="node/34?foo[]=1"

Am I missing something?

Webform provides this functionality by itself.

Define in your checkbox field a default value:

%get[customkey]

The url will be:

http://example.com/node/1?customkey=one,two


How to give class name to no results behavior in views I added price column first to view > hide it. I added special price column to view > in no results behavior i added price field token as below:

[field_price]

How to give a css class name to the 'no results behavior text'?

Thanks,

D

Can you add a class to the no results token? Like
[token].
Dunno if it works that way. Try that.


autocomplete on a multi value - custom field I have a field organizations on the user profile(the field can accept multiple values). I would like to add a autocomplete to this field. My code for this is

<?php
/**
 * Implementation of hook_menu()
 */
function org_ac_menu() {
  $items = array();
  $items['org_ac/autocomplete'] = array(
    'page callback' => 'org_ac_autocomplete',
    'access callback' => TRUE,
    'access arguments' => array('access dbpedia autocomplete'),
    'type' => MENU_CALLBACK,
  );
  return $items;
}

/**
 * Implementation of hook_form_alter()
 */
function org_ac_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_profile_form') {
    //$form['field_organization']['#autocomplete_path'] = 'org_ac/autocomplete';
    $form['field_organization']['und'][0]['value']['#autocomplete_path'] = 'org_ac/autocomplete'; **/* This works but only on the first input field! */**
  }
}

/**
 * Check for possibilities in dbpedia
 */
function org_ac_autocomplete($string = '') {
  $found = array();

  $url = 'http://lookup.dbpedia.org/api/search.asmx/PrefixSearch?QueryString='.urlencode($string).'&MaxHits=5';
  $result = file_get_contents($url);
  $data = simplexml_load_string($result);

  foreach($data->Result as $res_temp)
  {
      $found[check_plain($res_temp->Label)] = check_plain($res_temp->Label);
  }

  drupal_json_output($found);
}

The code works when I reference this element on the form, ->

$form['field_organization']['und'][0]['value']['#autocomplete_path'] = 'org_ac/autocomplete';

But since it can accept multiple values, the autocomplete doesn't work on the remaining elements ->$form['field_organization']['und'][1]  &  $form['field_organization']['und'][2]['value']['value']

How can I make it work on all the input elements for the organization field ?

Thanks

If you modify your hook_form_alter to loop through the $delta of field_organization it should work for you on multiples...

/**
 * Implementation of hook_form_alter()
 */
function org_ac_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'user_profile_form') {
    foreach($form['field_organization'][LANGUAGE_NONE] as $delta => $field) {
      if(is_array($field) && is_numeric($delta)) {
        $form['field_organization'][LANGUAGE_NONE][$delta]['value']['#autocomplete_path'] = 'org_ac/autocomplete';
      }
    }
  }
}


I18N, translating in template variables I've got a theme setup, and this theme has a header region (region--header.tpl.php). There are some small ui elements in this template that require translation, but are not tied to blocks, views or nodes. My understanding is that when using something like <?php print t('Select a topic'); ?> it should become available to the translation backend. But it does not for me? I have the I18N module and Multilingual Variables module installed.

What am I missing?

Ah I found that one needs to view the site in another language than English in order to have the strings to be registered.


How to get Views Criteria Filter arguments inside Views API hook? My question is related to:

https://drupal.stackexchange.com/questions/70551/how-to-sort-view-by-taxonomy-multiple-value-field-with-a-range-of-only-selected

I have an idea, but I didn't manage to find a way to get arguments passed to Views Filter Criteria.

I would like to get them inside hook_views_pre_render

Could someone give me any advice?

Ok, I found it.

In $view->filter property is an array of views filter handler objects. In selected object inside $hander->value array are arguments passed to this filter.


How to use rules to take a user from a group content page to the group page the content belongs to? I'm using Organic groups (7.x-1.5) and wonder how to write a rule that would take the user from a group content page to the group page the content belongs to?

The event could be triggered by a button on the group content.

For example: I am viewing the page of the University of Berkeley and if I click on the button there, I am taken to the California universities page (University of Berkeley page is group content, California universities page is group.)

Notice I did not say "back" to the group since the user can land on the group content page without first landing on the group page.

Any suggestions?

Many approaches available here. You can use the rules link module to do this. It can fetch the parent node and redirect to it when the link is clicked.
https://www.drupal.org/project/rules_link

However, check if organic groups provides tokens that you could use to build the link in html. Or a php snippet to grab the nid of the parent if it exists and print it as part of a link.

The other option is crumbs, the breadcrumbs module that automatically outputs the subgroup hierarchy.
https://www.drupal.org/project/crumbs

If you are using panels, I'm pretty sure there's a replacement pattern for the parent if you create custom content.


Share same database tables with multisite instances What I'm trying to do is to make 2 sites one for developing and one for live using which share same instalation and database. I want to see same content like on live site when I developing theme or module when the changes ready I want to push them via git to live server. Is it possible to make something like this.
example.com - live
developing.example.com -developing

I also found this http://drupal.org/node/22267 but I'm not sure how to setup :)

cheers

I understand your intention, but no. This is not the usual approach and has the potential to bring you all sorts of pains later on the line.

Once a project is deployed, you really need 2 databases. Say your live application needs a new feature, you would want to update your "dev" site with live server's data. So ...

You pull data from live server. Hint: drush sql-sync makes it as simple as drush sql-sync @live @dev.
You develop the feature ...
Push the code to production ... drush rsync @dev @live or whatever you use. (Git is also great for this btw)
Now we have to update the db changes and this is where it gets funky. If you have added or altered tables and data you cannot just sync the db because you will overwrite whatever data your users have posted since you pulled. The common way to handle this is having update hooks to insert the changes in your db. Following this approach, the update hook was deployed in step #3. All that is left to do is ..
Run live.com/update.php. This will trigger your update hooks and insert changes to db.

A few things to keep in mind that make this procedure dead easy:

Drush in conjunction with drush aliases and multiple settings.php for each environnment will make transferring code and  data back and forth a breeze.

Happy coding, cheers


How to modify Author Pane date fields? I have Author Pane installed along with D7 Advanced forum. I am wondering how to shorten the display format of 'Join' and how to remove 'Last seen:' from the pane?
I could not see any guidelines in the module's docs or issues about this.

Author Pane module contains appropriate templates files which control output.
author-pane.tpl.php is something that will help.

Just copy it in your theme directory, flush cache and do whatever you like with this file to customize Auth Pane block.

To remove 'Last seen:' from the pane comment or remove from the file

<?php /* Last active */ ?>
<?php if (!empty($last_active)): ?>

       <?php print t('Last seen'); ?>: <?php print t('!time ago', array('!time' => $last_active)); ?>

<?php endif; ?>

To shorten the display format of 'Join' find appropriate admin page (/admin/config/regional/date-time) and change Short date format to the format you prefer.

 * - $joined: Date the post author joined the site. (Uses shortdate format)


What module does this site use to handle its great badge system? Is this a functionality that exists within the existing badge module, or is it anything else?

This site (stackexchange.com) is not built with Drupal, but if you're looking for similar features in Drupal, check out User Badges, possibly in combination with Userpoints and/or Rules.


Can I host Drupal alongwith Google App Engine? I am new to Drupal as well as Google App Engine. I want to create a scalable website with few specialized apps in Google app engine and integrate with Drupal. Given both the platforms are extensively used, it seems to me that they should be supporting each other. However, I checked both Google app engine and Drupal website but could not figure out if they support each other. So my question is , is there any way I can host Drupal with Google app engine? Can they work together in the same platform?

Google App Engine now supports PHP, yes you can.
But Drupal technically is supposed to run on an Apache server (.htaccess rewrites, restrictions and options) with normal email servers that can be handled using normal PHP's mail(), and PDO, you will need to take care of providing alternatives for the services.

Mainly, GAE has limitations in emails, SQL, and writable file system.
Here is a link to a post that helped me a lot: http://blog.boombatower.com/drupal-google-app-engine


Drupal Commerce: Add content nodes to checkout steps We have a number of checkout steps that have some content in them that can only be edited via templates which is not ideal for clients.

Is it possible to create content nodes in the CMS that can then be used on the checkout?

It is! With the module commerce_extra_panes you can add nodes (content) to the checkout.


Allowing ajax link clicks to propagate A click event on a link with the use-ajax class on it does not seem to propagate up the DOM. Is this true? If so, is there a setting that will allow it to propagate?

Not being a JS whizz, I'm struggling to see where the call is made (preventDefault? return false?) that blocks the propagation. I've had a look at misc/ajax.js and there is a setting element_settings.prevent that looks like it might be relevant, but I haven't found any documentation on this.

It's in Drupal.ajax.prototype.eventResponse, round about line 265:

// For radio/checkbox, allow the default event. On IE, this means letting
// it actually check the box.
if (typeof element.type != 'undefined' && (element.type == 'checkbox' || element.type == 'radio')) {
  return true;
}
else {
  return false;
}

It's hard-coded, but this is JS - you can just monkey-patch Drupal.ajax.prototype.eventResponse and get it to do whatever you like :)


External JS libraries I have a few external js files that I call in my page, at the moment these are called via script tags in the header.

I am tempted to pull these locally and include them in my themes script file to decrease the load time of the page. I know there is an overhead to keeping the scripts up to date but if it decreases the total load time of the page it may be worth it.

Is there a good practice for this? Should I keep them external or is it good to include them in the drupal JS structure?

I think it highly depends on what the script is. There are definitely advantages to using third party scripts rather than including them locally. In most cases, I'll try to use the google Library API (http://code.google.com/apis/libraries/) when possible for things like swfobject, webfont loader, and the like. The advantage here is that clients may already have these libraries cached, giving a performance increase over hosting them locally. For situations where there is not a widely used third party host for scripts, I'll usually add them to sites/all/libraries/$library_name and include them locally, so you can take advantage of Drupal's ability to aggregate and minify JS.


How to get the image from the url and store in the custom path? if(empty($nodevalue->field_beachesimages)){
    $imageurl=array(explode(",",$nodevalue->field_beach_migrateurlhidden[$nodevalue->language]['0']['value']));
    foreach ($imageurl as $imagechange) {
        $countimagurl=count($imagechange);
        if($countimagurl>10)
            $imgdata=9;
        else
            $imgdata=$countimagurl;
        for($i=0;$i<$imgdata;$i++){
           $image =$imagechange[$i];
           $file = system_retrieve_file($image,'public://beachesmigration/', TRUE, $replace = FILE_EXISTS_REPLACE);
           echo "<pre>";print_r($file);echo "</pre>"; exit;
           file_save($file);
           file_usage_add($file, 'iks_beaches', 'beaches', $file->fid);
        }
    }
}

Hope this will help you.

In Drupal 7 , system_retrieve_file function will download a file from a remote source, copy it from temp to a specified destination and optionally save it to the file_managed table if you want it to be managed.

You need to create a folder beachesmigration inside sites\default\files.
By using system_retrieve_file it will be store your images inside beachesmigration folder with the filename you no need to specify the filename manually.

 $image = 'http://wordpress.ikitesurf.com/wp-content/uploads/2012/09/2032239599_fdce5e0ab0_z.jpg';
//I have used picture folder to store images using image field settings
 $file = system_retrieve_file($image, 'public://beachesmigration/', TRUE, $replace = FILE_EXISTS_REPLACE);

Source


Push Items to Array using drupal_add_js I'm using this code in a for loop to push items to an array but it doesn't add to the array, just overwrites it each time I think:

drupal_add_js(array('THINGS' => array('ONE' => array('VAR' => $var_one), 'TWO' => array('VAR' => $var_two), 'THREE' => array( 'VAR' => $var_three))), 'setting');

So this is what I end up with:

"THINGS":{"ONE":{"VAR":"blah blah blah"},"TWO":{"VAR":"blah blah blah two"},"THREE":{"VAR":"blah blah blah three"}}

When what I want is this:

"THINGS":{"ONE":{"VAR":"blah blah blah", "VAR":"blah blah blah one"},"TWO":{"VAR":"blah blah blah two","VAR":"blah blah blah two two"},"THREE":{"VAR":"blah blah blah three","VAR":"blah blah blah three three"}}

So I guess my question is, how do I print objects within objects using this method, or would it be easier to just push the variables with javascript within a script tag?

Any ideas? Am I doing this right?

The problem seems to be the key of the nested array, where you are using 'VAR', you are repeating this key and that makes PHP to override the value on the array (or on the object on Js).

I think you would have to use the 'VAR' key on a slightly different way:

drupal_add_js(array('THINGS' => array(
    'ONE' => array(
      'VAR' => 'blah blah blah',
      'VAR_ONE' => 'blah blah blah one'
    ),
    'TWO' => array(
      'VAR' => 'blah blah blah two',
      'VAR_ONE' => 'blah blah blah two'
    ),
    'THREE' => array(
      'VAR' => 'blah blah blah three',
      'VAR_ONE' => 'blah blah blah three three'
    )
  )
));

to get what you are looking:

"THINGS":{"ONE":{"VAR":"blah blah blah", "VAR":"blah blah blah one"},"TWO":{"VAR":"blah blah blah two","VAR":"blah blah blah two two"},"THREE":{"VAR":"blah blah blah three","VAR":"blah blah blah three three"}}


hook_load vs. hook_node_load? Can someone explain clearly the difference between hook_load and hook_node_load? hook_load says it is a "node-type-specific hook". What does that mean? hook_node_load actually has a types parameter.

This paragraph in hook_node_load() docs page explains it in details:

  This hook is invoked during node loading, which is handled by entity_load(), via classes NodeController and DrupalDefaultEntityController. After the node information is read from the database or the entity cache, hook_load() is invoked on the node's content type module, then field_attach_load_revision() or field_attach_load() is called, then hook_entity_load() is invoked on all implementing modules, and finally hook_node_load() is invoked on all implementing modules.

Here's the breakdown, from first to last call:

entity_load()
hook_load()
field_attach_load_revision() or field_attach_load()
hook_entity_load()
hook_node_load()

What this means to you is that using a different hook you will be able to modify values earlier or later. This matters if you're overriding value from another module for example. Otherwise, I think it's safe to use either.


Creating a relationship between taxonomy lists I'm working on a website about cars, the question is quite simple, but probably, will need as much information as possible.

So here's the situation, I need to create several vocabularies that define a car, starting from a car maker, car model, year, engine, etc... what I need to do is put it in a form of sorts, that filters every section, so say I want Skoda, then in the model, it gives me Fabia/Octavia/Superb/etc... because definitely, A corvette has nothing to do with skoda!!!! then I choose Octavia, and the next list gives me years which it was in production, so it doesn't matter which year I choose the next one is Engine, which engines did it have at that year?

Lets put it in a Graph:

Skoda <- Octavia <- 2000 <- 1.6 8v <- etc...

How do I create the relationship? Do I really need to structure the taxonomy in a very complicated way or what do I do?! Help me, I'm clueless :'( Many websites do it, why is it so complicated on drupal?

Any help will be greatly appreciated!

There are other ways to do this, in Drupal there are always other ways.  But before you try to implement a solution, ask the question 'what will I want to do with the information besides a direct look up' of say Corvette, year, motor size.  As soon as you find something else you want to include, say various models in a year - coupe, convertible, etc.- or information on colors, performance, displacement, maximum this and that,  you will find yourself redesigning that taxonomy again.  Drupal is a Content Management System and is entirely contained in the database.  Instead of laying out a taxonomy, work on the design of your database.  When you have a good structure for that, start creating fields and use the Views module to generate the content in whatever form you desire. Views is basically a UI for database queries with some great Drupal flexibility for assembling and displaying the content.

I hope this is helpful. By the way, Drupal is complicated.  It is very powerful and has a bit of a learning curve.  That's why this site has been successful.  Three months ago, I couldn't even spell Drupal, now I can :)

As you get going, come back to this site for more help.


How to load current user cart in Commerce 2? In Commerce 2, how can I load the current user's cart? The current user may be either anonymous or logged in. The site has multiple stores and I won't know which store the user is currently on.

It depends what you need, really. If you just need all carts for all stores, the cart provider service can give you that:

$all_carts = \Drupal::service('commerce_cart.cart_provider')
  ->getCarts();

If you need a cart for a particular store based on context, it gets trickier. A reference to the "current" store can be found via the current store service:

$store = \Drupal::service('commerce_store.current_store')->getStore();

And the cart related to that store via the cart provider:

$cart = \Drupal::service('commerce_cart.cart_provider')
  ->getCart('default', $store);

(incidentally in all the above snippets, if you can inject those services into your current context instead of using the static methods, all the better).

The problem is in Commerce's definition of a "current" store. Out of the box that either comes from the order entity when viewing an order, or it's the default store. From your description neither of those will do the job, so you'll need to write a custom store resolver.

I don't know what context you have available when needing the cart entity, so here's a naive example based on a product page. Since a product can be in more than one store, it just returns the first in the array.

namespace Drupal\MODULE\Resolver;

use Drupal\commerce_product\Entity\ProductInterface;
use Drupal\commerce_store\Resolver\StoreResolverInterface;
use Drupal\Core\Routing\RouteMatchInterface;

class ProductPageStoreResolver implements StoreResolverInterface {

  protected $routeMatch;

  public function __construct(RouteMatchInterface $route_match) {
    $this->routeMatch = $route_match;
  }

  public function resolve() {
    $product = $this->routeMatch->getParameter('commerce_product');
    if ($product instanceof ProductInterface) {
      $stores = $product->getStores();
      return reset($stores);
    }
    return NULL;
  }
}

And the entry for MODULE.services.yml:

MODULE.product_page_store_resolver:
  class: Drupal\MODULE\Resolver\ProductPageStoreResolver
  arguments: ['@current_route_match']
  tags:
    - { name: commerce_store.store_resolver, priority: 100 }

Once you clear the cache, the first code snippet above will return the first store a product is assigned (when viewing it).


Help learning OpenLayers for D7 I need to learn more about OpenLayers for Drupal 7. There is a ton of documentation for D6, some of which is helpful and some which isn't.

I'd like advice or suggestions for tutorials for a few different pieces..

When creating content, I want users to add a point or an area using a map. I know this is GeoField with the OpenLayers Map widget (so they don't type anything, but select visually), but I'm not sure how to then use this data in views.

In views, I need to create a map that displays the content. I want to set the default area based on the users' location.

Thanks.

This is the best tutorial I'm aware of: http://www.istos.it/blog/mapping/openlayers-and-addressfieldis


Variables used in template.php How should I know which variables and objects can be used directly in the template.php file?This is what a template.php file created by somebody else contains:

function garland_separate_terms($node_taxonomy) {
  if ($node_taxonomy) {
    foreach ($node_taxonomy as $term) {
      $links[$term->vid]['taxonomy_term_'. $term->tid] // …
      // …
    }
    // …
  }
}

Why can he use the $term object directly?

Simple answer - the line foreach ($node_taxonomy AS $term) is where the $term variable is coming from. That's a basic PHPism that treats $node_taxonomy as an array, and puts the current item from that array into the $term variable as it iterates over the array.

As snufkin noted, $node_taxonomy is the only variable you're getting access to automatically.


How do I create a text field in registration that only shows up if a checkbox is checked? I am making a registration process in which there needs to be a text field that only appears if a checkbox is "on". I would think "parent" fields would do this, but whenever I click the "parent" dropdown under account settings, the only option is "none". If I am being too vague, feel free to let me know and I will clarify.

Thank you,

Alex

Conditional Fields seems to be what you are looking for.

  Conditional Fields for Drupal 7 is an user interface to the new States API, plus the ability to modify fields appearance and behavior on certain conditions when viewing content.

Especially their example use case seems to match exactly your checkbox - text field need:

  When editing a node (or any other entity type that supports fields, like users and categories), the dependent fields are dynamically modified with the States API.
  You can, for example, define a custom “Article teaser" field that is shown only if a "Has teaser" checkbox is checked.

Emphasis mine.


How to get the uncached version of request headers? We need to programmatically get the request headers using the mymodule_preprocess_page hook. To do this we tried the following, however, because we have CDN, Varnish, and Drupal Cache all enabled, the request headers are being pulled from cache so if in the initial request the header value we are looking for is set to false, it is false in all requests afterwards.

How can we get the uncached request headers?

Here is what we tried, but it didn't work.

function mymodule_preprocess_page(&$variables) {
  $request = \Drupal::request();
  $request_hdrs = $request->headers;
  // This is the one that seems to be always caching. (true or false)
  // my-header is coming from another server.
  $request_custom = $request->get('my-header');

  // log this for troubleshooting
  \Drupal::logger('mymodule')->log(RfcLogLevel::INFRO, 'header value'.$request_custom);

  if($request_custom) {
    // based on the header value, redirect to another url.
    $response = new Symfony\Component\HttpFoundation\RedirectResponse('www.myurl.com');
    $response->send();
    return;
  }

}

Concerning CDNs or Varnish you need to ask in a different place. In Drupal you find two caches for requests/responses:

The Internal Page Cache, which is implemented in a kernel middleware, and you need to define a middleware with a higher priority to handle the uncached request.
The Dynamic Page Cache, which is implemented in a kernel request subscriber, and you need an event subscriber with a higher priority to handle the uncached request.

By the way, when you implement one of these methods, don't send the response, return it or set it in the event.

Example for a redirect middleware: https://drupal.stackexchange.com/a/247478/47547


Install a distro from an online repository core make file I would like to use the hosting tool Aegir to install this distribution from a make file directly:

http://cgit.drupalcode.org/elmsmedia/plain/drupal-org.make

what is the "workaround" to be able to insert the above URL as a string in Aegir platform make file field here:

I have tried a lot of distributions but all failed.

thanks

Unfortunately the Drush Make infra does not support this use-case well.

The quickest wordaround is to clone the project Git repository and provide a local path to the makefile in the Aegir UI.

For elmsmedia I guess the best makefile would be http://cgit.drupalcode.org/elmsmedia/tree/local.make.example

OpanAtrium has http://cgit.drupalcode.org/openatrium/tree/build-openatrium.make for this same purpose.


Exist a product discount in Drupal Commerce I'm using Drupal commerce kickstart. I installed Commerce sale price to manage the discounts for specific products. This is a great module, the only bad thing is that this module  actually creates another price to link to products. So if I use the filter price, this one will filter either regular price or sale price, but never both together.

I know that I can create discounts with rules, but I would like to find something simple,  that can be set up easily when the customer creates a product.

How would you fix this issue ?

Thanks

If the goal is: "the site administrator can create simple discounts for products".
You can add another field like "discount percentage" . By default would be set as 100 % (or 0% of discount).
Then, with rules, you check if this fields have another value than 100, and recalculates the price.


How to get the content owned by the currently logged-in user? A user is the owner of only one node, and I want to redirect the user, at login time, to his only owned node.

How can I get the node content if I know only the logged-in user?

This is how I have do it:

function MYHOOK_user_login(&$edit, $account) {
    global $user;
    $nid = db_query('SELECT nid FROM {node} WHERE uid = :uid', array(':uid' => $user->uid))->fetchField();
    drupal_goto('node/' . $nid);
}


Way for Admin to log in as an existing user without password for troubleshooting I'm the administrator & sysadmin for a Drupal site with a few thousand users. In maintaining the site, sometimes I need to troubleshoot issues reported by users that are difficult for me to reproduce when I'm logged in as me. Discrepancies in our abilities to reproduce the issue could be caused by (for example) roles and permissions or ownership of content. In any case, I'd like an easy way to log in as that particular user to test and troubleshoot the situation. And obviously I don't want to ask the the user tells me their password. Is there an easy way to do this?

Masquerade is what you need:

  The Masquerade module allows site administrators (or anyone with
  enough permissions) to switch users and surf the site as that user (no
  password required). That person can switch back to their own user
  account at any time.


Moving "vendor/" in a different location and symlinking it breaks drush I'd like to have vendor/ moved out of the Drupal 8 root and symlink it. Composer doesn't have any problem with that (all commands work) but when I issue any drush command, even drush --version, it breaks.

Steps to reproduce:

$ composer create-project drupal-composer/drupal-project:8.x-dev website --stability dev --no-interaction --prefer-dist
$ cd website
$ mv vendor ..
$ ln -s ../vendor vendor
$ drush --version

PHP Warning:  require(/tmp/test1/vendor/composer/../../load.environment.php): failed to open stream: No such file or directory in /tmp/test1/vendor/composer/autoload_real.php on line 70
PHP Fatal error:  require(): Failed opening required '/tmp/test1/vendor/composer/../../load.environment.php' (include_path='/tmp/test1/vendor/pear/archive_tar:/tmp/test1/vendor/pear/console_getopt:/tmp/test1/vendor/pear/pear-core-minimal/src:/tmp/test1/vendor/pear/pear_exception:.:/usr/share/php') in /tmp/test1/vendor/composer/autoload_real.php on line 70

Full log: https://pastebin.com/raw/eMDgkdHV

Can I achieve this somehow? Even if I need to temporarily edit some path in an autoloader php script.

I need to do this on the vagrant based dev environment where I'd like to pull vendor/ out of the synced folder which is very very slow.

I managed to solve it via specifying an absolute path in the vendor-dir configuration of composer.json: https://getcomposer.org/doc/06-config.md#vendor-dir


what does {node} node mean Background

I'm trying to understand the SQL queries that Drupal generates when I select different content to be displayed on my site so I can write my own php filters.

Issue

I see this in the query every time

SELECT...
FROM
{node} node
WHERE...

Question

What does the {node} mean does it refer to the content type I'm using?

It's the abstract way of referring to the node table in the database.  This notation is converted by Drupal to the real name of the table right before the query is executed (in most cases, for most configurations, {node} will simply become node at execution time).  Using this notation allows an instance of Drupal to use table prefixes without the code generating the queries having to know anything about those details.

The table name has the appearance of being repeated ({node} node) so that the table name {node} gets mapped to an alias node that can be used elsewhere in the query.  Consider if you have configured your site to use a table prefix of "dev_" then SELECT node.status FROM {node} node... would get translated to SELECT node.status FROM dev_node node..., thus allowing your node.status field to refer to the correct table without the code generating the query having to know anything about the fact that there's a table prefix configured for the site.  For this simple example it's silly because you could just write {node}.status, but for more complex examples, particularly with multiple joins it can be useful to set up the alias.


Pass no. of pages arguement to Drupal views pager I have created views with display as page. In pager there is option to set no. of page to show. How can I set this dynamically by passing it through url? I can pass the page using
?page=2 and offset using ?offset=2 but I cant find a way to pass the no. of pages to show.

I still don't quite get what you are asking about, but you should be able to examine $view->pager in a hook_views_pre_build and do what you want.  For example, this is a snippet of code I have used in Drupal 6 and Views 2 to set the number of items per page:

function mymodule_views_pre_build (&$view)
{
    if ($_GET["perpage"]) {
        $perpage = check_plain($_GET["perpage"]);

        if (is_numeric($perpage) && (int) $perpage > 1) {
            $view->pager["items_per_page"] = (int) $perpage;
        } else if ($perpage == "all") {
            $view->pager["use_pager"] = false;
            $view->pager["items_per_page"] = 0;
        }
    }
}


How show time period in one concrete time unit? How can I show "time period" in one concrete time unit?

E.g.: I have a movie node type with "length" field with display formatted by time period. But if you put more then 60 minutes into it then it's displayed as "1h XX m".

I've tried to tweak this widget in settings but there is only "Granularity." which allows me to limit display to one hour ("1h") without minutes.

How can I format time period only in one time unit (e.g.: in only hours or in only minutes or in only seconds)?

Perhaps it would be simplest to just use an integer field?

Set the field type to Integer
Click save, and then on the following page you should be able to set a "Suffix" of 'mins' or 'minutes' as you prefer.
If you want a space between the number and minutes, be sure to type that at the start of the suffix field.


Problem with product page (sidebar goes down) I am using Drupalcommerce (CommerceKickstart 7.x-2.0-rc2).
There is an issue with the display of the product page. The product page is composed of a content and a right-sidebar. Every page that uses this configuration is well displayed but not the product page : the sidebar goes down.
First I thought about a css problem but I found that it is a problem with the htlm structure :
- For good pages the markup "aside", that contains the sidebar", is included in the div "zone-content" that is included in the div "zone-content-wrapper".
- For product page the markup "aside" is included directly in the div "zone-content-wrapper".
I looked at the files tpl.php of the theme but found no issue (I don't have a good knowledge about templates...).

Does someone already faced with this issue?

Ok, mine is inside an article container. Go to Appearance -> Commerce Kickstart -> Settings -> Zone and Region Configuration and check Content Section -> Content Zone -> Regions.

There should be Sidebar First, Content, Sidebar Second in order. Make sure all of those are in there.

I do know I ran into this issue but mine was CSS related (I changed the width of the content region). Check your settings above and make sure everything looks good. No unassigned regions etc. Try a full wrapper if you don't have one and try without if you do and see if that changes anything.


How to stop download in hook_file_download I'm building a page with different download buttons linked to private zip files. Users have to log in to download. I am using module Permissions by Term to manage who can see which button.
I added a field to user entity to log each download. In hook_file_download() I check, if and how often this file is already downloaded by this user. Up to here everything works fine.
I want to stop or block the download and show a message to the user, if download counter reaches 5 or 10. Is hook_file_download the right hook to achieve this?

I have this to check that the users has remaining downloads or redirect them to an upgrade page.

/**
 * Implements hook_file_download().
 */
function mymodule_file_download($uri) {
  // Check if user is logged in
  if (\Drupal::currentUser()->isAuthenticated()) {
    // Load entity of current user
    $current_user = \Drupal\user\Entity\User::load(\Drupal::currentUser()->id());

    // Check if current user is: access || student || (professional && trial_actived)
    $download_control = $current_user->hasRole('professional') && $current_user->field_user_free_trial->value == 'trial_actived' ? TRUE : FALSE;
    $download_control = $download_control || $current_user->hasRole('access') || $current_user->hasRole('student') ? TRUE : FALSE;

if ($download_control) {

  // Declare files that decrease the counter
  $controlled_uris = [
    'private://mechanisms/files',
  ];

  // Check if requested uri matches with controlled uris
  foreach ($controlled_uris as $c_uri) {
    if (strpos($uri, $c_uri) !== FALSE) {

      // Check if user still has remaining downloads
      if ($current_user->field_user_download_counter->value > 0) {

        // Decrease user downloads counter
        $current_user->field_user_download_counter->value--;
        $current_user->save();
      }
      else {
        // Prepare redirect url to the prices page
        $url = \Drupal\Core\Url::fromRoute('entity.node.canonical', ['node' => 39])->toString();

        // Set message
        $message = t('Your account has reached the maximum limit of downloads.');
        \Drupal::messenger()->addWarning($message);

        // Send response to url
        $response = new \Symfony\Component\HttpFoundation\RedirectResponse($url);
        $response->send();
      }
    }
  }
}
  }
}


Is it possible to dynamically set Views' pager settings? Say for instance, you have a view that displays when viewing a certain node type, but you want the pager settings to be different for each individual node. I was thinking of making a CCK field like "pager setting" and then give it an integer option of x-y. But I don't know if it's possible to somehow dynamically plug that field into the Views' settings. Or is there another way to do this maybe?

The views hook that you would want to use is hook_views_pre_build which is called before the query is built. Now this is assuming you have some basic module development experience and that you are familiar with the views api.

You should be able to do :

/*
 * Implementation of hook_views_pre_build().
 */
function hook_views_pre_build(&$view) {

  // Make sure this is only for the specific view you want to modified
  if ($view->name == "foo_bar") {

    // Get the x-y value from where you're storing it (in your example the node object).
    $pager_count = get_count_for_this_node();

    // Lets also make sure that this is a number so we won't destroy our view.
    if (is_numeric($pager_count)) {

      // Now lets set the pager item to what ever out count is.
      $view->pager['items_per_page'] = $pager_count;
    }
  }
}

Above we're using a views hook that's called before the view query is built that way the pager and everything else will reflect the change.

Word of caution: views hooks should only be used if you understand whats going on. The above code is written for views-2.x.

Hope this helps.


Override entityreference autocomplete and return entityfieldquery output I am trying to override an entityreference autocomplete form item, I have managed to override the form, and get the arg passed to a hook_menu callback. However, I'm struggling with getting the callback to work based on what I type into the form box. Looking in the Entity reference module there is some code in the hook_autocomplete_callback that handles the $string argument and looks up matches $entity_labels = $handler->getReferencableEntities($tag_last, $instance['widget']['settings']['match_operator'] - something like that.

Can anyone assist?

My code:

/**
 * Implements hook_form_FORM_ID_alter().
 */
function wl_event_form_event_node_form_alter(&$form, &$form_state, $form_id) {
  dpm($form);
  // We will get our term id argument from the from build itself.
    $node_id  = $form['#node']->nid;
  // This is the path we will create in hook_menu().
     $new_path = "wl_event/autocomplete/{$node_id}";
  // Maximum number of descrete values (deltas) that are present.
 $max_delta = $form['field_wl_event_acquired_resource']['und']['#max_delta'];
  // Hijack the autocomplete callback for each of our values.
  for($x=0; $x <= $max_delta; $x++) {
    $form['field_wl_event_acquired_resource']['und'][$x]['target_id']['#autocomplete_path']= $new_path;
  }
}

/**
 * Implements hook_menu().
 */
// can be used to do a lookup on a menu path to return json
// probably entity reference autocomplete does a similar thing

//we want to get all of the resources of the user profiles of
//users who are registered on the event

//
function wl_event_menu() {
  $items = array();
  $items['wl_event/autocomplete/%'] = array(
    'title' => t('project call back'),
    'page callback' => 'wl_event_autocomplete_callback',
    'page arguments' => array(2),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK
  );
  return $items;
}

function wl_event_autocomplete_callback($arg1, $string = '') {
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'resource');
  // ->propertyCondition('nid', '1')
  $results = $query->execute();
  print_r(drupal_json_output($results));
  return drupal_json_output($results);
}

EntityReference uses the ctools plugin system to define selection handlers which feed into the autocomplete options.  The interface definition is defined in entityreference/plugins/selection/abstract.inc.  In that same directory, you will see the two included handlers, Simple and Views.  Each of these is defined by two files, one for the class itself, and one with an array to register the plugin with ctools.

To provide your own selection handler, first tell ctools where to look for your plugin by implementing hook_ctools_plugin_directory.

/**
 * Implements hook_ctools_plugin_directory().
 */
function wl_event_ctools_plugin_directory($module, $plugin) {
  if ($module == 'entityreference') {
    return 'plugins/' . $plugin;
  }
}

Then create 2 files in wl_event/plugins/selection similar to those in the entityreference.  The .inc file should define the ctools plugin info, and the .class.php file should contain your plugin class.  Most likely you'll want to subclass EntityReference_SelectionHandler_Generic and just override the appropriate methods.

Lastly, make sure you add the file with your plugin class to the files[] array in your modules info file so that the autoloader can find it.


How to get rid of an extra space in a twig date field template? I have a twig date field template that has a mysterious extra blank space that I want to remove.

In my twig template, field--comerce-product--field-ppromotion-enddate.html.twig, I have the following line:

{{ item.content }}{{ 'TEXT'|trans }}

Unfortunately, the printed output looks like this:

2017-12-25 TEXT

I don't know where the space is coming from.

I am using a similar template for an integer field that has this line:

{{ item.content }}{{ 'OFF!'|trans }}

This prints the discount percentage (integer field) and then the word "off" (example: 20%off)-- there is no space between the percentage and off, which is what I want.

(Why no space? My site actually uses an Asian language that doesn't use spaces.)

So where is this space coming from on the date field?  When the date field content is printed, it uses the template time.html.twig, but the content of that template is this single line (skipping the comments):

<time{{ attributes }}>{{ text }}</time>

EDIT: Based on the suggested answers, I have tried {{- foo -}} to remove the whitespace around the date and text, as well as {%spaceless%} to remove other whitespace, but the extra space is still there between the date and the text):

  {% spaceless %}

{{- item.content -}}{{- 'TEXT'|trans -}}

  {% endspaceless %}

Actual output of this code: 2017年12月25日 TEXT

Output should be: 2017年12月25日TEXT

You can also use Trim, if doesn't work please check this answer.


Import data from csv I am new on Drupal. I have a csv where I want to upload on a drupal site every week.

I tried to follow this tutorial enter link description here but "Data Processor" doesn't show. I have installed all the modules and clear the cache.

Any suggestions?

as i read in an issue in feeds  that:

  The Data processor was removed from Feeds in 7.x because Alex was unsure of the future of the data module. Seeing as there's a release of data for 7.x, it makes sense to revive it.

but if you need to implement it manually i guess this comment will help.


How can I check the fields I've created? I've got a basic question - in Drupal 7 is there a way to simply manage the fields you've created through some sort of UI that is not admin/structure/types/manage/NODE_TYPE/fields?

I'm getting an error:

FieldException: Cannot change an existing field's type. in field_update_field() (line 234 of /var/www/vhosts/server_path/modules/field/field.crud.inc).

I'm trying to track down why this error is occurring and so far I've had no luck. I've checked some stuff on drupal.org, but I've not been able to find anything definitive to clear this up.

And help would be greatly appreciated.

You can activate "Field UI" module in your modules list.


Newly (programmatically created) blocked user gets access denied when resetting I'm trying to import some users into Drupal programmatically as blocked. I found two methods to do this: user_save and drupal_execute. However, the first one doesn't send notification email with the link to reset the password while the other method does send the mail, but when clicking the link I get a denied access.

I tried the code in 2 environments (Ubuntu and Windows) with one fresh installation. Here is the code I'm actually using:

// register a new user
$form_state['values']['name'] = 'username';
$form_state['values']['mail'] = 'mail@example.com';

// generate and assign password
$pass = user_password(8);
$form_state['values']['pass'] = array (
    'pass1' => $pass,
    'pass2' => $pass
);
$form_state['values']['status'] = 0; // add user as blocked
$form_state['values']['notify'] = 1; // send notification with reset link
$form_state['values']['op'] = t('Create new account');

// check if user it's not already imported
$sql = "SELECT uid FROM {users} WHERE name = '%s'";
$result = db_query($sql, $form_state['values']['name'] );
$data = db_result($result);
#print_r($data);
if (!$data) {  // if the user does not exist, add it
    drupal_execute('user_register', $form_state);
}

The user is added correctly in the database as blocked, I receive the notification email but when I click on the reset link I get access denied (which, by the way, it's appearing twice: all the elements of my theme twice with the error as content; really nasty bug... don't know why, anyone?)

Here goes the second code:

// user details
$users = array(
    'name' => 'username',
    'pass' => user_password(8),
    'mail' => 'mail@example.com',
    'access' => '0',
    'status' => 0,
    'notify' => 1,
    'timezone' => 7200,
    'init' => 'mail@example.com'
);

$sql = "SELECT uid FROM {users} WHERE name = '%s'";
$result = db_query( $sql, $users['name'] );
$data = db_result( $result );
#print_r($data);
if (!$data)
    user_save( NULL, $users, NULL );
}

With this method, everything works fine but I don't get the email, which is pointless because the users are blocked.

I don't know if this is a hard question (only for Drupal gurus), but I would appreciate any help.

Thank you!

I'm assuming that you are wanting users to click on a link in the registration email to validate the address (this is configurable in your user settings)

You should set status=1 in the user as this is the default behavior and if it is 0 the login link will not work.

If you look at user_register_submit() there is code in it to send out emails.

I think you want

$account =  user_save( NULL, $users, NULL );
if($account) {
  _user_mail_notify('register_admin_created', $account);
}
else {
// Error code
}

at the end of your second method.


How can i maintain the database for CMS in Bitbucket for a Drupal used website I am using Drupal 7 for my website development and my question is  How can i maintain a database for a version control system (Bitbucket). is there any best tools/ modules available to do?

No. many have tried to version control databases and it simply does not work well.

If you want to manage config, you can use Features, which can save config and variables to code.


How to prevent users from changing Workbench Access Section I have different authors set up with rights to edit different pages of my site (using Workbench Access), and an unfortunate side effect of this is that, when editing a page, they can also assign it to a different Workbench Access Section.

This would, for instance, allow them to accidentally lock themselves out of a page, or allow someone else to gain editing rights to it.  This is definitely not a good thing.

I don't see anything in the permissions that would allow me to fix this, but here are my settings in case some are somehow relevant, despite appearing otherwise.

How can I fix this?  How can I prevent access to this field?

Users can only assign a node to a workbench access section if their user or role has permissions to do so? But perhaps it gets tricky with assigning permissions to the different transitions too.

Anyway, you can lock the workbench access field on node edits, so they can't lock themselves out if you like:

<?php
function MODULENAME_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Make sure this node type actually has workflow_access stuff setup.
  if (isset($form_state['node']->type) && variable_get('workbench_access_node_type_' . $form_state['node']->type, 1) == 0) {
    return;
  }
  // Once the page has been created, don't allow changing the workbench area again.
  if (preg_match("/^node\/([0-9]+)\/edit/", current_path())) {
    $form['workbench_access']['#disabled'] = TRUE;
  }
}


Ensure a given module (set) is enabled on a dev site Configuring dev-site specific settings is easy using the $conf array in settings.php

Sometimes I need to also disable (securepages) or enable (devel) certain modules on a dev site, but I don't know of an analogous method for doing this via settings.php

One hack which seems tempting is to define, say, menu_init() in settings.php (*gasp), and make that function check that the required modules are enabled using module_exists().

[* Yes, all manner of things might asplode if menu.module defined that function. OMG,ETC.]

So I'm wondering if people have done similar things to make sure their dev site is correctly configured, and if so, what. Is this the Poor Dev's Pantheon?

(It was me who wrote the instructions for the hook_init() hack at http://drupal.org/node/206368.)

Recent module-level ways of supporting this workflow are underway at the Environment module, and the Production check & Production monitor.

I feel they will rapidly become too bulky: Do you really need to enable a module to ensure another module is turned off?
But, at least they may be able to provide a few conventions for us, like putting the list in local.settings.php or equivalent.
I hide per-instance configs in in my site_aliases.drushrc, which is my alternative to local.settings.php

I'm not going for another script you have to call, unless it's part of a fully automated workflow.


How does Strongarm decide which variables need to be included in a feature When you enable Strongarm on a site that is already using Features, do these two modules work together to determine which Strongarm variables need to be included in a Feature, or is there additional work that needs to be done to ensure that the correct Strongarm variables are included?

If more work is needed, what needs to be done?

Strongarm provides a component to features where you can manually select the relevant variables to export with that feature.

Some variables may be included by default, e.g node_type variables when exporting a node type, others may need to be manually checked and exported with the feature module.


How to update the google fonts provided by @font-your-face module? I have enabled the @font-your-face module. Then I'm able to use google fonts in my site. Problem is that the list of fonts in the google directory shows more than 500 fonts: fonts but I just have 300 fonts available.

I need a font called Imprima. Is there any way to include this one in the @font-your-face module.

The module is updated to the last version.

If you just updated to a new version, have you gone and re-imported all the fonts you need/want (step 2 below)?  In D6 at least, the following worked here:

Install module, enable base and google apis.
Go to admin/settings/fontyourface and import google fonts -- 1449 fonts imported
Go to admin/build/themes/fontyourface and click browse -- 58 pages of 25 fonts displayed

and sure enough, Imprima is in there when you search.


How to route dynamic routes to a single node while keeping the urls? I have a node node/1 with the path alias /path. What I want is for /path/* to always behave like you went to /path, but not change the url. So going to /path/test?something=1 should behave identically to going to /path but the url will still be /path/test?something=1 in the user's browser.

Right now, I'm getting a redirect loop when I return the same url in the processOutbound method. If I just return $path in this method, the user gets redirected to /path?something=1.

My use case is a vue app that has it's own routing. But we need a node to allow the client to edit the content around the app.

Code below. Thanks!

<?php

namespace Drupal\gm_custom;

use Drupal\Core\PathProcessor\OutboundPathProcessorInterface;
use Drupal\Core\Render\BubbleableMetadata;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\PathProcessor\InboundPathProcessorInterface;

class PathSubscriber implements InboundPathProcessorInterface, OutboundPathProcessorInterface
{
    /**
     * Processes the inbound path.
     *
     * @param string $path
     *   The path to process, with a leading slash.
     * @param \Symfony\Component\HttpFoundation\Request $request
     *   The HttpRequest object representing the current request.
     *
     * @return string
     *   The processed path.
     */
    public function processInbound($path, Request $request)
    {
        if ($this->stringStartsWith('/plan/', strtolower($path))) {
            return '/node/1';
        }

        return $path;
    }

    public function processOutbound(
        $path,
        &$options = [],
        Request $request = null,
        BubbleableMetadata $bubbleable_metadata = null
    ) {
        $url = strtok($_SERVER[ "REQUEST_URI" ], '?');
        if ($this->stringStartsWith('/plan/', $_SERVER[ 'REQUEST_URI' ])) {
            return $url;
        }

        return $path;
    }

    protected function stringStartsWith($needle, $haystack)
    {
        return (substr($haystack, 0, strlen($needle)) === $needle);
    }
}

Edit
I've confirmed it's the redirect module is the issue. Simply installing it creates the above problem. Still looking for a solution.

Alright got it working! The redirect module hooks into the kernel.request event and will redirect if you're doing wildcard routing like I am below.

You may want to split this up into two services since we're hooking into two events, but they're directly related so I chose to keep it simple.
Basic explanation of methods in here is:

PathSubscriber::processInbound
Check the incoming url and map it to a single node

PathSubscriber::getSubscribedEvents
Register our callback for the kernel.request aka KernelEvents::REQUEST event so we can stop the redirect module from redirecting.

PathSubscriber::stopRedirectIfOurRoute
Check the path and if it matches against our wildcard routing from PathSubscriber::processInbound then set the _disable_route_normalizer to true to disable the redirect module from redirecting to the node's alias. Leave our urls alone!

mymodule/src/PathSubscriber.php

namespace Drupal\mymodule;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Drupal\Core\PathProcessor\InboundPathProcessorInterface;
use Symfony\Component\HttpKernel\KernelEvents;

class PathSubscriber implements InboundPathProcessorInterface, EventSubscriberInterface
{
    /**
     * Processes the inbound path.
     *
     * @param string $path
     *   The path to process, with a leading slash.
     * @param \Symfony\Component\HttpFoundation\Request $request
     *   The HttpRequest object representing the current request.
     *
     * @return string
     *   The processed path.
     */
    public function processInbound($path, Request $request)
    {
        if (self::stringStartsWith('/plan/', strtolower($path))) {
            return '/node/1';
        }

        return $path;
    }

    /**
     * {@inheritdoc}
     */
    public static function getSubscribedEvents()
    {
        // register our event right before the redirect module redirects
        $events[ KernelEvents::REQUEST ][] = ['stopRedirectIfOurRoute', 31];

        return $events;
    }

    /**
     * ------------------------------------
     * From the redirect module (redirect/src/EventSubscriber/RouteNormalizerRequestSubscriber.php):
     *
     * The normalization can be disabled by setting the "_disable_route_normalizer"
     * request parameter to TRUE. However, this should be done before
     * onKernelRequestRedirect() method is executed.
     * ------------------------------------
     *
     * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event
     *   The event to process.
     */
    public static function stopRedirectIfOurRoute(GetResponseEvent $event) {
        $path = $event->getRequest()->getPathInfo();

        if (self::stringStartsWith('/plan/', strtolower($path))) {
            $event->getRequest()->attributes->set('_disable_route_normalizer', true);
        }
    }

    public static function stringStartsWith($needle, $haystack)
    {
        return (substr($haystack, 0, strlen($needle)) === $needle);
    }
}

mymodule.services.yml

services:
  mymodule.path_subscriber:
    class: Drupal\mymodule\PathSubscriber
    tags:
     - { name: path_processor_inbound }
     - { name: event_subscriber }


Getting nodes related to a taxonomy term selecting from a drop down into another drop down I have a taxonomy drop down in a content type. Now when I select a particular taxonomy I want to show all nodes related to that taxonomy in another select box.

How can I implement this? If I need to do using Ajax, how can I get all contents after selecting a taxonomy? I am new to Drupal. Is there any module available for this purpose?

Or Please tell me how to get all contents using taxonomy programmatically? I have also to sort via price in a particular content type itself.

I need to do this in Drupal 7.

Thanks

Yes, you need to implement this using hook_form_alter() and #ajax. The following is an example code you could try. The field field_category and the table field_data_field_category would be your taxonomy field. The field_nodes would be your another drop-down where you want to list the selected nodes related to the selected taxonomy.

The example code would sort the nodes by content types. To sort price of each particular content type, you would need to join another table in the query, for example, field_data_field_price and add your price field to the order-by clause. HTH.

function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if( $form_id == 'your_node_form' ){

        $form['field_category']['und']['#ajax'] = array(
            // #ajax has two required keys: callback and wrapper.
            // 'callback' is a function that will be called when this element changes.
            'callback' => '_mymodule_ajax_dropdown_alter',
            // 'wrapper' is the HTML id of the page element that will be replaced.
            'wrapper' => 'replace_field_div',
        );

        $form['field_nodes'] = array(
            '#type'     => 'select',
            '#title'    => t('Nodes'),
            '#options'  => array('' => '- Select -'),
            '#required' => FALSE,
            '#prefix'   => '
',
            '#suffix'   => '
'
        );

        // An AJAX request calls the form builder function for every change.
        // We can change how we build the form based on $form_state.
        if(isset($form_state['values']['field_category']) && $form_state['values']['field_category']['und'][0]['tid'] ){
            # when the respective taxonomy is selected, get the nodes related to the selected taxonomy
            $tid = $form_state['values']['field_category']['und'][0]['tid'];

            $query = db_select('node', 'n');
            $query->join('field_data_field_category', 'c', 'n.nid = c.entity_id');
            $query->condition('n.status', 1, '=')
                    ->condition('c.field_category_tid', $tid)
                    ->fields('n', array('nid', 'title'))
                    ->orderBy('n.type', 'ASC');
            $result = $query->execute();
            foreach($result as $row){
                $form['field_nodes']['#options'][$row->nid] = $row->title;
            }
        }else{
            # No taxonomy selected
            $form['field_nodes']['#options'] = array('' => '- Select -');
        }
    }
}

function _mymodule_ajax_dropdown_alter($form, $form_state){
    return $form['field_nodes'];
}


Show Image from Referenced Node I am building a book review site. I have two kinds of content: 'Book Listing' and 'Review.' The Review content type has an entity reference field which links back to the Book Listing. Using entity prepopulate, I have created a button which opens the 'Review' add/edit form and automatically sets the value of the entity reference field to the corresponding Book Listing NID.

Now, what I would really like to do, since the button opens a new page, is add the book cover image that is on the Book Listing page to the add/edit form, to help the customer remember what they are reviewing. Amazon has a similar feature. To further complicate things, my 'Review' add/edit form is being rendered with panels. I've been playing around with views (with relationships) and passing arguments into the panel, but am not having any luck. Has anyone done something like this before? Any idea on what to try next?

With the relationship to the second content type properly defined (and possibly also required) you should be able to display the image requested.

One problem area I've seen is the base tables defined.  You can see the base table in the export text of a given view right on top.

If your base tables do in fact differ, then there are further nuances to the relational display in views, but it can be done.

Post back if you have more details to this view creation to guide a useful example.  I'll post more step by step instructions.


Why do start and end dates in views appear the same but are not in content? When adding fields to a view I have two entries for date.
One for the start date and one for the end date.
However in my view they are both the start date.
I check my content and it shows differing values for start and end dates.

Why does views not render the end date?

It sounds to me like you have a single date field in your content that you have set with an end date but in your view you have set this with two different fields. Instead you should edit the view and click the first date field and check the formatter settings to be one that includes start and end dates.


Popup w/overlay for content (Lightbox-esque) Is there a module/technique that allows for a popup of a node content?
I'm looking for a lightbox-esque affect that displays specifically content (node?), not an image.

See this question: Display node as a popup window

"There are a lot of solutions for this kind of stuff. I would do it in the theme layer to have something really light. You can also use the variety of popup modules for this. One simple way to do this, is use the Lightbox2 module, checkout this documentation page: http://drupal.org/node/252260"


How can I programmatically import configuration? I try to import specific configuration. I use this :

$config_path = config_get_config_directory(CONFIG_SYNC_DIRECTORY);
$source = new FileStorage($config_path);

$config_storage = \Drupal::service('config.storage');
$config_factory = \Drupal::configFactory();
$uuid_service = \Drupal::service('uuid');

$configs = [
  'field.storage.config_pages.field_areas',
  'field.field.config_pages.configuration_implantation_page.field_areas',
  'core.entity_form_display.config_pages.configuration_implantation_page.default',
  'core.entity_view_display.config_pages.configuration_implantation_page.default',
];

$config_storage->write('field.storage.config_pages.field_areas', $source->read('field.storage.config_pages.field_areas'));
$config_storage->write('field.field.config_pages.configuration_implantation_page.field_areas', $source->read('field.field.config_pages.configuration_implantation_page.field_areas'));
$config_storage->write('core.entity_form_display.config_pages.configuration_implantation_page.default', $source->read('core.entity_form_display.config_pages.configuration_implantation_page.default'));
$config_storage->write('core.entity_view_display.config_pages.configuration_implantation_page.default', $source->read('core.entity_view_display.config_pages.configuration_implantation_page.default'));

If the field is created, the table is not created.

How to create the tables associated?

You should save the config like $config_storage->save(); :
As @4K4 mentioned :

  The important thing is not simply store config, but create and save config entities and so run CRUD methods/hooks like https://api.drupal.org/api/drupal/core%21modules%21field%21src%21Entity%21FieldStorageConfig.php/function/FieldStorageConfig%3A%3ApreSave/8.7.x


Drupal 7 site crashed after enabling module - No DB backup. What do? I enabled the blog module on a website, after that the site crashed.
The error is the same on everypage:

  Catchable fatal error: Argument 2 passed to
  entity_views_field_definition() must be an array, null given, called
  in
  /homez.653/xxxxxxxxx/www/sites/all/modules/entity/views/entity.views.inc
  on line 152 and defined in
  /homez.653/xxxxxxxxx/www/sites/all/modules/entity/views/entity.views.inc
  on line 175

Problem is that I don't have any backyp of the DB......

Any any idea on what should I do?

Thanks you per advance.

The mention of "I do not have a backup of the DB" in the question/title makes it clear that you want to roll-back the change as opposed to debugging and making the modules work where it is - for that, you do not need a backup, but access to the code and logs.

Another way to bypass the blog module, an alternative to what @Jimajamma said is to remove the module from the filesystem.
Remember to clear the cache and ideally rebuilt the module registry after these steps.

drush cc all --yes;
drush rr;


Views Accordion not working when other Jquery plugins are used I am having problem with Views Accordion when I am using Views Accordion and the Isotope Jquery plugin both on same page.

Isotope Jquery plugin seems to be working fine, but the Views Accordion looks crashed no CSS and functionality is working.

There is a module called http://drupal.org/project/views_isotope

Using that would be better as it would play well with the rest of the js.

The js behavior with in drupal 7 has changed a bit and placing the js directly might not work well in many cases.


Application form and fee for Drupal Commerce I am taking application fees for application processing for a real estate broker.  When the user fills out an application, they need to submit payment immediately.

The issue is this isn't really a product.  It's a processing fee.  Am I stuck with using a product?  Can I create an order without the product and just use the fee?  I feel like I should create a line item for an order and do it that way, so the pricing rules flow normally.

When the user is ready to submit their application, I'm going to use the Drupal NoCart module to take the customer straight to payment.

I haven't been able to find a business case like this online anywhere.

For the new line item type, it looks like I should create a new one:

function mymodule_commerce_line_item_type_info() {
    $line_item_types = array();

    $line_item_types['appfee_type'] = array(
        'name' => t('Application Fee'),
        'description' => t('Line item type for app fee.'),
        'product' => FALSE,
        'base' => 'appfee_type'
    );
    return $line_item_types;
}

The new line item type and adding it to the order was the way to go it seems.  My code is posted in this post.

That code worked, however, I kept getting an access denied when trying to check out. DC runs a hook called hook_commerce_checkout_order_can_checkout().  The order is passed to this hook, and you can determine if you want to allow access.  I did on all instances and didn't need to write any logic, so I just returned TRUE, and everything worked.


Drupal 7 - Video Contest Website I'm new to drupal and I'm trying to create a video contest website. Each contest will have a time limit (Say 1 month). I need the following basic functionality.

Disable upload function after the contest ends.
People can vote during the contest but the total rating should be revealed only after the contest ends.

Is there a module for that purpose ? Or should I create a custom module?

Sorry if this is a silly question. I searched everywhere but couldn't find a solution.

Thanks In Advance.

You can do this with the Rules module, which includes a Rules Scheduler submodule.  (Node One tutorial on Rules Scheduler)
You can use Fivestar for voting.  To hide the votes, you should be able to use Views.

These are very general suggestions but it sounds like you're in the very early stages of your planning; if you have specific questions, you're welcome to post those later.  Basically, you should be able to use existing, well-tested modules for what you're trying to do, although you may need to customize them from time to time to match your specific use case.  It's generally not worth your time to write modules from scratch, except as a learning exercise.


Views header with custom summary Drupal 7 I have a content type called "Question" with a Answered/Not_answered field for editors.
I want to create a view of all questions which has a header of answered and unanswered questions. Something like this:

Answered questions: 10
Unanswered questions: 2

with links to answered and unanswered questions.

Can anyone please help me to create this view?

Many thanks, Alice

In order to accomplish this task you need to create two attachments and tie them to your page.
First attachment should display 'Global: Result summary' result with all answered questions.
Second attachment should display Global: Result summary' result with all unanswered questions.