Remove "comment delete" confirm page When I click on the "Delete comment" link, I get redirected to a page that tells me to confirm the action. How can I avoid this redirection, as I have build a pop-up that asks for confirmation?

The comment/%/delete menu entry is wired directly to the comment_confirm_delete_page form. You can modify it with with a hook_menu_alter, and change the function from drupal_get_form to a page callback of your own design that will just delete the comment.

Example:

In your module file you'd need:

function mymodule_menu_alter(&$items) {
  $items['comment/%/delete']['page callback'] = 'my_comment_delete_function';
  $items['comment/%/delete']['page arguments'] = array(1);
  $items['comment/%/delete']['module'] = 'mymodule';
  $items['comment/%/delete']['file'] = 'mymodule.pages.inc';
}

And in your mymodule.pages.inc file you'd need:

function my_comment_delete_function($cid) {
  if ($comment = comment_load($cid)) {
    comment_delete($comment->cid);
    drupal_set_message(t('The comment and all its replies have been deleted.'));
    watchdog('content', 'Deleted comment @cid and its replies.', array('@cid' => $comment->cid));
    // Clear the cache so an anonymous user sees that his comment was deleted.
    cache_clear_all();

    drupal_goto("node/$comment->nid");
  }
  return MENU_NOT_FOUND;
}


$base_path is not added to AJAX URL request in login form I have a D7 site in a subfolder, and would like for AJAX requests to find the correct docroot folder.

When trying to login from localhost/mysite/user, AJAX sends a request to localhost/system/ajax. I've read that you can use the global variable $base_path for this, so I gave it a try, still the same error. I've checked in Firebug and indeed Drupal.settings.basePath does have the correct path. In settings.php is it written like this $base_path = '/mysite/';.

This made me wonder if the JS logic does not include the $base_path value by default and what would be a correct way to add this in. The site is tracked in Git, so I've also experimented with Apache configurations, such as ProxyPass, ProxyPassReverse, and ReWrite rules in order to prevent having to push changes that would risk breaking the site on the remote server.

I'm new to Drupal and not so experienced with Apache directives, any help here would be awesome :)

First off, in the settings.php file you should have an example of http://www.example.com and a comment there, saying that you should not append a trailing slash.
Next, in your case looks like http://localhost would be the correct value of $base_url, if any - try hashing out $base_url line to see if the site is fine without it - as it might be.


How to create a "navicon" effect I would to create a "navicon menu", like in this article.

It seems to be a standard for mobile and responsive sites.
Is there some module that do this?

The Superfish module does that. It integrates the Superfish jQuery script into Drupal. It has two responsive menu options for small screens; either rendering it has an accordion or a drop-down. I strongly recommend using the Dev version as it is 'production ready' and has multiple improvements over the older release.


Modules i18n: How to set the default language home page url without alias I have a standard Drupal 7 installation with the i18n module and 3 languages defined.

one basic page "node/1" created with the URL alias "home"
in the Configuration > System > Site Information the default front page is "home"
created other 2 languages (pt-br and it)
created the translation of the basic page "node/1" to pt-br and it (are created "node/2" and "node/3" pages)
the 3 pages "node/1, 2 and 3" have the same alias "home"

If I go to mysite/en, I see the defined front page in english and all the site is in english: it's ok!

The problems:

If I go to mysite/pt-br/home, I see the site in portuguese and the "node/1" in porguguese: it's ok!
If I go to mysite/pt-br, I see the site in portuguese but the "node/1" content in english and not the "node/2" (portuguese version of the basic page): wrong!
the same thing to the italian version.

What is wrong? How to set the correct language node for front page in the default language url (mysite/pt-br and mysite/it)?

Note: In the Detection and Selection tab is the original items with the default order (URL, Session, User, Browser and Default) and I have been enabled all (in the Configure page of URL the selected option is the Path Prefix).

Make sure to declare your home page node as a "multilingual varialable". For more details on these kind of variables, and how to get this to work, refer to my answer at How to make content translation available for front page?.

I'd be interested to some day hear if this  resolved the issue here.


How to toggle price display with and without tax? In Europe  it is normal for trade suppliers to show prices exclusive of VAT, but for retail suppliers to display prices including VAT.

For the use case where merchants who supply both trade and retail. Many e-commerce sites have the option to toggle the price display to show values with and without tax.

See https://www.tool-wise.com/ (radio button, top right)

Does such an option exist for Drupal Commerce? I haven't found anything in contrib.

Check out commerce price by components module. You can show both prices with and without VAT. If you want to toggle I'm afraid you will have to write a custom module... .


handling file upload for drupal 6 I have a question about handling file uploads.  I am trying to implement a form that will allow the user to upload a file.  I do not need to store the file, though.  I just need to take the uploaded file, where its location happens to be, and pass it to an outside API, which uploads it to its server (its Jira).  Is there a way to do this?  The file has to be publicly available to be consumed by Jira's API (in other words, Jira won't be able to provide a username/password to validate against drupal).  This is what I have, so far:

in my _add_form hook:

$form['file'] = array(
                '#type' => 'file',
                '#title' => t('Document'),
                '#description' => t('Upload a file, allowed file types: pdf, images, documents'),
            );

in my _add_form_validate hook:

$validators =  array(
                'file_validate_extensions' => array( 'jpg jpeg gif png bmp txt doc docx xls xlsx pdf ppt pptx ' )
            );

            $file = file_save_upload('file', $validators);

            if (isset($file->filename)) {
                $form_state['storage']['file'] = $file;
            }

in my _add_form_submit hook:

i can see the object form_state->storage->file but I don't see the full path to where the file is residing.  All i see, thats close, is:

 file_name = "myfile.jpeg"
 file_path = "/tmp/myfile.jpeg"
 destination = "/tmp/myfile.jpeg"

but, as I mentioned, I need to full path to pass to another, external, API so that the file can be consumed.  I do not need to store or save the file afterwards.

admin/settings/file-system settings:

File System Path:  sites/mySite.net/files
Temporary Dir: /tmp
Download Method: Private

Ok here is high level overview of the file uploading. I took most of this from the Drupal 6 Developer modules but made some changes that should get you started on how to achieve your final goal here. I left all the original comments and denoted any new comments with // ** Comment Text so you should be able to skim through this and get the general idea.

<?php

//////////////// Tutorial Example 11 //////////////////////

// ** Will denote any changes or anything that I am pointing out below.

/**
 * Example 11: A form with a file upload field.
 *
 * This example allows the user to upload a file to Drupal which is stored
 * physically and with a reference in the database. In this example, only
 * png, gif, jpg, and jpeg files are allowed.
 *
 * @see form_example_tutorial_11_validate()
 * @see form_example_tutorial_11_submit()
 * @ingroup form_example
 *
 */
function form_example_tutorial_11($form_state) {
  // This is required to upload files.
  // enctype="multipart/form-data" required by browsers to handle files.
  $form = array(
    '#attributes' => array('enctype' => "multipart/form-data"),
  );

  $form['file'] = array(
    '#type' => 'file',
    '#title' => t('Image'),
    '#description' => t('Upload a file, allowed extensions: jpg, jpeg, png, gif'),
  );

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

  return $form;
}

/**
 * Validate handler for form_example_tutorial_11().
 * Verify the valid extensions, and verify content is an image also.
 */
function form_example_tutorial_11_validate($form, &$form_state) {

  // ** I just left this as image but you can change the ext array if needed.
  $file = file_save_upload('file', array(
    'file_validate_extensions' => array('png gif jpg jpeg'),
    'file_validate_is_image' => array(),
  ));

  // If the file passed validation: ** File is in /tmp folder now
  if (isset($file->filename)) {
    // Move the file, into the Drupal file system
    // ** Notice the 'jira-upload/', this would be where your file is placed,
    // ** It will be in your /files folder, but you need to make this directory,
    // ** You can do it in code but for simplicity I just left it as is for now.
    if (file_move($file, 'jira-upload/' . $file->filename)) {
      // Update the new file location in the database.
      // ** Change from /tmp/filename.ext to,
      // ** /sites/default/files/jira-upload/filename.ext in database.
      // ** This will be important for Drupal later.
      drupal_write_record('files', $file, 'fid');
      // Save the file for use in the submit handler.
      $form_state['storage']['file'] = $file;
    }
    else {
      form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
    }
  }
  else {
    form_set_error('file', t('Invalid file, only images with the extension png, gif, jpg, jpeg are allowed'));
  }
}

/**
 * Submit handler for form_example_tutorial_11().
 */
function form_example_tutorial_11_submit($form, &$form_state) {
  $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/temp
  // ** This will actually make it where you don't have to delete,
  // ** You can let Drupal clean it up later on cron runs after a certain,
  // ** Amount of time. This will be done automatically.
  file_set_status($file, FILE_STATUS_TEMPORARY);
  // ** This is what you wanted, was the public file that can be navigated to,
  // ** This should work pretty well, but there are other ways.
  // ** Since validation is already passed I would run the API call here as,
  // ** Well. You could pass the $file object to another function or your pref.
  $fileurl = file_create_url($file->filepath);
  // Set a response to the user.
  // ** I added the $fileurl so you could see it on the frontend,
  // ** Without having to know if devel is there.
  drupal_set_message(t('The form has been submitted and the image has been saved, fileurl: @fileurl. filename: @filename.', array('@filename' => $file->filename, '@fileurl' => $fileurl)));
}

?>

Note: For this to work with the way you are wanting to curl the image and send it you will need to set your file system to public. I'm placing a screenshot of that page with configuration.

Additional Hook:

If your file system is private you will have to run an additional hook in order to allow access to the file through Drupal without having it attached to a node or anything. I tested this with making my file-system private and clearing out all previous images, then along with the code that I edited from the Drupal 6 Examples module I placed the code below in the main module file (just incase anyone needs to know how to test this out without knowing all the code). This should give you the functionality that you need without having to change the file-system.

<?php

/**
 * Implements hook_file_download().
 */
function form_example_file_download($file) {
  //dpm($file);
  // Used jira- as indicator but it needs to match your folder where you are storing your files.
  if (strpos($file, 'jira-') === 0) {
    $info = image_get_info(file_create_path($file));
    return array('Content-type: ' . $info['mime_type']);
  }
}

?>


Page Arguments and Dynamic Pages I am trying to make dynamic pages using hook menu which is going fine but the problem is I want to add page arguments for the states. For example if someone goes to the url and there isnt a state in the url like california for example(site/listings/california) it would show a page not found error, and if found it would list the listings I have looped out in my function.

Any Suggestions?

/*
** Hook Menu
*/

function listings_menu() {
    $items = array();

    $items['site/listings/%'] = array(
        'title' => 'City Listings',
        'page callback' => 'business_listings',
        'access arguments' => array('access content'),
        'page arguments' => array('states', 'city_names'),
    );

    return $items;
}

/*
** State Listings
*/

function listing_states($state){
    $state = array(
        'alabama' => t('Alabama'),
        'alaska' => t('Alaska'),
        'arizona' => t('Arizona'),
    //ect.....

    );
    return $state;
}

/*
** Company Listings
*/

function business_listings(){

    $states = listing_states(arg(2));

    $dbquery = db_query("SELECT DISTINCT CityName FROM {zipcodes} WHERE StateName = '".ucfirst(arg(2))."' ORDER BY CityName ASC");

    $cityname = '';
    $cityname .= '
';
    foreach ($dbquery as $dbrow) {
        $cityname .='
';
        $cityname .= 'CityName)).'">'.$dbrow->CityName.'';
        $cityname .= '
';
    }
    $cityname .= '
';

    return array('states' => $states, 'city_names' => $cityname);
}

I believe you want to change your listings_menu()

function listings_menu() {
    $items = array();

    $items['site/listings/%'] = array(
        'title' => 'City Listings',
        'page callback' => 'business_listings',
        'access arguments' => array('access content'),
        'page arguments' => array(3),
    );

    return $items;
}

Then you need to change your listings to accept that argument

function business_listings($states){
  $states = listing_states($states);

  $dbquery = db_query("SELECT DISTINCT CityName FROM {zipcodes} WHERE StateName = '".ucfirst(arg(2))."' ORDER BY CityName ASC");

  $cityname = '';
  $cityname .= '
';
  foreach ($dbquery as $dbrow) {
      $cityname .='
';
      $cityname .= 'CityName)).'">'.$dbrow->CityName.'';
      $cityname .= '
';
  }
  $cityname .= '
';

  return array('states' => $states, 'city_names' => $cityname);
}


Where to put custom modules? If I create a custom module for a single site where should I put it?  Previously I would put it in sites/all/modules, or possibly sites/all/modules/custom.  However I just read this article, Creating Your First Module in Drupal 7 Module Development which say the best practice is to put them in sites/default/modules:

  However, as of this writing, /sites/all/modules is not the recommended
  place to put custom modules unless you are running a multi-site
  configuration and the custom module needs to be accessible on all
  sites.

  The current recommendation is to put custom modules in the
  /sites/default/modules directory, which does not exist by default.
  This has a few advantages. One is that standard add-on modules are
  stored elsewhere, and this separation makes it easier for us to find
  our own code without sorting through clutter. There are other benefits
  (such as the loading order of module directories), but none will have
  a direct impact on us.

  We will always be putting our custom modules in
  /sites/default/modules. This follows Drupal best practices, and also
  makes it easy to find our modules as opposed to all of the other
  add-on modules.

Is this really considered the current best practice?  Is there some official reference to this?

Modules can live in many places. If you use Apple's OSX it's alot like where Applications and Fonts can live in OSX ...

Modules can live at:

/profiles/PROFILENAME/modules/
/sites/default/modules/
/sites/all/modules/
/sites/SITENAME/modules/

core drupal modules are found in DRUPAL_INSTALL_DIRECTORY/modules.

Where a module lives deems how drupal sees it.

Modules in a profile directory can be seen by sites installed by that installation profile.
modules in /sites/default can only be seen by the default drupal site.
modules in /sites/all path can be seen by all drupal powered websites regardless how they were installed, or what subsite they are.
modules in /sites/SUBSITE/modules can only be seen by that subsite.

In general it is best practice to place the module folder where it is needed for its scope of use in your Drupal installation.

Additionally, it is a best-practice to place subfolders such as:

/sites/SUBSITE/modules/contrib
/sites/SUBSITE/modules/custom

to distinguish within a modules directory what is standard 3rd party contributed modules used for a site, and what is custom built drupal modules by your company in /custom.

Yes, there is documentation on this in your drupal installation folder at /sites/all/README.txt

Note: alot of this changes slightly with drupal 8

EDIT - references on /contrib and /custom directories.

Basically at some point in drupal development you want to organize your modules more and more, per site, per drupal installation. Many developers use these types of conventions. Drush Make (bundled into core Drush as of 5.x) allows specification of a subdirectory within /modules to place a module.

Organizing Drupal Modules
Drupal best practices
Drush Make subdir option


Why multilingual site url is not working in production site? I have multilingual site such as www.demo.com and bn.demo.com it works fine at dev and local site. but when i deployed at production it's url language is not working.

When I hit www.demo.com it goes english site. and then when i hit bn.demo.com it should come at bangla site but the strings are not translated.

Surprisingly when I logged in then switch url the translated string works fine. Why it does not works at logged out situation? how can I resolve it?

And my .htaccess files and rewrite condition

# (http://example.com/... will be redirected to http://www.example.com/...)
# uncomment the following:

RewriteCond %{HTTP_HOST} .
RewriteCond %{HTTP_HOST} !^(www|bn)\. [NC]
RewriteRule ^ http%{ENV:protossl}://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Just a beginner's suggestion... when you migrate your site, did you turn off clean URLs, clear cache and put into maintenance mode before migrating?  If not, I suggest you try that then turn back on clean URLs, and take out of maintenance mode.


Manually laying out specific articles on page I'm making a newspaper site and would like to manually lay out and embed a specific set of articles for the front page. Is there a way I can manually code the layout in columns and embed specific articles?

I don't want or expect the articles to be automatically populated when new content is published; I'd like this to be a manual process. Here's an example similar to what I'm hoping to accomplish pulled from today's New York Times layout:

There is (as often) more than one way of solving this.

The dirty and easy way of doing it is with Blocks and Regions, like in Drupal 7. You'll need regions in your theme to be laid out the way you want (and be responsive). Then you manually add nodes/blocks to the regions you have laid out. Even the method of choosing nodes/blocks can be done in different ways.

The sophisticated way of building such a page is with the Layout builder and Paragraphs or a similar module that allows you to reference things.

One Content Type will serve as the container for the layout and all the other content you want shown there. Although it's possible to apply it to only the one node, the one you'll be using for the front page, you decide what makes sense structurally and procedurally in your project.

With Paragraphs you create different reference possibilites for the content you want displayed, and then arrange them with the Layout builder. The Paragraphs and Layout builder parts are usually done up front, you build them once and have it ready when new content is created.

When you publish new nodes and want to update the front page node to show it you will only have to change the references within the front page node to keep the layout and have different content in each "box area".

You can, of course, create more than one layout in your theme, so when needed also choose a different layout for the new content combination.

It's a super powerfull new approach in D8 that makes your Drupal site feel like a website builder software. It does require some effort up-front, so it all depends on your specific needs.


How can I get the email field value from a webform and use the rules module to send mail on submit event? How can I get the value of the email field value in a webform and apply it in

rule > action > send email > to address

I have tried using a token but could not get the value.

If you have an email field on the webform then that field will be available to you at webform/emails in the selector alongside the radio button = Component Value

That then becomes the 'to' field unless you then overwrite it.

You will also find 'select' type fields in that selector as you can then set email address for each of the options in the email settings directly.

You would use this if for example you had a field on the form for 'country' and needed to send the submission to different contacts based on which country was chosen.

Hope that helps


Unexpected error during import . . . plugin does not exist error on drush config import This is an issue I've had occasionally when trying to delete a plugin in a custom module.  In this example, once a filter format filter plugin has been enabled it's impossible to remove.  If you disable it and remove the plugin class from the codebase, it still shows up in the "filter.format.full_html.yml" config.

If you try to edit this file to remove the dependency and then do drush cim, you get an error:

Unexpected error during import with operation update for filter.format.basic_html: The &quot;examplefilter&quot; plugin does not exist.

How do you get rid of this dependency if it shows up in the config when disabled and you can't remove it from the config and import the config without getting a fatal error that the plugin is missing?

I was able to solve this with an update hook.  By deleting the config and then reimporting it this way, it doesn't trigger the unexpected error.  You need to run "drush updb" first, before "drush cim" for this to work.

use Drupal\Core\Config\FileStorage;

/**
 * Reimport filter.format.full_html and filter.format.basic_html.
 *
 * This is to remove the dependency on the examplefilter filter
 * which is being deleted.
 */
function mymodule_update_8003() {

  $config_ids = [
    'filter.format.full_html',
    'filter.format.basic_html',
  ];

  foreach ($config_ids as $config_id) {
    Drupal::configFactory()
      ->getEditable($config_id)
      ->delete();

    $config_path = config_get_config_directory('sync');
    $source = new FileStorage($config_path);
    $config_storage = \Drupal::service('config.storage');
    $config_storage->write($config_id, $source->read($config_id));
  }
}


Version history/ revisioning Is there a way to get drupal 7 to keep version history for every node/page without having to remember to select the "Create new revision" option every single time?

Is there a module that improves this feature? Also, the ability to Diff two different revisions would be great.

You can set each content type to default to create a new revision; if you edit a content type you'll see something like this:

Select the 'Create new revision' checkbox and save the form; when you add/edit content of that type the 'Create new revision' option will be pre-selected.

As far as diffing revisions goes, you can install the Diff module:

  This module adds a tab for sufficiently permissioned users. The tab shows all revisions like standard Drupal but it also allows pretty viewing of all added/changed/deleted words between revisions.


How to call a SOAP function to send Drupal user data to a SOAP server? I'm trying to send user data to a remote SOAP server with the Rules module. I have installed the wsclient_soap module (a sub-module of the Web service client module) and put in the URL for the WSDL file.  It seems to work as I get a few of the data types back on the Drupal end.

What I do not see, is a way to use the SOAP "operation" to send the values of a Drupal user back to the SOAP server.

Has anyone had any luck sending this type of data to a remote SOAP server?

Here is the code for my php evaluation I'm using to test:

$client = new SoapClient('http://something.wsdl', array('trace' => 1));
syslog(1, print_r($client->__getFunctions(), TRUE)); //this shows the correct function
$newuser = array(
     'email' => 'test@test.com',
     'phone' => '+33 06 12 34 56 78',
);
$client->__soapCall("availableFunctionFromGetFunctions", $newuser);
syslog(1, print_r($client->__getLastRequest(), TRUE));
syslog(1, print_r($client->__getLastResponse(), TRUE));

For the available functions, when printed to syslog, it shows the one I want with THREE variables, the two I want to send and one called "authentication".  The documentation I was given does not say what the value of authentication is supposed to be, so I have a feeling the "error" that is being thrown when I act out the rule is caused by this.

I will update as I get more information.

You say you use the wsclient SOAP binding but your code doesn't use it. Instead, your code uses a direct query to the PHP SOAP interface.

This thread discusses the difference between the two binding and which one is preferrable.

From the module's readme file:

You can create web service descriptions in code, see for example
wsclient_examples.module
You can easily invoke web services by loading the description and executing
an operation (the operation name can be used a dynamic method name):

$service = wsclient_service_load('google');
$result = $service->translate('Hallo Welt', 'de|en');


How to get an array of values of node ids from entity reference field with EntityMetadataWrappers I'm using a EntityMetadataWrapper on a profile2 entity. One of the fields is a multi-value entity reference field to nodes.  I want to simple get the node ids as an array, so I can do a quick in_array() to see if a value already exists.

I can't seem to find how to easily do this.

Should be as simple as:

$ids = $wrapper->field_foo->raw();

And if you want an array of entities instead:

$entities = $wrapper->field_foo->value();


Migration time created of node I'm flowing article to migration my data. Every fields is working fine. But field created doesn't working. Field created always insert time import.

I try replace field created with setting

created:
  plugin: default_value
  default_value: 1389312000

but same result. So how to migration time created of node?

Most likely your source plugin isn't supplying the created field to do what is done in the reference article:

source:
  plugin: custom_article
destination:
  plugin: entity:node
  bundle: article
process:
  ...
  created: created

This part of the source plugin config is saying, "import article nodes by setting its created field from the source column created generated by the custom_article plugin".

Adding:

created:
  plugin: default_value
  default_value: 1389312000

Is telling the migration to "set created to 1389312000 as a default (if there's no source plugin data"

If you're copying the reference article's modules/migrate_custom/src/Plugin/migrate/source/Article.php, you'll need to make sure your plugin's query() method is correctly querying its source so that's available for processing and

process:
  ...
  created: created

Is set in your migration config so that it's sourced correctly.


How to code multiple values field in Views PHP? I need help setting up ViewsPHP to evaluate 3 pieces of data? (I barely know any PHP)

ViewFields

I have a View with three embedded Viewfields:

Node count
$row->view
[views_field_view_view]

Time ago (1 unit)
$row->view_1
[views_field_view_view_1]

Success rate
$row->view_2
[views_field_view_view_2]

Value code

In the Value Code text area I want to call all the values. I currently have:

return $data;

Output code

In the Output Code I want to do something like this:

<?php
if ($row->view >= 5 AND $row->view_1 >= 5 AND $row->view_2 >= 80) {
    echo "Amazing person";
}
elseif ($row->view >= 3 AND $row->view_1 >= 3 AND $row->view_2 >= 70) {
    echo "Good person";
}
elseif ($row->view >= 1 AND $row->view_2 >= 60) {
    echo "Interesting person";
}
else {
    echo "Content needed";
}
?>

It's only outputting "Content needed" so what have I done wrong?

EDIT: Updating to 7.x-2.x-dev makes this work.

Structurally, your code looks fine, it's probably because

$row->view =

5

 basically the 5 has HTML tags around it.

so

5

 does not equal 5

You can use the PHP strip_tags() function to get rid off the tags.

if (strip_tags($row->view) >= 5 AND strip_tags($row->view_1) >= 5 AND strip_tags($row->view_2) >= 80) {

So try this:

<?php

$a = strip_tags($row->view);
$b = strip_tags($row->view_1);
$c = strip_tags($row->view_2);

if ($a >= 5 AND $b >= 5 AND $c >= 80) {
    echo "Amazing person";
}
elseif ($a >= 3 AND $b >= 3 AND $c >= 70) {
    echo "Good person";
}
elseif ($a >= 1 AND $c >= 60) {
    echo "Interesting person";
}
else {
    echo "Content needed";
}
?>

PS: no need to have anything for value code return $data;.


How reliable is hook_post_action module? I am using this module under Drupal 7 to execute some code after nodes of a particular content type get updated. My question, is this module reliable? Would the post save event be called every time my target nodes get updated?

This is the module's page:
https://www.drupal.org/project/hook_post_action

The module register a shutdown function in hook_entiyt_delete(), hook_entity_insert(), and hook_entity_update().

/**
 * @param $entity
 * @param $type
 */
function hook_post_action_entity_insert($entity, $type) {
  drupal_register_shutdown_function('_hook_post_action_post_save', $entity, $type, 'insert');
}

As such, the hooks invoked from that shutdown function are always invoked, except in the case the shutdown function is not called, which as the documentation for register_shutdown() says, it can happen if the process is killed with a SIGTERM or SIGKILL signal. Since PHP doesn't have a function to removed a shutdown function, I would say the module is reliable.

As side note, hook_node_postsave() and hook_entity_postsave() are always invoked, whenever the entity is created, updated, or deleted.

/**
 * @param $entity
 * @param $type
 * @param $op
 */
function _hook_post_action_post_save($entity, $type, $op) {
  $entity_is_saved = FALSE;
  $new_entity = NULL;

  if ($op == 'insert' || $op == 'update') {
    $entity_is_saved = TRUE;
  }
  if ($op == 'delete') {
    list($id) = entity_extract_ids($type, $entity);
    $new_entity = entity_load($type, array($id));
    if (!$new_entity) {
      $entity_is_saved = TRUE;
    }
  }
  if ($entity_is_saved) {
    module_invoke_all('entity_post' . $op, $entity, $type);
    module_invoke_all('entity_postsave', $entity, $type, $op);

    if ($type == 'node') {
      module_invoke_all('node_post' . $op, $entity);
      module_invoke_all('node_postsave', $entity, $op);
    }
  }
}


Organic Groups: Error, The website encountered an unexpected error. I had OG working fine except I wasn't able to upload images to be displayed (but to still keep the File field for PDF uploads as private to just the group).

However I've gone through and removed the CKEditor module as people suggested to use WYSIWYG with CKEditor (js library) so I moved that.

Then I installed the IMCE - WYSIWYG bridge too and tried several things to get the images working.

They were working but I noticed PDFs were no longer private, now I seem to have narrowed it down to the OG field settings.

If I add the "Group Audience" field to the content type (which is set as OG group content), then I can no longer visit that page and get this error:

EntityMetadataWrapperException: Unknown data property og_group_ref. in EntityStructureWrapper->getPropertyInfo() (line 339 of sites/all/modules/entity/includes/entity.wrapper.inc).

As soon as I remove the Group Audience field, I can access the content type again (i.e. I can edit, add new etc. for this one content type). However I need the Group Audience field to keep the content secure/private.

Clearing the caches worked for me with a "drush cc all".


Programmatically set the format for each value of a multi-value text field I am trying to programmatically set the format of a multi value text field to 'full_html'.

I have tried:

$Links = array (1, 2, 3, 4, 5);

$node->field_article_links[] = $Links;
$node->field_article_links->format = 'full_html';
$node->save();

and

$Links = array (1, 2, 3, 4, 5);

foreach ($Links as $Link) {
$node->set('field_article_links', $Link);
$node->field_article_links->format = 'full_html';
}
$node->save();

But the results are always the same, only the format of the first value of the field is set to 'full_html' and the others remain unchanged.

What am i doing wrong ?

Please, do not start with capital letter when naming variables, every time you do that a puppy dies.

As 'field_article_links' can have more than one value (probably is a unlimited field), you should treat its value as an array and not as single entity, where each element has its value and format.

To do that, you have to build an array with the field data, then put this array into the field.

The following code is working as you expect:

$links = array (1, 2, 3, 4, 5);
$field_data = [];
foreach ($links as $link) {
    $element = [];
    $element['value'] = $link;
    if($link === 3) {
        $element['format'] = 'full_html';
    } else {
        $element['format'] = 'dasdas';
    }
    $field_data[] = $element;
}
$node->field_article_links = $field_data;
$node->save();


Accessing Login page shows You are not authorized to access this page Till about an hour ago my Drupal 7 site was working fine. But now when I access the login page (/user) I get an You are not authorized to access this page

So I checked the node_access table and I see a record for anonymous users - 0 0 all 1 0 0

I checked the sessions table and it didn't seem to be corrupted. But nevertheless cleared the records. But I am still unable to access the login page

The last time we applied a module update was 10 days back so I don't think its got to do anything with the module code written by us.

I am at my wits end! Have anyone of you faced a similar issue?

EDIT 21st Oct 2014 : A link that explains the exploit - is here


When should I "send mail by queue" with the SMTP module? On the SMTP module configuration page at /admin/config/system/smtp, it offers the option to Send mail by queue (Mails will be sent by drupal queue api.).

When would I want to check this box?  What are the advantages and disadvantages?

TL;DR: send the email by queue if you are sending larger number of emails at once, or if your SMTP server takes longer time to process a request (for whatever reason).
Below is a brief overview of the main pros/cons.
Pros

Better handling of large volume of emails. Email sending task will be split into batches, and Drupal will process them in smaller chunks during cron runs. This is better because your server might time out or become unresponsive for visitors if you are trying to send 500 emails at once.
If the same task is split into multiple batches, it will be easier to process them, and regular visitors will not experience as big decrease in performance.

Cons

Requires more frequent cron (or a custom script that will process the batches), which translates into more used resources at all times. You might see certain decrease in performance if the site is processing email batches and there are a lot of users online simultaneously. This of course depends on many factors (number of emails you are sending, frequency of your cron, speed at which remote SMTP server processes the requests, number of visitors on your site, complexity, and so on).
See Elysia Cron module for fine tuning the cron implementations of all modules on your site. It will help you use less resources during each cron run, because you will be able to choose how often will cron of certain modules be run.

In some cases this can result in slower email delivery. If you have a large number of emails to deliver (e.g. 100k newsletter subscription list), last user in the queue will receive the message significantly later than the first one. Also, all emails requested to be sent during that time, will be delayed as well.


Drupal Hook_Mail_Alter Custom Template fields We have a Drupal 6 contact us Webform with e-mail.  There is a custom template with the following fields:
Facility: %value[facility]
First Name: %value[first_name]
Last Name: %value[last_name]
Email: %value[email_address]
Phone: %value[phone_number]
I wish to be contacted: %value[contact_user]
Subject: %value[subject]
Comments: %value[comments]
The results of this submission may be viewed at:
%submission_url

I want to access both the subject and the facility field.  I'm not sure my keys are correct using "headers".  Is this the correct way to access both the subject and facility fields?

Here is my code in the custom module test:

test_mail_alter(&$message)
{

    if (($message['id'] == 'contact_us'))
    {
        $mail_listing = array();

        // pick up subject e-mails
        $subject = str_replace(' ','',$message['headers']['subject']);
        $subject_listing = explode(',',$subject);
        foreach ($subject_listing as $s){

            if (preg_match('/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/',$s)){
                array_push($mail_listing,$s);
            }

        }

        // pick up facility if it exists and combine it with the subject listing
        $facility = str_replace(' ','',$message['headers']['facility']);
        $facility_listing = explode(',',$facility);
        foreach ($facility_listing as $f){

            if (preg_match('/[a-zA-Z0-9_-.+]+@[a-zA-Z0-9-]+.[a-zA-Z]+/',$f)){
                array_push($mail_listing,$f);
            }

        }

        $message['headers']['to'] = implode(',',$mail_listing);
    }
}

In Drupal 6, you can specify further settings:

Navigate to the Contact Form settings page (http://example.com/admin/build/contact/settings)
In the "Additional Information" section, enter the text to display with the contact form.
In the "Hourly Threshold" list, select the maximum number of submissions that a user can make per hour.


Primary Links Not Showing Up On Certain Themes In Drupal 7, I have a page in the Primary links menu. I set the page content type to use the primary links. In Garland I can see the item at the top of the page, but in a bunch of other themes I can't, like AT Adaptive, Fusion, and Sky. What gives? How do I get the primary links to show up in those themes?

There are two ways to show primary links: through the theme settings or through a block placement. Check your theme's settings to see if it has a setting for display of primary links. If it does not, your only configuration option is to place the primary links block into a region through block administration.


Custom CSS for title fields of Articles specified in content creation Custom CSS for title fields of Articles specified in content creation

As an example, I have a view that displays my latest 10 articles but want the titles to be different colours. I want these colours to be determined based on what I input at the content creation form, whether it be in a separate field or by defining/attaching a specific class to each new Article.

Is there a way to do this or a better solution to my problem available? Thanks in advance :)

For the simplest and quickest implementation I'd suggest you create a array in your THEME_preprocess_node(&$vars) in  template.php:

<?php
$vars['color_cls'] = array(
    'red',
    'blue',
    'yellow'
);
?>

Then you could simply randomly address those in your node.tpl.php and print them as a class in your node, something like this:

<div class="node <?= $color_cls[array_rand($color_cls)]; ?>">

You could also make the color_cls array associative and give them, for example, priorities:

<?php
$vars['color_cls'] = array(
    'critical' => 'red',
    'important' => 'blue',
    'normal' => 'yellow'
);
?>

And ofcourse, then you just style them with your CSS. I'm assuming you do know how to style the classes, so I'll leave out the CSS  bit.


Translate the frontend part of the site only I am working at a project that needs a biilingual translation (content + interface). I've installed the following modules:

Locale + Content translation (core modules)
Internationalization Module (i18n)
Variable Module (required by Internationalization) – it deals with meta tags
Admin Menu

I can't find a way to:

To provide interface translation for front-end only. Admin should be in English

Note: I assume this can be done by deactivating the language block on admin side) but how can this be done without duplicating the theme (the same theme for admin but with the block language disable).

How can this tasks could be accomplished?

The Administration Language module can do this:

  This module lets the administrator see all administration pages in her preferred language.

  You can use this to display the frontend of the site in one language and still keep most of the backend in English (or another language of your choice).

  You can use the standard Languages page to choose the language of the admin pages.


Using hook_form_alter to set default values for multiple-value CCK fields I was previously using the Default Value PHP field in the CCK Field Properties page to define multi-value default which was working fine. However the code is now getting so complex and I need to pass arguments to it that developing it within the CMS is becoming unfeasible, so I'd like to move the functionality out to a custom module.

I'm successfully using hook_form_alter to set defaults for single value CCK fields, so this isn't a problem. What I'm curious about is that when $form is passed to hook_form_alter, only the first element (0 or $form['field_myfield'][0]) exists, whilst I need to have from 0 to x default values.

Is the best practice simply to clone element 0 for as many default values as I need? Or is there another hook I should be using to set the initial number of empty fields before setting the defaults or something else I'm not thinking of?

Thanks :D

I think you may need to use #after_build, to ensure that your alter code runs after CCK has completely built the form element. Try something like this

function mymodule_form_alter(&$form, &$form_state, $form_id) {
  $form['field_myfield']['#after_build'][] = 'mymodule_after_build';
}

function mymodule_after_build(&$form_element, &$form_state) {
  // Have a look at the element with devel's dsm
  dsm($form_element);

  // Code to adjust your form element here...

  return $form_element;
}

I'm not 100% on the above syntax. I'd sugest you have a look at this article entitled hook_form_alter() and CCK fields


InnoDB gone missing as database type - has anyone seen this error before? I'm working on the Drupal 7 site that's currently on Dreamhost.

Since this morning, the site is showing the following error message:

  Error
  The website encountered an unexpected error. Please try again
  later.
  Error message PDOException: SQLSTATE[42000]: Syntax error or
  access violation: 1286 Unknown table engine 'InnoDB': SELECT expire,
  value FROM {semaphore} WHERE name = :name; Array ( [:name] =>
  variable_init ) in lock_may_be_available() (line 167 of
  /home/mysite.com/includes/lock.inc). Uncaught exception thrown in
  shutdown function.

  PDOException: SQLSTATE[42000]: Syntax error or access violation: 1286
  Unknown table engine 'InnoDB': DELETE FROM {semaphore} WHERE
  (value = :db_condition_placeholder_0) ; Array (
  [:db_condition_placeholder_0] => 7584349655055df9b66b5c9.36234254 )
  in lock_release_all() (line 269 of
  /home/mysite.com/includes/lock.inc).

Has anyone seen this sort of error before? Yesterday, my database showed as InnoDB in PHPMyAdmin; today there's nothing showing as "type."

On Debian 6, this can also happen when you change the innodb_log_file_size parameter. Sometimes mysql does not start; other times, it just starts up, but the InnoDB engine is not enabled. The solution is to remove ib_logfiles from /var/lib/mysql and restart mysql.

See this issue in drupal.org.


How to remove a line of HTML in webform? The company I work for uses Drupal Webform to collect information regarding it's customers. At the very end of the webform, we have a file component with a size maximum of 64 MB. I was tasked with removing the description under the upload.

Just to clarify, I don't want to remove the max size, just the text that says what the max size is.

You need to add to your css file this style:

div.field-widget-file-generic p.help-block{
    display: none;
}


How to add a login to a tab I have a website, but I want to figure out how to create a tab or link within the website that users would have to log in to view. There would most likely be one set of log in information that everyone in my organization would use. For example, maybe the username is org27 and password is 222orgs and everyone would use that to access the tab or link. How would I do that or is that even possible? Thank you.

You might take a look at the module, Protected Pages.  https://www.drupal.org/project/protected_pagesIt seems your tab would direct users to a particular page with sensitive or unique information pertaining to only those users.  In that case a simple module protecting those pages might do the trick.


Bold text from exposed filters I'm using an exposed filter in views to find nodes that contain that word in the body field.

I would like to show that word in the body in bold.

You can achieve this using search_excerpt function.

for eg:

in your views tpl file add the following code

 <?php foreach ($rows as $id => $row):

      $keys = $_GET['body_value'];
      $row = search_excerpt($keys, $row);
 ?>

it will highlight the searched word, see the screenshot below


Drupal 7.13 and Services 3.5 XML Payload schema to Update Node? I have finally got Services up and running and setup an endpoint to nodes but can't work out how to update custom fields from a POST or PUT.

Been trawling through the docs, examples, and tutorials but none seem to offer a simple explanation of the XML payload schema to update custom fields of nodes (Using REST).

Below is an example of what I'm putting into by test client (Using REST console for Chrome plugin)

URL: http://example.com/task/node/65
Encoding: application/x-www-form-urlencoded
METHOD: PUT

Payload:-

<title>New Title</title>
<body>New Body Content</body>

However this doesn't update anything, I just get the following response:-

<?xml version="1.0" encoding="utf-8"?>
<result>
    <nid>65</nid>
    <uri>http://example.com/task/node/65</uri>
</result>

It seems to create a revision and logs the update, but no fields are updated.

Can anyone advise the schema I need to follow for the payload? Thanks for any help or pointers!

EDIT: Thanks to Clive for a key pointer: Sticking ".xml" on the end of the URL seemed to make it update the body field, and then changing the content-type header to application/xml seemed to help as well.

So the following REST client config is now working:-

URL: http://example.com/service_endpoint/node/nid.xml

REQUEST METHOD: PUT

CONTENT-TYPE: application/xml

RAW PAYLOAD:-

<?xml version="1.0" encoding="UTF-8"?>
<data>
    <name>user</name>
    <title>Change this owner!</title>
    <body>
        <und is_array="true">
               <item>
                <value>Another owner test</value>
            </item>
        </und>
    </body>
</data>

Screenshot to help anyone else using the Chrome REST Console plugin:-

NOTE: I removed all security for the service and content type to make testing it easier but wouldn't recommend this on a public server!

See updated EDIT above.

RAW PAYLOAD:-

<?xml version="1.0" encoding="UTF-8"?>
<data>
    <name>user</name>
    <title>Change this owner!</title>
    <body>
        <und is_array="true">
               <item>
                <value>Another owner test</value>
            </item>
        </und>
    </body>
</data>


What is the equivalent of hook_menu_alter() to change a menu item type? I want to change the menu type in Drupal 8. In Drupal 7 we can achieve this using hook_menu_alter

function module_menu_alter(&$items) {
  $items['admin/config/people/ip-blocking/default'] = array(
    'title' => 'Block IP Address',
    'type' => MENU_DEFAULT_LOCAL_TASK,
  );
}

Similarly I want to change the menu type in Drupal 8. How can I do it.
Thank You.

Drupal 8 has a new menu system, there is no hook_menu and no hook_menu_alter anymore.

If you want to alter an existing route, it is a little bit more complicated in comparison to Drupal 7.

In your module you have to create a class file at YOURMODULE/src/Routing/CLASSNAME.php that extends RouteSubscriberBase:

/**
 * @file
 * Contains \Drupal\YOURMODULE\Routing\RouteSubscriber.
 */

namespace Drupal\YOURMODULE\Routing;

use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;

/**
 * Listens to the dynamic route events.
 */
class RouteSubscriber extends RouteSubscriberBase {

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
    // Get the route you want to alter
    $route = $collection->get('system.admin_content');

    // alter the route...
  }
}

You can take the RouteSubsciber class of the node module as an example.

To let your RouteSubscriber be recognized you also have to create a YOURMODULE.services.yml file in the root of your modules directory:

services:
  node.route_subscriber:
    class: Drupal\YOURMODULE\Routing\RouteSubscriber
    tags:
      - { name: event_subscriber }

To get a better insight to the new menu system I would recommend the following articles:

D7 to D8 upgrade tutorial: Convert hook_menu() and hook_menu_alter() to Drupal 8 APIs
What Happened to Hook_Menu in Drupal 8?

Edit:
As mentioned by Berdir, the menu system has a different structure now, which has nothing to do with D7's menu system, so there is no such thing as a menu type anymore.


How to get all nodes referencing a particular node? I have two node types, which I'll call A and B. Type A is a fairly straightforward content type, the only thing special is that it has a field (field_appearances) that references B nodes (tag-style, so each A may have one or more B tagged).
I am using Views to create a nice listing of all my B nodes, and I would like to have each B in this view list the A nodes that are referencing it (basically, so that users can easily see a list of A's that reference that particular B).
Effectively, this should look something like this:

B.1

Used in: A.1, A.2, A.3

B.2

Used in: A.2, A.4

What I've tried
First, I tried setting a relationship Content using field_appearances, then added a Title field to the view that used that relationship. This created a row for each B+A like so:

B.1

Used in: A.1

B.1

Used in: A.2

B.1

Used in: A.3

(...and so on for each B)

Next, I enabled aggregation and tried using various setups to get this right. The closest I got was setting the (referenced) Title field to aggregate on COUNT, which got me the following:

B.1

Used in: 3

B.2

Used in: 2

Any suggestions? I tried dinking around with Contextual filters but didn't get anything close to being right.

The Relationships and Aggregation features are fairly limited as they directly work on the database query, so you can only aggregate using very simple functions like COUNT, AVG, MAX etc.

What you are trying to do (load multiple related values for each row, and render them together) can be done with a sub-view, for example with this module: https://www.drupal.org/project/views_field_view

That would allow you to create a separate view ("Nodes referencing a particular node") with a contextual filter, then add this view as a field to the main view. It slightly impacts performance, as each row in the parent view executes a new sub-view, but should be okay with caching.


Multisite files folders In a first try to setup a multi-site configuration, I run into the following problem : anything done with a site (pictures, styles...) is added to sites/default/files/ directory, and an image added to a content points to sites/default/files/styles/some_style/.../image.jpg.

Is it the expected behaviour ? I thought any file would stay in sites/site1/files...

This is my sites/sites.php  :

$sites = array(
  '8083.arbre.dd' => 'arbre.dd', //local devdesktop site
  '8083.site2.dd' => 'site2.dd', //future one
);

I have folders sites/all, sites/default, sites/arbre.dd, sites/site2.dd.
I added a files directory and a settings.php file to the future site folder.
I notice that the arbre.dd folder added by Devdesktop at initial setting, has a shortcut icon ???

Verify your configuration at admin/config/media/file-system on the multisites. "Public file system path" may be configured to sites/default/files.


How to programmatically refresh the current page? I need to customize a module and after an if statement check, refresh the page:

So what I need is to refresh the page right after this and print out a success message.

What you can do is still use Rules for this.

Go to your custom rule
Under the Actions section, click Add action
For Select the action to add, choose Page redirect.
For URL, place the internal or absolute path to where the page you want to go to a.k.a. be refreshed.
Then save the action. This solves your problem to refresh the page.
Now we add another action to display a message, click the Add action link again.
For Select the action to add, choose Show a message on the site.
Then place your message then Save.

This way, your actions based on an event is configurable just with Rules. This also opens an opportunity to convert your custom code to respond using Rule Events like to trigger the rule after a node is saved and etc.

Update

This is an option to programatically do the above method.

After the rule invoke method, add the drupal_set_message function
After the drupal_set_message method, you would need to add the drupal_goto function which you will pass a Drupal path or a full URL.


File Transfer failed, reason: Cannot create directory /var/www/html/modules I have installed Drupal 8 on EC2. I am trying to install a module (simple_sitemap-8.x-2.5.tar.gz).

When I use the interface, I get a failed transfer message:

I have chmod a+x the directory (which already exists), but to no avail.

How should I solve this one? Is there a workaround to install modules without FTP?

The chmod a+x isn't enough, the directory should have write permission for HTTP server user, so try:

chmod 755 /var/www/html

Prefix with sudo if it's necessary.

or if you've already some files in it, try:

chmod -R u+rwX,go+rX,go-w /var/www/html

and if you're using Apache, you should change the ownership by:

chown -R www-data:www-data /var/www/html

If www-data is not correct, you can find the Apache user by the following command:

ps axho user,comm|grep -E "httpd|apache"|uniq|grep -v "root"|awk 'END {if ($1) print $1}


Drupal hook menu and node form I have a content type leg and this hook_menu :

$items['leg'] = array(
    'title' => t('Choose Leg'),
    'page callback' => 'drupal_get_form',
    'access arguments' => array('create leg content'),
    'page arguments' => array('mymodule_leg_select_form'),
    'type' => MENU_NORMAL_ITEM,
    'weight' => 0,
);

$items['leg/select'] = array(
    'title' => t('Choose an existing leg'),
    'page callback' => 'drupal_get_form',
    'access arguments' => array('create leg content'),
    'page arguments' => array('mymodule_leg_select_form'),
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => 1,
);

$items['leg/add'] = array(
    'title' => t('Create a new leg'),
    'page callback' => 'drupal_get_form',
    'access arguments' => array('create leg content'),
    'page arguments' => array('leg_node_form'),
    'type' => MENU_LOCAL_TASK,
    'weight' => 2,
);
return $items;

Here is the code snippet from mymodule_leg_select_form() which is called as MENU DEFAULT LOCAL TASK :

$form = array();
$result = db_query('SELECT nid, title FROM {node} WHERE type = :type AND status = :status ORDER BY title', array(':type'=>'leg', ':status'=>1));
$options = array();
foreach($result as $row){
    $options[$row->nid] = $row->title;
}
$form['leg'] = array(
    '#type' => 'select',
    '#title' => t('Leg'),
    '#options' => $options,
    '#required' => TRUE,
);

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

return $form;

The node form is not rendered correctly as you can see in the screen shot. I have two fields - field_from and field_to. They are not rendered in the form. The menu path "leg/select" which is default local task did work and correctly rendered my custom form.

The problem only is to integrate node add form in the second tab.
How can I fix this error ?

The problem is not your hook_menu implementation, but your function leg_node_form. That function probably calles node_form, which is in file modules/node/node.pages.inc you have to include that file manually using module_load_include.


How do I process a huge list of files? I have a huge list (> 100 000) of files that need to be processed. I want processing to run in the background and continuously (when it has processed the last, it just restarts on the first).

I've tried to do it with hook_cron(). There is a limit on how long cron can run, so to prevent cron timeouts, I throttle cron to process about 1000 files each time it runs (that is about the max cron can handle without timeouts).

To keep track of things between cron runs I use two db variables:

$mymodule_huge_array_data = variable_get('mymodule_huge_array_data', array());
$mymodule_counter_index = variable_get('mymodule_huge_array_index', 0);

After setting things up, cron get these two variables, and use $mymodule_counter_index to know where to start in the list of files. After processing 1000 files, it does:

$mymodule_counter_index += 1000;
variable_set('mymodule_huge_array_index', $mymodule_counter_index);

My problem is that getting that huge blob of an array from the database at the start of each cron makes the site slow during cron runs - even if I throttle cron to process only a single file.

I've looked at various alternatives.  The core batch API (Batch operations) alone can not be run from cron. Job Scheduler just uses cron to schedule jobs, so I don't think it will improve anything here.

Should I replace the single db variable holding the huge array blob with a table (with one file per record)?

I am currently looking Background Process and its Background Batch submodule. Is it suitable for this use case? It doesn't look so, it runs in the background, but just like the core batch API (Batch operations) alone, you need to initiate the process manually.

The accepted answer to this also looks like an option: Do I need a cron task for processing a queue?

Are there other (better) ways to do this?

What is the right way to chop up a large job into smaller bits, keeping track of the state as it progress through operations?

(To prevent this from being closed as "opinion based", let me emphasis that I am not asking for opinions about this.  I am asking for the correct way to process a huge list of files with Drupal.)

You can try

Method I - Using Cron and queue

Cron will run the query and push the list of nodes to the queue
queue will pick the items one by one and Unpublish them

Method - II Using Cron and batch

Cron will run the query and push the list of nodes to the Batch process
Batch process will be launched programmatically using background_process module

References

Batch API
How to create a batch operation in Drupal 7
SE Answer
D.ORG post


Getting views contextual filter from url for display suite block I have a URL for an event content type that concatenates two other content types, namely "name-of-venue" and "name-of-performer" with "date-of-event", so the url is "name-of-venue/name-of-performer/dateofevent".

I wish to place a block on the event content type that shows only the events for that venue.

I have tried to configure the contextual filter as shown on the screen shot,

using the PHP code:

  $np = explode('/', drupal_get_normal_path($argument)); if
  (!empty($np[3])) {   $handler->argument = $np[3];   return TRUE; }
  else {   return FALSE; }

However this does not return just those events for that specific venue, but for all venues.

Consequently I fear that I am not actually exploding the url and so failing to obtain the NID for "name-of-venue" that I need for the contextual filter.

Any suggestions would be very much appreciated.

Thank you.

Here is a kind-of-complex sketch for your problem, using only Views:

Create a block view displaying Content of type Event
Add a "Content: Nid" contextual filter, using the default settings. You may need to set the default value to "Content ID from URL" for the case "When the filter value is NOT available"
In your View configuration, under "Relationships", create a "Entity Reference: Referenced entity" relationship for your reference field (e.g. field_venue) and click on "Require this relationship": This relationship will retrieve the venue of the Event that is defined from the contextual filter.
Create a second relationship, one of type "Entity Reference: Referencing entity", again for your reference field (e.g. field_venue) and click on "Require this relationship". Important: Use the first relationship (step 3) for this one: This second relationship will retrieve the events that reference the venue we got from the first relationship.
Set your Views format to use fields (either by using a Table or by ticking the "Force using fields" option).
Add the fields you want to display and select the second relationship you created for them.

At this point your block should list all events for the venue of your current event. The problem that still remains is excluding the current event from that list. Follow steps take care of that:

Add two "Content: Nid" fields, set one of them to use the second relationship and exlude them from display.
Set a "Global: Fields comparison" filter and set it to filter out rows when the two excluded fields from above are equal: This will take care of excluding the actual event from showing in the block.

Once you place this block inside an event node page, it should display a list of Events from the same venue excluding the current event.

Cheers and let me know how this goes.

Appendix A:

Appendix B:


Show current date in a view title Is there a way to insert a PHP date into a title of a view block like so?

Thanks!

I'm not sure if this solution works and I'm not able to test it right bow, but download and install views_php module. it allows you to add a field which is fill by any php code. so in your views you must select fields instead of content. search for php then you can add this field. in this field try

drupal_set_title('TITLE');

if this works then you can put your php code there. If not you must modify the template file.


How to filter nodes by role (Content Access for nodes activated)? I have activated content access per node, so that I can control the access of the node directly on the node.
Now I want to create a view, with an exposed filter. The filter should contain the roles which are activated directly on the nodes.
So that I can find nodes which have maybe role A and B activated but not C.

Matroschker

Data related to access permissions per node settings are stored in content_access table created by content access module along with acl module tables like ace and acl_node

It is stored in serialized format.. For example

Content access doesn't have any views integration to list content filtered by roles based on settings...

I am afraid you need to read serialized array and then filter nodes using code...

To read values per node see per node settings page code below implemented in content access module..

/**
 * Per node settings page.
 */
function content_access_page($form, &$form_state, $node) {
  drupal_set_title(t('Access control for @title', array('@title' => $node->title)));

  foreach (_content_access_get_operations() as $op => $label) {
    $defaults[$op] = content_access_per_node_setting($op, $node);
  }

  // Get roles form
  content_access_role_based_form($form, $defaults, $node->type);

  // Add an after_build handler that disables checkboxes, which are enforced by permissions.
  $form['per_role']['#after_build'] = array('content_access_force_permissions');

  // ACL form
  if (module_exists('acl')) {
    // This is disabled when there is no node passed.
    $form['acl'] = array(
      '#type' => 'fieldset',
      '#title' => t('User access control lists'),
      '#description' => t('These settings allow you to grant access to specific users.'),
      '#collapsible' => TRUE,
      '#tree' => TRUE,
    );

    foreach (array('view', 'update', 'delete') as $op) {
      $acl_id = content_access_get_acl_id($node, $op);
      acl_node_add_acl($node->nid, $acl_id, (int) ($op == 'view'), (int) ($op == 'update'), (int) ($op == 'delete'), content_access_get_settings('priority', $node->type));

      $form['acl'][$op] = acl_edit_form($form_state, $acl_id, t('Grant !op access', array('!op' => $op)));
      $form['acl'][$op]['#collapsed'] = !isset($_POST['acl_' . $acl_id]) && !unserialize($form['acl'][$op]['user_list']['#default_value']);
    }
  }

  $form_state['node'] = $node;

  $form['reset'] = array(
    '#type' => 'submit',
    '#value' => t('Reset to defaults'),
    '#weight' => 10,
    '#submit' => array('content_access_page_reset'),
    '#access' => count(content_access_get_per_node_settings($node)) > 0,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#weight' => 10,
  );

  // @todo not true anymore?
  // http://drupal.org/update/modules/6/7#hook_node_access_records
  if (!$node->status) {
    drupal_set_message(t("Warning: Your content is not published, so this settings are not taken into account as long as the content remains unpublished."), 'error');
  }

  return $form;
}


Attach or embed node add form to a view I want to attach or embed a node form to a view so that when a user submits the form, the view below the form will be updated in realtime via ajax. The form will be shown above the view. My views block name is Statuses Stream.

I tried formblock module and putting the form in the header section of my view using views ui, but after submit, it was redirecting to the node created page.

Then I tried Advanced Form Block module. I created a form using AFB module. It is submitting the form with ajax, but it is not updating the view in the realtime.

I have just tried the Ajax Form Entity module. It is submitting and updating via ajax, but I cannot find a way to attach a view with it. However, in its settings, I can select a view mode. I need a little more flexibility.

How to Attach or embed node form to a view so that it submits via ajax and updates the view in realtime? I am open to any solution programmatically or through a module. Better if done programmatically because it will give more flexibility.

I'ld take it from the other side: Attach a view to a node form.

First I tried it with the built-in node form. But this turned out to be quite a hassle. Instead I built a small custom form and created new nodes programmatically. Ajax submit. View refreshed. Happy, happy.

Here comes the code for a custom module. Presuming a fresh D7 standard installation.

Info file

name = MYMODULE
description = Provides cool stuff.
core = 7.x
package = Custom
dependencies[] = views

Module file

First provide a view.

/**
 * Implements hook_views_api().
 */
function MYMODULE_views_api() {

  return [
    'api' => 3,
  ];
}

/**
 * Implements hook_views_default_views().
 */
function MYMODULE_views_default_views() {

  $view = new view();
  $view->name = 'nodes';
  $view->description = '';
  $view->tag = 'default';
  $view->base_table = 'node';
  $view->human_name = 'Nodes';
  $view->core = 7;
  $view->api_version = '3.0';
  $view->disabled = FALSE;

  /* Display: Master */
  $handler = $view->new_display('default', 'Master', 'default');
  $handler->display->display_options['title'] = 'Nodes';
  $handler->display->display_options['use_more_always'] = FALSE;
  $handler->display->display_options['access']['type'] = 'none';
  $handler->display->display_options['cache']['type'] = 'none';
  $handler->display->display_options['query']['type'] = 'views_query';
  $handler->display->display_options['exposed_form']['type'] = 'basic';
  $handler->display->display_options['pager']['type'] = 'none';
  $handler->display->display_options['pager']['options']['offset'] = '0';
  $handler->display->display_options['style_plugin'] = 'default';
  $handler->display->display_options['row_plugin'] = 'fields';
  /* Field: Content: Title */
  $handler->display->display_options['fields']['title']['id'] = 'title';
  $handler->display->display_options['fields']['title']['table'] = 'node';
  $handler->display->display_options['fields']['title']['field'] = 'title';
  $handler->display->display_options['fields']['title']['label'] = '';
  $handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
  $handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
  /* Sort criterion: Content: Post date */
  $handler->display->display_options['sorts']['created']['id'] = 'created';
  $handler->display->display_options['sorts']['created']['table'] = 'node';
  $handler->display->display_options['sorts']['created']['field'] = 'created';
  $handler->display->display_options['sorts']['created']['order'] = 'DESC';

  /* Display: Block */
  $handler = $view->new_display('block', 'Block', 'block');

  $views[$view->name] = $view;
  return $views;
}

Then do the form.

/**
 * Provide a form.
 */
function MYMODULE_form($form, &$form_state) {

  $form['wrapper'] = [
    '#type'       => 'container',
    '#attributes' => [
      'id' => 'mywrapper',
    ],
  ];

  $form['wrapper']['node_form'] = [
    '#type'  => 'fieldset',
    '#title' => t('Add article'),
  ];

  $form['wrapper']['node_form']['node_title'] = [
    '#type'     => 'textfield',
    '#title'    => t('Article title'),
    '#required' => TRUE,
  ];

  $form['wrapper']['submit'] = [
    '#type'   => 'submit',
    '#value'  => t('Save'),
    '#submit' => ['MYMODULE_form_submit'],
    '#ajax'   => [
      'callback' => 'MYMODULE_MYCALLBACK',
      'wrapper'  => 'mywrapper',
    ],
  ];

  $form['wrapper']['view_display'] = [
    // view machine name && display/block name
    '#markup' => views_embed_view('nodes', 'block'),
  ];

  return $form;
}

/**
 * Do some validation.
 */
function MYMODULE_form_validate($form, &$form_state) {
  // Better do some validation.
  // Here or via #element_validate.
  // @see https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7.x#element_validate
}

/**
 * Form submit. Node creation.
 */
function MYMODULE_form_submit($form, &$form_state) {

  global $user;
  $node = new stdClass();

  $node->type     = 'article';
  $node->title    = $form_state['values']['node_title'];
  $node->language = LANGUAGE_NONE;
  $node->uid      = $user->uid;

  node_object_prepare($node);
  node_save($node);

  // Empty out title field on rebuild.
  $form_state['input']['node_title'] = '';

  // Rebuild form.
  $form_state['rebuild'] = TRUE;
}

/**
 * Ajax callback to return the whole wrapper.
 */
function MYMODULE_MYCALLBACK($form, &$form_state) {

  return $form['wrapper'];
}

I've put it on a sample page to see it in action.

/**
 * Implements hook_menu().
 */
function MYMODULE_menu() {

  $items['example/form'] = [
    'title'            => 'Example Form',
    'description'      => 'A form to mess around with.',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => ['MYMODULE_form'],
    'access arguments' => ['create article content'],
  ];

  return $items;
}


Convert node data to pdf via Rules I have a project plan content type. I would like to be able to change the "start date" field value to the current date, and set the "deadline date" field value to 2 weeks after. Then I would like to convert this data into a file (eg. pdf) which I can then attach to another entity.

The majority of this can be achieved using the Set Data Value action in Rules module; except of course for converting the data into a file. The module FillPDF comes quite close although it only allows for converting Webform data to pdf and not node data.

The following modules are able to convert nodes to pdf, however they do not have Rules integration: PDF using mPDF, Printer, email, PDF versions

What is the best way to achieve this?

rules download module will definitely working with your requirement. This was previously discussed on drupal issue.

Rules Download:

Exposes some Rules actions to download files from the internet using HTTP and use them within rules.

This module exposes the following actions:

Download a file from the internet.

There's a possibility, if you fetches an URL from the site that triggered the rule, that, depending on your configuration, it triggers the same rule again. To prevent that, each file that is downloaded is appended with a special URL parameter (drupal_rules_download=1) that prevent the action to be run again.

Downloaded files are stored within the Drupal files system, so they can then be used to set file fields on entities and other drupal actions in which a file field item is expected. For adding it to a single File field use "Set a data value" and for a multiple File field use "Add an item to a list".

This module started of as an attempt to create PDF with the print module and use it in Rules, but because of how Print module works, it was safer to do it as a separate request and then, the module involved into something more general and flexible.


Display a grid view without border columns I'm trying to display a specific number of products in a e-commerce drupal site in the front page.

I would like to use a display as in my theme's demo : http://demo.morethanthemes.com/tophit/

I tried one module for horizontal slideshow but it turned out to have some bugs and another one for responsive grid did not help me fix my problem.

I am now using the original grid view, without pager.

I want to change the column color from grey to white, in order to be my products aligned but not displayed as a table.

Do you know any way to simple display a set of products/nodes horizontal ?
I prefer to use views, because the products probably will change.

Thank you,

Konstantina

I would use the Views Slideshow Module to build your slider, it's been the easiest to install and configure in my experience.

As far as changing colors, you are likely going to need to change your theme's CSS, which is not a Drupal specific problem. This search should get you started.


$form_state values show node title instead of integer I'm using a select list in my custom module. When I select some option in the list after submitting the form, I can see the $form_state['values']['select_field'] is showing an integer.

How can I make the form_state values to show the title of the list,  instead of number of the selected option?

Whatever you set as the array keys for options will be the values, so if you want to see option content rather than value, you need to set it up like that:

$form['select_field'] = array(
  '#options' => array('Text' => 'Text', 'More Text' => 'More Text'),
);

Or, leave the numeric keys where they are, and refer back to the original options array in your submit handler:

$selected_index = $form_state['values']['select_field'];
$display_value = $form['select_field']['#options'][$selected_index];

If you go with the first option, drupal_map_assoc() will probably be useful.


automatically fill the field info based on user selected I have content type "A" and I have field_users, and field_mail, where in the fields_users is entity reference field referring node of users, now when we select the user from the select list automatically the field_email should update based on the user selected since the user already created in D7.Is there any way to achieve this?

Please make a try by using Entity reference autofill and Entityreference prepopulate Modules.

Add an entity reference field.
The entity reference autofill will automatically fill reference value into field.
Entityreference prepopulate will prepopulate the values. (you have to add existing fields for that.)

For more details please refer project page.

Another approach using ajax. Try the following code in a custom module.

function your_module_form_alter(&$form, &$form_state, $form_id){
  if($form_id =='your_node_form_id') {
     $form['your-email-field']['#prefix'] = '
';
     $form['your-email-field']['#suffix'] = '
';
}
$form['your-user-field']['und'][0]['#ajax'] = array('callback' => 'your_module_callback', 'wrapper' => 'field-email-replace','method' => 'replace',);
}

function your_module_callback($form, $form_state){
  $uid = $form_state['values']['your-user-field']['und'][0]['value'];
  $user = user_load($uid);
  $form['your-email-field']['und'][0]['value'] = $user->email;

  $commands = array();
  $commands[] = ajax_command_replace("#field-email-replace",  render($form['your-email-field'])); // use render if you want to render field.

 return array('#type' => 'ajax', '#commands' => $commands);
}

Hope this will help you.


Bypass permissions in custom module I have written a custom module which generates a PDF when a Webform is submitted and mails it to the admin. I am using the Print module to generate the PDF. The problem is, it seems to use the user's permissions when generating the PDF, and not the admin's. This is generally ok for authenticated users, but for guests, it just fails completely.

I have enabled "Access the PDF version" and "Access own webform submissions" permissions for all users (anonymous and authenticated), but I guess "own" still checks for a user ID and fails for guests.

The Print module uses this code to get the content of the $node from the url

$node = new stdClass();
$node->body = menu_execute_active_handler($path, FALSE);

And here is how I am using the Print module to generate the PDF contents

module_load_include('inc', 'print_pdf', 'print_pdf.pages');
$pdf_url = 'node/' . $nid . '/submission/' . $sid;
$file_content = module_invoke('print_pdf', 'generate_path', $pdf_url);

When it's a user with permission (authenticated), this works fine, it generates and mails the PDF successfully. The contents of $node->body are fully populated.

However, when it's a guest, the contents of $node->body is just an integer. Is there any way for me to tell it to bypass the permissions when generating the PDF? Or is there a better, secure way around this?

Looking at webform_submission_access, prior to getting the PDF url, try:

// Where $sid is the webform submission id
$_SESSION['webform_submission'][$sid] = TRUE;

If that works for the anonymous user, it may grant access to view that submission.


Get field from another content type in Views I have two content types, 'user' content type where I have some info about user and then 'post' content type.

Now I have a view that gets all 'posts' and shows them correctly but I would need to get image (field_user_image) from 'user' content type. How can I get in views from this another content type this image field?

EDIT: Can I do this somehow on code level in template.php?

I cannot give you a very detailed answer, mainly because it has been too long since I built new things with Drupal 6, but also because I don't know which Views version you are using.

But anyway, the key to your answer is "relationships". Views allows you to define a relationship from one item to another (for instance: node -> author (user)) and then query properties of the related item (node -> author[name]). You can even chain relationships, so you can query a property of a related item of a related item. This seems to be what you need: node -> author -> node[field].

For more info I recommend that you find some video's or tutorials about views relationships, like these ones:

http://gotdrupal.com/videos/drupal-views-relationships
http://drupaleasy.com/blogs/ultimike/2009/07/using-views-relationships-arguments-attachments


How to create and set a new menu block in some content region, programmatically I want to create a new menu programmatically add for him some elements and the activate it in some content region as a block.

How can I do this programmatically?

I know how to add for an existing menu new elements, but I don't know how to create a new menu.

You save the menu using menu_save:

$menu = array(
  'menu_name' => '',
  'title' => '',
  'description' => '',
);
menu_save($menu);

I'm not sure if there is an api function to activate a block, but it can be done, by inserting  a row in the blocks table. You need to know the module, delta, theme and region. For menus, the menu module will create one with the delta being the menu_name.

So with the above you could do something like this:

$menu_block = array(
  'module' => 'menu',
  'delta' => $menu['menu_name'],
  'theme' => '', // Either get the active theme or you can do it for all themes
  'region' => 'content', // Where you want to place it, theme dependant
  'status' => 1,
);

So while you can do it, you probably want to make this theme specific, or do this in an install profile, where you know which theme should be the active one etc.


Considerations displaying page titles in page or node template This is very similar to this, hopefully its different enough to warrant its own question: How to display a field before node title?.

On our Drupal sites we have a dozen content types, many of which have custom node templates to control how they are rendered. We like this setup because our design/web production team can edit the template files easily but not more heavy drupal code.

However, we currently have only 1 page.tpl.php (we have a custom theme loosely based on bartik). In this template, we have ugly if-statements to make the page print different things based on the content type. Unfortunately, as the number of nodes increases this page.tpl.php is becoming unwieldy. The problem is that each node usually has different fields printed above and below the title, and usually modifies the ID of the title attribute.

What are the alternatives to adding more IF-statements into the page.tpl.php?

Move the printing of the title (and content above and below the title) down into each node.tpl.php
Modify the way that we are adding content above and below the title to use the existing title_prefix and title_suffix arrays
other?

If we switch to render arrays method, I worry that coming up with the ordering and formatting of the content above and below the title will become more difficult for non-coders.

It would be a much better practice to move most of this logic to the theme's preprocess_page: http://api.drupal.org/api/drupal/includes--theme.inc/function/template_preprocess_page function so you can keep the separation of logic and presentation and make things easier on your designers.

You could add variables that could contain the different fields and classes that change based on the nodes content type in the preprocess_page.


How to set default role as 'Member' in drupal 7? If I have a role i.e. Member. How to set 'Member' as a default role for the users after they registered yourself ? Please help. Thanks

Use Auto Assign Role module to set a default role at the time of user registration.

You can also use registration_role module to fulfill your requirement.


How do I use a different structure of a theme on different pages? The picture shows the block region demonstration of a Drupal theme that I am using.

I am new to Drupal.

As the structure is given, I want to use different structure in different pages of my site.
Say, at home page I want to use all the block regions Left Sidebar, Content and Right Sidebar. But for another page (one of the main navigation) I only want to use one of the sidebars with content and leave other sidebar. Also I want to add custom blocks at various regions on different pages.

Is this possible? If yes, how should I do it?

Theme block regions are just empty placeholders that mark up certain points within your HTML. Regions don't affect your site on their own, it is only when you put Blocks inside them that they show up.

Most (if not all) themes first check that a region isn't empty before printing the region container into the HTML. So regions don't appear in your HTML if there are no Blocks inside them.

What you should be focused on instead is Block Visibility, not regions. It makes more sense to control where each piece of content should appear, instead of controlling the containers/regions.

And you can control for each Block on which pages it should appear, so that is how you achieve the different structure of the pages. Some Blocks you set to display for example in sidebars regions but only on the front page. Some Blocks you put in the sidebar but only on node pages.

If there is a page that doesn't have any blocks set to appear in sidebars, then this page will not show any "sidebar area". It will be up to your theme CSS to style what the page without sidebars looks like. Most likely it will just be a simple one column area for your content.

There are modules that allow you for more control over the Blocks placement (Context for example), that do something that could be described as turning regions on or off, but that is a slightly different approach and I think you should play with the original Blocks arrangement first if you're new to Drupal. It is much easier to understand and setup Blocks to be visible on only sections of your website.

In Drupal 8 you can place the same Block more than once, in another region, or even the same region. You can then adjust the Visibility to different conditions, so for example you can have your Main navigation displayed in Header region on the front page, but displayed in the sidebar on all other pages.

BTW the above example isn't the best one, navigation should be always in the same place for accessibility and other reasons. But I hope you understand the concept of placing Blocks in regions, but then using Visibility to make them appear on only certain pages, and not others.


How to give permission for a role for editing help text for fields of custom types? I want role "RoleFoo" to have only the permission to edit the Help Text of all fields of  specific content types (contentypefoo1 and contentypefoo2).

How to do this?

The Field help helper module seems to be a good fit for this. some more details about it (from its project page, which is also here the image originates from):

The Field help helper module adds a link to entity configurable fields so that users with the appropriate permissions may easily edit the help text and label for a field in context of where the field displays.
Once a user's role is given the Edit field help text permission any user with that permission will be able to edit the help text or label of a configurable field without having access to administer fields.

Extra bonus: comes wth an official release for both D7 and D8 ...


n00b question, form callback and form_alter My highly-n00b question is: suppose I have a form callback which could be used as argument to drupal_get_form().

How can I specify an ID for the form so I can compare it inside hook_form_alter against the given-as-argument $form_id?

This means: I want to give a form id to the form, e.g. "my-system-form", and distinguish it to apply some alter-logic (don't want to apply that logic to the rest of the forms).

hook_form_alter() has $form_id as an argument:

function hook_form_alter(&$form, &$form_state, $form_id) {

Which is:

  String representing the name of the form itself. Typically this is the name of the function that generated the form.

(emphasis mine)

To understand the "typically" in there, have a read through the docs for hook_forms() (chances are it won't apply to your situation, or if it does, you probably already know about it).

So, generally speaking, you can use:

function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'MYMODULE_some_form') {
    ...
  }
}

Or, the more specific hook_form_FORM_ID_alter(), which will only be invoked for that specific form:

function MYMODULE_form_MYMODULE_some_form_alter(&$form, &$form_state, $form_id) {
  ...
}


What is the best way to migrate and optimize 300 GB database to drupal? I have a database that was running on a propitiatory system with a hosting company. The data is about 10 years old and mostly text. The database it too large aprox 300GB. We are trying to migrate the database to Drupal and I am wondering if this is a good idea and whether drupal/mysql could support such large databases or not. I have a few thoughts such as archiving the data and using caching tools such as varnish. Is this a good idea? Can drupal support/serve it? What impact could this have on performance?

Edit: We have already migrated the database but performance is a extremely bad. ~17 million nodes, and ~90 million comments. What could I optimize? what kind of infrastructure would you recommend? caching and architecture? Load balancing? Any hints or tips that could help run such big site with drupal is what I need. Case studies if anyone is aware of.

The answer is Yes.
First - because you are asking on Drupal Answers site.
I would recommend you using configuration like this:

0 Load balancer managing several servers
1 Varnish (proxy cache)
2 Nginx (php-fpm)
3 Drupal
4 MySQL (Master+Slave)

Also memcache can be used. The main problem will be when you will try to update/insert new record in DB. All read queries will be managed by caching-proxying systems.
If you need text search - use ApacheSolr.
Try to not views or panels, with such DB size you can have perfomance issues.


Custom form set error for user login validate I have used a custom validate function.

function user_information_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_login' || 'user_login_block') {
    array_unshift($form['#validate'],'user_information_user_login_form_validate');
  }
}

function user_information_user_login_form_validate(&$form, &$form_state) {
  // print_r($form_state);
  form_set_error('name', t('Password invalid'));
}

But I am unable to log in to the site any more.

you cant submit your form because you have set the error.

the form set error should be applied inside some condition

 function user_information_user_login_form_validate(&$form, &$form_state) {
    //print_r($form_state);
    //set some condition
     if($form_state["some_field"] != "somevalue")// only when the condition satisfies the form set error should display. if not all the time your from set error will be called
      form_set_error('name', t('Password invalid'));
    }

above condition is a sample condition you have to replace it with your own condition for validating your password.


How to add a nolink menu item I'm creating a menu item for my main navigation bar. It looks like this:

module/module.links.menu.yml:

top.link:
  title: 'Operations'
  description: 'Operations'
  parent: main
  menu_name: main
  url: 'route:<nolink>'
  expanded: TRUE
  weight: -49

mod.first_option:
  title: 'Functionality 1'
  description: 'Functionality 1'
  parent: 'top.link'
  menu_name: 'top.link'
  route_name: 'mod.route_name1'
  expanded: TRUE
  weight: -49

mod.secon_option:
  title: 'Functionality 2'
  description: 'Functionality 2'
  parent: 'top.link'
  menu_name: 'top.link'
  route_name: 'mod.route_name2'
  expanded: TRUE
  weight: -47

I'm trying to create an empty top level link, with nested elements beneath it for a menu. I've tried url: 'internal:##', url: 'route:<nolink>', and link: '<nolink>',  Anything else I could try?

Try adding the following, but this will still reload the page, which may not be ideal.

url: 'internal:#nolink'

These module maybe interesting as it may not be necessary to manually edit the menu code. You can add a class to a menu item and add CSS

pointer-events:none; cursor:default; text-decoration:none;

https://www.drupal.org/project/link_attributes
https://www.drupal.org/project/menu_link_attributes


How to change the output of a theme function? I know this question already has some "kind" of answer in documentations but they are too abstract for me. Most documentation I have seen on Drupal doesn't explain all the details of how to properly override a theme function, or maybe I don't understand.

My problem is that I need to change the output of theme function theme('links__system_main_menu', ...), which is used in page.tpl.php to print the content of the main menu. I don't understand how to make it done. Please explain me every step you take and why did you take that step.

To override the output of a theme function in a theme, you simply take the name of your theme, and the name of the theme function, and join them together with an underscore.

So for your example, the function would be called:

function MYTHEME_links__system_main_menu($variables) {
  $html = '<ul>';

  // Loop over links

  $html .= '</ul>';

  return $html;
}

Your function should return the HTML string that you want to be rendered when this theme is used, any variables that have been passed to the theme() function will be available to you in $variables.

Usually it's enough to look at the original theme function to find out what's available to build your HTML, but sometimes you'll need to get the Devel module installed and inspect vars with dpm to properly see what's going on.


Creating a language in code I want to set create a language in PHP code (for example, using a hook_update_n implementation) so I can deploy and automate it.

How?

Note that Features module supports exporting languages.

Answering the question:

// Example language: fr.
$language = (object)array(
  'language' => 'fr',
  'name' => 'French',
  'native' => 'Français',
  'direction' => 0,
  'enabled' => 1,
  'plurals' => 0,
  'formula' => '',
  'domain' => '',
  'prefix' => 'fr',
  'weight' => 0,
);

locale_add_language($language->language,
  $language->name,
  $language->native,
  $language->direction,
  $language->domain,
  $language->prefix,
  $language->enabled);

// Additional params not implemented in locale_add_language().
db_update('languages')
  ->fields(array(
    'plurals' => $language->plurals,
    'formula' => $language->formula,
  ))
  ->condition('language', $language->language)
  ->execute();


Can we use current views exposed filter values to prepopulate another form? I've set up a view that displays users and has exposed filters user first and last names. If there is no user matching the filter values, I'd like to display a link to create a new user and prepopulate the name fields with the values searched in views.

I know there's the prepopulate module and likely other methods to do the actual prepopulating, but I guess this question is more centered on how to grab the filter values so they can be added to the new link url as properly formatted arguments.

EDIT: Got this solved with help from the answer below. Ending up grabbing the filter values with the "exposed filter values" module and populating the field values in a custom module with this code:

function hook_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == 'user_register_form') {

        //Prepopulate the name fields with url args
        $field_lang = $form['field_name']['#language'];
        if(isset($_GET['first'])) {
            $first = $_GET['first'];
            $form['field_name'][$field_lang][0]['#default_value']['given'] = $first;
        }

        if(isset($_GET['last'])) {
            $last = $_GET['last'];
            $form['field_name'][$field_lang][0]['#default_value']['family']= $last;
        }
    }
}

After googling this question some, I came up with the following receipe:

Install prepopulate and exposed filter data
Modify exposed_filter_data.tpl.php provided by exposed filter data to produce a dynamic prepopulate URL for creating a new user

Hope this helps!

P.S.: Inspired from this discussion => https://www.drupal.org/node/1630198


Have the same rendered output, whether the video is a local or remote ressource I need to let contributor either upload video or link to some remote streams (youtube).

For this, I use media (and media_youtube) module.

I works well for remote ressources, however when I try to upload a video instead, the video appears as a link, on the front (though I tried to fumble with the manage display settings for this peculiar field).

I tried to implement jwplayer for the local videos, but it did not work this time. I also had a look at mediafront module, but as far as I know, it does not handle "local" videos (I may be wrong, but it seems overkill).

Have you been facing such a problem before, that is render a consistent display (a player with the same dimensions), regardless of the source (local or remote) ?
Can you point me to some resources ?

Thank you.

Haven't tried it yet, but I believe that is what is good about the mediafront module.  It wraps the youtube or local videos in it's own themeable player.

You could also try http://drupal.org/project/mediaelement module, though I'm not sure how well that display's youtube videos.