Do I need to manually destroy the EntityFieldQuery object? I'm using an EFQ object inside a foreach loop:

  //bundle those terms with nodes they each have
  foreach($relevantTerms as $dishType)
  {
    $nodeQuery = new EntityFieldQuery();

    $entities = $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'food_menu_item')
      ->propertyCondition('status', 1)
      ->execute();

    $nodes = entity_load('node', array_keys($entities['node']));
    krumo($nodes);
  }

After the loop stops executing, am I correct in thinking one instance of $nodeQuery will remain in memory for the rest of the request? Do I need to destroy this using unset() for performance?

You shouldn't really have to care about this much. Because PHP will clean up all this stuff at the end of the page's request lifetime. If you really want to cleanup this lingering instance of anything you just unset() it as-needed.

Something is fishy with your code as your EFQ is in a loop, but it's not being used in the loop for anything what-so-ever.


Sign out not working properly in OpenID Connect I have integrated OpenID Connect(Generic), where my Signin was successful(Redirects to destination server, provided credentials, redirect to drupal & authenticated).

While i make Sign out, it was successful. But what i found is, log out happens only at drupal side whereas my destined server session still exists(I have checked it by relogin in drupal, it was authenticated without providing credentials).

Is there is any option to log out from both Drupal & destined server?

The openid_connect module is great for authenticating/adding users via external identity providers. However, it does not provide single sign out capabilities.

You will have to implement them yourself.

A viable way of doing so is to implement hook_openid_connect_post_authorize() to add information about the used identity provider/tokens to the user session/database, and e.g. hook_user_logout() to invoking the sign-out endpoint of your identity provider, if the above saved information is present when the user logs off your Drupal.


How to disable Ctools modal form from running on mobile devices? I am using Drupal 7 Totem distro (a responsive site). My problem is that the pop-up modal form works fine on large screens but doesn't respond well on mobile devices/smartphones.

How do I disable the modal form from runnning on mobile devices?

You can hack wonders with a little "@mediaquery" and "!important".
I used this little bit with "modal_forms", not sure if the #id is the same.

@media (max-width: 580px) {
    #modalContent {
      position: fixed !important;
      top: 12% !important;
      bottom: 12% !important;
      right: 4% !important;
      left: 4% !important;
    }
    div.ctools-modal-content {
      width: 100% !important;
      margin: 0 auto;
    }
    div.ctools-modal-content .modal-content {
      width: 100% !important;
    }
}


How do I increase the number of shortcuts allowed in admin menu? The number of shorctuts is limited to 7 (second row)

When I add an 8th shortcut it is in the disabled section

How do I change that?

The maximum number of shortcuts is defined in shortcut_max_slots(), which just returns a variable:

return variable_get('shortcut_max_slots', 7);

So all you need to do is change that variable to something larger than 7. You can use the devel variable editor to do it, or just run the following code from somewhere:

variable_set('shortcut_max_slots', 10);


How easy is Drupal for E-Commerce? I'm looking for the right tool to develop a peer to peer trading website that would include E-Commerce. The site would need to allow registered sellers to enter details about their products this information would then need to be stored in a database that would allow buyers to search based on a set of parameters.

Would all this be achievable with current Drupal modules and how much additional coding would be required to knit it all together?

You don't need any coding to achieve this functionality, you can just go with Commerce and using Drupal's built-in roles, manage who has the permission to create content (items to sell) and who has the permission to buy it.

for the search aspect of it, I suggest trying Search API, which gives you facet like filtering feature (Like ebay), also you might wanna check Apache Solr for faster indexing


How do I use MariaDB instead of MySQL? I need to use MariaDB instead of MySQL in Drupal 8. I have already installed MariaDB in my local system.

How do I use it with Drupal 8? What changes are required to use it?

MariaDB is a drop-in replacement for MySQL. No changes are required.

You'll obviously need to update your connection/credential details to match the new server, but as far as configuring Drupal to use MariaDB, there's nothing to do.


Custom module causes an AJAX error I created a custom module which creates a content type (FAQs) with a paragraph field whose type is FAQ Item (with 2 fields, title and text).
After installing the module, I have a new content type as expected.
I add this new content type (which works), but when I want to add more paragraphs, I get this error.

edit start
↵An AJAX HTTP error occurred.↵HTTP Result Code: 200↵Debugging information follows.↵Path: /node/add/faq?ajax_form=1↵StatusText: OK↵ResponseText:

edit end
Is there any missing configuration the module should provide?
The YAML files are inside faq/config/optional. They have been created from the UI on another site and exported.
edit 2 start
My module files and structure

.info.yml file I have basic info link name, type, description, core_version_requirement and package.
.libraries.yml Am importing a JS file, inside "src-js"
.module is empty, without any php code.
.routing.yml also have basic stuff:
faq:
path: '/faqs'
defaults:
  _controller: 'Drupal\faq\Controller\GetFaqController::getFaq'
  _title: 'FAQs Page'
requirements:
  _permission: 'access content'

Inside config-optional folder I have my YML to create content type, fields and paragraph. Those .yml files I exported from another website where I create all of this and deleted "uuid" line.

Then in my controller I also have basic stuff (for now).
class GetFaqController extends ControllerBase {
public function getFaq() {

    echo '
FAQs
';

    return [
        '#title' => 'test'
    ];
}

}
This is my module structure/files.
Have very basic configs, that's why I am a bit lost with this error and what I search online I found same error but it is not related.
It seems something is missing with paragraphs and ajax request to add more.
edit 2 end
edit 3 start
I have created another module, this new module only creates a paragraph type with 2 fields (title and text), then I add manually this paragraph to "Article" content type and I get same error.
Another thing I have notice, in a clean drupal site with paragrpahs module installed, when I create a paragraph type manually via backoffice and then add it to any content type works correctly, when I install my module all paragraphs fields stop working and give this error.
If I uninstall my module and delete paragraph type created by my module, other paragraphs type start working again.
Here a repository of my custom module if someone want to test.
https://gitlab.com/drase15/custom-module
edit 3 end

After a lot of digging I just need to change a folder name -.-
Changed from "optional" to "install", after that everything works as expected.
Thanks for your help.


How to get ip address? I used the following code:

services:
  foo:
    class: Drupal\MYMODULE\Foo
    arguments: ['@request']

In MYMODULE/src/Foo.php

namespace Drupal\MYMODULE;

use Symfony\Component\HttpFoundation\Request;

class Foo {
  /**
   * @var \Symfony\Component\HttpFoundation\Request
   */
  protected $request;

  /**
   * Constructs a Foo object.
   *
   * @param Symfony\Component\HttpFoundation\Request $request
   *   The request object.
   */
  public function __construct(Request $request) {
    $this->request = $request;
  }

  public function bar() {
    if ($ip == $this->request->getClientIp()) {
      drupal_set_message('ip', t('You may not ban your own IP address.'));
    }
  }

}

but this gives me error:

  Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException'
  with message 'The service "foo" has a dependency on a non-existent
  service "request".

According to Get the user IP address and Symfony HttpFoundation you can get visitor IP by

first add use Symfony\Component\HttpFoundation; then

 \Drupal::request()->getClientIp()


How does entity_metadata_wrapper work with array? This is my code to return value of fields in a content type called library

$wrapper = entity_metadata_wrapper('node',$variables['node']);
$variables['name']= $wrapper->field_library_book_name->value();
$variables['writer']= $wrapper->field_library_book_writer->value();
$variables['detail']= $wrapper->field_library_book_detail->value();
$variables['photo']= $wrapper->field_library_photo->value();

it works right for name, writer and detail but for image it only prints Array(). this is the var_dump() output of this array:

array(13) {
  ["fid"] => string(3) "382"
  ["alt"]=> string(0) ""
  ["title"]=> string(0) ""
  ["width"]=> string(3) "145"
  ["height"]=> string(3) "194"
  ["uid"]=> string(2) "23"
  ["filename"]=> string(15) "n_471_1_img.png"
  ["uri"]=> string(43) "public://library_book_photo/n_471_1_img.png"
  ["filemime"]=> string(9) "image/png"
  ["filesize"]=> string(5) "40854"
  ["status"]=> string(1) "1"
  ["timestamp"]=> string(10) "1389166558"
  ["rdf_mapping"]=> array(0) { }
}

this is my question: how to output the image itself ?

The function theme_image will output the value as an img-tag. Is that what you are looking for?

$photo_field = $wrapper->field_library_photo->value();
$image = theme('image_style',
  array(
    'style_name' => 'large',
    'path' => $photo_field['uri'],
  )
);


How to force rendering by the site theme instead of the admin theme? When rendering HTML in hook_node_presave(), everything works as expected when I save the node manually.
However, when I use the "Save content" action on the content admin view (at /admin/content), then the page is rendered with the admin theme templates (Seven), instead of the templates of my custom theme/the site theme.
I tried using both Claro and Seven as the admin theme, and I get the same result: I can save the page manually and the site theme's templates are used, but if I use the "Save content" action to bulk re-save nodes, they are rendered incorrectly with the admin theme templates.
Here's the code that is causing the issue:
function MYMODULE_node_presave(NodeInterface $node) {
  $content_type = $node->getType();
  if ($content_type == 'page') {
    // Render the entire node and save that HTML to a specific field.
    $render_controller = \Drupal::entityTypeManager()
      ->getViewBuilder($node->getEntityTypeId());
    $render_output = $render_controller->view($node, 'mymarkup_torender', 'ja');
    $html = \Drupal::service('renderer')->renderPlain($render_output);
    $node->set('field_text_cached_html', $html);
    $node->field_text_cached_html->format = 'mymarkup_processed';
  }

Is there a way to force Drupal to use the site theme instead of the admin theme when rendering?
On the Appearance administration page, "Use the administration theme when editing or creating content" is unchecked.

Based on the comment by @MrD, I found a working solution.
I implemented a custom theme negotiator based on this information:

Blog post: Dynamic theme switching in Drupal 8
Blog post: Choose your theme dynamically in Drupal 8 with theme negotiation
Drupal Answers: How can I programmatically change the active theme?

I needed to change the theme for the admin content page, so here is the code I used:
mymodule.services.yml
  MYMODULE.theme.negotiator:
    class: Drupal\MYMODULE\Theme\ThemeNegotiator
    tags:
      - { name: theme_negotiator, priority: -20 }

Here, I used a low priority to ensure my code runs first.
MYMODULE/src/Theme/ThemeNegotiator.php
<?php

namespace Drupal\MYMODULE\Theme;

use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Theme\ThemeNegotiatorInterface;

/**
 * Select the correct theme for various routes.
 */
class ThemeNegotiator implements ThemeNegotiatorInterface {

  /**
   * {@inheritDoc}
   */
  public function applies(RouteMatchInterface $route_match) {
    return $this->negotiateRoute($route_match) ? TRUE : FALSE;
  }

  /**
   * {@inheritDoc}
   */
  public function determineActiveTheme(RouteMatchInterface $route_match) {
    return $this->negotiateRoute($route_match) ?: NULL;
  }

  /**
   * Select the theme for special cases.
   *
   * @param \Drupal\Core\Routing\RouteMatchInterface $route_match
   *   The currently matched route.
   *
   * @return bool|string
   *   The theme name to use (string) or false (bool).
   */
  private function negotiateRoute(RouteMatchInterface $route_match) {
    $route_name = $route_match->getRouteName();
    if ($route_name === 'system.admin_content') {
      return 'MYTHEMENAME';
    }
    else {
      return FALSE;
    }
  }

}


Add a remove item button on checkout page i have an express-checkout page and the cart is shown but i have to give the customer the chance to remove items from his cart at this stage.

i edited the view Shopping cart summary (Commerce Order) by adding a (Line Item) Commerce Line Item: Delete button (Remove)

now when i click that button the form-validation starts and the item wont be removed. any chance to fix this? a multistep-form is not an option for me.

This is a pretty common support request, and the gist of it is you cannot use Views form functionality on Views embedded in the checkout form. The reason is pretty simple to understand - you end up nesting a FORM tag within a FORM tag because Views doesn't know that it's building form elements to render inside another form. The solution is not so simple.

The best advice I've been able to give thus far is to disable the cart contents checkout pane and create a Views block instead that uses the form functionality. However, if someone removes an item from the cart after making a change elsewhere on the page, the page would refresh and that data would be lost. Thus you'll want to figure out a way to have that remove button work via AJAX, which is totally possible through the forms API but remains undocumented as far as I know. If you do code a solution, a blog post about it or doc page on d.o would be great.


How to get rid of a duplicate title on the front page? When I first made the front page, I created a Basic Page and selected "Promoted to Front Page" and thought I was done.  Drupal insisted on showing this page as an article summary, and no manner of tweaking settings on my part prevented this behavior.  I decided instead to put the main front page content in a block because it will seldom ever change.

I created my block, and yay!  No more summarized front page content.  However, the title of the page shows twice.  The first is the title of the original basic page I created, the second is the title of the block I created.  I've already cleared the cache and there was no change.

How do I get rid of the duplicate?

It sounds like you have node as your front page which lists summaries of content that is promoted to the front page by default. That's the way Drupal comes configured out of the box. If I understand correctly, what you're looking for though is a single node to be displayed in full on the front page.

You can change it from node (which shows a list) to your specific Node at admin/config/system/site-information or Configuration -> Site Information under the "Front Page" section. Simply change "node" to "node/[node-id]" where [node-id] = the nid of the node you want to appear on the front page:


Loading Personal contact form and access denied Into a user profile page I provide a personal contact to conact the profile woner and that contact form is loaded like this:

$recipient = user_load(array('uid' => $fptr->uid));
$output .= drupal_render(drupal_get_form(
    'contact_personal_form', $recipient));

The form shows up nicely and all is well so far. While testing this form after sending 5 test messages I get the warning that I cannot send more than 5 messages within 1 hour. That is OK, but it seems the access to the entire user profile page is denied and it screws up the page layout.

Is there any way I can just lock the personal contact form instead of locking the entire profile page?In other words, is there a way to check if an anonymous user can send a personal message, and based on that check to show or hide just the message form?

Thanks for your help, also I hope that is easy to accomplish:-)

You need to check for flood before rendering the contact form

global $user;
// Check if flood control has been activated for sending e-mails.
$limit = variable_get('contact_threshold_limit', 5);
$window = variable_get('contact_threshold_window', 3600);
if (!flood_is_allowed('contact', $limit, $window) && !user_access('administer contact forms')) {
// Don't display forms
}
else {
  $recipient = user_load(array('uid' => $fptr->uid));
  $output .= drupal_render(drupal_get_form(
  'contact_personal_form', $recipient));
}


Drush memory exhaustion hi guys any of you experience having problems regarding memory exhaustion when running a drush command? I made a batch to add taxonomy and do a node_save after to all nodes (a lots of nodes) i've set the limit on settings.php to 1GB and still no luck, it always throws an error regarding memory exhaustion.

Drush includes a sample php.ini file (there's an online copy here) with instructions on how to override your the php.ini file that Apache uses.

Just copy the contents of the example file into one of the three locations listed in the sample file and save the new file as php.ini. I would recommend using either option except for your Drush installation as this will require you to re-create a php.ini every time you update Drush.

Running drush status shows you which PHP configuration file it is using in case you're unsure if your changes took effect.


How to calculate datetime in hours? I have a date time field to input working hours and then I need calculate total work hours. I was try using Global math expression in views, but the results is 0, although I was try to change views formmater from date and time, ago and plain.

This is the condition, lets say the rule in office is:

Employee In 1: 08.00
Employee Out 1: 12.00
Employee In 2 : 13.00
Employee Out 2 : 17.00

It's mean that employees must have 8 hours a day.

The question is, how can I calculate that employee is late in 2 hours if the field value like this:

filed Employee In 1: 09.00 <- late
field Employee Out 1: 12.00
field Employee In 2 : 13.00
field Employee Out 2 : 16.00 <- earlier out

Is there any module date related or some one chould assist me ho to solve my problem?

Have a look at the Computed Field module. Some details about it (from its project page):

  Computed Field is a very powerful field module that lets you add a custom "computed fields" to your content types. These computed fields are populated with values that you define via PHP code. You may draw on anything available to Drupal, including other fields, the current user, database tables, you name it. (Feeling the power yet? :) ) You can also choose whether to store your computed field values in the database with other content fields, or have them "calculated" on the fly during node views. (Although you should note that Views use requires database stored values.) This field is literally the Swiss Army knife of fields. So start cooking up your PHP based values!

You may also want to look at its Community documentation, especially its child page about "Calculating a duration given a start and end time", here is a quote from it:

  ... create a new computed field to calculate the duration as a decimal number of hours (where 1.5 is 1 hour and 30 minutes).


Drupal 7 Bartik Menu tabs changed to vertical list - how to reset back to tabs? I have been working on a Drupal 7 install with the Bartik theme.  Today, the main menu tabs changed to a vertical list on the left side of the page.  I do not know how to reset this.  I checked the theme folder and none of the css files have been changed, so I suspect it is either a module I installed today or something I did when I was working on editing some pages.  Any suggestions would be aprpeciated.

Try turning off "Aggregate and compress CSS files" on /admin/config/development/performance and then use right-click inspect element (firefox or chrome) to identify the css responsible for the override. You should see the bartik css files overridden by something else causing this behavior.

A clear cache never hurts either.


Changing file name on upload I'm trying to automatically add prefixes to uploaded file names so they can later be processed by non-drupal scripts. I want to do that while the user is uploading files during creation/editing of a node.

To do that I am using hook_file_validate($field) where I check if the file is correct and then using $field->destination I define a new file name.

Surprisingly my issue lies in getting context to generate the proper file name (nid of the node,nid of the parent group, or info from other fields). When I upload a file, only part of the website is reloaded by javascript and hook_file_validate is triggered before hook_form_alter . Whene it is triggered I have no access to any data that would tell me where am I.

So far I have tried:

$_REQUEST['destination']

while defined (not a typo) when the whole form is loaded, it is undefined when the file field of the form is reloaded

$_GET['nid']

again - undefined

arg(0); arg(1); arg(2);

returns file ajax field_quest_file
which is not very usefull

I can access uid but it is not enough for me to create unique file names.

Following on from my comment suggesting you do this in an additional submit handler something like this should work:

Add the new submit handler:

function misc_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'YOUR_CONTENT_TYPE_node_form') {
    $form['actions']['submit']['#submit'][] = 'rename_files';
  }
}

And then in the new submit handler:

function rename_files($form, &$form_state) {

  $node = $form_state['node'];

  global $user;

  // Loop over the uploaded files. Be sure to re-name field_files to the name of
  // your file field.
  foreach($node->field_files[LANGUAGE_NONE] as $item) {

    // Load the file object
    $file = file_load($item['fid']);

    // To set the destination first remove the filename from the stream wrapper
    // URI.
    $destination = str_replace($file->filename, '', $file->uri);

    // Modify this line to the name of your group field.
    $group = $node->field_group[LANGUAGE_NONE][0]['value'];

    // And then append the group, uid and put the filename back on the end.
    $destination .= $group.$user->uid.$file->filename;

    // And finally rename the file.
    file_move($file, $destination);
  }

}


getting uploaded file name at node title Users will upload files.  The user will tag the file with a project name and some keywords and an optional text comment.  I have made a content-type called 'image', that has filed for title, file, project, keywords and comments.

I want the tile of the node to be the name of the uploaded file.  The name of the filed is 'file' the field is of type File, the widget is of type File, and the filed name is field_file.  I have the token module and the "Automatic Nodetitles" module.  The token module gives me token "node:field_file_body", this is not the file name.

How do I set the title of the each "image" node to the name of the uploaded file?

I also battled with this; this is my solution:

Use the Automatic Nodetitles Module as described by the others, and in the Pattern for the title text box load up the filefield and extract the filename that way. Example:

<?php
//Load the file
$file = file_load($node->field_document['und'][0]['fid']);

// Filename
return $file->filename;
?>

Obviously you need to check the Evaluate PHP in pattern. checkbox at the bottom for this to work, and replace "field_document" with the name of your own file field.

Hope this helps somebody!


How do I enable the PHP filter only for webforms? How do I enable the PHP filter only for webforms, and not other content types?

I suggest is in your custom module add more description to your field that user enter php code with Not surround it with<?php ?> then in your submit handler that runs before other submit handler ( add it with array_unshift) use php eval then put your returned data in your field.

  Eval :mixed eval ( string $code ) eval — Evaluate a string as PHP code

  code

Valid PHP code to be evaluated.

The code mustn't be wrapped in opening and closing PHP tags, i.e. 'echo "Hi!";' must be passed instead of '<? echo "Hi!"; >'. It is

  still possible to leave and reenter PHP mode though using the
  appropriate PHP tags, e.g. 'echo "In PHP mode!"; ?>In HTML mode!

Apart from that the passed code must be valid PHP. This includes that all statements must be properly terminated using a semicolon.

  'echo "Hi!"' for example will cause a parse error, whereas 'echo
  "Hi!";' will work.

A return statement will immediately terminate the evaluation of the code.

The code will be executed in the scope of the code calling eval(). Thus any variables defined or changed in the eval() call will remain

  visible after it terminates.

  Return Values ¶

  eval() returns NULL unless return is called in the evaluated code, in
  which case the value passed to return is returned. If there is a parse
  error in the evaluated code, eval() returns FALSE and execution of the
  following code continues normally. It is not possible to catch a parse
  error in eval() using set_error_handler().


Insert data in table using drupal form alter submit I am currently work with a drupal's inbuilt form which is coming from it's system function.
Now I added a extra field with value in the form with Drupal's custommodule_form_deal_node_form_alter().
It is working perfectly.
But my problem is How to insert the value in the database with the default form's value. As the form's has its own default submit function.  I know it may be done using custommodule_form_deal_node_form_alter_submit($form,$form_state)
But dont know how to merge my value with the default form's submit function.
Please help me.

In your alter hook you can create custom submit handlers.
Ex.

function custommodule_form_deal_node_form_alter() {
    if (isset($form['actions']['submit'])) {
        $form['actions']['submit']['#submit'][] = 'custom_form_submit';
      }
    }

then you implement the custom submit handlers.

function custom_form_submit(&$form, &$form_state) {
 // $form_state will have the form value which you can insert into database.
}


Using module_invoke() and render() causes PHP warnings From within a block, I've used the following PHP to add additional blocks inside it:

$content_search = module_invoke('search_api_page', 'block_view', 'content_search');
$user_search = module_invoke('search_api_page', 'block_view', 'user_search');

print render($content_search);
print render($user_search);

When I do so, I get the following warnings:

  Warning: Invalid argument supplied for foreach() in element_children() (line 6541 of /var/www/mysite.dev/public_html/includes/common.inc).
  Warning: Illegal string offset '#children' in drupal_render() (line 5998 of /var/www/mysite.dev/public_html/includes/common.inc).
  Warning: Illegal string offset '#children' in drupal_render() (line 6008 of /var/www/mysite.dev/public_html/includes/common.inc).

It appears that the problem is tied to the render() function as I can call print_r($content_search) and everything looks good, but I can't render the blocks without these warnings.

Blocks aren't render arrays, they're made up of a subject and content key.

You'll probably have better luck referring to those explicitly:

$content_search = module_invoke('search_api_page', 'block_view', 'content_search');
$user_search = module_invoke('search_api_page', 'block_view', 'user_search');

print render($content_search['content']);
print render($user_search['content']);


Views: Return the nodes either side of current node Is there a way in views to return 1 node that was published before the current node being viewed and the 1 node after?

Currently I have a view using a contextual filter which is the current NID from URL but I can't find a way to pass that to the filter criteria.

Is it possible? It can be split in to 2 views if needed so in 1 I get the previous node and the other I get the next one.

e.g.

current nid = 2

View returns 1, 3

You can use Previous/Next API to get the previous and next nodes of particular nodes.
It also provides Views plugin to display Previous/Next links in View.


Problem with database migrating Drupal 8 site from local to web host (multiple databases) I'm trying to migrate over a Drupal 8 site developed on my local PC to the web host. Everything is fine with the files transferred over (/site/files, /modules, /themes, etc.), the database has been transferred successfully, but it's not being read by Drupal (the new site is blank but with the CSS working fine). My web host insists that everything is fine with the settings.php and other files and suggested that I look here for solutions.

The only lead I have is that I notice that the local site I created on Bitnami/Xampp has five different databases: "bitnami_drupal8", "information_schema", "mysql", "performance_schema", and "sys".

I've been trying to export and import back in the "bitnami_drupal8" database because that seemed to be the main database. There is only one database on my web server (I'm only allowed two).

Do I need to export/import these five databases and merge them into the one on my web host? If not, are there any other suggestions?

Note too: I've tried the Backup & Migrate module with backups of the entire site, imported that in, and it still didn't show anything. It's like there's some incompatibility between the local and web host databases.

Thanks a lot

Okay I figured it out. It was the database prefix value in the settings.php file that was the problem.

I set up the site on another web host and got it to work there, then I compared the two settings.php files and noticed that the working one had the database prefix blank. The problem occurred with InMotion Hosting but it worked fine on Bluehost.

Thanks for the help.


Form '#theme' preprocess doesn't invoke I have form where '#theme' => 'ebanq_transfer_theme'. Template file is rendered but preprocess hook doesn't invoke. Any ideas?

/**
 * Implements hook_theme().
 */
function ebanq_transfer_theme() {
    return array(
        'user_accounts_form' => array(
            'render element' => 'form',
            'template' => 'user-accounts-form',
            'path' => drupal_get_path('module', 'ebanq_transfer') . '/templates',
        ),
    );
}

/**
 * Accounts form preprocess.
 */
function ebanq_transfer_prepocess_user_accounts_form(&$vars) {
    $form = $vars['form'];
    dpm($form);
}

This function

  ebanq_transfer_preprocess_user_accounts_form(&$vars)

must be called

  template_preprocess_user_accounts_form(&$vars)

So the Drupal bootstrap / hook system will know that.


Why isn't local.css file used in styling a page on a site? I have been transferring a development site to a new computer and ran into a problem when I transferred the local.css file I had been using to style my content.  While the file works fine on the old computer it is not working on the new even though the file configuration is identical.

The site is using a subtheme for Stark.  Both theme are present and enabled. The general appearance of the site is now consistent with the Stark theme.  I am using firebug to determine the css sources.  If I select a superfish menu on my site, I get css input from system and superfish.css, but not from local.css.  It is not being used at all because I can copy over a setting from superfish and change it in local without affect.  My caches are constantly being flushed so that is not the problem.

Here is the directory structure:

"example.div/themes/stark/stark.css" - used
"example.div/sites/all/libraries/superfish/superfish.css" - used
"example.div/sites/all/themes/sub_stark/css/local.css" - not used.

The sub-stark info file reads:

       name=sub stark
       description = Stark
       sub-theme base theme = stark
       core = 7.x
       engine = phptemplate

       stylesheets[all][] = css/local.css

Configuration looks good. Caches are cleared. Have I forgotten a setting somewhere?

Well, I've got it to work by moving  the file into the Sub-stark directory instead of a sub directory and changing the .info file.  I am working on Windows 7 using an Oracle VM with Ubuntu, so there may be that is causing a problem.


drupal webform sliding radio button I m trying to build a form that has questions with radio button answers when someone clicks on a radio button the next question comes up and it should have a next and prev button is there any php code i need to put in? or will it be just jquery as i m very new to php and javascript

You may use Webform module and read this.

The full documentation is at http://drupal.org/documentation/modules/webform.

You can achieve the conditional field with Webform Conditional.

  This modules enhances the existing Conditional Rules of the Webform
  Module. It adds the ability to make components dependent on select
  components(i.e. listboxes, radio buttons, and checkboxes) that appear
  on the same page.

Here's a youtube video Screencast demo.

  Webform already has support for conditional fields on multi-page
  forms. For example Field C on Page 2 can be dependent on Field A on
  Page 1. This module adds the ability to have conditional fields on the
  same page. This module adds the ability to have Field B on page 1 be
  dependent on Field A also on Page 1.

Check the version of the Webform module; you may have it already.


use title content as existing field I have created content type with multiple entries some of them have term reference / autocomplete.

Why cant i do that to the title for the content type?
Is there a way I can make that happen?

Also why can't I use the title in other content types?

Attached image with title .

The reason you can't use the title as you wish, is because it's not a Field, but a Property.

Unfortunately I can't find a meaningful explanation of the difference between the two at this time, so no link, sorry.

If it helps in any way, you can create your own title field, which will then behave more like you expect. Of course, you'll then have two "titles", so this will various annoying side effects.


PostCreate/Hook on User Registration I want to hook into user registration but there doesn't seem to be any hook for it anymore. This is what I see from Drupal 8.8:
hook_user_cancel
hook_user_cancel_methods_alter
hook_user_format_name_alter
hook_user_login
hook_user_logout
Furthermore I can't find any events for it neither.
So how can I hook into user registration?

It depends from what exactly the code needs to achieve.
hook_form_alter() and hook_form_FORM_ID_alter() are still used from Drupal 9, and they can be used to hook into account registration before users can enter values for the account to create. They should not be used to add an entity field, or add a validation handler for an entity, for which hook_entity_base_field_info() and hook_entity_bundle_field_info() (to add entity fields to an entity) or hook_entity_type_alter() (to add constrains to validate an entity) are preferable.
If you are instead looking for the Drupal 9 equivalent of Drupal 7 hook_user_insert(), hook_user_update(), and hook_user_presave(), which are invoked after the users entered the account data (and they should not be used to invalidate the entered data), they are still used, but they are documented under hook_ENTITY_TYPE_insert(), hook_ENTITY_TYPE_update(), and hook_ENTITY_TYPE_presave(). When you implement those hooks, you replace ENTITY_TYPE with user, for the User entity. This means that the name of the function implementing those hooks for the User entity doesn't change respect of the function name used in Drupal 7; it's just a matter of documentation.
Note also that the generic hooks, invoked for every entity implemented in Drupal, for example hook_entity_insert() are still used in Drupal 9. (See hook_entity_insert().) The documentation page for that hook for Drupal 9 contains a reference to the equivalent hook invoked for a single entity type (See also hook_ENTITY_TYPE_insert(), written on two lines).
Further reading

Drupal Entity Validation API: Create Custom Entity Constraints
Documentation for entity hooks has been consolidated


PDOException: SQLSTATE[40001]: Serialization failure: 1213 Deadlock found when trying to get lock; I am getting the following error on my D7 site:

PDOException: SQLSTATE[40001]: Serialization failure: 1213
Deadlock found when  trying to get lock; try restarting transaction:
INSERT INTO {node} (type, language, title, uid, status, created, changed, promote, sticky)
VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2,
:db_insert_placeholder_3, :db_insert_placeholder_4,
:db_insert_placeholder_5, :db_insert_placeholder_6,
:db_insert_placeholder_7, :db_insert_placeholder_8); Array
(
[:db_insert_placeholder_0] => baby_clothes
[:db_insert_placeholder_1] => und
[:db_insert_placeholder_2] => Boys clothes and swing
[:db_insert_placeholder_3] => 1
[:db_insert_placeholder_4] => 1
[:db_insert_placeholder_5] => 1333240131
[:db_insert_placeholder_6] => 1333240131
[:db_insert_placeholder_7] => 1
[:db_insert_placeholder_8] => 0
)

in drupal_write_record() (line 6975 of includes/common.inc).

I have a module that saves nodes programatically on cron run.  There is the possibiliy that two nodes could save simultaneously.  Is that what could be causing this? The table locking mechanism is not working correctly to prevent collisions? If I put the site in maintenance mode and just run the batch of nodes to be saved, this never happens. Thoughts? thanks!

This is a known issue in drupal 7.x core and has been resolved in the latest release (see this bug report for more information). Make sure you've upgraded to the latest version of Drupal 7, or try applying the patch if you need to get your site operational.


Drupal error. Drupal safe mode possible? I added organic groups module to a drupal website. For some reason the website crashed and gives the following error:

Fatal error: Unsupported operand types in /home/content/39/7384539/html/salvare12/sites/default/modules/og/includes/og.info inc on line 115

I removed the organic groups module manually and disabled it in the database. But then it gives a file missing error. I have uploaded the organic groups module once again but it does not work.

How can this be fixed? Is there some safe mode in drupal, to which i can revert when such an error occurs?

Try deleting the row for the og module in the system table. Then run a query for each database table beginning with cache_:

TRUNCATE TABLE cache_*

This should make Drupal forget anything it knew about organic groups (this is how to clear the cache manually).

I'd suggest keeping your modules in the standard location which is /sites/all/modules rather than /sites/default. I don't know if thats part of the problem here but it might be.


How to do simple subtraction in Computed Field? I'm trying to calculate the price difference between old price and new price, and if the price has dropped to display by how much, both Nominally and in Percent.

So, basically these are 2 simple formulas that should look like this:

  NOMINAL PRICE DROP = field_price_original - field_price_new

  PERCENTAGE PRICE DROP =  ( (field_price_new - field_price_original) /
  field_price_original ) * 100

I tried setting this up through Rules (unsuccessfully), but it seems that doing it through Computed Field will not be so heavy on the server.
Using Computing Field I have the following formula:

  $entity_field[0]['value'] =
  array_pop(array_pop(field_get_items($entity_type, $entity,
  'field_price_original'))) -
  array_pop(array_pop(field_get_items($entity_type, $entity,
  'field_price_new')));

The number is set as float, 10.2.   But for some reason it doesn't work.

Can someone please help and provide the correct syntax for Computed Field?

As per the documentation of computation field module to calculate the difference of two fields you need to use the PEAR:

$path = '/pathToPearsParentDirectory/pear/PEAR';
set_include_path(get_include_path() . PATH_SEPARATOR . $path);

require_once 'PEAR.php';
include_once "Text/Diff.php";
include_once "Text/Diff/Renderer.php";
include_once "Text/Diff/Renderer/inline.php";

$diff = &new Text_Diff('auto', array(array($node->field_nameOfOneFieldToCompare[0]['value']), array($node->field_nameOfOtherFieldToCompare[0]['value']))); $renderer
= &new Text_Diff_Renderer_inline();

$node_field[0]['value'] = $renderer->render($diff);

More info about it available here http://arencambre.com/blog/2009/05/17/how-i-got-field-diffs-working-with-drupal-pear-text_diff-and-dreamhost


IF statement to check if loaded entity is of type In my module (fork of ECK Clone) I'm trying to set a default value when an entity of type "Course" is cloned.
Currently I do:
function eck_clone_clone_entity($entity, $account = FALSE) {

  $original_entity = clone $entity;

  $entity->id = NULL;

  if ($account && isset($entity->uid)) {
    $entity->uid = $account->uid;
  }

  if (isset($entity->created)) {
    $entity->created = NULL;
  }

  if (isset($entity->changed)) {
    $entity->changed = NULL;
  }

  if (isset($entity->title)) {
    $entity->title = t('Clone of !title', array('!title' => $entity->title));
  }

  $entity->status = 1;
  $entity->some_boolean = 1;
  $entity->content_status = 1164;

  $context = array('original_entity' => $original_entity);

  drupal_alter('clone_eck', $entity, $context);

  entity_save($entity->type, $entity);

  return $entity;
}

PS: some_boolean value gets set, but not the status. I wonder why.
What I need is to check if the $entity is of the type "Course".
I thought it would be as simple as wrapping it in an if statement like so:
if($type == 'course') {
    $entity->some_boolean = 0;
    $entity->content_status = 665;
    $entity->course_number = 3;
    $entity->tag_line = "some other tag line here";
  }

But that doesn't work. Any idea?
PS: some_boolean value gets set, but not the status.

Like @Kevin pointed out, $type was never set. That was helpful.
I believe this works:
if($entity->type == 'course') {
  $entity->some_boolean = 0;
  $entity->content_status = 665;
  $entity->course_number = 3;
  $entity->tag_line = "some other tag line here";
}

If you can improve this, please let me know. Much appreciated.


How detect format of date field in form alter? How can I find if a form has date/time field or not and if it has, how can I detect what is date format for it?

For the Date popup selector, the #date_format element in the form element. For example:

    //The date field has the format of "d-m-Y"
    $form['date_field'] = array(
      '#type' => 'date_select',
      '#title' => t('My Date'),
      '#date_format' => 'd-m-Y',
      '#date_label_position' => 'within',
      '#date_year_range' => '0:+1',
      '#description' => t('This is a test date picker'),
      '#default_value' => date('Y-m-d H:i:s'),
    );

There's an D6 documentation page on d.o, but it's still valid for D7 last I looked.


Bootstrap sub-theme navbar buttons It looks like when you use the default Bootstrap subtheme, it renders a navbar with the Main Menu links at the top of the page, as
...
 elements inside of a navbar-nav block. How can one, instead of using
..., instead use
...
, so that my navbar has links styled as buttons instead of normal links?

I'm using the Bootstrap 7.x-3.0 subtheme. Thanks in advance!

Why do you need to add a class btn just to make it a button? Can't you just use the following css:

#navbar ul a {}

and style that to make it look like a button?


Drupal Commons notifications queue is not working I have a site where we noticed the notifications are no longer working. The Queue states there are 238 notifications, and they are set to process immediately. The send method is "mail," and other emails go out from the site with no issue (e.g. registration emails).

I'm looking for any information which may help me troubleshoot this issue. There are no entries made in the watchdog table, no settings that I can see to log any kind of debug information, and no general setting or indication where I can see that would cause the problem.

The only thing I can guess is that updating Drupal Commons from an early version to 1.5 broke notifications in some way that I'm not familiar with.  The only significant thing I turned up on Google is this: http://network.acquia.com/node/1469103.

It's a combination of so many modules interacting that I'm honestly not even sure where to start.

The most obvious thing would be that cron is not running. You can see the last time it ran by looking at the site status report, that will also give you a link to run it manually.


how to get all the last level term id's of taxonomy in drupal 7? i have a  taxonomy

 State
      - district 1
          -block 1
            -village 1
            -Village 2
          -block 2
          -block 3
      - district 2
      - district 3

How to get all the term id's of all the villages in a state?

<?php
function get_term_depth($tid) {
  $limit = 5; // level of your term
  $depth = 0;
  while ($parent = db_select('taxonomy_term_hierarchy', 't') ->condition('tid', $tid, '=') ->fields('t') ->execute() ->fetchAssoc()) {
    $depth ++;
    $tid = $parent['parent'];
    if ($depth > $limit) {
      break;
    }
  }
  return $depth;
}
?>


which views template controls the field div sections I have created a view which displays the fields of different node types. Therefore, visually, the user will see apple fields bunched together and orange fields bunched together, and the page makes sense.

However, for each view row, a div is created for EVERY field in the view, orange or apple. For particular reasons, I need to be able to get rid of the divs which don't apply to that row.

I would imagine doing something like:

if($row->_field_data['nid']['entity']->type == '[node-type]'):

but I can't figure out which template to do this in. I tried in views-view-unformatted.tpl.php and views-view.tpl.php, and in views-view-fields.tpl.php (which are the outer wrappers) but none seemed to do it.

I thought it would be in views-view-fields.tpl.php, but when I tried inserting this into the (overriding) template

drupal_set_message("wrapper-prefix:" . $field->wrapper_prefix . " wrapper-label:" . $field->label_html . " wrapper-content:" . $field->content . "  wrapper-suffix:" . $field->wrapper_suffix);

the only thing which came back with info was $field->content

You should be able to accomplish this through the UI from each field settings form:


What causes 'Invalid form POST data' when removing an attached file from a node? I have an attached PDF file on a file field. When I click the 'Remove' button, the AJAX throbber appears and then the file remains unremoved. Adding an file to a new node still works.

I checked the error logs; it states "Invalid form POST data."

What is causing this problem?

I can confirm, increasing 'max_allowed_packet' in our MySQL config solved this problem. MySQL's default of 1 megabyte was too small. Increasing it to 16M, then restarting MySQL has resolved this issue.

Info on our solution was found here:
https://www.shift8web.ca/blog/2014/11/drupal-problem-an-ajax-http-request-terminated-abnormally/


Custom reference field settings in different content types I have a field called booked user and two types of content types, event-type-A and event-type-B.

I am referring to the same field from both content types. However, along the process I figured out that I want to have multiple values for this field in event type-A and single value for event-type-B. Initially both had multiple values.

Whenever I change the field settings in one content type, it also changes in the other.

How can I overcome this? Considering that I have content created in type-B and I can not really add a new field to replace that one, cause I will lose all the previous field content for that user.

The solution a colleague proposed is to add the following code in the hook_form_alter():

$language = $form['field_user']['#language'];
$form['field_user'][$language]['#multiple'] = 0;

If you want to be a bit more aggressive on data consistency you can also hook into the form validator and check that the correct number of values is inserted.


Allow authenticated user to create an article hey im fairly new to D7 and ive noticed that there isn't really a way to create an article without the admin toolbar, but i would like users of my websites to be able to create articles. How would i do this without giving them access to the toolbar?

Go to admin/people/permissions and check the permission "Article: create content"
and maybe on a block create a link for them called create content.


Download a backup of the files directory I've researched this a little bit, but I'm wondering if anyone else has an idea on how to do this. The request is to be able to create a weekly archive of the files uploaded through a document content type, basically downloading all files. The client is a team of non-technical, financial advisors - so the simpler, the better.

Obviously Backup & Migrate doesn't fit the bill since that's database only. The only thing I can really think of is writing a bash script to gzip their document folder, and then have a continually updating URL based on a date that links to that zipped folder.

There is actually Backup and Migrate Files too.


Add external javascripts Is it possible to add external javascripts directly into the .info file of a theme?
e.g scripts[] = http://cdn.jquerytools.org/1.2.6/jquery.tools.min.js

In your theme's template.php file use drupal_add_js() to the page preprocess method (or an equivalent preprocess).

function hook_preprocess_page(&$vars) {
  drupal_add_js('http://cdn.jquerytools.org/1.2.6/jquery.tools.min.js', 'external');
}


Will Migrating Content Between Sites Preserve CKEditor Styles? I have been entering content on my dev site using CKEditor, but now I'm worried that moving to the live site will erase all the styling I have done to these articles. Maybe that is a dumb question, because I have not found anything addressing this topic online. If I have the CKEditor module installed on the live site, when I transfer my content there, will all their fonts/colors/styling/etc be preserved? Thanks in advance

Yes, as long as you keep your database integrity when migrating.

CKEditor basically adds HTML tags and attributes to your data, which are saved in your fields' tables in the database. So, for example, if you have a body field that contains  text formatted like "Hello, body", and take a look at your field_data_body table, you will see something like this:

Hello, body...


NFS Directories between 2 Servers I have 2 parallel Drupal Web Servers running (serving for one Drupal Instance together) and now i need to install NFS. My experience in multi Drupal Servers is, each Drupal Instance (Server) uses their own Aggregated JS + CSS files (storing in: sites/default/files/js and sites/default/files/css folders) which can NOT be used as common. (Files can not be the same for both Servers. They use their own ones.)

Based on these issues, my questions are:

How NFS actually works between Multi Drupal Servers?
Which directories will be/need to be shared between?
What will happen to Aggregated Files?
What will happen to Web User Uploads paths and files? (Need any configuration in Drupal?)

Can anyone share these knowledge/experience please?

To prevent synchronization issues, you should mount the files directory as a shared folder over NFS between the drupal webservers, so that each Drupal instance has a symlink to the same file share

e.g:

/var/www/drupal-site-mysite/sites/default/files -> /var/lib/sitedata/drupal-site-mysite/files

where /var/lib/sitedata/drupal-site-mysite/files is a NFS mount/share.


How do I require the user submitted content to be approved before it is published? I need to have content that is submitted by users of a certain role to be approved by an administrator before it is published. I thought this functionality was build in already, but I just can't seem to find where it is.

You may be interested in the Workbench module combined with Workbench Moderation.

From the Workbench project page:

  Workbench provides overall improvements for managing content that
  Drupal does not provide out of the box. Workbench gives us three
  important solutions:

  a unified and simplified user interface for users who ONLY have to
  work with content. This decreases training and support time.
  the ability to control who has access to edit any content based on an
  organization's structure not the web site structure
  a customizable editorial workflow that integrates with the access control feature
  described above or works independently on its own

From the Workbench Moderation project page:

  Workbench Moderation adds arbitrary moderation states to Drupal core's
  "unpublished" and "published" node states, and affects the behavior of
  node revisions when nodes are published. Moderation states are tracked
  per-revision; rather than moderating nodes, Workbench Moderation
  moderates revisions.


How can I make a node link to another node According to this site http://asblab.mie.utoronto.ca/news, you can see how
Home>>News just below the menu. If I could add in this node http://asblab.mie.utoronto.ca/node/12525

such that Rise of the robots page would have

Home>>News>>Rise of the robots . How do I link them together?

Thank you guys, this forum has been helping me alot. If my question doesnt make sense, please inform me so I can try my best to edit and make the question better.

Try to use drupal_set_breadcrumb() in template file if you want to do it programmatic.

Or configure Custom Breadcrumb module.


How to declare core requirements in composer.json? If a module depends on a particular minor release of Drupal (eg 8.4.*), the best practice is to declare this in info.yml: This blocks installation of the module if core is too old.

However, this just blocks installation, and doesn't help at all with falling back to a compatible version. We can make this much easier by also declaring the compatibility in composer.json.

Requiring drupal/core in the composer.json of a module seems like a major change, though. For one thing, it means that your local dev environment pulls in core as well as all its dependencies (about 40 packages), and not their default locked versions either, but the latest supported ones (same effect as running composer update in a core checkout). For another, it will cause problems for all environments that use composer for contrib only.

I think "conflict": {"drupal/core": "<8.4"} might be a low-impact solution here.

Is there an accepted best practice for this already?

On further experimentation, it appears that it is unnecessary to add this to the composer.json file. It is enough to add drupal:system (>=8.3) to the info.yml requirements. This seems to be automatically interpreted by the drupal.org package repository.

Even when the composer.json file does not specify any dependencies, composer show drupal/MODULE will show that it requires ^8.3, and it will be impossible to install the composer package on an 8.2 site.


How can I ensure a referenced entity is cached separately per paragraph? I have a situation where two Paragraphs on single page may potentially reference the same entity.

The affected paragraphs have a field to change their colour, and this colour value is passed down to the referenced entity (via hook_preprocess_[entity-type]) for use in its template.

Node

field_paragraph

Paragraph1

field_colour
field_entity_reference (references entity:1234)

Paragraph2

field_colour
field_entity_reference (references entity:1234)

When I update Paragraph 1 to change its colour, this is currently affecting the colour of Paragraph 2 (because the entity is cached, including the colour value that is preprocessed into it).

I have tried adding a cacheable dependency (in hook_preprocess_[entity-type]) to transfer the cache tags for the paragraph to the entity, so that when the paragraph is updated, it invalidates the cache for the entity it is referencing:

$renderer = \Drupal::service('renderer');
$renderer->addCacheableDependency($variables, $referring_entity);

I have also tried replacing $variables in the above with $variables['elements'] and $variables['content'], but either way this does not seem to work as I expected.

Any advice appreciated.

So the easiest option likely is to just disable caching completely for the embedded entities.

In hook_entity_view(), unset $build['cache']['keys']. They are then still cached as part of the paragraph render cache, but don't have their own cache entry anymore.

To avoid not caching them when they are shown somewhere else, you should use a special view mode when you integrate them in paragraphs and only disable caching for that.

Note that you could also set max-age = 0 but that means "this content must not be cached at all", that information would bubble up to the paragraph and host entity and none of those would be cached anymore. That's not what you want.

Or you could change your approach and apply that color through a class that is set on the paragraph level, without changing the HTML of the embedded entity. Doesn't work for everything, but for a simple color change, that is likely easier to implement.


EntityFieldQuery in rules - no result I try to set a new variable in rules. I try to get nid of a node selected by efq like this:

<?php
$termid = $node->field_terms['und'][0]['tid'];
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'mybundle')
->fieldCondition('field_terms', 'tid', $termid)

$result = $query->execute();
$nid = array_keys($result['node'])->nid;
print $nid;
?>

The problem is that no matter I do, I am not getting nid output. Can anybody help? Thank you.

array_keys($result['node']) isn't going to return an object that you can select a nid property from; it's going to return an array of nids that have $termid tagged in its field_terms field. If you're just looking for the first nid in the query results you can do $nid = array_keys($result['node'])[0];


How do you create a custom permission to administer a custom module? I just finished the Hello World module tutorial for Drupal 8. The tutorial takes you through the process of creating an administration page to configure the module so that you can change via settings to whom the page says hello.

By default, the config page only requires the 'access content' user permission to view. I realize I can change the value to require any other already defined permission if I want, but how can I define a new permission specifically to administer just this module and nothing else? I found this similar question by searching, but it's for Drupal 7 instead of 8, and the solution leaves a lot to be desired; I would like my module to be self-contained, and requiring that the user download a non-core third-party module is not something I am prepared to do.

Permissions can be added in the mymodule.permissions.yml file of the custom module.
You can also define permissions with a callback, if they depend on other items in the application.
See: https://kevinquillen.com/drupal/2016/02/21/dynamic-permissions-in-drupal-8


Auto increment in views table I have views with table display, the table consist of two column(name[string], salary[float]).
How can i set a auto increment for the table rows?
like this want i want  .
Thanks.

You need to add a new field to the view, and choose the "Global" filter from the available drop down.

Then choose the "Global: View result counter" type:

That wiill give you a counter as a field which you can put into whichever column in the table is appropriate for what you need.


Commerce: Modify the order price I want to modify the price of the order, but I was unable to change that if the order status is either "Shopping cart" or "Checkout".

What I did is changed the order status to "Pending", then the price can be modify. After modifying the price, I changed back the order status to "Shopping cart", then the price becomes disabled again.

When I check my cart, the price is same as with the original price, so I looked at the order again and find out that the price has been changed back into its original price.

Why is this happening? I'm not familiar yet with commerce.

If I understand it correctly, a shopping cart refresh causes the recalculation of your line item price(s). For documentation on this topic, see sell price calculation on drupalcommerce.org and the referenced Prezi presentation on that page.

Maybe you can adjust the price calculation, by adding pricing rules that react on the event 'Calculating the sell price of a product' and use the action 'Set the unit price to a specific amount'.

Otherwise, you could implement one of the hooks provided by commerce_product_pricing.api.php.


Error Message are not coming I have create a template for user-register page

I have created a module under hook_form_alter as

if($form_id == 'user_register_form') {

            $form['account']['pass']['#type'] = 'password';
            $form['account']['pass']['#title'] = 'Password';
            $form['account']['mail']['#title'] = 'Email';
            $form['actions']['submit']['#value'] = 'Request Access';
             $form['#theme'] = 'user_register';

    }

Edited:

  function custom_user_register_form_validate($form, &$form_state) {

        if($form_state['input']['field_first_name']['und'][0]['value'] == ''){
            form_set_error('field_first_name', t('Email can not be empty'));
        }
          drupal_set_message($message, 'error');

     if($form_state['input']['field_last_name']['und'][0]['value'] == ''){
        form_set_error('field_last_name', 'Title cannot be "test"');
         drupal_set_message($message, 'error');
     }

                return $form;
    }

And i have created a user-regiter.tpl.php file

under this i have code like this

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

Which is working fine

Now when i submit form. it doesnt display error message . But it is showing red border in input box.

Why it is not showing error message . Please help

Thanks

It's probably because you're not showing the Drupal messages in your theme.  Take a look to ensure you have the following (somewhere, probably in your page.tpl.php file);

<?php print $messages; ?>

Note that you've made some other mistakes though (not related to your issue) - First, you should use $form_state['values'] to gain the values when using _validate(); second, you can lose the two drupal_set_message($message, 'error'); lines as they aren't doing anything?


Drupal 7: adding an image and a link to a user page I have a new Drupal 7 website with user profile pages like this one.

I'm new to Drupal and do not want to install any modules besides the core ones and the few written by me - because this will keep the site easy to maintain and upgrade for me at the beginning.

I have already written the 3 blocks displayed at my site's Triptych.

Now I'd like to add an image (will be a static Google map with a marker at user's city, for example: http://maps.google.com/maps/api/staticmap?sensor=false&markers=color:0x336699|Bern&&size=300x300 ) and a dynamic link to the user profile pages (i.e. the link depends on the user's id).

I.e. I know how to get user's city for my map:

$result = db_query('select field_city_value from {field_data_field_city} where entity_id=:uid', array(':uid' => array($viewer_id)));
$city   = $result->fetchField();

but I don't know how to extend the user profile page.

Please give me few hints on how to do it, which hook to use here and maybe few lines code.

And maybe anyone also knows how to add a Tab to a user profile page as well?

For images, just enable the Image module and add an Image field to your users just like you already did with other fields.

For a link, assuming you want that to actually display it as a link and not just as text, I really suggest you have a look at http://drupal.org/project/link. I know you said you don't want any contrib modules but again, there is no reason to not do that. Drupal only really gets it's power from contributed modules. Upgrading minor versions is pretty much always trivial and Drupal 8 is most likely still years away and Drupal 7 will be supported until Drupal 9 is released, so you don't have to worry about that for quite some time. Using link.module will certainly be better than trying to develop your own module. link.module has already been tested on 2000 other D7 sites (and 70k D6 sites..).

The Tab question is something completely different, so I suggest you create a new question for that. For a start, you will need to implement hook_menu() and add a 'user/%user/something' menu item of type MENU_LOCAL_TASK.


t() strings can't able to translate I'm wondering that Drupal t() strings are not available for the translation.

Let me explain what I did. I'm going to make my site as multilingual (English & Dutch). English is my source language.

For this, I have added locale module and enabled English and Dutch language.

Then I installed Entity Translation && i18n module on my site.

And then I wanted to show some multilingual text in the user profile edit form. Hence I put form alter and given some string inside t('My topics').

Then I went to /admin/config/regional/translate/translate this page to add a translation for my custom string "My topics". But it not available there.

Where did I'm going wrong?

I'm using
 - Drupal 7.54
 - Enabled Drupal's core locale module
 - Entity Translation(7.x-1.0-beta6)
 - Internalization (7.x-1.17)

I have found the solution.

Initially, my site is in English(source language).

We have to switch the language to other languages on the site(in my case it is Dutch) using this path admin/config/regional/language. Then, we have to view the page which is consists of t(). Then only the t() strings would register for translation.

Now go to admin/config/regional/translate/translate and search your t() string, it will be available and add translation !!!


Drupal 7's States API: Why won't this code work? Scratching my head on this.  Trying to get a few fields in a node edit form to be visible only when a select element's value is 'sponsor':

function iv_persona_helper_form_persona_node_form_alter(&$form, $form_state) {
  $lang = $form['field_persona_type']['#language'];

  $sponsored_control_states = array(
    'visible' => array(
      ':input[name="field_persona_type['. $lang .']"]' => array('value', 'sponsor'),
    ),
  );

  $form['field_sponsored_url']['#states'] = $sponsored_control_states;
  $form['field_sponsored_text']['#states'] = $sponsored_control_states;
  $form['field_sponsored_description']['#states'] = $sponsored_control_states;

  $form['#validate'][] = 'iv_persona_helper_form_persona_node_form_validate';
}

I know the form_alter is being invoked, but those fields visibility is not at all changed.

Try 'value' => 'sponsor' instead of 'value', 'sponsor'.


Nodewords: how do I use hook_metatags_default_values_alter? I posted this question a week ago on the nodewords issue queue, but have had no reply and I'm stumped.

I want to programatically set the default value for a couple of tags, but the code comments for hook_metatags_default_values_alter read like hieroglyphics to me. An example would allow me to understand clearly. If I want to set the og:latitude tag to the value 43.701536, what should the call look like?

Thanks!

Without ever having used that hook, I would suppose that you could do it very similar to the example in the documentation for hook_metatags_default_value_alter():

function hook_metatags_default_values_alter(&$values, $parameters) {
  if ($parameters['phase'] == 'post_load' && $parameters['type'] == NODEWORDS_TYPE_USER) {
    $values['og:latitude'] = 43.701536;
  }
}

For a better understanding it might be worth the effort to dig through the code of _nodewords_tag_value which seems to have the only invocation of the hook. You can see there, that it is invoked twice with a different $phase parameter. I think I would go for post_load, assuming that the defaults are not empty.

For the type parameter, you can see the available constants in the nodewords.module doc under constants. This value depends on where you want to alter the tag.

If the above code doesn't work, use dpm or something similar to inspect the $values that are passed in. That should give you enough information concerning the expected data.


Authentication required (git.drupalcode.org) On Drupal 9, I want to install the Taxonomy menu module using Composer, but I get the following error.

Using version ^3.4 for drupal/taxonomy_menu
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Package operations: 1 install, 0 updates, 0 removals

Installing drupal/taxonomy_menu (dev-3.x e89d1e8):
Authentication required (git.drupalcode.org): Username:

The command is waiting for a Git username/password, but two days ago the installation ran smoothly.
How can I ask for a stable version of the module?
On the project's page they write that, as of 21 May 2019, Taxonomy menu 8.x-3.x-dev is already fully compatible with Drupal 9.
This must be why composer require initially proposed 3.4 version and ultimately tried to install the dev-3.x version.

How can I ask for a stable version of the module?

You can't install a stable version of Taxonomy Menu module for Drupal 9 at the moment because no such version exists.
If you look at the project page, you see the latest version is 3.4 which is marked Requires Drupal: 8.x.

So, if you want to use a stable version, you have to stay with Drupal 8 for now.
To use the dev version on Drupal 9, you can do this in composer.json:
    "drupal/taxonomy_menu": "3.x-dev",

Normally you should not need to authenticate to git.  It's probably a proxy issue; you might find some hints in this discussion.


How to check in a Rules Condition if an Ubercart product is out of order? There isn't a good support for "out of order" in Ubercart for Drupal. I'm trying to fix that with the Rules module.

I'm trying to add a rule that disables the product after the stock is updated, using Rules event After updating existing content of type Product.
I want to disable the product that is sold out (stock = 0).

Here is an export of the rule I have so far:

{ "rules_product_sold_out_check" : {
    "LABEL" : "Product sold out check",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_update--product" : { "bundle" : "product" } },
    "DO" : []
  }
}

But the stock isn't a field of the node. How can I select that field within a Rules Condition? I have no idea how to use that in the Rules module as a data selector.

  The data to be compared, specified by using a data selector, e.g.
  "node:author:name".

I'm using the stock also in a view. This is what I use there (export-code-view to show the fieldnames / structure).

$handler->display->display_options['fields']['stock']['id'] = 'stock';
$handler->display->display_options['fields']['stock']['table'] = 'uc_product_stock';
$handler->display->display_options['fields']['stock']['field'] = 'stock';

I use Ubercart 7.x-3.10 (with Stock 7.x-3.10), Drupal 7, Rules 7.x-2.10

As per the UC issue about "Stock transaction should be more flexible through Rules" (from 6 years ago, status "needs work" ...), it seems that at this time trying to use the Rules module for such "out of order" situations may not be a good idea.

You may want to try to use the Ubercart Out of stock Notification module instead. Some details about it (from its project page):

  Out of stock notification for
  Ubercart.

  It uses ajax and jquery and asks the server for available stock and
  replaces the 'Add to cart' button with some configurable HTML.

  ...

  It also provides server-side validation so this module can prevent the
  addition of out of stock items even if JS is disabled or if the user
  clicks on an "Add to cart" button too quickly.


node reference ordering I have a content type "Review" and there there is dropdown for brands, I want to order dropdown list by alphabetical order. is there any way to reordering drupal node reference dropdown?

If you chose auto-complete for your node reference field & if number of item to be added is set to unlimited then you get to re-order the values which appear.

Though my answer is not proper for question which you have asked as you are asking for select field but this way I have done it..


View will not group the taxonomy terms I am litterally pulling my hair out and I hope that someone can help!  I'm working in Drupal 7 with Commerce Kickstart and all I want is to be able to view the flowers, grouped by their taxonomy term.

For example:
Flowers with bloom size of 5.5 inches:
flower teaser      flower teaser      flower teaser      flower teaser

Flowers with bloom size of 4 inches
flower teaser      flower teaser      flower teaser      flower teaser

etc.

Right now in the view I'm using the "grid" format grouping by the Taxonomy term name Bloom size - I have the "use rendered output to group rows" checked, but it will not group my terms and it keeps putting the same heading on down the page above each teaser.  You can see it here:  64.34.70.141/~henryl/bloom-size

I have a feeling it's something simple that I'm missing but I've spent DAYS on this one page and combing through other view examples and google searches and I can't figure it out.  Does anyone have any ideas?

Thank you!!!!!!

Candace

What do you have the "sort" criteria set to? Also, I find the default Views grid-view to be quite awful. I use the Views Fixed Grid module for any grid views. It will give you better output and greater control in my humble opinion.


How to output plain URL to the node in Views? I would like to output plain absolute URL of the node from Views as part of my XML feed (via Views Datasource).

So far I have found the following field handler:

  Content: Link - Provide a simple link to the content.

which is provided by Views it-self, but checking views_handler_field_node_link.inc file doesn't seems to support displaying plain text (and there are no any field formatters, as it's field specific), but instead I've got:

view

without possibility to change the format (apart of the text it-self).

Is there any other way to display just plain URL of the node using Views field handler (without having actual field)?

Content: Path works with Drupal 7. Select Use absolute link (begins with "http://") in Rewrite results section of the field settings.


Why does cloning a private git repository via Drush make file fail using SSH authentication? I have multiple private git accounts set up with SSH system's keychain authentication for each git repo.

It works to clone private git repos from command line:

git clone git@git_ssh_alias:git-account/some_repo.git

The git_ssh_alias is the alias name declared in .ssh/config file that specifies the SSH key that should be used.

However, this same clone doesn't work when running from make file via Drush script as following.

From Make file:

projects[theme_name][type] = "theme"
projects[theme_name][version] = 7.x-1.0
projects[theme_name][download][type] = "git"
projects[theme_name][download][url] = "git@git_ssh_alias:git-account/some_repo.git"
projects[theme_name][download][branch] = "master"

From Drush script:

drush_invoke_process('@self', 'make', array($make_file), $options)

where $make_file is a path to a make file and options are:

$options = array();
$options['no-core'] = TRUE;
$options['yes'] = TRUE;
$options['contrib-destination'] = 'sites/all';

My question: How to clone private git repo with local ssh keychain authentication enabled?

Using modules and not theme_name may resolve this.

projects[modules][type] = modules
projects[modules][download][type] = git
projects[modules][download][url] = git@bitbucket.org:company/repo.git
projects[modules][download][branch] = master

Here are a couple of useful links:

https://groups.drupal.org/node/194303#comment-918073
http://www.systemseed.com/blog/drush-make-private-git-repository-github


How do exposed views filters make their queries URL safe? I'm creating my own search form in D7, and I need to sanitize the search text so that it is URL safe. I need to mimic the way that the views module does it because I'm using the search_api module and views.

In short, I need to make this:

"what is going on around here, anyway?"

look like this:

what+is+going+on+around+here%2C+anyway%3F

How do I do that?

Use the url() function to encode your URLs.

url("what is going on around here, anyway?");

this will return the string '/what%20is%20going%20on%20around%20here%2C%20anyway%3F'

You could also use this to get the full, absolute URL.

url("what is going on around here, anyway?", array('absolute' => TRUE));

You may also be interested in the l() function if you need html output.


Contact for per node in Drupal 8? This was quite easy on Drupal 7. You could just use Webform. In Drupal 8, I'm not so sure.

I have nodes of type "Business". I want a form to appear on this page, that when filled in, it must send an email to the business. The "Business" content type has a field on it called "Business Contact Email Address". This is where the mail must go...

I was thinking of:

Finding a way to do it using the inherent Drupal 8 contact forms... any clues as to how?
Creating a new content type called "Node Contact Form" that references a node and then use Rules to mail the field on the referenced node.

Is there an easy way to do this?

Not without code, but its fairly easy.

You could add a reference field to contact forms to your node type, and "view" the contact form. contact_storage provides a view builder that will display the form then. That doesn't work for your additional mail requirement, however.

To be able to do that, you need custom code to display the form, something like this in hook_node_view(). field_node_reference is an entity reference field that points back to the node. that will allow you to easily see for which node it was submitted and also use it later on to change the recipient:

  $message = \Drupal::entityManager()->getStorage('contact_message')
    ->create(array(
      'contact_form' => 'YOUR_FORM_ID',
      'field_node_reference' => $node,
      // You can generate a default subject or even hide it completely
      // and always use this value.
      'subject' => t('Contact about "@title".', ['@title' => $node->label()]),
    ));
  $form = \Drupal::getContainer()->get('entity.form_builder')->getForm($message);
  $build['yourmodule_contact_form'] = array(
    '#type' => 'details',
    '#open' => TRUE,
    '#title' => t('Contact the business'),
  );
  $build['yourmodule_contact_form']['form'] = $form;

yourmodule_contact_form can be defined as an extra field (hook_entity_extra_field_info), then you can conditionally display it using if ($component = $display->getComponent('yourmodule_contact_form')) { and you can configure the place and if it should be displayed per view mode.

The final piece is then to override the mail recipient of the sent mail using a hook_mail_alter():

function yourmodule_mail_alter(&$message) {
  if (!empty($message['params']['contact_form']) && !empty($message['params']['contact_message'])) {
    /** @var \Drupal\contact\Entity\ContactForm $contact_form */
    $contact_form = $message['params']['contact_form'];
    /** @var \Drupal\contact\Entity\Message $contact_message */
    $contact_message = $message['params']['contact_message'];

    if ($contact_form->id() == 'YOUR_FORM_ID' && $contact_message->hasField('field_node_reference')) {
      /** @var \Drupal\node\NodeInterface $node */
      $node = $contact_message->field_node_reference->entity;
      if ($node && $email = $node->field_email->value) {
        $message['to'] = $email;
      }
    }
  }

This could possibly be built in a generic way but it would require configuration for the mail and reference fields.


Fixing Notice: Undefined variable: content_share in include() (line 39....node.tpl.php)? I followed online tutorials and defined a new region in litejazz Drupal 7 theme info file as :

regions[content_share] = Content Bottom

and exposed the new block using the code below in node.tpl.php as :

  <?php if (!empty($content['links']['node']['#links']) || !empty($content['links']['comment']['#links']) || !empty($content['links']['blog']['#links'])): ?>

&raquo; <?php print render($content['links']); ?>

  <?php endif; ?>
      <?php if ($content_share): ?> //<<<<<<<<<<<- THIS LINE CAUSES WARNING

    <?php print render($content_share); ?>

<?php endif; ?>
  <?php if ($content['comments'] && ($page)) { ?>
    <?php print render($content['comments']); ?>
  <?php }; ?>

Now my logs are getting filled with following warning :

  Notice: Undefined variable: content_share in include() (line 39 of
  /srv/bindings/ertr88c9reretrea25f7b405eeee/code/sites/all/themes/litejazz/templates/node.tpl.php).

I had tried clearing cache as suggested in other solutions but none worked.

Regions are only available in page.tpl.php, not node.tpl.php.

In page.tpl.php you can use

print render($page['content_share']);


Custom POST Resource Not Working but GET is I created a custom resource and my GET Resource works but my POST does not:

<?php

namespace Drupal\xeno_dashboard\Plugin\rest\resource;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Psr\Log\LoggerInterface;

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "snap_shots_resource",
 *   label = @Translation("Snap shots resource"),
 *   uri_paths = {
 *     "canonical" = "/snapshots"
 *   }
 * )
 */
class SnapShotsResource extends ResourceBase {

  /**
   * A current user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

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

    $this->currentUser = $current_user;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('xeno_dashboard'),
      $container->get('current_user')
    );
  }

  /**
   * Responds to entity GET requests.
   * @return \Drupal\rest\ResourceResponse
   */
  public function get() {
    $response = ['message' => 'Hello, this is a rest service'];
    return  new ResourceResponse($response);
  }

  /**
   * Responds to entity POST requests.
   * @return \Drupal\rest\ResourceResponse
   */
  public function post() {
    $response = ['message' => 'Hello, this is a POST response!'];
    return  new ResourceResponse($response);
  }

}

This is the response from the POST:

{
    "message": "No route found for \"POST /snapshots\": Method Not Allowed (Allow: GET, HEAD)"
}

This is the code we are using to determine the POST path:

    $create_path = isset($definition['uri_paths']['create']) ? $definition['uri_paths']['create'] : '/' . strtr($this->pluginId, ':', '/');
    // BC: the REST module originally created the POST URL for a resource by
    // reading the 'https://www.drupal.org/link-relations/create' URI path from
    // the plugin annotation. For consistency with entity type definitions, that
    // then changed to reading the 'create' URI path. For any REST Resource
    // plugins that were using the old mechanism, we continue to support that.
    if (!isset($definition['uri_paths']['create']) && isset($definition['uri_paths']['https://www.drupal.org/link-relations/create'])) {
      $create_path = $definition['uri_paths']['https://www.drupal.org/link-relations/create'];
    }

This would mean it is /snap_shots_resource as path, but you probably want to set a 'create' uri path to the value you want.


How to manage the order of the modules execution? I have a 2 modules which has javascript files modify the height of an element (through jquery).

module one set the height to 100px
module two set the height to 200px

I seems like the module one is fired after module two. I need the js file of module two to be fired after the js file of module one. This is to change the weight of the js files.

I included the js file in the module_one.info file like this:

scripts[] = js/myfile.js

Can I do this?

Should I add the js files in myTheme.info ?

You can change the module weight in your system table in the data base. This will reorder the execution of the modules and also the inclusion of js.

You can update the weight via myphp admin or you can do it via a custom modules .install file in a hook_install. for example:

db_update('system')
 ->fields(array(
   'weight' => 10,
 ))
 ->condition('name', 'module_name')
 ->execute();

Replace module_name with the name of the module you would like to delay.

Clear all cache afterwards


How to configure list page/detail page view? I have created a new content type and show a list of all content of this type (list page). I have used the page URL article.

The detail page should be a child of article f.e. article/1. I configured the second view with path article/%.

How can I configure the detail view correctly and change the link in the list?

You don't need a URL argument for this. You can make the View path 'articles' and give it the following:

Filter by content type = article
Filter by status = published
Sort by created date, descending
Enable pager

That will give you a basic View listing articles, paged out, in descending order, on the url "articles".


how to insert a block within a cck input form in Drupal 7? I wanted to insert a block within the CCK input field in drupal 7. I have created a block which would display all the custom content types and the nodes created with those content type in tree structure and categories,sub categories from Magento. The tree value is dynamically populated every time.

I want to display this tree in the cck input form to enable the user to make the selection. I was trying to do this using hook_theme in hook_form_FORM_ID_alter. I used module_invoke to insert the block module within the module template file. but its look like I cant insert the block within the template.
Could anyone tell me why I module_invoke is not working and suggest me a way to insert this tree in the CCK input field. I want to get the value selected in this field and store for use in some other module.

So you're block is created and working?  You just want to insert it as a field?  You can do that using Display Suite, or if you want to insert it within a text field you could try Insert Block (still in dev)

I think Display Suite is the way to go, it is a very comprehensive module so it takes time to take it all in, but it provides very intuitive solutions for Drupal shortcomings, such as displaying a block as if it were a field.


How include hash (#) in drupal_goto path? Is there any way to include a # in drupal_goto?

i want something like this

function MYMODULE_preprocess_node(&$variables) {
  $node = $variables['node'];
  switch ($node->type) {
    case 'product':
      drupal_goto("products#".$node->nid);
  }
}

For Drupal 6,

It should be 3rd parameter

drupal_goto($path = '', $query = NULL, $fragment = NULL, $http_response_code = 302)

drupal_goto("products", NULL, $node->nid);

For Drupal 7

drupal_goto($path = '', array $options = array(), $http_response_code = 302)
drupal_goto("products", array('fragment' => $node->nid));


Change drupal admin password for 100 sites using drush I've a requirement to change admin password for drupal 7 sites which are over 100 and i would like to do it with drush. I know one method of doing it is updating user table with a shell script listing databases in a queue, but i want to achieve this with drush. Would be great if anyone can put me in some reference if they have any idea.

Cheers,

Swaroop.

Recover password with Drush

Drush offers several ways of recovering the administrator's password.
Generate login-link

Drush can generate a one-time login link.

drush uli

Reset password

drush upwd --password="givememypasswordback" admin

(where "admin" is the user name)

For more info visit here


How do I create a role-specific registration page? I would like to create a "hidden" registration page that I can send to our wholesale customers in order to sign up as dealers, instead of standard authenticated users.

As our dealers have access to wholesale pricing, I will require that this type of user be approved by the admin.

I will need to add a few new fields that I would only like to be shown on this dealer-specific registration page (vs. std), e.g. company, company address, POC. Do I create a new template for this form?

How can I add a Honeypot field to this form?

I suggest you to try the Multiple Registration module (https://www.drupal.org/project/multiple_registration), since this is precisely what it does "adds ability to create role-specific registration pages."

And as for the need to add the "admin approval" functionality, too, for specific user roles on your site, I would recommend you the Registration Role with Approval module (https://www.drupal.org/project/registration_role_with_approval)

Also, see if you will find this post of any help: https://www.optasy.com/blog/how-create-role-specific-user-registration-forms-drupal

Good luck!


Fatal Error when trying to log in DRUPAL My Drupal 7 website is throwing 500 internal server error, when I try to log in as Admin.

I checked the apache error log it throws below error

 PHP Fatal error:  require_once(): Failed opening required '/*****/******/sites/all/modules/context/context_ui/export_ui/context.inc' (include_path='.:/usr/share/pear:/usr/share/php') in /******/******/sites/all/modules/ctools/includes/plugins.inc on line 480, referer: http://*******/user

What could be the problem ?

Thanks

Can you confirm which version of php you are using? I just realized that the magic php constant "DIR" (which I first used here in beta4) may only work in php versions 5.3 or greater, so I'm guessing you have a version that's below v5.3.

According to the Drupal requirements, the PHP requirement for Drupal 7 is "PHP 5.2.5 or higher (5.3 recommended)", So I may have made a mistake by introducing a construct that's not compatible with some php versions that Drupal 7 still supports. I'll need to fix this, but either way if you can confirm your php version that would be very helpfu


How can I filter a view by date ranges from another content type? I am building a site in Drupal 7 that has a list of events.  I would like to be able to filter these events by specific date ranges from another content type.

I have successfully been able to set up a view that enables users to filter the list of events by a number of criteria including an arbitrary date range. That much is fine.

However, I would like to allow users to filter the events into date ranges that come from another content type.  In this particular case I want the site to show events that occur within the term of office of UK prime ministers.  I have set up a content type that has the start and end dates of the term of office of the prime ministers but I can't see how to use this to filter the events.

Ideally I would like a drop down list that allows the user to select a prime minister and this will show a list of events that occur during that prime minister's term of office.

How would you suggest that I do this?

Thank you in advance for your help.

It's not a dropdown list, but if you don't want to write code, consider the following.

Create a view of all UK PM's in a view. Rewrite the results to output links in the format: events/start_date/end_date.

On your events view (with 'events' path). Add contextual filters catching start_date and end_date.

You could make the first view a jump menu and show it as a block above your events view. This will have the same effect as exposed filters, but will be harder to combine with actual exposed filters.


Tao overriding parent reset.css file. I wish to override one of the default css files provided from the theme I am inheriting from. According to Creating a sub-theme page I need to do the following:

  Overriding inherited style sheets: Specify a style sheet with the same
  filename in the sub-theme. For instance, to override style.css
  inherited from a parent theme, add the following line to your
  sub-theme's .info file:

  stylesheets[all][]   = style.css

  You will also need to create the style.css stylesheet file; if you
  simply wish to disable the imported styles, you can create an empty
  file.

My parent theme (Tao) has a reset.css file. In mytheme I have added the following to mytheme.info

stylesheets[all][]   = reset.css

I have then create a blank file called reset.css and it is in the root of my theme. I have run drush cc all but the parent css file is still being read.

What am I doing wrong?

Tao inclueds reset for print and for screen so you should override like so.

stylesheets[print][]   = reset.css
stylesheets[screen][]   = reset.css

Using the all array will only override other items in the all array not both screen and print


How do I make block only visible if the 'field_date_value' is in the past? What code do I use on a D7 website if I want a block only to be visible if the field_date_value of a date node is in the past?

On a D6 site, I had this working for all date nodes:

$match = FALSE;
$types = array('date' => 1);
if (arg(0) == 'node' && is_numeric(arg(1) )) {
  $nid = arg(1);
  $node = node_load(array('nid' => $nid));
  $type = $node->type;
  if (isset($types[$type])) {
    $match = TRUE;
  }
}
return $match;

But this code does not work on a D7 site. Besides, all that I want is it to only show a date node when the date in the past. (For a past event.)

Pretend you need a block to be visible on a node depending on the value of a date field on the node.

A good example is a website that lists classes as nodes. You want a block visible only on class nodes. You also only want that block visible if the date of the class is in the future.

The classes are created by making nodes of a custom content type called "class". Each class node contains an date field called "class_date" that contains the date of the first day of the class. The date field is a regular ISO date field type. This PHP snippet returns TRUE if the node is a "class" and the "class_date" field is in the future and the block is then visible.

<?php
$node = menu_get_object();
if ( !empty($node)  && $node->type == 'class' ) {
  if ( !empty($node->field_class_date) && !empty($node->field_class_date['und']) && !empty($node->field_class_date['und'][0]) ) {
     $parts = explode('T', $node->field_class_date['und'][0]['value']);
     $date_parts =  explode('-', $parts[0]);
     $class_date = $date_parts[1] . '/' . $date_parts[2] . '/' . $date_parts[0] . ' ' .  $parts[1];
     $on = strtotime($class_date);
     $now = time();
     if ( $on >= $now ) {
        return TRUE;
     }
  }
}
return FALSE;
?>


How can I have a second alias for a node to be displayed in a different view mode? I have nodes whose content type is X that I would like to render differently based on the node path.  I'd like to use the default view mode for a path alias and a custom view mode for the other path alias.  These aliases were created using the Pathauto module; both of them point to the same node.

/url/alias1/path => /node/123 (default view mode)
/url/alias2/path => /node/123 (custom view mode)

I tried using mymodule.routing.yml to do this, but it does not appear to be picked up by the route system.

mymodule.program:
  path: '/url/alias2/path'
  defaults:
    _controller: '\Drupal\mymodule\Controller\RoutesController::setViewMode'
  requirements:
    _access: 'TRUE'

When I click on the alias with the custom view mode, I get the default view mode.  I put a logger statement in the routes controller setViewMode function and it is not reached. This suggests that the routing is not being 'tripped'.

Am I missing something or trying to do something Drupal 8 cannot handle?

I looked at Routing and path aliases but that doesn't quite address my question.

There are many approaches in aliasing and routing, but I think splitting the task between both is the most effective:

Add an internal node route for the second view mode:

mymodule.custom_node:
  path: '/node_custom/{node}'
  defaults:
    _entity_view: 'node.custom_view_mode'
  requirements:
    _access: 'TRUE'

Then change the source path to /node_custom/123 before Pathauto saves the second alias in hook_pathauto_alias_alter().