Uploaded images broken with secure site turned on Images I upload through CCK appear broken, the path they are referenced to is blocked with secure site.  When I view the image I am taken to the secure site login page, once I enter my login info I can view the image. But I am already logged in. The strange thing is sometimes one of these uploaded images is visible. Uploaded images have the following url structure.

All permissions are set correctly and only these images are blocked by Secure Site.

/sites/default/files/imagecache/142x142/imagefield_default_images/def_expert_4.png

/sites/default/files/imagecache/142x142/def_expert_4_19.png

sometimes one url works sometimes the other

This is because of Imagecache functionality, first URL is your actual size image, the second is your Imagecached image, Imagecache creates seperate image sizes depend on your image-styles that you defined so it can loads the proper image when you print it.

about the login issue, it must be because of your Secure Site module configuration


Are the revision settings on a content type respected when the content is changed programatically? I want to practice making some bulk updates via code, but I also want the option of reverting back to an earlier versions in case some of the changes are incorrect.

Are the revision settings respected when revisioning by default is enabled for a content type?

No, not by default, if you're using node_load() & node_save(), without any other code, it will not retrieve the content type's revision setting. For example:

$my_node = node_load(123);
$my_node->title = 'new title';
node_save($my_node);

node_save() uses the $my_node->revision property to determine if it's creating a new revision. In the above example, $my_node will not have the revision flag set from a node_load() retrieval.

If you manually set the $my_node->revision to TRUE it will do this:

$my_node = node_load(123);
$my_node->revision = TRUE;
$my_node->title = 'new title';
node_save($my_node);


Service links - Facebook "like" error I am using the Service links module in my Drupal 7 site.

When using the Facebook "like" widget, I get the word "error" (in red color), in the place where the Facebook "Like" button should be.

When clicking on the word "Error", a Facebook popup window is opened with the error like so:

  The href URL must be absolute

Note: I am using the Service links widgets inside a view. Other Services links widgets are working great, such as the Facebook share widget, Twitter, Google+ and Pinterest widgets.

What is the problem of the Facebook "like" button?

Replace this line(in sites\all\modules\service_links\js\facebook_like.js):

iframe.src = $(this).attr('href').replace('http://', '//').replace(/http[s]*\%3A\/\//, '');

with the below line:

iframe.src = $(this).attr('href').replace('http://', '//');


How to get the URL for the re sized image I have built a custom form in Drupal 7. The form has a file type field which allows the user to upload an image. I'm using the below code in the submit function to save and re size the image:

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

    $file = $form_state['storage']['file'];
    // We are done with the file, remove it from storage.
    unset($form_state['storage']['file']);
    // Make the storage of the file permanent
    $file->status = FILE_STATUS_PERMANENT;
    // Save file status.
    file_save($file);
    //get the url for the saved file
    $url = file_create_url($file->uri);
    echo $url;
    echo '<br>';

    $destination = 'public://ImageThumbnail';
    $img = image_load($file->uri);
    image_resize($img, 200, 200);
    $result = image_save($img,$destination);
    echo $result;

    exit;
  }

The image is re-sizing and saving correctly as the $result is printing 1. I need to know how to get the URL for the re sized image. Am I missing something?

Thanks for you help.

I wouldn't use your approach because as you can see by yourself now you have no reference to the resized image, what I would do is use image_style_path :

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

    $file = $form_state['storage']['file'];
    unset($form_state['storage']['file']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    $url = file_create_url($file->uri);
    // this
    $derivative_uri = image_style_path($your_style, $file->uri);
    $url = image_style_create_derivative(image_style_load('your_style'), $file->uri, $derivative_uri);
}

This creates a folder in your files folder with your style name and stores the image there, then wherever in your code you want to get that image you just reutilize this code:

$derivative_uri = image_style_path($your_style, $file->uri);
$url = image_style_create_derivative(image_style_load('your_style'), $file->uri, $derivative_uri);

Drupal checks if an image is there and gives you back the $url, if it's not there it creates the image applying your style.

P.S. you need to register your style in configuration and once the style folder is created check it's permission settings.


Bidirectional entity relationships? I am doing a migration right now and have a need to maintain how entities are related in a way that the core entity reference field does not seem to support.

Lets say I have two content types, Foo and Bar. I am migrating Foo first, and Bar gets stubbed.

I need to relate Foo to Bar, but the relationship is not one way. Bar is also related to Foo, but there is no way (when editing Bar) to see this relationship. If Foo or Bar are deleted, it needs to unlink that.

Does Drupal 8 do that yet? How would you effectively do this? Do you need to create a custom entity to hold links?

I looked at the Dynamic Entity Reference module and it does not seem to do this. I also looked at the Corresponding Entity Reference module and it looks dead with a lot of logged bugs (last release 2017).

I would use 2 entity reference field, one in each content type referencing the other. With some custom logic, you could add the desired behavior, eg remove reference Foo -> Bar when the user removes Bar -> Foo.

Regarding the migation, you can run the first migration twice with the --update flag the 2nd time:

Step 1. Migrate Foo. The migration_lookup plugin will not find any values for the entity reference so it will be empty.
Step 2. Migrate Bar. Foo already exists, you should have no problem with the entity reference.
Step 3. Migrate Foo again, with the --update flag. Bar already exists, so the entity reference field will filled.


Modifying login/user panel position in a theme For our site, we're looking at designing a relatively simple log-in widget/panel. We want it to be in the header of our site (for reference, we're modifying the excellent "Orange" Drupal theme), and we want to design it in the following way:

When a user is logged out, it merely shows the log-in form. It would sit in the upper right-hand corner, embedded in a rectangular shape.
When a user is logged in, it would show a "Welcome Back, $USERNAME$!", with an avatar, a message counter for private messages, and a few links for managing a profile, accessing a shopping cart, etc.

My question is, where do I start with all of this? As far as I'm aware, documentation for this type of thing appears to be a little bit sparse. What do I need to do in order to set up this small widget so that it:

Sits in the correct position.
Displays the user avatar, links, etc.
Replaces the default log-in form?

Do I need to go into Panels and Views and try to build a custom log-in form there? Do I need to write it all in CSS and jQuery? What's the best way to approach this?

The user login form is a core block you can position. The other bit you'll have to write in a custom module as a custom block. The menu links part should be a menu block.


How do I translate the Book module tree navigation? We only have English and Spanish translations on our website. I can easily translate each book page, but there doesn't seem to be a way to translate the book tree navigation. Is there a way to translate the book tree navigation so the links will display translated text and link to the translated pages?

I found this that outlines the path to doing this with menus in general:
https://www.drupal.org/node/2182497

After testing it appears that this does NOT work with the Book module menus. All configuration options I have tried thus far have not been successful and I'm guessing the only options left are probably a custom code alter of the book_navigation or a custom book menu all together.

Those steps would included either using the book_navigation preprocess hook:
function template_preprocess_book_navigation
https://api.drupal.org/api/drupal/core%21modules%21book%21book.module/function/template_preprocess_book_navigation/8.2.x

and/or the twig template that renders the menu:
book-navigation.html.twig
https://api.drupal.org/api/drupal/core%21modules%21book%21templates%21book-navigation.html.twig/8.2.x

Hopefully those are a good start.


Set total cart amout If the user didn't buy anything ever, at the first time he gets a 20% tax of total shopping cart amount.
I'm newbie in Drupal and can't understand how to implement it.
Say I'll do checking for first order (I imagine how), but I can't find how to change total cart amount without changing every item price.

I hope you can help me :)

The trick to this is to create a discount. Force users to register before purchasing an item and than check the order history of a user at checkout. If the user has no order history at checkout than give him a 20% discount, if not than charge retail price.

This can be achieved with

http://drupal.org/project/commerce_checkout_login
And either a custom module or rules


Create a user via the Installation profile I am using Installation Profiles to automate the process of installing Drupal 7 websites

I would like to create a user via the installation profile and assign it a username, password and email address, plus give it a role (This will be a special administrative user that I want every website to have).

How can I do this?
This is the closest tutorial I can find. However, it requires you to set a username/password and email address manually. I would like to store a default values for all these fields.

If you still want a configuration form, then you can build upon the "Client step" and change the function brochure_client_form_submit($form, &$form_state) so that it suits your needs (all code is untested):

function brochure_client_form_submit($form, &$form_state) {

  // Setup the user account array to programatically create a new user.
  $account = array(
    'name' => YOUR_NAME,
    'pass' => YOUR_PASS,
    'mail' => YOUR_MAIL,
    'status' => 1,
    'init' => 'install profile', // Just an example
  );
  $account = user_save(null, $account);
}

If you don't need a separate configuration form during install, you can define a "formless" task like this:

/**
 * Implements hook_install_tasks().
 */
function mymodule_install_tasks() {
  $tasks['mymodule_setup_admin_account'] = array(
    'display_name' => st('Setup admin account'),
  );
  return $tasks;
}

function mymodule_setup_admin_account() {
  // Setup the user account array to programatically create a new user.
  $account = array(
    'name' => YOUR_NAME,
    'pass' => YOUR_PASS,
    'mail' => YOUR_MAIL,
    'status' => 1,
    'init' => 'install profile', // Just an example
  );
  $account = user_save(null, $account);
}

You still have to create the role and add it to the created user. If you have created the role prior to the user creation, then you can also pass it directly to user_save:

$account = array(
  'name' => YOUR_NAME,
  'pass' => YOUR_PASS,
  'mail' => YOUR_MAIL,
  'status' => 1,
  'init' => 'install profile', // Just an example
  'roles' => array(
    ROLE_ID => ROLE_ID,
  ),
);
$account = user_save(null, $account);

More on install profiles: How to Write a Drupal 7 Installation Profile


Is there a fast way to see a site without the drupal admin elements? Once in a while various Drupal elements can be a real pain:

The context menu covers the search menu & prevents me from clicking into the text field
A co-worker is worried that the user is seeing things like 'Available Updates' notifications
View/Edit tabs and action links are present in screenshots

The easy answer is to log out and view the page again, but that's a pain when you just want to do a very quick thing.

What is a quick, easy way to jump in/out of Drupal?

I put together a simple javascriptlet that I can click on to show/hide most admin elements.  It is kind of a static solution (I'll need to update it periodically as new admin elements appear that need to be hidden), but it's simple.  Works with the Admin-Menu module too.

Just make a new bookmark and paste this into the 'url' field:

javascript:(function($){ if( $('html').data('drupal_clutter_hidden') ){ $('html').data('drupal_clutter_hidden', false); $('#block-search-form').css('z-index', ''); if( $('html').data('drupal_has_adv_toolbar') ){$('body').addClass( $('html').data('drupal_has_adv_toolbar') );$('#admin-menu').show();$('html').removeData('drupal_has_adv_toolbar');} else {$('body').css('padding-top', '64px'); $('#toolbar').show(); }$('.alpha-grid-toggle, .alpha-block-toggle,em.placeholder, #messages, .krumo-root, ul.tabs.primary, .region-inner > .tabs, .contextual-links-wrapper').show(); } else { $('html').data('drupal_clutter_hidden', true); $('#block-search-form').css('z-index', '100'); if( $('body').hasClass('admin-menu') ){var classes = $('body').hasClass('admin-menu-with-shortcuts') ? 'admin-menu admin-menu-with-shortcuts' : 'admin-menu';$('html').data('drupal_has_adv_toolbar', classes); $('body').removeClass( $('html').data('drupal_has_adv_toolbar') );$('#admin-menu').hide();} else {$('body').css('padding-top', '0'); $('#toolbar').hide(); }$('.alpha-grid-toggle, .alpha-block-toggle,em.placeholder, #messages, .krumo-root, ul.tabs.primary, .region-inner > .tabs, .contextual-links-wrapper').hide(); } }(jQuery));

Before:

After:


Views Block Caching issue for not logged in User We are using Drupal inbuilt caching with Memcache. Our website home page has more than 5 blocks created using Views for which we have enabled Time based caching. But the contents are not getting listing in these views even after the query caching time. Following is the views cache settings:

Query Caching : 15 mins and Render Caching 6 days
Block Caching : Do not Cache

Following is the Drupal cache settings:

Also, like to add one more point that the contents are published using Scheduler module.

I have found out the issue. Views Query caching and Render Caching are not related. If we set render caching higher than query caching then Drupal will always fetch from Render cache and hence the result will remains. So its recommended to set both as same values. I modified the same to 15mins Query caching and 15mins Render caching.


Is it ever okay to ignore a warning about an inconsistent Database schema? Can it ever be ok to ignore a Database schema = Inconsistent report?

The schema module is reporting the following mismatches:

contact

page_title: unexpected column in database
page_info: unexpected column in database

search_dataset

column type - differences on: length, default
declared: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => 16, 'not null' => TRUE)
actual: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => '64', 'not null' => TRUE, 'default' => '')

search_index

column type - differences on: length, default
declared: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => 16, 'not null' => TRUE)
actual: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => '64', 'not null' => TRUE, 'default' => '')

search_node_links

column type - difference on: length
declared: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => 16, 'not null' => TRUE, 'default' => '')
actual: array('description' => 'TODO: please describe this field!', 'type' => 'varchar', 'length' => '64', 'not null' => TRUE, 'default' => '')

It could be okay, for a time, until the module that has an out of date schema attempts to read, save, update, or delete data from an out-of-date database table. At that point, you'd get inconsistent data in your database at least, and possibly end up with a corrupted database or have your site return the WSOD (white screen of death) at worst.

The warning simply means there is at least one update that hasn't yet been run. It's always a good idea to run updates by visiting update.php or using drush updatedb whenever you update any modules or Drupal core.


how to tell which book node is the root node programatically If I have some nodes that are of type book, how can I go through them in a php script and tell which is the root?  thanks

You can try to build the menu tree for your book. Book nodes do not have direct parents. The relationship is defined by the menu structure.

This will give you the structure of the book menu.

$book = $node->book;
$tree = menu_tree_all_data(book_menu_name($book['bid']));


migrating from multiple csv files in one migration class I have multiple CSV files in different folders.
The folder names are the node ids. And each folder contains its own CSV file.
Now I want to loop these directories and import from the CSV files in one migration class but it only migrate from the last CSV  file.

Here is my code

class MigrateNodes extends Migration {
  public function __construct($arguments) {
    parent::__construct();
    $columns[0] = array('Number', 'Number');
    $columns[1] = array('Title', 'Title');
    $columns[2] = array('Description', 'Description');
    //The Description of the import. This desription is shown on the Migrate GUI
    $this->description = t('Import lots from excell file ');
    $nids = db_select('node', 'n')
        ->fields('n', array('nid'))
        ->condition('n.type', 'type')
        ->execute()
        ->fetchCol();
    foreach ($nids as $nid) {
   $path = $nid . "/nodes.csv";
      //The Source of the import
      $this->source = new MigrateSourceCSV($path', $columns, array('header_rows' => 1));
      if ($this->source) {
        $this->destination = new MigrateDestinationNode('lot');
        $this->map = new MigrateSQLMap(
            $this->machineName, array(
          "Number" => array(
            'type' => 'int',
            'unsigned' => TRUE,
            'not null' => TRUE,
            'alias' => 'import'
          )
            ), MigrateDestinationNode::getKeySchema()
        );
        //Field ampping
        $this->addFieldMapping('title', 'Title');
        $this->addFieldMapping('field_lot_description', 'Description');
      //}
      }
   }
  }
}

The Number field is unique.
Any one knows what I am doing wrong?

I have solved it.
Just place the following line after the field mappings if it is the import process.

$this->processImport();


How to reset admin password with drush and Acquia Dev Desktop? I realize that this is a pretty standard question that there is a lot of answers for elsewhere. The issue I have is that it seems that my drush commands aren't being reflected on my dev server.

I got locked out of my site, so I tried to use two methods to get in

1) drush upwd --password="mynewpass" "myuser"

and

2) drush ucrt "mynewuser" --password="mynewpass" followed by drush urol "administrator" "mynewuser"

Both command variations don't give me any errors and confirm the newly created user and his roles. Not sure what else I can do here. Before you ask, yes, I'm flushing my caches.

I'm not sure why it's failing for you.
Probably check the error logs to see if there are any warnings or notices being logged there.

The latest versions of drush have drush uli which just gives you a one-time login link for admin.

$ drush uli
http://default/user/reset/1/1311169130/gf-1uDYC51jONONNF-jq3_ciKfLqhE93SsS9YNAnaEY
Unfortunately it doesn't get the hostname right in most cases (probably there's no way to know it if base_url is not set) so you have to change "default" correct hostname.

So in the case above, I would paste the link into a browser and then change it to

http://example.com/user/reset/1/1311169130/gf-1uDYC51jONONNF-jq3_ciKfLqhE93SsS9YNAnaEY
There I have a one-time login link to user 1 on the site. Works flawlessly.

You can also run drush as admin by adding this:

drush -u 1 "command"

Eg:

drush -u 1 cc all


Feed imports don't seem to trigger The Feeds module is still in development for D8, but I'm trying to test it. I can set up Feed Types, but the actual imports do not seem to trigger.

Does anyone know how to do this on Drupal 8?

1. Go to Administration > Content > Feeds (http://www.example.com/admin/content/feed)

  2. Add a Feed (http://www.example.com/feed/add).

  source: https://www.drupal.org/node/2604358#comment-10865318


How to collect and publish input from user, using webform and views? I want to build a form, with a lot of fields that can collect data from a lot of users.
than, I want to have the option to play with this data and publish it through views (with sorting options).

How to do that (general steps)?

This is what it tried so far:

I built a new content type, with a few specific fields, that allow me to publish all the data in a lot of ways through views. but, I don't know how to make a form from this content type and these fields, in order to allow anonymous and other users to insert data.

and if I use webform module, I can collect data from users, but I don't know how to publish this data through views (if this possible at all).

For web-form refer to the link http://www.cmsquickstart.com/blog/build-styled-user-feedback-form-webform-drupal-7

And for view you can create node pages and give the permissions to the user to be able to create the node page....


field collection v seperate content types For my property management admin application I want to assign charges of different types to the properties being managed (e.g. service charge, utilities bill, maintenance costs etc.). So each property on an estate will have many charges associated with it.

In my original spec I have a table for properties/flats and an table for charges that records a foreign key from the property table in order to associate a charge with a property.

New to drupal I implemented this by creating a content type for properties and a content type for charges with a entity reference field to record which property node is related to which charge node. Next I will look into building a form that allows me to fill fields from more than one node at a time and some code to grab the correct property and autofill the entity reference field when adding a new charge by selecting say. 'add charge' from a page that lists properties.

Now I have doubts. I could also create a field collection with all the fields required for a charge (type, amount, date, comment) and allow unlimited values for this field collection. As this field collection is stored as an entity, doesn't this do the same thing as above without having to use the entity reference field and so avoiding some of the coding? Also, if I wanted to add a charge to many apartments at the same time, wouldn't it be simpler using a field collection?

I am too new to drupal to understand the difference. I now it is related to what I want to do with the data after it is stored (it should be available for use in calculated fields, to be listed with data from other nodes, searched for by charge type, for instance) but I don't know how to know which is better without building it twice!

Good question, but hard to answer. I can't tell you what to choose but I hope my thoughts will help.

If I understand your needs correctly, Field Collection definitely has some advantages. Firstly, field collections are purpose built to be related to other entities. Each field collection entity is always related to one (and only one) node. That seems so match your use case, although I wouldn't know how if it's easy to add multiple field collections to multiple nodes at once. In my experience, field collection provides a pretty smooth way for site maintainers to add new data, so that's good.

The downside of field collections is that many contrib modules are still node-centered. For every site you build, it's hard to predict which problems you will be solving or which features you will be adding 6 months after the launch. If you decide to use field collections, you may find yourself in a situation where you want to add something that would have been really easy with nodes.

Since you're exploring different solutions, maybe you should also look at Drupal Commerce, if only for inspiration. It's a really flexible system which adds line item entities to orders more or less like you want to add charges to properties.


Create a custom template for displaying a custom content type - and Views in Drupal 7 I'm creating custom templates for my Drupal 7 site. There is a custom content type called flowers.

Which template file (.tpl.php) should I put under templates directory of my theme's folder for displaying a single flower-type node?
Can I use the Views module to create different views (i.e displaying picture of a flower in a view & displaying species of the flower in another view) for displaying only a single flower-type node? So far I can create pages that displays list of flower-type nodes. I want to display just a single (perhaps providing it's node-id) flower-type node. How do I do that?

2.1. For displaying different types of views to display a single flower-type node, which template files (.tpl.php) should I edit?

Thanks in advance for caring :)

Create node--flowers.tpl.php, put the default code from modules/node/node.tpl.php, and edit it.


Howto limit access to a main menu link using drupal 7 api in my scenario I am using Drupal 7 with the ubercart modules. I like to add a link in my main menu that is only visible if you are an authenticated user.

For testing purposes I am using the bartik theme.

It is the same function like user/login, which is only visible if you are an anonymus user.

I found some hints and even examples in the drupal api - like

https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_menu_alter/7

The following implements hook_menu_alter to remove access to the "forum" tab for the anonymous user:

/**
* Implements hook_menu_alter.
* Check access for forum menu item.
*/
function MYMODULE_menu_alter(&$items) {
$items['forum']['access callback'] = '_accesscheck';
}

/**
* Callback to disallow access for the anonymous user.
*/
function _accesscheck(){
  global $user;
 return $user->uid;
}

Even after many attempts, I can't catch a value for $items, I was using main_menu.

I like to use the function in the theme template. How can I find the variables that I need to alter one item of my menu - I called it > cart <.

I even tried to print_r($items), but nothing was found.

How can I retrieve $items for the main menue

hook_menu_alter only gets executed when you clear cache or rebuilding menu. I would suggest if you want to debug the $items variable, What I used to do
is do print_r($items) and die() after that. Then I would try to clear the cache from the admin UI or save it into watchdog for debugging.


javasript invoking custom module to update user response I have created Multiple choice questions in drupal . One node (page ) has one mcq . The answers are displayed by simple radio buttons and javascript .
Now  I am planing to give some dynamic behavior to users . When a user click the wrong option , I want to capture the response in a custom table in drupal , having userid , nodeid .
can I invoke a custom module by the present javascript  which gets the userid and nid and update the table . I did some  research , and found that form hook is the way to do such things ,But i have hard time understanding this. Can someone please give me right direction .

Thanks a ton !

So, lets start from the top.

You have a table with userid, nodeid, responseid declared in a hook_schema. This will create the table.

Then, you declare with hook_menu a callback to capture incorrect values and db_insert them into the table.

Then, on the form page with the multiple choice, you extend the behaviour that if the answer is incorrect upon click, it makes an ajax request with the item selected and the node id to the callback, and the callback will determine the user from the current user session, and store it in the table.

So for the content type, you will probably have a multifield for the potential answers, and a single field with the relative id for the correct answer. So if the content creator creates five answers, and the first item is the correct item, a hook form alter will need to extract and #attach the correct answer so that the behaviour on the page can pick it up, use it to determine which of the items is the correct one, extract the field id of the incorrect items and then ping it to the server.


How can I hide a field with Views if another field has a certain value? In my Drupal 7.8 website (with the Views and Panels modules installed), I'm trying to display a view pane in a panel. However, I only want to show certain fields in that pane if another field has a certain value.

Example: I display fields Foods, Healthy, and Unhealthy from a node using a custom view pane. But I only want to display fields Healthy and Unhealthy if field Foods (which is a multi-select field) contains the value "Cheetos"

Does anybody know how I can do this with a plugin or with views default functionality?

Solution1:
You can add filter in view by selecting and restricting the value of "Foods" field since if foods has the selected option then only it will display the results.

Solution2:
Just add one more field with php custom field(use views customfield module) and exclude display of all other 3 fields. In this php field you can get all the previous field values in $data variable so you can print the result as you wish by validating using php.

Hope this can help you out!


How do I check if the form is an add/edit/delete form? I need to check if the form is for creating, editing, or deleting a node.

Currently, the below snippet allows me to check if the form is for adding or editing a node. How do I check if the form is for deleting a node?

    if (!isset($node->nid) || isset($node->is_new)) {
      // The form is for creating a new node.
    }
    else {
      // The form is for editing the node.
    }

You could use what said in this answer, with a slight modification.

function example_form_alter(&$form, &$form_state, $form_id) {
  if (strpos(request_path(), '/add') !== FALSE) {
    $page = 'add';
  }
  elseif (strpos(request_path(), '/edit') !== FALSE) {
    $page = 'edit';
  }
  else if (strpos(request_path(), '/delete') !== FALSE) {
    $page = 'edit';
  }
}


How to 'store' email templates in the site? On certain events, defined in code, specific mails are sent to certain users in the site (such as on node_save if some value has changed etc).

The content managers need access to those mail templates in order to be able to change literals.

I've thought about having the mail's body inside the node as a field with a 'dummy' default value, but that seems a bit crude. Is there a better way to have my mail templates stored somewhere in the site and access them from code?

It all depends on usage patterns of that feature.

For example if you only need one master template and edits are global (e.g apply to all events) then the "correct" storage could be inside the variable table.

You can expand on the above design by suffixing those variable keys with the node type (or whatever differentiates one template from another). So you could have entries such as:

mail_template_event
mail_template_publication
mail_template_press_release

or in the case of "typed" events:

mail_template_event_internal
mail_template_event_external
mail_template_event_generic

Keeping the mail template on a node field will be easier in terms of programming though. Because if you fetch the template from an "external" source (such as the variable table) you'll need to handle presentation within the node edit screen and update of the template in case it was altered.


Authenticated users can't edit their own content even with permissions set accordingly As an authenticated user, I've created a node. The Tasks menu is completely absent. If I try to access it via node/476/edit, I see "Access Denied".

The Task menu (edit, view, revisions) is seen by the Administrator but Authenticated users. How can I bedug this further?

However, I have permission set for this Content Type as follows below. I've included another Node TYpe called Event as well.

I even tried looking into the table node_type to see if anything was off

       type: user_posted_content
       name: User Posted Content
       base: node_content
     module: node
description: Postings by users
       help:
  has_title: 1
title_label: Title
     custom: 1
   modified: 1
     locked: 0
   disabled: 0
  orig_type: user_posted_content

Other Modules
I previously had tried both Content Access (content_access) and Node view permissions (node_view_permissions) but ended up deactivating both.

Digging deeper
It appears I may have some residual from one of those modules.

MariaDB [s7data]> select * from node_access where nid = 476;
+-----+-----+-------+------------+--------------+--------------+
| nid | gid | realm | grant_view | grant_update | grant_delete |
+-----+-----+-------+------------+--------------+--------------+
| 476 |   0 | all   |          1 |            0 |            0 |
+-----+-----+-------+------------+--------------+--------------+

You don't need to restore your database, you only need to enable your nodeaccess module in your modules page and it should restore on its own and you will have access to all stored data. Then go to nodeaccess config, undo all the restrictions, save, then go back to modules page and uninstall nodeaccess. And rebuild permissions. Hopefully that'd do the trick!


OWASP security and drupal Recently, To improve our site security we implemented and enabled OWASP security in our server using mod_security.

After we enabled the OWASP security, whenever I try to create or edit contents in my site after logging in as admin, It is showing it as SQL INJECTION and it does not allow to crate or edit new node.

When I edit content it redirects me to "/node/1078/edit"  and then it shows error

"Error
The website encountered an unexpected error. Please try again later."

I also tried to find solution here but so far nothing helps. We have used drupal database API for all our database operations. I am not sure why OWASP is showing "SQL INJECTION".

How can I fix this?

It would appear that OWASP think your site is vulnerable to SQL injection. You'll need to find the exact reason yourself (it requires debugging with the site in front of you), but here are some pointers:

Make sure your core version is >=7.32. There was a massive SQL hole in Drupal before that update.
Once that's confirmed, start disabling custom and contrib modules one-by-one, checking the edit form each time. If one of those is to blame, that simple process will find it. If you find a contrib module that's to blame, be sure to open a bug report on Drupal.org.
If your Drupal core version is up to date, and none of the custom/contrib modules are responsible, you'll need to contact OWASP to ask them for their criteria, and how they've arrived at the conclusion that your site is vulnerable.
On the off-chance they respond by pointing out another SQL injection vulnerability in Drupal core (very, very unlikely), be sure to report it to the security team. Same thing for contrib modules (more likely).


Why does jQuery slideToggle revert back to initial hidden state after running? I have a Superfish menu and a simple jquery slideToggle animation attached to each menu item. I am using Drupal 7 & the Superfish module.

The idea is that on click it will show the body content of the site which is initially being hidden. All seems to work fine the click event fires the toggle but after the animation is done, it quickly reversed the animation back to the initial hidden state.

Doing this is seems pretty trivial with straight HTML / jQuery. But it's not quite working within my Drupal theme.

Here is my jQuery:

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

$('#content').hide();
$('.sf-depth-1 a' || '.sf-depth-2 a' ).bind(
    'click', function() {$('#content').slideToggle('slow');}
     ) // /click
    }   // /attach
}; // /Drupal Behaviors
})(jQuery);

I am fairly new to working with jQuery. It seems like the answer is pretty simple, but I am not sure how to set this up.

Any suggestions?

Try this code below.

$('#content').hide();
$('.sf-depth-1 a' || '.sf-depth-2 a' ).click(function() {
  $('#content').toggle('slow', function() {
    // Animation complete.
  });
});


Nested select with Drupals DataBase interface I have the following SQL query and need to translate it to the drupal API:

SELECT
  *,
  (SELECT COUNT(*)
    FROM newsletter
    WHERE email = pupils.email
  ) AS newsletter_flag
FROM
  memberdata.pupils
LEFT JOIN
  memberdata.pupil_profiles
ON
  memberdata.pupils.id = memberdata.pupil_profiles."pupils.id"
WHERE
  pupils.status != 'u'
ORDER BY
  pupils.timestamp DESC
LIMIT 10;

Background: There is a table with pupils (some basic info including mail adress) and a table newsletter containing the email addresses of pupils that registered for the newsletter. I need a list of all pupil with their fields and additionally the field newsletter_flag, indicating if the pupils email adress is in the newsletter table or not. Additionally I need a join to another table with primary foreign key. I've come this far:

$query = Database::getConnection('default', 'for_migration')
->select('memberdata.pupils', 'pupils')
->fields('pupils', array('id', 'firstname', 'lastname', 'birthday', 'gender'))
->condition('status', 'u', '!=')
->range(0, 10)
->orderBy('pupils.timestamp', 'DESC');

$alias = $query->leftjoin('newsletter', 'nl', 'pupils.email = nl.email');
$query->addExpression("COUNT($alias.email)", 'newsletter_flag');

But it does not what I want (the pupil_profiles join is still missing of course, but the newsletter flag is the bigger problem I guess). The source database is a PostgreSQL one and the query itself is part of a Migration subclass, in which a MigrateSourceSQL is used as source. Therefore the query needs to be a SelectQueryInterface.

Ok, figured it out but do not like it:

$query = Database::getConnection('default', 'for_migration')
   ->select('memberdata.pupils', 'p')
   ->fields('p', array('id', 'firstname', 'lastname', 'birthday', 'gender'))
   ->condition('status', 'u', '!=')
   ->range(0, 10);
$query->addExpression("(SELECT COUNT(*) FROM newsletter WHERE email = p.email)", 'newsletter_flag');

There should be a smoother way for the newsletter_flag problem.


Body field not saving it's summary data I've inherited a Drupal 7 site that was built in 2014. We've noticed that the body field (on any content type) has a summary textarea, but it does not save data upon submission.

Also, in comparing with other D7 sites that we have, I find it odd that on this site the Body field is assigned a 'Long text' field type whereas normally the body field uses a 'Long text and summary' field type.

Also of note, the 'Summary input' check-box on the content type setting page (/admin/structure/types/manage/page/fields/body) does not exist.

Any ideas on how to debug this issue?

Change the body field widget to Long text and summary


Clean URL leads to duplicate URL after migration to another hosting I have enabled clean URLs on the site after various article has been published on the site.

But when I migrate from Bluehost VPS to Bluehost Share hosting, the clean URLs is not accessible again. And when I remove ?q= I will see the enable box, and it has lead to duplicate URL on articles on the site.

To correctly enable/configure Clean URLs, refer to Configure Clean URLs in the installation guide.

If you're not familiar with Clean URLs yet, I suggest to review that documentation in the installation guide carefully (for the version of Drupal that you're using) and make sure your server is correctly configured before proceeding.

Here is a summary of common steps/issues:

With Apache HTTPD as web-server, you have to enable mod_rewrite and configure the necessary rewrite rules in the .htaccess file.
Usually, theses rules are applied automatically, when mod_rewrite is enabled. But in some cases, the AllowOverride directive is too restrictive to allow this.


Value of the input is not preserved when it is an HTML array Suppose, we have a form, containing 3 elements:

Checkbox with special name 'name[attached]', indicating that it is a part of an array of checkboxes.
Text input
Submit button

Code

function bundles_test_form($form, &$form_state)
{
    $form['name[attached]'] = array(
        '#type' => 'checkbox',
        '#required' => false,
        '#attributes' => array('name' => 'name[attached]'),
        );

    $form['date'] = array(
        '#type' => 'textfield',
        '#required' => false,
        );

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

    return $form;
}

function bundles_test_form_validate($form, &$form_state)
{
    if (isset($form_state['input']['name']['attached']))
    {
        if ($form_state['input']['date'] === '')
        {
            form_set_error("date", 'date is required');
        }
    }
}

Question

When the form throws an error, the checkbox must be checked, but it is not. When I change the name to "name" or anything that it not the array, it works correctly. So the error is caused by the non-standard name of the input.

IMO this should work

    function mm_definition_of_the_form($form, &$form_state) {
      //other code
      $form_state['rebuild'] = TRUE;

      if (isset($form_state['check_field'])) {
        //set default value of the field
      }
    }

    function mm_definition_of_the_form_validate(&$form, &$form_state) {
      //if is error
      $form_state['check_field'] = TRUE;
    }


User automatically redirected to main language page In my website I have the users automatically redirected to the main language page.

If for example: node/2 is the translation of node/1
when I type: www.mywebsite.com/node/2 I'm immediately redirected to www.mywebsite.com/node/1

Note that it happens only for the anonymous users

What's that?
How could I check which module is redirecting the user?

You can check your admin's modules page, for some module related to translation or the locale module.

But some modules can cause this behavior, such as Translation redirect module, part of the Internationalization (i18n) package.


How do I strip spaces from a Twig variable? Example code I'm working with:

<a{{ attributes.addClass(classes, 'field__item') }} name="{{ item.content }}">{{ item.content }}</a>

In this example, I have created a Brick with a field called anchor_id. The idea is that content creators can name an anchor whatever they want, and then add that brick to a page.

I can get the field to show up fine. But, I'd like to strip out spaces so if they enter "my awesome tag" it instead gets rendered as name="myawesometag.

I've tried a few methods, but can't seem to figure it out. Seems like it would be some simple filter, but if it is I'm not seeing it.

Thanks in advance!

You can use "replace" - much like you would in PHP - and replace the space with no space

{{ anchor_id|replace({' ': ''})

More info: https://twig.symfony.com/doc/3.x/filters/replace.html


How to get a specific field in a table layout in Views templates This is my first time using a table to display a Views template. How do you access a specific field so you can reorder them one by one yourself? I have 3 fields I want to place but I want one of the fields field_house to come out first, followed by field_door and field_table. I'm also asking so I can wrap each one in their own class making it easier to layout.

@Chaulky it should be pretty easy to make the changes suggested by @enhance.

Take the views table template and copy it to your theme.
Make the edits to your copy of the template as per @enhance's directions.
Since you mentioned adding classes, you could either add the classes in the template or in the views interface.
Save it as views-view-table-YOUR_VIEW_NAME.tpl.php.
Clear caches, at least twice if once didn't do it.
Continue theming and enjoy.


How to use subquery in views where clause In my project user can created by profile2 module. When user is created i am assigning some role,initially user is block state. I have another user role ie.user app rover  who can approved these user and send activation link for active user.

I am using Mail Logger module for saving sending mail
Now i have created a view for user unapprove list

    SELECT users.name AS users_name, users.uid AS uid, users.mail AS users_mail,
    profile_users.pid AS profile_users_pid, users.created AS users_created, 'profile2' AS
    field_data_field_cc_first_name_profile2_entity_type, 'profile2' AS
    field_data_field_cc_address_office_profile2_entity_type, 'profile2' AS
    field_data_field_cc_designation_profile2_entity_type
         FROM
         {users} users
         LEFT JOIN {profile} profile_users ON users.uid = profile_users.uid AND
         profile_users.type IN ( 'company', 'goverment_profile' )
         WHERE (( (users.status = '0') AND (users.login = 0) AND (profile_users.type IN
            ('company', 'goverment_profile')) ))
            ORDER BY users_created DESC
            LIMIT 10 OFFSET 0

Hear i want to add sub-query in where condition
user those already send activation link who will not list in view.

My other table is mail_logger.

Is there any module by which i can use sub-query in where condition?

Just ran into the same question, here is what I found:

You can add a sub query to your view using the hook_views_query_alter hook in a custom module (documentation). Inside the module you should add something like the following:

function your_module_views_query_alter(&$view, &$query) {
  if ( $view->current_display == '[display in question]'){
    $query->add_where_expression([group], [sub query]);
  }
}

documentation for $query->add_where_expression.  You can add whatever where clause you need using this function.

hook_views_query_alter should go in your_module.views.inc.  Make sure you declare hook_views_api in your_module.module, otherwise views wont know to look for the file. For example:

function your_module_views_api() { // declare your views api # here
  return array(
    'api' => 3,
  );
}


Link to content in views doesn't translated to fr I made a content ( type = article).
I made a view ( list of articles) and i add link to content.
I activate fr language in the site => so

www.example.com/liste-des-articles => english page.

www.example.com/fr/liste-des-articles => french page.

My problem is the link to content doesn't work correcly in french => when i click to it => redirection to english page.

what shall i do ??

Thanks for the response.

One way to solve this would be to construct the "Link to content" field on your own, using Views. You will need to:

Add 2 fields to your view:

a "Content: Node ID (Node ID)" field
a "Content: Translation language (Translation language)" field.

Exclude the "Content: Node ID" field from display.
Rewrite the "Content: Translation Language" field as a custom link.
The text in the "Rewriting" would look something like this:
Link path: {{ langcode_value }}/node/{{ nid }}

Hope this helps!


Clear region with menu's per url cache I have a region with menus, a menus displays depending on the url example if on the about page(sitename/about-us), display about menu and links as a sub menu.

It works, but the problem is after navigating through the site a couple of times, the region caches. is the anyway i can clear the regions cache on page reload.

I tried the below in my .theme

   /**
   *  Implements hook_preprocess_HOOK() for block.html.twig.
   */
  function themename_preprocess_block(&$vars) {
    //the menu block id name in the region
    if ($vars['derivative_plugin_id'] == 'submenu') {
      //-- This stops the block being cache in drupal 8
      $vars['#cache']['max-age'] = 0;

    }
  }

also tried

  /**
   * Implements hook_preprocess_HOOK() for block.html.twig.
   */
  function themename_preprocess_block(&$vars) {
    if ($vars['derivative_plugin_id'] == 'theme-block-branding') {
      //-- This stops the block being cache in drupal 8
      $vars['#cache']['max-age'] = 0;
    }
  }

not sure what steps I can follow to achieve the above

Add code below:

class MYCUSTOMBLOCK extends BlockBase {
  public function build() {
    return array(
      '#markup' => '', // the content of your block
    );
  }
  public function getCacheMaxAge() {
   return 0; // No caching gets applied here
  }
}


Form Ajax submission: erratic behavior I'm experiencing a weird behavior with an ajax form submit that I cannot find an answer to.

This is my first attempt at making an ajax form so bear with me if I'm making a rookie mistake somewhere.

namespace Drupal\MYMODULE\Forms;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\HtmlCommand;

class InputForm extends FormBase {

  public function getFormID() {
    return 'authForm';
  }
  /**
   * Implements \Drupal\Core\Form\FormInterface::buildForm().
   */
  public function buildForm(array $form, FormStateInterface $form_state) {

    $form['#prefix'] = '

';

    $form['key'] = array(
        '#type' => 'textfield',
        '#title' => t('Key'),
        '#size' => 10,
        '#name' => 'key',
        '#required' => TRUE,
        '#attributes' => ['id'=>'key','name'=>'key','class'=>array('input-sm')]
    );

    $form['code'] = array(
        '#type' => 'textfield',
        '#title' => t('code'),
        '#name' => 'code',
        '#required' => TRUE,
        '#attributes' => ['id'=>'code','name'=>'code','class'=>array('input-sm')]
    );

    $form['form_submit'] = array(
        '#type' => 'submit',
        '#value' => t('submit'),
        '#name' => 'submit',
        '#ajax' => [
            'callback' => '::test',
            'prevent' => 'submit',
            'progress' => []
        ]
    );
    return $form;
  }
  public function validateForm(array &$form, FormStateInterface $form_state) {

      if (strlen($form_state->getValue('key')) < 10) {
        $form_state->setErrorByName('key', $this->t('Key is too short'));
      }

  }

  public function submitForm(array &$form, FormStateInterface $form_state) {
    // Handle submitted form data.
  }

  public function test(array &$form, FormStateInterface $form_state) {
    if($form_state->hasAnyErrors()) {
        $form_state->setRebuild(TRUE);

        return($form);
    }

    $response = new AjaxResponse();
    $response->addCommand(
        new HtmlCommand(
            '#testdiv',
            '
HELLO
'
        )
    );
    return $response;

  }

}

So the erratic behavior is in the validation of the form. What is happening is when I click the submit button (with no values in the input fields) the ajax fires and through var dumping I know the $form_state->hasAnyErrors() returns true but the form rebuild that is returned is not modifying the form highlighting the fields with errors as expected.

So after spending a couple hours trying to sort out this issue I got frustrated and mashed the submit button over and over again in a rage and low and behold it did what it's supposed to do after about eight clicks.

So then I tried to narrow down how many times it would take hitting the button before it would work correctly and it would always happen at random clicks. Sometimes after 2, sometimes after 3... sometimes after 10.

I'm stumped as to why it doesn't happen each and every single time the button is clicked rebuilding the form properly with errors.

Of Note:

Have tried removing the prevent key
Have tried with Bartik theme with same results
Have tried setting an ID on the submit button but then ajax doesn't fire
Have confirmed that the form does have errors
Have input values into the fields (key value shorter than 10) and the same
behavior happens in the validateForm() function

If anyone could point me to what I could be doing wrong I'd very much appreciate it. Thanks in advance!

Edit for visual example:
Gif showing behavior

What you can see in the Gif looks more like the validation of the form in javascript not in ajax.

Normally you decide in the submit button by including the option 'wrapper' => 'ajax-wrapper-id', if you want to use the wrapper method and return in the ajax callback the new version of the form or parts of it, or use the response method and build an ajax response in the callback. Doubt that you can mix it like this.

If you use the wrapper method you don't need to rebuild the form, because it is already rebuilt, when it reaches the ajax callback.


What is the most robust way to assert for a validation error? I want to test the validation function in my custom module, and so I've written a simpletest that inputs an illegal value in a field and then attempts to save the node. Currently I'm using assertText() to find the string contained in the validation failure message on the page, but if someone changes the wording of the failure message in the future, this could break. Is there a more robust way to check that a field, or even a node save generally, failed validation?

Since you are talking of custom validation, if the code is using form_set_error() or form_error(), then there should not be any problem, if the test code and the form validation handler use the same string (which is passed / not passed to t() in both the cases).

Keep in mind that the modules enabled during a test execution are Drupal core modules enabled from the profile used for the tests, or modules explicitly enabled from the test class. The error message output from your form validation handler is not altered, if the modules enabled from the test class don't alter it.

An alternative method of checking if a validation handler returned an error would be setting a global variable, for example; that is something Drupal does, but only from a module that is used only for testing, not a module that is normally executed. For example, entity_crud_hook_test_comment_delete() (the implementation of hook_comment_delete() done from the Entity CRUD Hooks Test module) uses a session variable that is set when the hook is invoked.
Notice that this is what Drupal normally does to verify a hook is effectively invoked when it should. When you need to verify if a form validation handler returned an error, I would rather use the method you are using, since:

It doesn't require the form validation handler to know if it is being executed during test, or not
It doesn't require the use of a test module

There are some cases where a module needs to be created with the only purpose of testing something, but that is not generally the case of verifying a form validation handler effectively returns an error when it should.


In code alter user registration and override approval to no approval required In my module I want to override the approval for certain users so that they are immediately approved and get the corresponding email.

The module looks at the subdomain to decide if approval is required. If it is, then the register-with-approve email should be sent. If no approval is required, the account should be activated and the no-approval-required email should be sent.

I have looked for hooks that I could use for this, but haven't got anything working yet. I'm using Drupal 7.

I suggest you to code this directly in your module :

use _user_mail_notify()


How to include a PHP Framework / Library in my module? I wanted to include PHPExcel.php in a testing module. So I put this file and the rest of the lib into:
sites/all/libraries/phpexcel/
and I used this in my module:

function mymod_libraries_info() {

$libraries['phpexcel'] = array(
'name' => 'PHP Excel',
'version arguments' => array(
  'file' => 'PHPExcel.php', // Could be any file with version info
  'pattern' => '/Version (\d+)/',
  'lines' => 5,
),
'files' => array(
  'php' => array('PHPExcel.php'),
),
);
return $libraries;
}

But after a:

$objPHPExcel = new PHPExcel();

I get a:

  Fatal error: Class 'PHPExcel' not found in sites/all/modules/mymod/mymod.module on line 81

Should be an easy inclusion somewhere? But where and how?

I found a composer.json as well along with the PHPExcel Lib - should I rather try to install composer_manager and try to get the composer installation working?

Thanks in advance

Your file path is maybe incorrect. Try the code below:

function mymod_libraries_info() {

    global $base_url;
    $path = $base_url . '/sites/all/libraries/phpexcel/PHPExcel.php';

    $libraries['phpexcel'] = array(
        'name' => 'PHP Excel',
        'version arguments' => array(
            'file' => $path,
            'pattern' => '/Version (\d+)/',
            'lines' => 5,
        ),
    'files' => array(
       'php' => array('PHPExcel.php'),
    ),
);
return $libraries;
}


Unable to Get Image to Un-Cache I've replaced an image on my home page with another image. I've verified that the new image is there (with the same name as the old image). And it's the only copy. I've run cron and cleared caches multiple times but the old image is still showing!

I'm using the following modules:
Advagg
Global Redirect
Cache Expiration (File update set under File Actions)
Elysia Cron
Boost
Boost Crawler
HTTPRL
Metatag
Metatag: Views
XML Sitemap

Anyone know what might be causing the problem?

Ok, well, I don't know what the problem was. I tried everything I could think of (see above). So I just changed the name of the image in 'default/files' and changed the name of the file in the link to it in the block. Now it's showing correctly.


Sending form to mail from custom module fails without error I've created a module with a form and a block.
When I push the subscribe button, the submitForm function is executed.
The successmessage is shown, but no e-mail is send ...
There are no errors reported in the recent logmessages or in on the server in the folder /logs.
public function submitForm(array &$form, FormStateInterface $form_state)
    {
        /**
         * @var MailManager $mailer
         */
        $mailer = \Drupal::service('plugin.manager.mail');

        $email = $form_state->getValue('email');
        $params['context']['subject'] = "Subscribe newsletter";
        $params['context']['message'] = 'Someone subscribed: ' . $email;
        $params['email'] = $email;

        try {
            $response = $mailer->mail('my_module', 'subscribe', 'to@email.com', 'nl', $params);
            if ($response) {
                $this->messenger()->addStatus($this->t('You are successfully subscribed to our newsletter with your e-mail: @email', ['@email' => $email]));
            } else {
                $this->messenger()->addStatus($this->t('There was an error.'));
            }
        } catch (MailHandlerException $e) {
            \Drupal::logger('mailinglist_send_mail_error')->notice('
' . print_r($e, true) . '
');
        }

    }

Did you implement hook_mail in your module? – Alfred Armstrong
where to place the hook_mail function? – Lance

Goes in the .module file. Ex: my_module.module
/*
* Implements hook_mail().
*/
function my_module_mail($key, &$message, $params) {
  switch($key) {
    case 'my_module':
      $options = [
        'langcode' => $message['langcode'],
      ];
      $message['subject'] = t('@title', ['@title' => $params['context']['subject']], $options);
      $message['body'][] = t('@body', ['@body' => $params['context']['message']], $options);
      break;
  }
}

Flush all caches so hook gets picked up.


How to perform a redirect to custom page after node save or delete? What I'm trying to do doesn't work, I still get redirected to /node/{id}:

function hook_form_alter(&$form, $form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'callback_set_redirect';
}
function callback_set_redirect($form, FormStateInterface $form_state) {
  $form_state->setRedirect('custom.landing.page');
}

Basically the code will work for submit action alone, but drupal node save form have many actions, I think you would have logged in as admin and trying it, then follow the code below.

if you want this to be work for other actions too, That means login as admin and see the node save button, you will have select option "save and publish" , "save and unpublish". as mentioned

use Drupal\Core\Form\FormStateInterface;

//hook_form_alter
function hook_form_alter(&$form, $form_state, $form_id) {
  foreach (array_keys($form['actions']) as $action) {
    if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
      $form['actions'][$action]['#submit'][] = 'callback_submit';
    }
  }
}

function callback_submit($form, FormStateInterface $form_state) {
  $form_state->setRedirect('custom.page');
}


Disable 1 step for one time login Is it possible to disable the page of one time login which can be accessed from the reset user password URL sent to the mail:

  www.example.com/user/reset/1234/1429007410/5H-zpRSsUsNNdiiFMZeaIZVthjO4uJjjrsVJ8Jg75Ys

and send the user directly to logged in edit profile page:

  example.com/user/1234/edit?pass-reset-token=fNWPgVXjnHocvcT3mWxp38vOCuLpz1e5lErOCCDGTe0

so we can make it 1 step instead of 2 steps and consider the user clicked the login button from the page 1 which can be dispensable !?

I found simple solution with this module Simple Password Reset


Page Manager URL arguments This seems like it should be simple, but I can't figure out how to get Page Manager and Pathauto to play nice together.

I'm trying to use Page Manager/Panels for a set of pages of a specific node type.  If I use the built-in (System) "node-view" page, the URLs work fine...

/content/nice-clean-node-title

But if I try to create my own Pages, I'm forced to use the node id as an argument?

/content/1

When you get to the arguments for a URL, there is no option to use node title.

My question is... how do I create variants within Page Manager that deliver node content in different ways based on a (clean) URL...

/content/some-node-title/overview

/content/some-node-title/detail

/content/some-node-title/specs

etc.

Am I missing something?  Or is this really difficult to achieve with Drupal?

Node titles are not unique, so they cannot be used directly. You need to create page with nice, machine-readable, numerical ID, and then assign it it's own URL Alias. Works similar in Drupal from 5 to 8 as far as I know, menu names might be a bit different, that's all.

Pathauto is nice automation for aliases, but only on nodes. There was already similar, but not identical question with some answers.


Instructions to install a ready-made site in localhost I am trying to install a ready-made instructional site on my local Linux webserver.
How should I proceed?

Thank you J.Reynolds for answer.

Please understand that after I posted question I did some homework and read the article you mention, that is why I am editing question.

mod-rewrite is enabled and so is AllowOverride, the site is correctly chowned and I opened the perms to 777 to get it going, I will correct that later.

I imported the db and edited settings.php to "glue" files and db, basically I replicated the settings of another settings.php file from a site that I created from scratch and virtualized same as this one, the differences are only the site customizations of course.

I entered correct $base_url.

The site is still failing and here is the error message:

  "The specified file temporary://fileK7hduG could not be copied,
  because the destination directory is not properly configured. This may
  be caused by a problem with file or directory permissions. More
  information is available in the system log."

This message keeps repeating for 6 times with different temp files.
I looked at the apache2 log and there is nothing useful there.
I cannot figure out how to launch this site correctly.

You need to tell Drupal where the database is that you imported.

Make sure to copy default.settings.php in sites/default to settings.php (if it does not already exist, in which case you can skip this step.).
Edit $databases array (lines 213 or so) in setttings.php. You should add the username and password of a user with full privileges on your MySQL installation (usually it will be user root, with password root).

For instance:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => 'NAME OF DATABASE YOU IMPORTED',
      'username' => 'USERNAME',
      'password' => 'PASSWORD',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
);

You should now browse to admin/reports/status which, will give you instructions to change file permissions for settings.php so that it is not publicly writable, and maybe to run Cron or Drupal updates.

Please also look at Migrating a site for more in-depth instructions.

Chances are that the default root username and password for your MySQL instance would be: root, and root. If it is not, then please open PHPMyAdmin and have a look at the User tab section/or google for assistance on how to create a new user with 'ALL Privileges'.


How to add Views name to body class? At moment Drupal add css class page-VIEWPATH to the body tag. How can I add css class page-VIEWNAME to the body tag without third party module or JQuery?

Thank you in advance!

It turns out, this can be done with a combination of hook_preprocess_html  and function views_get_page_view to get a true <body> class for a given view and display (see the API page).

So wrapping it up within the hook_preprocess_html context, it would look something like this:

/**
 * Implements template_preprocess_html().
 *
 * Misc page preprocess functions.
 */
function mytheme_preprocess_html(&$vars) {

// Query the view and add a class
$view = views_get_page_view();
 if (
  isset($view) &&
  $view->name == 'actions' &&
  $view->current_display == "page"
) {
    $vars['classes_array'][] = 'views-actions-page';
  }
}

So above, I query the view name and display and the key is $view = views_get_page_view();. This works great for custom Views body classes per view and display.

The rendered HTML result is something like this:

<body class="html not-front logged-in no-sidebars
page-actions section-actions page-views flush-header views-actions-page">

** views-actions-page is the class that we added with the function above.

It should be noted that the advantage of this vs. using views generated classes are that if the URL of the page changes, your custom Views class will not whereas page-actions section-actions would change based on the URL. So using those classes could be unreliable if they are used for theming as it would have a negative ripple effect.


Unable to create Menu Item I am creating a menu item using the following code.

$item = array(
'link_path' => 'node/custom',
'link_title' => 'Custom Title 001',
'menu_name' => 'menu-custom-menu', // Menu machine name, for example: main-menu
'weight' => 0,
'plid' => 0, // Parent menu item, 0 if menu item is on top level
'module' => 'menu',
);
menu_link_save($item);

I can see the entries is menu_links table, but can not see this menu item under the menu at 'admin/structure/menu/manage/menu-custom-menu'. What is wrong with my code?

Please note this path('node/custom' actually doesn't exist in Drupal System.

Please note this path('node/custom') actually doesn't exist in Drupal System.

Whenever we create using admin a menu it asks for a valid path otherwise it shows error of Url doesn't exist. So probably it enters the data in database directly but will not be listed in the admin unless it has a valid path assigned.

Please try by adding a page, e.g node/1 to the path and then try.

$item = array(
'link_path' => 'node/1',
'link_title' => 'Custom Title 001',
'menu_name' => 'menu-custom-menu', // Menu machine name, for example: main-menu
'weight' => 0,
'plid' => 0, // Parent menu item, 0 if menu item is on top level
'module' => 'menu',
);
menu_link_save($item);

and make sure node/1 exists in the system.

Hope it will help you.


Retrieving the primary Key column I have been using this query to query Postgres Table Primary Key Column.

SELECT a.attname, format_type(a.atttypid, a.atttypmod) AS data_type
FROM   pg_index i
JOIN   pg_attribute a ON a.attrelid = i.indrelid
                     AND a.attnum = ANY(i.indkey)
WHERE  i.indrelid = 'semstudent'::regclass
AND    i.indisprimary;

I want to perform the above query in Drupal. Below is my code:

$query=db_select('pg_index', 'i',array('target' => 'import'));
$query->join('pg_attribute' , 'a' ,'a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)');
$result = $query
    ->fields('a', array('attname','atttypid','atttypmod'))
    ->condition('i.indrelid', '"semstudent"::regclass')
    ->condition('i.indisprimary', true)
    ->execute();

The query above create the error below:

  PDOException: SQLSTATE[22P02]: Invalid text representation: 7 ERROR:  invalid input syntax for type oid: ""semstudent"::regclass"
      LINE 5: WHERE  (i.indrelid = '"semstudent"::regclass') AND   (i.indisp...
                               ^: SELECT a.attname AS attname, a.atttypid AS atttypid,   a.atttypmod AS atttypmod
      FROM
      {pg_index} i
      INNER JOIN {pg_attribute} a ON a.attrelid = i.indrelid AND a.attnum =     ANY(i.indkey)
      WHERE  (i.indrelid = :db_condition_placeholder_0) AND (i.indisprimary =   :db_condition_placeholder_1) ; Array
      (
          [:db_condition_placeholder_0] => "semstudent"::regclass
          [:db_condition_placeholder_1] => 1
      )
      in myid_get_template_table_primary_key() (line 755 of C:\xampp\htdocs\drupal-  7.34\sites\all\modules\myid\includes\myid_inputting.inc).

I guess it has something to do with the statement below.

->condition('i.indrelid', '"semstudent"::regclass')

How do I convert it?

UPDATE:

Suggestions below are appreciated but it doesnt make any changes in my code. I have somehow managed to get it working manually. See code below:

 $database = 'import';
 $table = 'semstudent';

 $query=db_select('pg_index', 't1',array('target' => $database));
 $query->join('pg_attribute' , 't2' ,'t2.attrelid = t1.indrelid AND t2.attnum = ANY(t1.indkey)');
 $result = $query
    ->fields('t2', array('attname','atttypid','atttypmod'))
    ->condition('t1.indrelid', myid_get_table_oid($table, $database))
    ->condition('t1.indisprimary', true)
    ->execute();

I have made the function myid_get_table_oid supplied with two parameters: $table and $database. $table represents the name of the the table. $database represents the target database.

//A function that returns the oid of a particular table.
function myid_get_table_oid($table_name, $database){

    $query=db_select('pg_class ', 't1',array('target' => $database));
    $result = $query
        ->fields('t1', array('relfilenode'))
        ->condition('t1.relname', $table_name)
        ->execute();

    $oid = '';
    foreach($result as $record){
        $oid = $record->relfilenode;
        break;
    }
    return $oid;
}

In many instances, the code I made is working but there is one scenario the function returns no primary key. When I use the code above with a particular table myid_template_27 in my database. The function myid_get_table_oid returns an oid    8948915. But the converted query doesnt return anything.

I am pretty sure that the table myid_template_27 have a primary key column. It must return the column biginta.See image below:

To see if biginta really exist on pg_attribute table, I made a query below:

SELECT t1.indrelid, t2.attname AS attname, t2.atttypid AS atttypid, t2.atttypmod
AS atttypmod
FROM pg_index t1
INNER JOIN pg_attribute t2 ON t2.attrelid = t1.indrelid AND t2.attnum =     ANY(t1.indkey)
WHERE  (t1.indisprimary = true)  AND (t2.attname = 'biginta')

The result shows a different indrelid oid which is different from the value returned by my function myid_get_table_oid.

Where did I go wrong?

As some people already mentioned and the error itself describes, this is a variable interpolation/auto-quoting problem.

The most appropriate option here - following the D.O.'s documentation - would be to use where(), instead of condition().

  $query->where($snippet, $args = array())

  The where() method allows for the addition of arbitrary SQL as a conditional fragment. $snippet may contain any legal SQL fragment, and
  if it has variable content it must be added using a named placeholder.
  The $args array is an array of placeholders and values that will be
  substituted into the snippet. It is up to the developer to ensure that
  the snippet is valid SQL. No database-specific modifications are made
  to the snippet.

  (Copied from https://www.drupal.org/node/310086)

And here is a rewrite of your code:

$query=db_select('pg_index', 'i',array('target' => 'import'));
$query->join('pg_attribute' , 'a' ,'a.attrelid = i.indrelid AND a.attnum = ANY(i.indkey)');
$result = $query
    ->fields('a', array('attname','atttypid','atttypmod'))
    ->where("i.indrelid = 'semstudent'::regclass")
    ->condition('i.indisprimary', true)
    ->execute();

I just tried this and it worked without any problems, hope it works for you too!


Is there a way to safely downgrade modules after installing a version that has a database update? I have a site with a lot of modules running Drupal 7.  I just installed a bunch of module updates, ran update.php, and then started running some tests, upon which I noticed that one of the module updates broke an important function on my site.

After some more testing, I discovered which module update broke the function (an update from rc1 to rc2).  Reverting this module back to the previous version (rc1) restores the function on my site.  However, when I installed rc2, there was an update to the database for that module which was performed when I ran update.php.

I'm going to wait for rc3/a 1.0 release of this module to update again.  However, is it safe to simply re-install the old rc1 version over rc2?  Or could this cause major problems down the line and should I instead revert from a backup?

I'm not giving specific module names because I'd like to know what the general best practice (if any) is for "downgrading" modules.

I think the answer is that "it depends".

If the hook_update_N just added indexes, then you should be safe.  If it added or changed columns, then you could have the instance were particular parts of the module work but others will fail (eg, parts that save to the database).  Or, worse, you could start getting inconsistent data in the database for the custom tables.  You should also see an error about the database on the status report.

I would look at the module in question, search for the hook_update_N definitions and see what changed.  It may be documented in the changelog, but I don't always trust that everything was logged.  Then make a judgement call about what to do.


404 errors with Nginx I'm trying to test nginx on Dreamhost following the instructions in the wiki, but going to any page except for the front page results in a 404 error: http://wiki.dreamhost.com/Nginx#Drupal.

Certain things are assumed, and from that assumption I cannot tell if they apply to what I'm trying to do or not. I'm guessing its some kind of clean URL based error.

For example, /home/YOURUSER/nginx/example.com/drupal.conf; my path is /home/YOURUSER/example.com/drupal.conf.

I'm assuming at this point that is not the issue.  I've tried various things including just putting in what appears to be the bare minimum to no effect:

if (!-e $request_filename) {
rewrite ^/(.*)$ /index.php?q=$1 last;
}

Any pointers would be helpful.  I'd like to get this working with Boost.

I also attempted to use this: http://wiki.nginx.org/Drupal#Not_So_Simple.

Disabling clean URLs allows me to log in, and Drupal states that clean URLs are not enabled.

This is what I use (with Drupal 6 and Boost), most is self explanatory but I added additional comments here and there:

server {
        listen          80;
        server_name     IP.NR example.com www.example.com;  # Multiple hostnames seperated by spaces
        root            /path/to/drupal; # Replace this
        charset         utf-8;
        access_log  /var/log/nginx/example.com.access.log  combined;
        error_log   /var/log/nginx/example.com.error.log;

        index  index.php;

        if ($host ~* (^example.com|www.example2.com)) { # Redirect to www.example.com
                rewrite ^(.*)   http://www.example.com$1 permanent;
        }

    ## 6.x starts
        location / {
                #rewrite ^/(.*)/$ /$1 permanent; # remove trailing slashes - disabled
                try_files $uri @cache;
        }

        location @cache {
                if ( $request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                if ($http_cookie ~ "DRUPAL_UID") {
                        return 405;
                }
                error_page  405 = @drupal;
                add_header  Expires "Tue, 24 Jan 1984 08:00:00 GMT";
                add_header  Cache-Control "must-revalidate, post-check=0, pre-check=0";
                add_header  X-Header "Boost Citrus 1.9";
                charset         utf-8;
                try_files   /cache/normal/$host${uri}_$args.html /cache/$host${uri}_$args.html @drupal;
        }

        location @drupal {
                ###
                ### now simplified to reduce rewrites
                ###
                rewrite ^/(.*)$  /index.php?q=$1 last;
        }

        location ~*
        (/\..*|settings\.php$|\.(htaccess|engine|inc|info|install|module|profile|pl|po|sh|.*sql|theme|tpl(\.php)?|xtmpl)$|^(Entries.*|Repository|Root|Tag|Template))$
        {
                deny all;
        }

        location ~* /files/.*\.php$ {
                return 444;
        }
        location ~* /themes/.*\.php$ {
                return 444;
        }

        location ~ \.php$ {
                try_files $uri @drupal;           #check for existence of php file
                fastcgi_param  SCRIPT_FILENAME    $document_root$fastcgi_script_name;
                include /etc/nginx/conf.d/php_fpm; # Includes config for PHP-FPM (see below)
        }

        location ~ \.css$ {
                if ( $request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                if ($http_cookie ~ "DRUPAL_UID") {
                        return 405;
            }
                error_page 405 = @uncached;
                #access_log     off;
                expires         max; #if using aggregator
                add_header      X-Header "Boost Citrus 2.1";
            try_files   /cache/perm/$host${uri}_.css /cache/$host${uri}_.css $uri =404;
        }

        location ~ \.js$ {

                if ( $request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                if ($http_cookie ~ "DRUPAL_UID") {
                    return 405;
                }
                error_page 405 = @uncached;
                #access_log  off;
                expires  max; # if using aggregator
                add_header X-Header "Boost Citrus 2.2";
            try_files /cache/perm/$host${uri}_.js /cache/$host${uri}_.js $uri =404;
        }

        location @uncached {
                #access_log  off;
                expires  max; # max if using aggregator, otherwise sane expire time
        }

        location ~* /files/imagecache/ {
                #access_log         off;
                try_files $uri @drupal;  #imagecache support - now it works
        }

        location ~* /files/backup_migrate/ {
                deny all;
        }

        location ~* ^.+\.(jpg|jpeg|gif|png|ico)$ {
                #access_log  off;
            expires          14d;
            try_files $uri = 404;
        }

        location ~* \.xml$ {
                if ( $request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                if ($http_cookie ~ "DRUPAL_UID") {
                        return 405;
                }
                error_page 405 = @drupal;
                add_header Expires "Tue, 24 Jan 1984 08:00:00 GMT";
                add_header Cache-Control "must-revalidate, post-check=0, pre-check=0";
                add_header X-Header "Boost Citrus 2.4";
                charset utf-8;
                types { }
                default_type application/rss+xml;
                try_files /cache/normal/$host${uri}_.xml /cache/normal/$host${uri}_.html /cache/$host${uri}_.xml $uri @drupal;
        }

        location ~* /feed$ {
                if ( $request_method !~ ^(GET|HEAD)$ ) {
                        return 405;
                }
                if ($http_cookie ~ "DRUPAL_UID") {
                        return 405;
                }
                error_page 405 = @drupal;
                add_header Expires "Tue, 24 Jan 1984 08:00:00 GMT";
                add_header Cache-Control "must-revalidate, post-check=0, pre-check=0";
                add_header X-Header "Boost Citrus 2.5";
                charset utf-8;
                types { }

                default_type application/rss+xml;
                try_files /cache/normal/$host${uri}_.xml /cache/normal/$host${uri}_.html /cache/$host${uri}_.xml $uri @drupal;
        }

#        error_page  404              /index.php;

        # redirect server error pages to the static page /50x.html
        #
#        error_page   500 502 503 504  /50x.html;
#        location = /50x.html {
#            root   html;
#        }

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}

        location /server-status {
                stub_status on;
                access_log off;

        }

     }

I'm using PHP-FPM (which is included in PHP 5.3 but I'm using 5.2) so I also include this file (...conf.d/php_fpm)

        fastcgi_pass   127.0.0.1:9000;    #php-fpm listening on port 9000
        fastcgi_index  index.php;
        fastcgi_param  QUERY_STRING   $query_string;
        fastcgi_param  REQUEST_METHOD     $request_method;
        fastcgi_param  CONTENT_TYPE   $content_type;
        fastcgi_param  CONTENT_LENGTH     $content_length;

        fastcgi_param  SCRIPT_NAME        $fastcgi_script_name;
        fastcgi_param  REQUEST_URI        $request_uri;
        fastcgi_param  DOCUMENT_URI   $document_uri;
        fastcgi_param  DOCUMENT_ROOT      $document_root;
        fastcgi_param  SERVER_PROTOCOL    $server_protocol;

        fastcgi_param  GATEWAY_INTERFACE  CGI/1.1;
        fastcgi_param  SERVER_SOFTWARE    nginx/$nginx_version;

        fastcgi_param  REMOTE_ADDR        $remote_addr;
        fastcgi_param  REMOTE_PORT        $remote_port;
        fastcgi_param  SERVER_ADDR        $server_addr;
        fastcgi_param  SERVER_PORT        $server_port;
        fastcgi_param  SERVER_NAME        $server_name;

        # PHP only, required if PHP was built with --enable-force-cgi-redirect
        fastcgi_param  REDIRECT_STATUS    200;

        fastcgi_connect_timeout         60;
        fastcgi_send_timeout            180;
        fastcgi_read_timeout            180;
        fastcgi_buffer_size             128k;
        fastcgi_buffers 4 256k;
        fastcgi_busy_buffers_size   256k;
        fastcgi_temp_file_write_size    256k;
#   fastcgi_intercept_errors        on;

Just ask if you have any questions about specificities.


Where does a blank theme inherit its templates from? I just enabled my theme only containing an MYTHEME.info file. Now I have one query here.

As a output I got broken page. I have checked source of this page. I got some HTML structure.

As per my knowledge, theme renders from html.tpl.php. But my theme doesn't contain this file. So from where did it get its HTML structure?

From any core theme/themes?

I have also disabled all previously enabled themes except for the admin theme.

So from where it got html structure.

It comes from either your theme's base theme, or the default HTML template file included in the system module.


How do you inject dependencies in your classes from external packages? My project has external PHP packages pulled in via Composer.

I would like to inject one of the classes in that package as a dependency, instead of do new Class(); inside my Controller methods.

The documentation says you can define a service like the following:

services:
  mymodule.example_service:
    class: Drupal\path\to\Class

What do you do when you want to use an external PHP package not native to Drupal?

You should be able to use the fully qualified namespace for the injection:

services:
  mymodule.example_service:
    class: path\to\Class


WSOD appears in Drupal During making of new variants performing steps.
node edit form->add new variant->variant type ->panel->selection rules->node type->context continue->choose layout 2 column->continue->render->standard->continue after this white display occur,i am stuck here.what is the problem.

There are some PHP settings that can lead to WSOD. These are as follows:

max_execution_time: Apparently, on WAMP, the default is 30 seconds,
but some administrative pages may take longer than that to process
and load.

  Go to XAMPP/php/php.ini and change :

    max_execution_time = 360

PHP Memory Limits: Another common reason for the WSOD is issues with
memory limit.

memory_limit = 128M


How to control content access based on value of a List (text) field in user profile? When my users sign up, they must choose whether they are a Man or a Woman, via a List (text) field. If a user chooses "Man", they should only be able to see Woman users on the site. Likewise, if a user chooses "Woman", they should only be able to see Man users on the site. The users cannot edit the value of this field once it is set. The user is assigned a custom user role (man or woman) when they sign up, based on what they choose from that field.

I am also open to using Profile2 with two Profile types (man and woman), but I would still need a method to restrict one profile type from viewing other users of that same profile type.

How can I set up a permission that will allow this type of access restriction? I have not been able to find a solution to solve this scenario.

Check taxonomy_permissions (I think will do in combination with role assignment and has a stable release too), term_access module, Access by Term


drupal views with contextual filter I  have created a content type page named events where several fields are there. also I have created a  view page where list comes of events(title,body and read more). when we click on read more it takes me to the content display page

what I want to do is on display content page i want some sidebar links so that other fields should comes related to that particular node.

is the view page of events when we click on read more its takes me to the content display page (the second image) like there are sponsers block is there of individual node above that i need page links to show other fields which i use to save during creating the node like speakers and other thingd]1


How can i set a pagination in detailed page How can i set a pagination in detailed pages? for example i have 10 pages in common blogs and the main page contain only the description about the content.When we click on the title of the page or readmore then it will displaying the detail of specified content here i want to set the pager how is it possible?

What you're describing is one of Drupal's most commonly used modules, Views. Views lets you:

Select any content you want of your choice (in your case blog posts)
Show only the fields you want on that content (in your case a title link & description).
Display it in a form of your choice (in your case a dedicated page with a pager).

You shouldn't have any trouble finding tutorials on Views. For example, here is one from Acquia.


How to create nodes from shell script at server? I need to create nodes from shell script at my server (some server statistics).

As I know drush cannot add new node. (It was a discovery for me)

So I think make shell script which will create CSV file with node fields and make periodical import by Feeds.

Is there more smart solution?

If you are going to start scripting on the command line, you can always script a php script and run it via drush. That way, you have access to your Drupal system and data. For example, if you place the following code in a file, e.g. script_create_node.php:

<?php

// Expect title as $args[1] and body as $args[2]
if( !isset($args[1]) || trim($args[1]) == '' || !isset($args[2]) || trim($args[2]) == '') {
  print "Expecting two arguments on the command line, title and body, for the new article\n";
  exit;
}

$node = new stdClass();  // Create a new node object
$node->type = 'article';  // Content type
$node->language = LANGUAGE_NONE;  // Or e.g. 'en' if locale is enabled
node_object_prepare($node);  //Set some default values

$node->title = $args[1];
$node->body[$node->language][0]['value'] = $args[2];

$node->status = 1;   // (1 or 0): published or unpublished
$node->promote = 0;  // (1 or 0): promoted to front page or not
$node->sticky = 0;  // (1 or 0): sticky at top of lists or not
$node->comment = 1;  // 2 = comments open, 1 = comments closed, 0 = comments hidden
// Add author of the node
$node->uid = 1;

// Save the node
node_save($node);

you can always call this on the terminal like this:

drush scr script_create_node.php "Article Title" "Article Body"

You can extend such a script to include the logic you would use in your shell script, but instead of writing to a CSV file, you can write directly to the database. It's a great advantage having both PHP-CLI and a bootstrapped Drupal available at the same time.

Hope this helps some!

P.S: Lots of pages out there answering the question "programmatically creating nodes", one random pick would be http://www.group42.ca/creating_and_updating_nodes_programmatically_in_drupal_7


hook_views_pre_render(&$view) seems to be called after the pager rendering I am designing and ecommerce store and I am trying to sort the products by availability using a hook_view. My function product_eta_seconds return the current eta of a product. Here is my module:

function availability_sort_views_pre_render(&$view) {
  if ('uc_products' == $view->name && 'page_1' == $view->current_display) {

    $view->result = array_reverse($view->result);
    $deliveryTime=array();
    foreach ($view->result as $viewRow){
        $deliveryTime[] = product_eta_seconds($viewRow->nid);
    }
    asort($deliveryTime);
    $view->result = sortArrayByArray($view->result,$deliveryTime);
  }
}

function sortArrayByArray($array,$orderArray) {
    $ordered = array();
    foreach($orderArray as $key=>$value) {
        if(array_key_exists($key,$array)) {

                $ordered[$key] = $array[$key];
                unset($array[$key]);
        }
    }
    return $ordered + $array;
}

The problem is the view->result returns only 9 items (my pager value) so when I look at page 2, there are results that should show up on the 1st page (with a lower eta). Is there a solution to get all items of the view without the pager and apply the pager, when the view is rendered ? Any other solution would suit though.

I couldn't find any hook to sort the views result after the results so I ended up using the module "Views PHP" and sort my view using the following:

<?php
    $deliveryTime1Arr = delivery_time_lookup($row1->nid);
    $deliveryTimeRow1=$deliveryTime1Arr[3];
    $deliveryTime2Arr = delivery_time_lookup($row2->nid);
    $deliveryTimeRow2=$deliveryTime2Arr[3];
    if($deliveryTimeRow1>$deliveryTimeRow2) return 1;
    else if($deliveryTimeRow1 == $deliveryTimeRow2) return 0;
    else if($deliveryTimeRow1 < $deliveryTimeRow2) return -1;
?>


How to programmatically get node ID in custom Rules Action Need to create a custom Rules Action. How do I pragmatically get the node ID for an action such as when a node is saved?

You can pass parameter node then you will get full node object into your action.

function MODULEname_rules_action_info() {
  return array(
    'CALLBACK_FUNCTION_NAME' => array(
      'label' => t('Send Mail to users for new content'),
      'parameter' => array(
        'node' => array('type' => 'node', 'label' => t('Current Node')),
      ),
      'group' => t('MODULE'),
    ),
  );
}


How to use the Menu Badges to show the number of recieved messages via Privatemsg? I use Privatemsg on my site to allow users to communicate with one another. New messages appear in the "Inbox" tab.

I also have the Menu Badges module installed to have a count of unread messages displayed in a badge. The Tab Menu Badges edit page does not list the inbox path (it's /messages/received). It lists other paths like /messages/list, /messages/blocked, /messages/sent, etc. (all being Privatemsg paths). But there is no path for Received messages.

So, I cannot display a badge on the inbox tab.

Is this a common error? Is there a fix or a workaround for this?

After peeking into the database, it appears the path /messages/received does not exist. This is probably due to the fact that the inbox being the first tab (default tab,) the path defaults to /messages. This path is also the path of the main menu tab. The Menu Badge module does not have an uninstall file, therefore uninstalling it does not clear up the database.

The work around I used is by putting the badge on the All Messages tab (/messages/list) The count of unread messages is the same as with the Inbox tab. Then, I used a little css to move the badge 222px to the left (position: relative) so that it falls on the Inbox tab instead.

It's like using scotch tape, but it works. :)


Updating the PHP version of an existing site? I am asking this as a total ignorant in differences between PHP versions: Is it possible to update the PHP version of an existing Drupal site that is installed on a local server on Ubuntu?

I mean, let's assume my Apache is in the last version possible, as well as my mySQL, and PHPmyadmin, and I want to update from PHP 5.x.x to 7.x.x. Is this possible? Is it done by an internal Drupal module or an external tool?

Is it possible to update the PHP version of an existing Drupal site that is installed on a local server on Ubuntu?

Yes, upgrading server software for existing applications is common practice both inside and outside of the PHP/Drupal worlds.

If your operating system supports a newer version of php than you currently have, and Drupal (plus the contrib modules you're using) supports the same version you're planning to upgrade to, then you should have no problems.

  Is it done by an internal Drupal module or an external tool?

Drupal can't upgrade the software on your server, that's something that gets done at the operating system level; consult the documentation for your OS for details on how to actually do it (Google "ubuntu upgrade php 7").  Make sure you back up and perform this in a test environment before doing anything on a production server, just in case.

PHP 7 has significant performance improvements, and Drupal 8 supports it, so the particular upgrade you're suggesting would be a good move.


user_save() returns FALSE I am trying to use user_save api. i have passed the following object ($user)

object(stdClass)#30 (6) {
  ["name"]=>
  string(12) "user_name"
  ["mail"]=>
  string(22) "myemail@gmail.com"
  ["pass"]=>
  int(1311514302)
  ["created"]=>
  int(1311514302)
  ["status"]=>
  int(1)
  ["roles"]=>
  array(1) {
    [0]=>
    string(10) "OauthUsers"
  }
}

I have used the following function:

$user = new stdClass();
$user->name = $userdata['name'];
$user->mail = $userdata['email'];
$user->pass = time();
$user->created = time();
$user->status = 1;
$user->roles = array('OauthUsers');
user_save($user);

I have tried to drop the "roles" property as well, but in all the cases user_save() returns FALSE.

Do you have any idea of what I am doing wrong?

UPDATED:

If you are going to create new users using user_save() then follow the following syntax.

$user = array(
   'name' => $userdata['name'],
   'mail' => $userdata['mail'],
   'init' => $userdata['mail'],
   'pass' => user_password(8),
);

Now call the function user_save() and pass the user info as second arg.

$account = user_save(null, $user);
if($account){
     _user_mail_notify('register_admin_created', $account);
}

To update values for already saved user.

$account = user_load(array('uid' => $userdata['uid']));
$updates = array(
    'pass' => user_password(),
    'name' => 'new_name',
    'roles' => array(
        <rid> => '<role title>';
    ),
);

user_save($account, $updates);


display status report even though the module is disabled I want to execute some code in my custom module to display status reports even though my custom module is disabled.

Hook_requirements can be used to display status reports. But it seems that it only works when the module is enabled. I want this to work even though the module is disabled.

Please tell if anybody knows the solution. Thanks in advance.

That's not possible.

For hooks to be executed, your module must be enabled. From the docs:

  To extend Drupal, a module need simply implement a hook. When Drupal wishes to allow intervention from modules, it determines which modules implement a hook and calls that hook in all enabled modules that implement it.

Emphasis mine.

Allowing modules to run code even when they're not enabled would be a massive security risk, and could cause all sorts of other unforeseen problems.


Group date field by day for chart I have a custom database table with a datetime column that I have made accessible to Views. I want to create a line charts of number of rows per day but I can't get the View right.

With aggregation on I have a COUNT on my ID field and I'm trying to group on my date field by day (it currently has year -month - day - hour - minute - second). I have set the date format to d/m/Y and aggregation to group results together but they are still separate.

Obviously this makes for a pretty bad line chart

What I really want is

18/01/2017    23
19/01/2017    25
20/01/2017    19

I tried the Views Date Format SQL Field module (dev version too) but it doesn't seem to work as I don't get an option to format my date as SQL.

Is this possible in Views?

I believe there is a way to do this by rewriting the field described in this issue: https://www.drupal.org/project/charts/issues/2915097. There is also grouping enabled now if you want to stack your charts. Please download the latest -dev version.