Pressflow 6 forms creating session cookies

// Default backend definition.  Set this to point to your content
// server.
//
backend default {
  .host = "127.0.0.1";
.port = "81";
.connect_timeout = 600s;
.first_byte_timeout = 600s;
.between_bytes_timeout = 600s;
// enable to use status script for health of backend
//  .probe = { .url = "/status.php"; .interval = 5s; .timeout = 1s; .window = 5;.threshold = 3; }
}

//
// BOOSTED VARNISH - by Trellon, LLC
//
// - Based on a configuration by Lullabot and VCL examples for Varnish Wiki.
//
// Logic is:
//
// * Assume: A cookie is set (we add __varnish=1 to client request to make this always true)
// * If boosted URL -> unset cookie
// * If backend not healthy -> unset cookie
// * If graphic or CSS file -> unset cookie
//
// Backend response:
//
// * If no (SESSION) cookie was send in, don't allow a cookie to go out, because
//   this would overwrite the current SESSION.

// Respond to incoming requests.
sub vcl_recv {

////// START BOOST Logic (Prerequisite)
  // We always send a cookie, so that empty requests are
  // handled by below boost logic, too.
  set req.http.Cookie = ";__varnish=1;" req.http.Cookie;
////// END BOOST Logic (Prerequisite)

// Enable to disable varnish
//      return (pipe);

////// START DEFAULT RULES
 // -------- CloudFlare ----------
  remove req.http.X-Forwarded-For;
  if (req.http.CF-Connecting-IP) {
    set req.http.X-Forwarded-For = req.http.CF-Connecting-IP;
  } else {
    set req.http.X-Forwarded-For = client.ip;
  }

  // Remove a ";" prefix, if present.
  set req.http.Cookie = regsub(req.http.Cookie, "^;\s*", "");
  set req.http.Cookie = regsub(req.http.Cookie, "^__\s*", "");
  set req.http.Cookie = regsuball(req.http.Cookie, "(^|;\s*)(__[a-z]+|cfduid)=[^;]*","");
  // -------- CloudFlare ----------

 if (req.request != "GET" &&
    req.request != "HEAD" &&
    req.request != "PUT" &&
    req.request != "POST" &&
    req.request != "TRACE" &&
    req.request != "OPTIONS" &&
    req.request != "DELETE") {
      // Non-RFC2616 or CONNECT which is weird.
      return (pipe);
  }
  if (req.request != "GET" && req.request != "HEAD") {
    // We only deal with GET and HEAD by default
    return (pass);
  }

////// END DEFAULT RULES

  // Allow the backend to serve up stale content if it is responding slowly.
  set req.grace = 1h;

  // Do not cache these paths.
  if (req.url ~ "^/status\.php$" ||
      req.url ~ "^/sitemap\.xml$" ||
      req.url ~ "^/update\.php$" ||
      req.url ~ "^/jstats\.php$" ||
      req.url ~ "^/boost_stats\.php$" ||
      req.url ~ "^/cron\.php$" ||
      req.url ~ "^/ooyala/ping$" ||
      req.url ~ "^/admin/" ||
      req.url ~ "^/info/.*$" ||
      req.url ~ "^/flag/.*$" ||
      req.url ~ "^.*/ajax/.*$" ||
      req.url ~ "^.*/ahah/.*$") {
       return (pass);
  }

  // Pipe these paths directly to Apache for streaming.
  if (req.url ~ "^/admin/") {
    return (pipe);
  }

  // Do not allow outside access to cron.php or install.php.
  if (req.url ~ "^/(install)\.php$" && !client.ip ~ internal) {
    // Have Varnish throw the error directly.
    error 404 "Page not found.";
    // Use a custom error page that you've defined in Drupal at the path "404".
    // set req.url = "/404";
  }

  // Handle compression correctly. Different browsers send different
  // "Accept-Encoding" headers, even though they mostly all support the same
  // compression mechanisms. By consolidating these compression headers into
  // a consistent format, we can reduce the size of the cache and get more hits.=
  // @see: http:// varnish.projects.linpro.no/wiki/FAQ/Compression
  if (req.http.Accept-Encoding) {
    if (req.url ~ "\.(jpg|png|gif|gz|tgz|bz2|tbz|mp3|ogg|mp4|flv|f4v)$") {
      // No point in compressing these
      remove req.http.Accept-Encoding;
    }
    else if (req.http.Accept-Encoding ~ "gzip") {
      // If the browser supports it, we'll use gzip.
      set req.http.Accept-Encoding = "gzip";
    }
    else {
      // Unknown or deflate algorithm. Remove it and send unencoded.
      unset req.http.Accept-Encoding;
    }
  }

////// START .htaccess rewrite rules

// Strip out Google Analytics campaign variables. They are only needed
// by the javascript running on the page
// utm_source, utm_medium, utm_campaign, gclid
  if(req.url ~ "(\?|&)(gclid|utm_[a-z]+)=") {
    set req.url = regsuball(req.url, "(gclid|utm_[a-z]+)=[^\&]+&?", "");
    set req.url = regsub(req.url, "(\?|&)$", "");
  }

////// END .htaccess rewrite rules

////// START BOOST Logic

  // This is no pressflow, so we always have a SESSION

  // but boost will always set the DRUPAL_UID cookie
  // when the user is logged in.
  //
  // So it is safe to remove all cookies for the boosted paths.
  if (!(req.http.Cookie ~ "DRUPAL_UID=")) {
     // User is anonymous

     // Boost rules from .htaccess
     if (!(req.url ~ "(^/(admin|cache|misc|modules|sites|system|openid|themes|node/add))|(/(comment/reply|edit|user|user/(login|password|register))$)")) {

////////// BOOST CONFIG: Change this to your needs
       // Boost rules from boost configuration
       if (!(req.url ~ "/(excluded-url-to-be-configured)")) {
         unset req.http.Cookie;
       }
////////// END BOOST CONFIG: Change this to your needs
    }
  }

////// END BOOST LOGIC

////// Cookie removal logic

  // Always cache the following file types for all users.
  if (req.url ~ "(?i)\.(png|gif|jpeg|jpg|ico|swf|css|js|html|htm|gz|tgz|bz2|tbz|mp3|ogg|mp4|flv|f4v|pdf)(\?[a-z0-9]+)?$") {
    unset req.http.Cookie;
  }

  // Use anonymous, cached pages if all backends are down.
  if (!req.backend.healthy) {
    unset req.http.Cookie;
  }

}

// Routine used to determine the cache key if storing/retrieving a cached page.
sub vcl_hash {
  // Include cookie in cache hash.
  // This check is unnecessary because we already pass on all cookies.
  // if (req.http.Cookie) {
  //   set req.hash += req.http.Cookie;
  // }
}

// Code determining what to do when serving items from the Apache servers.
sub vcl_fetch {

////// START BOOST Logic

  // This is no pressflow, so we always have a SESSION
  // but we only set SESSION if we actually send cookies
  //
  // So logic is: If we did not send a cookie in,
  // we do not allow a cookie out.

  if (!req.http.Cookie) {
    unset beresp.http.set-cookie;
  }

////// END BOOST LOGIC

  // Don't allow static files to set cookies.
  if (req.url ~ "(?i)\.(png|gif|jpeg|jpg|ico|swf|css|js|html|htm|gz|tgz|bz2|tbz|mp3|ogg|mp4|flv|f4v|pdf)(\?[a-z0-9]+)?$") {
    // beresp == Back-end response from the web server.
    unset beresp.http.set-cookie;
  }

  // Allow items to be stale if needed.
  set beresp.grace = 1h;

  // Serve the good page from the cache and re-check in one minute

  if (beresp.status == 503 || beresp.status == 501 || beresp.status == 500) {
    set beresp.grace = 60s;
    restart;
  }

  // Anything that is cacheable, but has expiration date too low
  // which prevents caching gets cached by varnish to take the
  // load off apache.

  if (beresp.cacheable && beresp.ttl < 1h) {

////////// MINIMUM CACHE LIFETIME: Change this to your needs
    // Set how long Varnish will keep it
    set beresp.ttl = 1h;
////////// END MINIMUM CACHE LIFETIME: Change this to your needs

    // marker for vcl_deliver to reset Age:
    set beresp.http.magicmarker = "1";
  }

}

sub vcl_deliver {
////// START DEBUG
  if (obj.hits > 0) {
    set resp.http.X-Varnish-Cache = "HIT Varnish (" obj.hits ")";
  }
  else {
    set resp.http.X-Varnish-Cache = "MISS";
  }
////// END DEBUG

  // The magic marker is used to reset the age to 0
  // as else the object is older than its ttl.

  if (resp.http.magicmarker) {
    // Remove the magic marker
    unset resp.http.magicmarker;

    // By definition we have a fresh object
    set resp.http.Age = "0";
  }
}

// In the event of an error, show friendlier messages.
sub vcl_error {
  // Redirect to some other URL in the case of a homepage failure.
  //if (req.url ~ "^/?$") {
  //  set obj.status = 302;
  //  set obj.http.Location = "http://www.megaleecher.net";
  //}

  // Otherwise redirect to the homepage, which will likely be in the cache.
  set obj.http.Content-Type = "text/html; charset=utf-8";
  synthetic {"

  <title>"} obj.status " " obj.response {"</title>

Page Could Not Be Loaded

The page you requested is temporarily unavailable.

We're very sorry, but the page could not be loaded properly. This should be fixed very soon, and we apologize for any inconvenience.

We're redirecting you to the Tech Blogs Homepage in 5 seconds.

(Error: "} obj.status " " obj.response {")

"};
  return (deliver);
}

The above worked for me, if you are not using Cloudflare make sure to remove that section.


how to add credits each month with rules?

Check out Rules Example which is an example module showing how to integrate custom module with rules.

You can add a new parameter (e.g. condition - check if this is first day of the month) and perform all checks/actions you need there.


Install Vanilla Wordpress to Drupal to use Vanilla Forum

You might need to install Orchid. Only by using this module you can integrate Drupal with Vannila Forum.


composer require fails because it can't delete default.services.yml

Make your "local" machine work as intended, and maintain the security of your live site.
Since you want to use composer require command only on non-production environments, the following steps affect only on the machines you deliberately set up. Drupal's recommended configuration will be preserved on all other machines, including production servers.
Don't make this change to settings.php to avoid having it on PROD or propagating it silently to other developers' machines.
Steps

enable settings.local.php (here are the instructions from the docblock in settings.local.php):

 * To activate this feature, copy and rename it such that its path plus
 * filename is 'sites/default/settings.local.php'. Then, go to the bottom of
 * 'sites/default/settings.php' and uncomment the commented lines that mention
 * 'settings.local.php'.
 *
 * If you are using a site name in the path [... read about exceptions in file]

set file permissions to allow user and group to write to the file on your local machine:
$ chmod ug+w {name_of_docroot}/sites/default

How this approach matches up with the established community approach
By default, settings.local.php contains the following line:
$settings['skip_permissions_hardening'] = TRUE;

This line tells Drupal to avoid resetting permissions on the default folder only on your local, and allows you to work more smoothly with composer on your local without weakening permissions on any other copy of the codebase.


This is a way to it:

Add the feature exportable manually to the module.info.
You can check the available features with the drush features-list command. You have to find the field dependency format within that list, it could be a variable that looks like your field name.
If you module.info has the new field dependency, you can update the feature drush fu myfeature_module
Then review the generated files, maybe with git diff. You should see the change.

I am not sure what an exported field dependency looks like, there are different formats, these are examples so that you have an idea of what it would look like:

features[ctools][] = field_group:field_group:1

features[ctools][] = strongarm:strongarm:1

features[features_api][] = api:2

features[field_base][] = field_image

features[field_group][] = group_teaser|node

features[field_instance][] = node-about_page-field_image

features[node][] = about_page

features[variable][] = comment_about_page


How to get an entity create route, given an entity type and bundle?

Given Clive's comment, and some further thought about it, one thing I could do is create an annotation, such that custom entity developers can declare their route. Further, I can add annotations to the module that cover all core cases (node/user/taxonomy), such that the module works with core out of the box.

From there, I could add conditional logic that looks for a given entity's annotation, and if it doesn't find it, it would then make the same assumption (/{entity_type}/add/{bundle}) as above. I suppose from there either developers can declare an annotation in their own module, or if a particular custom entity is popular and keeps hitting the issue queue, I could add that as well.


How to override the widget of an exposed form filter?

Ok, so after spending a day digging around the net, it seems that there are two ways to do this.

First off, for clarification, the exposed filter from the view is not a widget, at least in the Drupal sense of the word. In the traditional Drupal sense of the word, a widget is something used on an edit form or add form. Hooks like hook_field_widget_alter() and it's brethren operate on these widgets.

Just because the views-exposed-form.php.tpl has $widget as a variable, THAT DOES NOT MAKE IT A WIDGET!!!

Now that that confusion is out of the way, there are two ways to change the exposed filter.

Add a custom module and use hook_form_alter to change things about the exposed filter form. I got as far as creating a custom module (called bypass) and creating a hook to display some simple debugging info:

function bypass_form_alter(&$form, &$form_state, $form_id){
    dsm($form_id);
    dsm($form);
}

when I discovered the Better Exposed Filters module.

Use the Better Exposed Filters module to display the filters as checkboxes, radio buttons, etc. and style those.

Option 2 is what I'm doing now.  Hope this helps someone :)


You can use apache module mod-auth-token (https://code.google.com/p/mod-auth-token/) to generate a one-time url. Please refer to the documentation for more specific instructions (there is both apache configuration and php example how to use it).


You can use REWRITE RESULTS with REPLACEMENT PATTERNS

Any Text

Example
If i want to edit any node

Any Text


Blocks are cached by default, so not specifiying anything should mean your guzzle call should only run once.

max-age 600 then means that the cache is not valid indefinitely but only 600s.

Note that anonymous page cache currently doesn't respect that setting. You have to disable that if you need this to update every 600s.


I found following solution which works for me.....

VIEW > ADVANCED > Contextual filters

Add filter and look for WHEN THE FILTER VALUE IS NOT IN THE URL section.

Select 'Provide default value' > Type: Raw value from url > Path component: ____ (set url id value path number)

e.g if this is url, to get 239066 I will set Path component: 3

(https://drupal.abc.com/questions/239066)

VIEW > Attachment settings > HEADER > Add: Text area > Replacement patterns section will display your url id i.e {{ arguments.url_id }}


How can I obscure what I am using to run my site?

You can't hide it completely. Most of what's needed to do it, would require hacking core. The biggest tell, is the Drupal JavaScript variable which is readable from the front page, or any page for that matter.

If you want to improve your sites security by hiding that it's a Drupal site, your effort is better spent on code reviews than it is on trying to hide the fact that the site is made with Drupal.


How to override individual blogs/% page?

blogs/[username] is the path alias; the internal path is blog/[uid]. Change your view to use the internal path blog/%.

Where % represents the passed value that you are capturing like the userid. Then you will need to add an argument as well like User: User ID so that everything is consistent


I'd wager that the stylesheet has not been added to the page. The documentation is pretty solid on this: Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme.

This page isn't likely to go anywhere, but I'll summarise here. Please go and read the full documentation page though, there is MUCH more there:

  The general steps for loading assets (CSS/JS) are:

  Save the CSS or JS to a file.
  Define a "library", which can contain
  both CSS and JS files.
  "Attach" the library to a render array in a
  hook.

  But in the case of themes, there is an alternative to step 3:
  themes can choose to load any number of asset libraries on all pages.

  Libraries

  [...] a library could just as well only contain CSS assets, or only contain JS assets. Most themes will probably want to have a global-styling asset library, for the stylesheets (CSS assets) that it wants to be loaded globally (i.e. on all pages where the theme is active — usually the whole site except the administration pages):

global-styling:
  version: 1.x
  css:
    theme:
      css/layout.css: {}
      css/style.css: {}
      css/colors.css: {}
      css/print.css: { media: print }

  Attaching a library to page(s)

  Attaching to all pages

  To attach a library to all the pages on the site that use your theme,
  declare it in your theme's *.info.yml file, under the libraries key:

name: Example
type: theme
core: 8.x
libraries:
  - fluffiness/cuddly-slider


Change the filter widget type in a views

I think you might be looking for something like Views Autocomplete Filters.  The D7 version is in development but it sounds like it might be worth a try.


How to programmatically create a product display(node) with reference to the product?

Try this function in a custom module

function commerce_display_product_create_method($product){
    $node = new stdClass();
    $node->type = 'product_display';
    node_object_prepare($node);

    $node->title    = $product->title;
    $node->language = LANGUAGE_NONE;

    $node->field_product['und'][0]['product_id'] = $product->product_id;
    node_save($node);
}


How to show the content on ajax or Jquery lightbox

You should describe the problem you are facing ...
What 'lightbox-meme' are you trying to implement ?

If you are using the lightbox module for drupal, you should read the README.txt, that is pretty self-explanatory.

Hope this helps.


Is it possible to wrap the fields of a view inside a  and ?

You will need to add a View template to your theme, take a look at Views template files to give you an idea of how to accomplish this


How to change the position of a block in a particular page?

You can place the default User Login block in Sidebar first region at the last position. You can exclude this block from being shown in Homepage using 'Visibility settings' which is available in the block edit page.

Then you can use front page template page--front.tpl.php and render the block manually by passing the block markup through hook_preprocess_page().

function THEME_NAME_preprocess_page(&$vars, $hook) {
  $front_page = drupal_is_front_page();
  if ($front_page) {
    $user_login= block_load('user', 'login');
    $vars['user_login'] = _block_get_renderable_array(_block_render_blocks(array($user_login)));
  }
}

Then you should print the $user_login variable in the front page template inside the Footer Fourth region.


How to get price to update when changing attrubutes within a View

Found it:

you must add a content: NID field and exclude from display to get the token of [nid] available
Then under style settings of the price field, select 'customize field HTML'
HTML element = DIV
Select Create a CSS class
the CSS class for Price is: node-[nid]-product-commerce-price

The NID token will update when a certain attribute changes. This can also be applied to other fields as well finding the CSS with firebug and then adding in the [nid] token


How to insert field value programmatically after node is created?

I suppose it is due to your field_attach_insert(). Usually one should save the entire node using node_save().
However it is a lot easier if you install the entity API module and utilize its Entity Metadata Wrappers.

And I'd really recommend creating a custom module. You will need something similar to this:

function mymodule_node_insert($node) {
  if ($node->type == 'article') {
    mymodule_update_empty_value($node);
  }
}

function mymodule_node_update($node) {
  if ($node->type == 'article') {
    mymodule_update_empty_value($node);
  }
}

function mymodule_update_empty_value($node) {
  $wrapper = entity_metadata_wrapper('node', $node);
  // No value?
  if  (empty($wrapper->field_myfield->value())) {
    $wrapper->field_myfield->set('NA');
    $wrapper->save();
  }
}


How to send email using Rules from user references CCK Field?

In the recipient input, try to write a php code which returns the email :

$customer_node = node_load( $node->field_customer['und'][0]['nid'] );
$account = user_load( $customer_node->field_user['und'][0]['uid'] );
print $account->mail;

Note that a better way is to use a custom function in a custom module :

print _get_customer_email( $node );

and

function _get_customer_email( $node ){
  $customer_node = node_load( $node->field_customer['und'][0]['nid'] );
  $account = user_load( $customer_node->field_user['und'][0]['uid'] );
  return $account->mail;
}


'Notify user of new account' checkbox to be selected as default

found here - http://drupal.org/node/1295268#comment-5060488

<?php
function MODULE_NAME_form_alter(&$form, $form_state, $form_id){
    if ($form_id == 'user_register') {
        $form['account']['notify']['#default_value'] = TRUE;
    }
}
?>


Can View content be filtered to what's new since user's last login?

In your view, add a new filter criteria for "Content: Has new content." This should do exactly what you want.


Drupal Form Checkbox having different name and id (of my choice)

Found answer,
done like this:

$form['wrapper'][$unitClean.'_container'][$unitClean.'_cb'] = array(
                '#type' =>'checkbox',
                '#title' => t($unit),
                '#attributes' => array(
                  'name' => $unitClean.'_name',
                  'id' => $unitClean.'_id',
                  'onclick' => 'checkall();'
                    )
                );


How to limit users to a create only one instance of a node type?

FWIW I've been using Node Limit on a dev site for a few weeks now, it's had thorough testing and seems to work perfectly. I'm using the 'Node Limit Type' and 'Node Limit User of Role' sub-modules.

If you want to implement it yourself, you can't really look anywhere better than inside the Node Limit module itself. It implements hook_node_prepare() to deny access to the node add form if the user has exceeded the maximum nodes, based on various rules.

A very simple custom implementation might look like this:

function MYMODULE_node_prepare($node) {
  if (empty($node->nid) && $node->type == 'the_content_type') {
    // Grab the number of nodes of this type the user has already created.
    $args = array(':type' => 'the_content_type', ':uid' => $GLOBALS['user']->uid);
    $node_count = db_query('SELECT COUNT(nid) FROM {node} WHERE type = :type AND uid = :uid', $args)->fetchField();

    // Get the max allowed number of nodes
    $limit = function_to_get_limit();

    // If the user is at/has exceeded the limit, set a message and send the user
    // off somewhere else.
    if ($limit >= $node_count) {
      drupal_set_message(t('Node limit exceeded'));

      drupal_goto('somewhere');
    }
  }
}

You could obviously add further checks in there to make sure the user has a certain role, etc. I'd advise having a flick through the code in the Node Limit module to see how the above could be improved upon.

The above is a 'friendly' way to perform the check (i.e. one that doesn't just throw out a 403 page). If you want to be more militant, you could put roughly the same code in a hook_node_access() implementation instead:

function MYMODULE_node_access($node, $op, $account) {
  if ($op == 'create' && $node->type == 'the_content_type') {
    // Grab the number of nodes of this type the user has already created.
    $args = array(':type' => 'the_content_type', ':uid' => $account->uid);
    $node_count = db_query('SELECT COUNT(nid) FROM {node} WHERE type = :type AND uid = :uid', $args)->fetchField();

    // Get the max allowed number of nodes
    $limit = function_to_get_limit();

    // If the user us at/has exceeded the limit, set a message and send the user
    // off somewhere else.
    if ($limit >= $node_count) {
      return NODE_ACCESS_DENY;
    }

    return NODE_ACCESS_ALLOW;
  }

  return NODE_ACCESS_IGNORE;
}


How to pass the node id from a View Block to an associated Views Attachment for use in filters so that both operate on same content node id?

Since the attachment is linked to a specific view block, it should gain access to the information in the block.  You can inform the block of the node ID by using contextual filters.
1. In the block  add a contextual filter of the type content:nid.
2. Since blocks do not have paths you must explicitly tell the block to find the display node, so under form heading of "When the filter value is not available", choose "Provide default value" and select "Content ID from the URL".  This should provide the Node ID to the view block.


Create a View of Group Posts Who's Group has a Specific Tax Term?

In addition to your view configuration, you need to set up a group node relationship and filter out group nodes by taxonomy term. This should do it for you:

Add relationship: Organic groups: Group node (post)
Require this relationship: checked

Add filter: Taxonomy: Term
Vocabulary: Your Vocabulary
Selection type: Dropdown
Relationship: Group node (post)
Operator: Is one of
Select terms from vocabulary Your Vocabulary: blog


This feature is intended for Node title not Fieldable Panels Panes as per the screenshot  below:

Your best option is to override the panels-pane.tpl according to theme suggestions for your target pane and manually add the <h1> tag in place of the $title_heading variable.
It might not be an elegant solution but it works!


It's a wee bit of a hack, but you could add a tag to any EntityFieldQuery you're interested in printing the query for, then implement hook_query_alter() to intercept it when it's a standard SelectQuery, then cast it to string for debugging:

function MYMODULE_query_alter($query) {
  if ($query->hasTag('efq_debug')) {
    dpm((string)$query);
  }
}

$q = new EntityFieldQuery;
$q->entityCondition('entity_type', 'node')
  ->addTag('efq_debug')
  ->execute();

It's a bit of a hack but does the trick. The output for the above is:

SELECT node.nid AS entity_id, node.vid AS revision_id, node.type AS bundle, :entity_type
AS entity_type
FROM {node} node

Presumably this will also only work when using MySQL as the field storage system.


Using REST API for data storage for user definable content

This is achieved by creating a custom Entity Controller class, extending either the DrupalDefaultEntityController or creating a DrupalEntityControllerInterface implementation.

Then create a field storage engine, using the Field Storage API and  attach the correct fields where required.

I used the MongoDB mongodb_field_storage module for reference.

This all works as expected, and I do not use the Drupal database to store any Entity Metadata or field data. Only the field_config table is used.

The only hiccup I have is that the Drupal 7 'Per Field' storage engine actually needs to be defined in the variable table setting the field_storage_default to your custom storage engine. I have yet to find a way to hook into this on a per field basis without patching core. See here for more details.


Exposed filter on field collection with unlimited values without creating duplicates in view?

The "distinct" button exists in Drupal 7 as it did in Drupal 6 but is buried. Go into "Query Settings" under "Advanced -> Other" and check the box for "distinct." That'll display duplicate values only once regardless of how many deltas exist.


Is upgrading MySQL to MariaDB seamless for Drupal sites

Drupal runs fine on both MariaDB and MySQL, so you should be able to replace one with the other without any issues at the application layer (Drupal).  I don't believe the abstraction layer does anything differently between the two so you shouldn't have issues with needing to change field types (swapping to Postgres or other engines Drupal supports would change that answer significantly).

I would expect with an update like that to require some downtime, and a change of username and passwords for the database itself. So you will probably need to update the database connection settings once the update is complete.

All that of course depends on WHM doing the actual update of the database layer correctly so that "test first" caveat is a big deal.


Thanks to Krister Andersson answer, I seem to have got it right.

function THEME_preprocess_page(&$variables, $hook) {
   $status = drupal_get_http_header("status");
   if($status == "404 Not Found") {
      // get the configured 404 error page url :
      $not_found_url = variable_get('site_404');
      unset($_GET['destination']);
      drupal_goto($not_found_url);
   }
}

It will rewrite the url according to the configured default 404 error page, it works with multilingual variable too.


I wanted to do the same thing and after struggling with all kind of hooks/theme functions, I finally found a solution directly inspired from bootstrap.

Here the 2 links of bootstrap implementation:

bootstrap_form_alter
bootstrap theme function

And for my purpose, I've created a custom module to implement a custom search block.
So in MYMODULE.module file, I've put:

/**
 * Implements hook_theme()
 */
function MYMODULE_theme() {
  return array(
    'MYMODULE_search_form_wrapper' => array(
      'render element'  => 'element',
    ),
  );
}

/**
 * Implements hook_form_alter()
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'search_block_form') {
    //other implementations in themes/MY-THEME/template.php
    $form['actions']['submit']['#attributes']['class'][] = 'element-invisible';
    $form['search_block_form']['#theme_wrappers'] = array('MYMODULE_search_form_wrapper');
  }
}

function theme_MYMODULE_search_form_wrapper($variables) {

  $output = $variables['element']['#children'];
  $output .= '<button type="submit" class="btn-foldingsearch">';
  $output .= t('Search');
  $output .= '</button>';
  $output .= '';

  return $output;
}

Anyway, you'll have to adapt it to your configuration. Hope it helps.


Caching only works for anonymous users (people who are not logged in).

So, a simple test would be to add new content to your view or make a change to your view. Ex: change your view title.

On another browser have your page open, but as anonymous. If your view doesn't change, it means the cache worked.

The View will NOT change to anonymous users until you clear the cache.


You could also download and install the site / database on a local machine, delete the terms, and then restore the updated database using the 'backup and migrate' module. That way you would have full control of php.ini settings.


How should I change the permissions PRIVATEMSG for users in order them to have the access?

The normal user interface is at /messages, user/uid/messages is only meant to read messages of other users and is not a full replacement.

6.x-2.x has a feature that allows to move it around but it's relatively complex and I wouldn't necessarly recommend using.


The easiest way to do this is just create a view using a page display
if you did not know you can use dynamic replacement in your views page urls

aka
"This view will be displayed by visiting this path on your site. You may use "%" in your URL to represent values that will be used for contextual filters: For example, "node/%/feed". If needed you can even specify named route parameters like taxonomy/term/%taxonomy_term" - copied direct from views (page) PAGE SETTINGS - path.

so you would set the path to be "/products/%taxonomy_term"

then in views "ADVANCED", CONTEXTUAL FILTERS you would add taxonomy term filter
you can look at "yoursite.com/admin/structure/views/view/taxonomy_term" . for a better idea on how to do this...

if all this sounds hard please look into creating filters:
example https://www.youtube.com/watch?v=aVwclF9TfBo

NOTE:  this will use the term_id as there is no default filter for term name
if you want to use the term name ... then follow
https://evolvingweb.ca/blog/how-create-custom-views-argument-plugin-drupal-8

or In a nutshell with no code:

Add a new field to your term and call it URL To Access of type plain text
and make it required.
Edit your terms and in the URL To Access field you would enter for a example "t-shirt" or "pants" or "what-ever-you-are-selling".
On your product type add the term reference field such as "Category"
Edit products to make sure they have a value for the "Category" field
Make New View of type product with page display and  url "/products/%"
Add RELATIONSHIPS of the field "Category" and require that relationship
Add a CONTEXTUAL FILTER for the field field URL To Access. Inside the settings do the followin:
a From the 'WHEN THE FILTER VALUE IS NOT IN THE URL' section
b Click on 'Provide default value'
c Then from the 'Type' dropdown select "Raw value from URL"
d And from the 'Path component' dropdown select "2"

then save it.

You can now go to : /products/t-shirt and see the products under this category.


Since you are using a getSubscribedEvents() static method, I get you are implementing an event subscriber. In this case, you don't access \Drupal::currentUser() (and any static method returning a service that \Drupal exposes) in that method since it would be getting called too early, when Drupal has not yet initialized the dependency container.
That static method is supposed to return a static array describing the events to which the module wants to subscribe; the methods used to subscribe to the events will eventually take a different action basing on the user currently logged-in, and the user permissions that user account has.

Event subscribers are services, and as such they get their dependency injected. Instead of using \Drupal::currentUser(), you define @current_user as one of the arguments of your service, which is what the authentication_subscriber service does.

class: Drupal\Core\EventSubscriber\AuthenticationSubscriber
arguments:
  - '@authentication'
  - '@current_user'
tags:
  - { name: event_subscriber }

If you look at AuthenticationSubscriber::__construct(), you will see how it gets the current user object.

public function __construct(AuthenticationProviderInterface $authentication_provider, AccountProxyInterface $account_proxy) {
  $this->authenticationProvider = $authentication_provider;
  $this->filter = ($authentication_provider instanceof AuthenticationProviderFilterInterface) ? $authentication_provider : NULL;
  $this->challengeProvider = ($authentication_provider instanceof AuthenticationProviderChallengeInterface) ? $authentication_provider : NULL;
  $this->accountProxy = $account_proxy;
}

In your case, I would use the following code.

mymodule.services.yml

services:
  mymodule.eventsubscriber:
    class: Drupal\mymodule\EventSubscriber\MyModuleSubscriber
    arguments:
      - '@current_user'
    tags:
      - { name: event_subscriber }

src/EventSubscriber/MyModuleSubscriber.php

namespace Drupal\mymodule\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class MymoduleSubscriber implements EventSubscriberInterface {

  /**
   * {@inheritdoc}
   */
  static function getSubscribedEvents() {
    // Return the array describing the events to which you subscribe.
  }

  public function __construct(AccountProxyInterface $account_proxy) {
    $this->accountProxy = $account_proxy;
  }

}

Notice that @current_user is an instance of AccountProxyInterface, so for example, you can check the user has some user permissions with $this->accountProxy->hasPermission().


How can I use jQuery 1.7 without having issues in the admin pages?

I would look at Clive's advice on doing it manually here:

How do I update jQuery to the latest version I can download?

and add some more intelligence into the script to not do it on admin pages, eg:

if (arg(0)=='admin') {
  return;
}

You would also have to do that on node/#/add and node/#/edit pages etc so as to not disrupt anything "core" there, or, if you want, dive into drupal core and bring everything else up to 1.7 as well.

Depending on what version of Drupal you are running, this might also work:

function YOURTHEME_preprocess_page(&$vars) {
  if (YOUR CONDITION HERE) {
    $scripts = drupal_add_js('PATH TO YOUR JQUERY FILE');
    unset($scripts['core']['PATH TO DRUPAL JQUERY FILE']);
    $variables['scripts'] = drupal_get_js('header', $scripts);
  }
}

where you could set "YOUR CONDITION HERE" to be whatever pages you want the new jquery on, eg, arg(0)!='admin' etc.


One of the strengths of Drupal is that it's not just a tool for building a single website. It can be used equally well for managing multiple companion sites together. This capability has existed for many years, but is not always well understood.

And in true Drupal fashion, modern Drupal has several different options available for users looking to run a series of Drupal sites together, each with its own trade-offs.

Separate installs
Features-based installs
Multi-site
Domain Access
Organic Groups
Mix and match

Separate installs :
Sometimes the best strategy is to not unify sites at all. In this case, any similarity between different sites is largely coincidental. If there will be a large number of sites then some automation tools such as Drush or Aegir may make spinning up new sites easier, but from a site building perspective they are different sites.

Features-based installs :
As a slight variation of separate installs, it's possible to run multiple installs with the Features module. For those not yet familiar with it (and you should be), Features is essentially an automation tool for those pieces of configuration that Drupal allows to be mirrored to code so that they may be checked into version control. These days much (but sadly not all) of Drupal's configuration can be feature-ized. The most effective configuration components to manage this way include content types, views, panels, and image styles.

Multi-site :
For years Drupal has had the ability to run multiple sites off of a single install base. In this case, there is a single copy of Drupal's code base but each college or department has its own settings.php file, which points to a different database. From a site builder perspective, this is almost the same as having separate installs. Every site must be configured independently, but every site may also be configured independently. Each site may also live on its own domain or in subdirectories, although the latter requires some symbolic link trickery and editing the Apache .htaccess file to make work.

Domain Access :
Domain Access (DA) is actually an access control module that uses the node grants system. With DA, a site administrator can point multiple domains to a single Drupal install. Drupal will then self-filter any nodes in the system to display only on specific domains. There is still a single database, single code base, single user base, and single content pool.

Organic Groups :
With OG, each node (any entity, really) can be made into a "group", and then other nodes can be associated to one or more groups. Depending on the configuration, that could impact navigation, path aliases, theme selection, and so forth, to give the impression of different "sites".

Mix and match :
When planning a large-scale Drupal rollout, it's also possible to consider combining strategies. For instance, both Domain Access and Organic Groups can run on their own Drupal instance that just so happens to be multi-site... and have other Drupal sites hosted on it as well. Workbench can be used for administration of content on a single Drupal instance independently of whether it uses DA or OG, and can easily be enabled on multiple instances on the same install as well. As of this writing Workbench does not integrate with either module, so for instance Organic Groups or Domains cannot be used to define "sections" in Workbench, but such integration is possible.

Conclusion

Drupal offers a variety of solutions to address multiple sites with shared and separate content. As with all things Drupal there is no right solution — just options for your specific needs. Evaluate your goals and make decisions based on them; you may find that Domain Access is a better fit for your content editors or a multi-site setup is much easier to manage for your system administrators.


How can I create a custom variable to use it in my layout template page?

Your approach is right but this has less to do with omega than with the order in which Drupal is preprocessing your hook. The html template hook is too late in the process, this is just for rendering the html wrapper and already assumes the existing variables. Instead, following the 1st handbook link above, use the base preprocess hook to establish your variables, ex:

function theme_preprocess(&$variables) {
  $variables['my_variable'] = 'My New Variable';
}


Display edit and delete button using content view

Node Full Content is displayed using node.tpl.php. If you would like to override tpl you can copy node.tpl.php and rename it to node--blog.tpl.php in your theme templates folder. For more information refer Drupal 7 Template Suggestions.

You can add Edit and Delete buttons using below code to the overrided template..

<?php
   if (drupal_valid_path('node/' . $node->nid . '/edit')) {
     print l('Edit', 'node/' . $node->nid . '/edit');
   }
?>
<?php
   if (drupal_valid_path('node/' . $node->nid . '/delete')) {
     print l('Delete', 'node/' . $node->nid . '/delete');
   }
?>


You can go through AJAX Forms in Drupal 7. It describes how you can use ajax in your form with examples


Views content show current state - workbench

Have you already installed workbench moderation module?

I have used this module and it gives you a Workbench page with the tabs for each state of the nodes. The user can see which nodes are in Draft state and which are in review state.

You can adjust the look and feel of the page using panels and make it the way you want to display the content of each state.

In the views, you can add exposed filters for any other specific field you want to filter.


How do I delete a vocabulary programmatically?

I believe I have figured this out. You have to load the vocabulary using the Vocabulary entity class, then call the delete method on it. So something like this:

Vocabulary::load($vid)->delete();


How do I save uploaded file permanently in file_manged table?

Thank you @Clive &  @kiamlaluno

/* Fetch the array of the file stored temporarily in database */
   $image = $form_state->getValue('image');

/* Load the object of the file by it's fid */
   $file = File::load( $image[0] );

/* Set the status flag permanent of the file object */
   $file->setPermanent();

/* Save the file in database */
   $file->save();


How to create a better (more userfriendly) admin interface for non-technical "admin user"?

I don't use this myself as I prefer the slimer Administration Menu, but I think Navbar is more newbie friendly


How to remove image script if it has no image?

Go to Image field configuration:

Click on No results behavior section.

You will get the option to hide.


It's in url_alias table, you'll need concatenate it with your domain name.

SELECT `alias`  FROM `url_alias` WHERE source = "node/XXX";

Note: if you have more than one alias it will return multiple results.


Need way semi complex way to display author posts in views

It looks like you might want to use views>advanced>other aggregation to make the posts distinct on the author field.
Summary
Create a view of nodes that displayed recent posts by selected authors, then ensure that each author did not repeat by making them distinct.
To allow the site administrators (or other users by role) to  select authors
I would suggest using a flag to indicate the top authors. You could then  sort the view by the flag date (make sure you create a relationship to the flag) and limit the view to 5 results
Solution (updated)
To 'filter by distinct', install views_distinct module, and in your view of recent nodes by selected author, set a filter (in author uid field settings) based on the author uid field:

Here is an export of an example view of article nodes (does not include flag selection for portability):
$view = new view();
$view->name = 'drupal_answers_97449';
$view->description = 'http://goo.gl/gQLr2A';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'drupal answers 97449';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['title'] = 'Top 5 authors';
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['query']['options']['distinct'] = TRUE;
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'some';
$handler->display->display_options['pager']['options']['items_per_page'] = '5';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'table';
$handler->display->display_options['style_options']['columns'] = array(
  'title' => 'title',
  'name' => 'name',
);
$handler->display->display_options['style_options']['default'] = '-1';
$handler->display->display_options['style_options']['info'] = array(
  'title' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
  'name' => array(
    'sortable' => 1,
    'default_sort_order' => 'asc',
    'align' => '',
    'separator' => '',
    'empty_column' => 0,
  ),
);
/* Relationship: Content: Author */
$handler->display->display_options['relationships']['uid']['id'] = 'uid';
$handler->display->display_options['relationships']['uid']['table'] = 'node';
$handler->display->display_options['relationships']['uid']['field'] = 'uid';
/* Field: Content: Author uid */
$handler->display->display_options['fields']['uid']['id'] = 'uid';
$handler->display->display_options['fields']['uid']['table'] = 'node';
$handler->display->display_options['fields']['uid']['field'] = 'uid';
$handler->display->display_options['fields']['uid']['exclude'] = TRUE;
/* Field: User: Name */
$handler->display->display_options['fields']['name']['id'] = 'name';
$handler->display->display_options['fields']['name']['table'] = 'users';
$handler->display->display_options['fields']['name']['field'] = 'name';
$handler->display->display_options['fields']['name']['relationship'] = 'uid';
$handler->display->display_options['fields']['name']['label'] = 'author';
$handler->display->display_options['fields']['name']['element_label_colon'] = FALSE;
/* 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'] = 'post title';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
$handler->display->display_options['fields']['title']['element_label_colon'] = 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';
/* Filter criterion: Content: Published */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'node';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Page */
$handler = $view->new_display('page', 'Page', 'page');
$handler->display->display_options['path'] = 'drupal-answers-97449';


Adding a custom js file to a core theme like Seven

Asset injector has been made specifically to carry out the functionality that you stated. Simply install the module & flush cache.

Within configuration you'll see the link Asset injector and there you can select the theme to add your custom CSS/JS.

Hope that helps!


Is it possible to alter nodes on export with Node Export

You can manipulate the nodes in hook_node_export_node_alter() and hook_node_export_node_import_alter()
See node_export.api.php for more information.


How to return JSONP from a menu callback

The array was being double encoded. First by the $json_response = drupal_json_encode($response); and then again by the menu delivery callback 'delivery callback' => 'drupal_json_output'.

To fix this, remove the delivery callback, and use just 'type' => MENU_CALLBACK,.

In the function change this:

if (isset($callback) && $callback != '') {
  $json_response = drupal_json_encode($response);
  echo $callback ."(". $json_response .");";
}

to this:

if (isset($callback) && $callback != '') {
  $json_response = drupal_json_encode($response);
  drupal_add_http_header('Content-Type', 'application/javascript');
  echo $callback . "(" . $json_response . ");";
  drupal_exit();
}


Why isn't code for $op == 'presave' being executed in hook_nodeapi?

Regarding your problem, you're editing the node right ? Because presave acts during saving.

On a site I use this module which is quite handy, maybe it can help you: Publish Content


Commerce Paypal- How can I change the "Order No. at Site Name" string?

All of my payment gateway modules, and my recommended best practice for others', is to include a final opportunity before the payment API request is dispatched for developers to alter the request parameters if desired. How you do that in the PayPal modules depends on which payment method you're using. I'm going to assume this is a PayPal Payments Standard (WPS) initiated payment, so the hook you want is:

hook_commerce_paypal_wps_order_form_data_alter()

If it's one of the others, refer to their *.api.php files to find the appropriate hook, but note that some API requests are run through a helper function in the root commerce_paypal.module.


I have disabled the Login Tobogan and I have enabled again the Login Tobogan again and the error was fixed.


How to change placement of block or region on events?

You can use the flexbox order property: https://css-tricks.com/almanac/properties/o/order/


Is it possible to invoke cron within a hook or route class?

The reason why you get that error is because run is not expected to be called statically. \Drupal\Core\Cron is a service class managed by Drupal, registered in core.services.yml. To get a reference to the instance of this service, you'll need to inject the dependency to your controller.

namespace Drupal\mymodule\Controller;

use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\CronInterface;

class MyController extends ControllerBase {

  protected $cron;

  public function __construct(CronInterface $cron) {
    $this->cron = $cron;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('cron')
    );
  }

  public function myPage() {
    $this->cron->run();
  }

To call it from a hook, if you'll need to use \Drupal::service() to get a reference to the instance:

$cron = \Drupal::service('cron');
$cron->run();

A full example of how to manually run cron can be found in the implementation of the Cron settings page (Configure -> System -> Cron). In that page, you have a button to manually run the cron. See the runCron method, which is attached as the submit handler of the "Run cron" button.


How do I delete an old node when a new node is created?

with views rules is possible, a bit complicated, make a user view, you will need a contextual filter, "When the filter value is NOT available", "Provide default value", php code, then add something like:

global $user; // gets current logged in user object

 if (isset($user->field_user_address[LANGUAGE_NONE][0]['country'])) {
  $user_country = $user->field_user_address[LANGUAGE_NONE][0]
['country'];
return $user_country;}

instead of using & returning $user_country, use & return your email field, and that view will return only the loggedin user field-email, add a relationship on node author, then add "node title" or whatever form the relationship, then apply a rule on that view and delete (or unplubish) that content. hope it helps.

EDIT: may be is over-coded my solution, just add a user view, contextual filter, loggedin user from URL, apply filters and relationships as needed to only get the node you are looking for, then apply a rule on that view.


Dynamic route's controller method not firing

Well, I'm an idiot. The problem was nginx after all. There actually was a block to handle CSS/JS assets that was preventing the dynamic route from executing because of a lack of physical files. I had to place the following above that rule:

location ~ ^/sites/.*/files/background_image/ {
    try_files $uri @drupal;
}

Here's the offending rule:

location ~* ^.+\.(?:css|cur|js|jpe?g|gif|htc|ico|png|xml|otf|ttf|eot|woff|woff2|svg|svgz)$ {
    expires 30d;
    tcp_nodelay off;
    open_file_cache off;
    open_file_cache_valid 45s;
    open_file_cache_min_uses 2;
    open_file_cache_errors off;

    location ~* ^.+\.svgz$ {
        gzip off;
        add_header Content-Encoding gzip;
    }
}

I found the solution after searching for relevant issues on other modules that generate dynamic files, such as imagecache, which led me to the official nginx Drupal guide. Definitely a learning exercise.


By looking at the filecache module description:

  This module allows Drupal cache bins to be stored in files instead of
  storing in database.

This means that the data is stored in a folder and I guess this folder is not shared between your web servers.

I think you have 3 options:

(easy solution) Disable Filecache and rely on the builtin cache of drupal. This will store the bins content on your database and it will be shared/invalidated for your two servers as they share the same DB
(best solution) Replace FileCache with another caching module as Memcache or Redis. Depending on your server you might want to run those in a separate virtual machine and link them back to your web servers.
Share the folder used by FileCache across your servers.

Hope this helps.


TL;DR
web_root = /web/htdocs4/username/home/, where username is (at least in my case) my ftp login (they use the following convension: for domain example.com the username is examplecom)
Full Story
I’ve just accidently found out what is the absolute path of the web_root.
I installed TCPDF module and enabled both TCPDF and TCPDF Example. The latter created a link TCPDF example in the second (right) sidebar, and when clicked that link, it showed me the following error:
 Fatal error: Class 'TCPDF' not found in /web/htdocs4/username/home/www/modules/tcpdf/src/TCPDFDrupal.php on line 16


Migrate dashboard goes to content dashboard

I am not sure why it happened but I was able to resolve this issue by uninstalling and then reinstalling migrate module.


How can I iterate through all the key and value of configuration object

You could try the following to get the raw values back:

$config->getRawData()

E.g. the following

$config = \Drupal::config('system.maintenance');
$config->getRawData()

Returns and array of something like:
'message' => string(93) "@site is currently under maintenance. We should be back shortly. Thank you for y…"
'langcode' => "en"
→'_core' => array(1)


Programatically Attach a Field to a CCK Type in Drupal 6

Anything in the UI eventually has to call a function, so...

The UI for editing a content type goes to path:

admin/content/node-type/NODETYPE

This path is "owned" by the cck module.  Looking in there, you can dig through the forms and hook_menu()s etc to see it eventually calls a function:

content_field_instance_create($field)

which is defined in

content.crud.inc

inside the cck module's inc directory.


Drupal 7 adding rel to the href's of Login and Registration

Yes you could spend time tearing apart templates, and hacking in the required code, I would say the cleaner, 'more drupal' solution would be to use a combination of

Menu and menu items
The module menu attributes

From the project page:

  This simple module allows you to specify some additional attributes
  for menu items such as id, name, class, style, and rel.


Creating your own install profile doesn't need to be a big project in itself, especially for Drupal 7, that has simplified making install profiles. Features also helps a lot, making it easy to save settings, content types, views etc in a module.

All you really need to do in the install profile is to

Enable modules
Save settings
Enable blocks (maybe)
Create content (maybe)

I suggest that you build your own install profile that fits your needs, instead of trying to find one. You could start out with how it's done in Open Atrium, and just edit it to fit your needs.


How to add an existing variation to a product

Turns out I know what you're talking about Nikolaos, and you're in luck! There's a checkbox!

Here's an animated gif that walks you through the steps that I've outlined below:

Navigate to your Content Types
Manage Fields on your Product Display (you may have more than one of these)
Locate the Product Reference or Product Variations Field, click "Edit"
Scroll to the middle and locate the checkbox "Allow users to add existing variations"
...
Profit!


Delete all users and there content apart from user 1

You can use Views Bulk Operations (VBO) module...

Above module allows to execute bulk operations on nodes, users, comments; it also permits to apply the selected operation to all the nodes, users, or comments using the Batch API. The batch API allows forms processing to be spread out over several page requests, thus ensuring that the processing does not get interrupted because of a PHP timeout, while allowing the user to receive feedback on the progress of the ongoing operations.

There is a setting in the View's VBO options to enable a select all button that select all items across all users and unselect admin.


How to exclude forms from processing by Hide Submit module?

The 2.x branch introduced hook_hide_submit_alter() which can be implemented to exclude certain forms based on the current path:

function MYMODULE_hide_submit_alter($hide_submit_settings) {

  // IMPORTANT NOTE: given the way module_invoke_all and array_merge work you
  // should not modify and return the original array. Instead create a new one
  // and add only the keys you care about. If two modules implement this hook
  // and try to modify the same values then the default will be used instead.
  $altered_settings = array();

  // Disable the module for my special form page.
  if (arg(0) == 'my-special-form') {
    $altered_settings['hide_submit']['hide_submit_status'] = FALSE;
  }

  return $altered_settings;
}

There doesn't look to be a way to turn the functionality off for a specific form, just by path. Might be worth a feature request on the module issue queue if that's something you'd like to see.


Increase the Length of the block title field

That will be tricky. Block titles can only be 64 character. You need to alter the database and make the title field for blocks longer.

Put this in a custom modules .install file.

function mymodule_schema_alter(&$schema) {
  // Change length of title field for block.
  $schema['block']['fields']'title'] = array(
    'type' => 'varchar',
    'length' => 128,
    'not null' => TRUE,
    'default' => '',
    'description' => 'Custom title for the block. (Empty string will use block default title, <none> will remove the title, text will cause block to use specified title.)',
    'translatable' => TRUE,
  );
}

and then alter the block title maxlength attribute in a form alter

$form['block_settings']['title']['#maxlength'] = 128;

Another way is that you put your long title in the content of the block instead of using the "real" block title field.

In Drupal 7 I would hint you to checkout Bean module, but as this is Drupal 6 I'm not sure.


From Comments:

If you want to do a popup for first time visitors, try the Popup announcements or Popup on load modules.


You can certainly do that. If you setup a view and tell it to grab Ubercart Order data it will allow you to access information on orders such as the payment type, amount, order id, etc.

So if you grab the following information you'll be set to feed it into the Views PHP field.

Payment Method
Order Total (Exclude this from the display)

Then if you add the Global: PHP field you need to put the following into the Value code field:

if ($data->uc_orders_payment_method == "cod") {
  return number_format($data->uc_orders_order_total, 2, '.', ',');
} else {
  return number_format(0, 2, '.', ',');
}

And this in the output code field:

<?php
  print $value;
?>


If it's just menu links you're after you can give Menu Attributes a whirl.


Latest added data in a particular contenty-type on custom page

There are many, many ways to accomplish this but here is one of the simplest ways I can think of.

I'm going to use the Drupal Views module to do this.  The intent of this is not to cover all things Drupal, rather it's to give you a crash course in creating a block using Views to accomplish what you're looking to do.

First, install and enable Views.  There are several tutorials out there that show you how to do this.  Nodeone has an awesome video introduction to Drupal Views.  (Personally this is one of my favorite Drupal resources. :)

Now that Views is installed and enabled, go to Structure, then 'Views' (In D7 this will be at http://www.example.com/admin/structure/views.)

Next create a new view (Add New View.)

Next, configure your View settings.  The example settings below will create a new block that contains the three most recent News items that link to the full version of each article article.  Views is capable of far more, but for the sake of simplicity I'll stick to creating a simple block.

Now go back to "Structure" and this time go to "Blocks."

My theme will be different from yours, but what you need to do is find the view you created, choose a location on your theme where you would like it to be displayed and then click save.  In this example I'm moving the block to the top of the navigation bar on the right hand side of my theme.

Once saved you should see similar output on your site as in the image below.  Note that this has my theme applied and your block will look different.

Lastly, to control which pages this block will be displayed on you can use the Blocks visibility settings.  How do I show blocks only on certain pages? is a great resource.

There are likely a million other ways to accomplish this, but this was the quickest I could think of using my nifty Greenshot app.


How to use hook_node_presave to change field's value

For starters, you're probably using the wrong array key for the field value that you're saving; 'name' should be 'value' there.

$node->field_par_contact_name['und'][0]['value'];

Second, you're actually using Taxonomy Term Reference fields for your "first name" and "surname" fields. One important point about Reference fields is that you can't always assume that the referenced entities have been fully loaded and are available in your object. By default, when the node object is loaded, that field only looks like this:

$node->field_par_contact_first_name (Array)
  'und' (Array)
    0 (Array)
      'tid' => 284

Only the 'tid' key is definitely there. 'name' is a property of the referenced term, and isn't usually automatically available. (Subsequent code may actually load the referenced term and make it available within the $node object, but that's just happenstance if so.)

You would have a much easier time of it if your "First Name" and "Surname" fields were text fields instead of references. Then, those values would belong directly to the node itself, rather than to a separate taxonomy term being referenced.

If you're stuck using taxonomy term references, though, then you should make a point in your code to load the referenced term, then get the values you need from the $term->name property itself.


Hooks called after installation profile is installed?

Move your post-installation hooks to a module/part-of-your-profile (that can implement any hook and move things around even after the system modules is installed).

That way you can overcome problems like custom block's BLOCK_VISIBILITY_LISTED not working on profile installation hook_install()?, and have a solid last installation step, that makes all your final configs.

bonus * why not even choose or make configs in that installation step's form_alter() ;)


Is there any Menu Module to show thumb image, content tile when mouse over on menu item

This can be done using Views Module and MaxiMenu.

Edit: you might also need the Menu Views Module and potentially Nice Menus Module to achieve the perfect style you want.

I have not tested this but a Coworker built a client's dropdown menu with images this way, So i know it is possible. I just personally haven't done it =-)

I hope this gets you close!


Which Drupal clients allow editing of non-Blog nodes?

Depending on how much work you want to do, you could write a custom interface in HTML5/JS, then wrap it in Titanium (link below) or Air
http://www.appcelerator.com/products/titanium-desktop-application-development/

Then use the Services module http://drupal.org/project/services as the API - you might want to extend the functionality yourself

Also, not sure if this is for a particular client requirement. But if it was just node creation without opening a browser you could consider this http://drupal.org/node/1045918

...Or you can pull out the necessary code from the blog api and extend :o)

Either way I've got no simple answer I'm afraid


How to right align text in custom form textfield in Drupal 7?

Yes, add a custom class, or use an existing one. You can add custom CSS styles to your form using #attached.


Assign User Points in existing website which already contains content

I think User Points Contributed modules is your best alternative available today. I. e. submodule userpoints_retroactive. Excerpt from that project page:

  Award users points for their nodes, comments and votes that they have created so far, before userpoints was enabled on the site.

However, the port of this module to D7 still needs work. Maybe you can/want to somehow contriute to the finishing touch of that issue?

PS: there is also Berdir's Api documentation about this submodule ... (maybe that helps somehow).


implementing user has password in hook menu

If you check the functions being called, you'll there's a randomness in generating the hash for security reasons. I think that is not a problem. Have you tried using that as the stored password and logging in afterwards?


Reference a filename in form validation for an image

You can to this in the submit handler to rename the file.

function SUBMIT_HANDLER($form, &$form_state) {

  $node = $form_state['node'];

  global $user;

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

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

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

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

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

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

}


How can I format the content in horizontal tabular form?

Do you really care to have tables in the semantic meaning of it?
I mean, you can just print your fields to divs and use float: left for the 3 content elements and for the labels print it manually on a div on the header.

Might not be the most elegant solution but will work and be easier than making it with panels...

The best way to do it would be to print
First Field: Label | Line 1 | Line 2 | Line 3
Second Field: Label | Line 1 | Line 2 | Line 3
But that's not how Views works.

You could also retrieve all the information in a custom module and then manage it however you want. But then, you wouldn't need to use Views module...


Can you link an image field to a link field by 'Manage display'?

Using Linked Field and Token module, you can easily do this by checking "Link this field", and entering the appropriate token of your Link field.

Here is an example:

Destination:

[node:field-test-link:url]

Title:

[node:field-test-link:title]


Make sure you have Taxonomy: Term selected under the Sort Criteria box and not Taxonomy: Term ID.

I believe the sort that you are seeing under Format -> Settings is where you can select which fields are sortable and the default sort for a view of format: Table.  Making a field sortable creates a clickable link as a header for the table column allowing you to change the sort order by that field.


how to use user profile field information as biodata list

While creating the View,

  create View (Show:User)
  add relationship, (User:Profile); give the Identifier a unique name ie 'MainProfile'; select a single checkbox for 'Profile type', in my
  case 'Main profile';
  add another relationship, (User:Profile); give the Identifier a unique name ie 'EducationProfile'; select the other checkbox for
  'Profile type', in my case 'Education profile';
  add Fields to view; select Profile2 field items; use Relationship dropdown in 'Configure field' to associate w/ correct relationship;


How can I index all remaining items programatically?

One way to do it is exec("drush search-index");.


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

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

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


It's not totally clear what you're asking, but here's a stab:

It doesn't sound like the data will be updated frequently enough to justify processing it on every cron run - you mentioned recent deliveries... what do you mean by recent? In the last hour? Last day? 30 days? Find the right balance based on the freshness of the data itself, and only update what's new, especially if you're doing it on every cron run.
Get the data out of Access in a reasonably ready-to-consume format - don't expose the ugliness of your Access data structures to Drupal. This could mean setting up a custom view in Access to summarize and reformat the data you need for Drupal.
Setup a scheduled export from Access.
Use Drupal Feeds to import/update the data from Access into Drupal, either on demand or periodically.

HTH.


Yes, you can done it in form_alter . first need to know what is your button name in $form in form_alter, I suggest you print_r or var_dump $form and found your button (buttons usually are in #actions) . after it I suggest you handle your job with add a css class or id to your button and with css style it .

function yourcustom_form_alter(&$form,$form_state) {
  $form['actions]['yourbuttonname']['#value'] ='';
   $form['actions]['yourbuttonname']['#attributes'] =array('class'=>array('yourcssclass'));
}


How to exclude Admin Toolbar from being Translated in Drupal 8?

You can set a separate language for administrator pages on the account edit page for each administrator account.

Under Language settings, set the Administration pages language.

BUT! There is a major core bug related to this feature: if admins are creating fields, the config will be screwed up.  See the issue for workarounds.

Admin toolbar module

If the question is specifically about the Admin Toolbar contrib module, you can not download the translation for it.  If no translations are downloaded, the module will always show in English.


How to associate a product cost to a product in Drupal Commerce?

Just add a new price field to your product type, call it cost, and populate it at will. That's what I do to track my cost on realmilkcheese.com.


I recently created a hierarchical taxonomy on our main premium site using some data exported from our SQLServer and used Taxonomy CSV import/export to import the file. I used LibreOffice Calc to massage the data into place, then exported from LibreOffice to CSV. A Google Docs version of my data  is available, if you're interested.

Two things I remember doing:

I choose to import as a 'taxonomy_manager' file
Any term which will be used as a parent needs to appear at the top before any of its children appear.


You can create using hook_form_alter() and I get my button on the Add/Edit node form:

$form['actions']['accept_and_adduser'] = array(
  '#type' => 'submit',
  '#value' => 'Save & Add a Lesson',
  '#name' => 'op',
  '#submit' => array('mymodule_node_form_submit'), /* NEED this */
  '#weight' => 1000
);

But, clicking the button doesn't seem to hit hook_node_submit() or hook_node_insert(). I'm assuming I'm missing a hook or something in the button creation...anyone have any ideas?

Then added this function:

function mymodule_node_form_submit($form, &$form_state) {
  // Do stuff before saving the node, saving the data of users in some table and calculate it

  // Call this to save the node
  node_form_submit($form, $form_state);

  // Do stuff after saving the node
}


How do I build a user table with aggregated article data?

Welcome to the Drupal StackExchange !

You can achieve this with some custom php code and couple of queries.

<?php

   $articles_publishers = db_query("SELECT DISTINCT u.uid FROM {node} n LEFT JOIN {users} u on n.uid = u.uid where n.type = 'article'");
   foreach ($articles_publishers as $articles_publisher) {
     $publisher = user_load($articles_publisher->uid);
     $username = theme('username', array('account' => $publisher));
     $articles_published = db_query("SELECT count(*) FROM {node} where uid = :uid and status = 1 and type='article'", array(':uid' => $articles_publisher->uid))->fetchField();
     $articles_published_with_comments = db_query("SELECT count(*) FROM {node} n INNER JOIN {comment} c ON n.nid = c.nid where n.uid = :uid and n.status = 1 and n.type='article'", array(':uid' => $articles_publisher->uid))->fetchField();

     // Theme the information with above results

     print "Username :" . $username;
     print "articles published :" . $articles_published;
     print "articles with comments :" .  $articles_published_with_comments;
   }

?>

use above code in a module custom block or Add Block with php option to display the information.

Hope it helps.


How to debug 404 on user/login user/register user/logout?

@AndrewKillen:

  Checked with Devel and it says "Unable to load route for url
  '/user/login'" when checking the user.login route.

How this could be debugged (on an working example, because I don't have a broken site):

Enable Xdebug and go to the url: /devel/routes/item?path=/user/login

Drupal\devel\Controller\RouteInfoController::routeDetail:

  public function routeDetail(Request $request, RouteMatchInterface $route_match) {
    $route = NULL;

    // Get the route object from the path query string if available.
    if ($path = $request->query->get('path')) {
      try {
        $route = $this->router->match($path);

Set a breakpoint for the last line and step into match($path). Then after a new request with the path info is created you get to:

Router::matchRequest:

  public function matchRequest(Request $request) {
    $collection = $this->getInitialRouteCollection($request);
    if ($collection->count() === 0) {
      throw new ResourceNotFoundException(sprintf('No routes found for "%s".', $this->currentPath->getPath()));
    }
    $collection = $this->applyRouteFilters($collection, $request);

    if ($ret = $this->matchCollection(rawurldecode($this->currentPath->getPath($request)), $collection)) {
      return $this->applyRouteEnhancers($ret, $request);
    }

getInitialRouteCollection() results in three possible matches:

user.login
user.login.http
entity.user.canonical

The second one is filtered in applyRouteFilters() because this is POST only and for JSON. The entity route is removed after the compiled routes are matched in matchCollection() because "login" is not a valid user.

And so the route user.login is the last one remaining and returned. If not you have to check where on this way the route is not collected or filtered out.


How to create a collapsible Webform form?

Okay, the easy way would be to go through FORMS API http://drupal.org/node/37775

You may also look into MultiStep module once you are done with the FORM API overview.

Below are some links that you can follow:-

http://www.youtube.com/watch?v=EgGhUN2zKw4
http://randyfay.com/states
Search youtube/drupalize.me/buildamodule.com for more Form API tutorials.
http://tedbow.com/content/drupal/webform-conditional-demo-form

Please go through Form Api first.


Here's a Drupal 7 example showing how to use:

field_get_items() to select the field from the node,

file_load() to load the image file,

image_load() to get the URI from the image file

image_style_url() to format the image differently for different
   contexts

... and as a bonus, check for good data and substitute a default image if the field image is no good.

// If there is a field image.
if (!empty($node->field_image)) {
  $field = field_get_items('node', $node, 'field_image');
  if (!empty($field[0]['fid'])) {
    $image_file = file_load($field[0]['fid']);
    $image      = image_load($image_file->uri);
  }
}
// If image, then scale it. If not use the default image.
if (!empty($image)) {
  if (is_string($image)) {
    $image_source = $image;
  }
  else {
    $image_source = $image->source;
  }
  $url        = image_style_url('image_style', $image_source);
  $url_mobile = image_style_url('image_style_mobile', $image_source);
}
else {
  $url        = 'https://example.com/sites/default/files/default_image.png';
  $url_mobile = 'https://example.com/sites/default/files/default_image_mobile.png';
}

Hope this helps. Good luck!

EDIT: @Kevin makes a very good point in the comments above:

  All of this complexity can be avoided by using entity view modes and not doing field based views.

Basically, Drupal gives you the ability to set up view modes in the "Manage Display" tab for each content type. There, you can decide which fields will be shown or hidden in each view mode, and how they should be formatted for display. If you use this feature, you shouldn't need to deal with it in PHP template files.


hook_node_view() is only invoked when a node is prepared for display (normally either through node_view() or node_view_multiple()).

Since the node isn't prepared for display when you request it via a services call, your hook won't be called. If you think about it this makes perfect sense; you're requesting a json/xml representation of the node so there's absolutely no reason why the node should be prepared for display.

The only way round this would be to move your logic into hook_node_load(), which is called for all node loads. The same data that you attach in hook_node_load() is available to you on the node object in hook_node_view(), so you'll be able to move your logic without any problem at all.

I suppose the other, more complicated method, would be to write your own Services resource that loads the node view as well as the node, so the extra data you're adding would get picked up.

But semantically speaking, unless the actions you're taking relate specifically to the HTML that will be output for the node, hook_node_view() is not the right place to add your extra data.


Exactly, that is the point. I need just 2 Views, which one shows some
completely different data than the other, and for different kind of
brands. But all of these brands can be grouped in 2 big groups. Now I
solve it by using views_embed_view in template.tpl.php, and using a
View or other in the function via database logics, but I was not sure
if there was an ideal way of doing without "hard code", via Rules,
Context or something.

Here is an alternative.
Create taxonomy terms.
go to   /admin/structure/taxonomy

Add Vocabulary, call it Products
Then click on list terms (/admin/structure/taxonomy/products) and add terms

Brand A with url alias /products/brandA
Brand B with url alias /products/brandB

Then on your actual products content type (lets pretend it's Articles) add a term reference field of Bundle Type: Products.
Then edit your Article and select A or B for that node.
Create 2 block views (one for each type)

under advance, add relationship of terms on node

Then Add a contextual filter of Taxonomy Term Name

Provide Default Value

Fixed Value

Brand A

Then go to blocks, and find your 2 view blocks and configure them.

I only showed A here, repeat steps for B.


db_affected_rows() return "1" when the query is wrong

Edit:
db_affected_rows() returns an unexpected value because watchdog is turned on. I watched to see if there was another query after the one I ran and before my db_affected_rows() call, and sure enough:

  INSERT INTO watchdog (uid, type, message, variables, severity, link, location, referer, hostname, timestamp) VALUES (1, 'php', '%message in %file on line %line.', 'a:4:{s:6:\"%error\";s:12:\"user warning\";s:8:\"%message\";s:104:\"Unknown column 'name2' in 'field list'\nquery: UPDATE users SET name2 = 'a'\"; [...]

So, db_affected_rows() is returning 1 because watchdog is logging an error. Thus, the proper way to see if a query had an error or not -- and count the rows affected if it was successful -- is:

$result = db_query("UPDATE users SET name2 = 'a'");
if ($result) {
  printf("Records affected: %d\n", db_affected_rows());
}
else {
  print "Query not successful";
}

Hope this helps!

Original answer for posterity:

I'd have to see the code around your query. Try running this:

<?php
function db_affected_rows() {
  global $link;
  return mysql_affected_rows($link);
}

$link = mysql_connect('localhost', 'root', 'root');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
mysql_select_db('d6.devl');

/* this should return the correct numbers of deleted records */
mysql_query("UPDATE user SET creator = 'creator'");
printf("Records affected: %d\n", mysql_affected_rows());

printf("Records affected: %d\n", db_affected_rows());

I did and it worked alright:

  $ php -f test.php

  Records affected: -1

  Records affected: -1


#ajax-processed not added on a form inside a custom callback (MY_MODULE_deliver_html_page)

The problem why the ajax is not working with loaded forms through ajax is because of the missing javascript behaviors attached to the form. These provides all client side code (and which adds the .ajax-processed class on the element).

To be able to add these needed behaviors, you need to make used of the ajax_pre_render_element and attaching these to the page. Also important, is that you print out the JS code by calling drupal_get_js().

This is how I managed to get it working.

function YOURMODULE_form($form, &$form_state)
{
    // Same form build as your example
    $form = array();

    $form['#id'] = 'statusupdate-confirm-form';
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Delete'),
        "#ajax" => array(
            "callback" => 'delete_statusupdate_callback',
            "effect" => "fade",
        ),
    );

    return $form;
}

// Menu callback used to only how the form (standalone) without the theme HTML
function YOURMODULE_page()
{
    // Get the form
    $form = drupal_get_form('YOURMODULE_form');

    // Process the submit button which uses ajax
    $form['submit'] = ajax_pre_render_element($form['submit']);

    // Build renderable array
    $build = array(
        'form' => $form,
        '#attached' => $form['submit']['#attached'], // This will attach all needed JS behaviors onto the page
    );

    // Print $form
    print drupal_render($build);

    // Print JS
    print drupal_get_js();

    return null;
}


You can use Views to do this . create a view of poll and show display as content (full content) not field and you're done


Solution 1

Add a custom access callback to your paths, that will then determine whether or not the user should have access to a path.

Important: the code below will deny access to those paths. If you just wanted to show a slightly different menu and not block the access to those pages, see solution #2.

For example:

function YOUR_MODULE_menu_alter(&$items) {
  $items['your_path']['access callback'] = 'YOUR_MODULE_menu_access_callback';
}

function YOUR_MODULE_menu_access_callback(){
  global $user;
  if ($user->uid) {
    // Load user's Profile2 profile.
    $profile = profile2_by_uid_load($user->uid, 'NAME_OF_YOUR_PROFILE');
    // Allow access only if the user selected the checkbox.
    if (isset($profile->field_YOUR_FIELD[LANGUAGE_NONE][0]['value']) && $profile->field_YOUR_FIELD[LANGUAGE_NONE][0]['value']) {
      return TRUE;
    }
  }

  // This assumes that anonymous users should not have the access to a
  // particular menu.
  return FALSE;
}

This code would go in a custom module.

Solution 2

Add a simple theme_menu_link() override in your front-end theme, and skip rendering of those links.

Important: this will not prevent the access to those pages, it will just skip rendering of those list items. Also, you must be rendering the links using a menu, e.g. place a menu block somewhere in your theme, and not render the menu directly (e.g. theme('links__system_main_menu', ...) or theme('links__system_secondary_menu), ...)).

For example:

function YOUR_THEME_menu_link($variables) {
  global $user;
  $element = $variables ['element'];
  $sub_menu = '';

  // Exclude certain paths.
  if ($user->uid) {
    // Load user's Profile2 profile.
    $profile = profile2_by_uid_load($user->uid, 'NAME_OF_YOUR_PROFILE');
    // Allow access only if the user selected the checkbox.
    if (!isset($profile->field_YOUR_FIELD[LANGUAGE_NONE][0]['value']) || !$profile->field_YOUR_FIELD[LANGUAGE_NONE][0]['value']) {
      // Define the list of paths that should be excluded.
      $paths_to_exclude = array(
        'sample',
      );
      if (in_array($element['#href'], $paths_to_exclude)) {
        // Stop processing here, meaning this list item will not be included in
        // the menu.
        return;
      }
    }
  }

  if ($element ['#below']) {
    $sub_menu = drupal_render($element ['#below']);
  }
  $output = l($element ['#title'], $element ['#href'], $element ['#localized_options']);
  return '<li' . drupal_attributes($element ['#attributes']) . '>' . $output . $sub_menu . "</li>\n";
}

This code would go in the template.php file of your front-end theme.


There are contexts where Drupal allows you to use a notation like  '\Drupal\module_name\Controller\MyController::_field_p_rpservicename_validate' to refer to a public function of an object. In the case of validation handlers, since Drupal is calling them with call_user_func_array(), with a notation like '\Drupal\module_name\Controller\MyController::_field_p_rpservicename_validate' you are referring to a static function of a class.

Change  the definition of that method as follows, and your code will work.

public static function _field_p_rpservicename_validate(&$form, FormStateInterface $form_state) {}

Keep in mind that a static method cannot use $this.


User role can't view/edit their own unpublished content

For me, the solution was to enable the "Bypass content access control" permission setting.  In my case it was for an internal role, so I was comfortable with that but some roles I would not give that to.

I am running Drupal 7, BTW.


Sounds like a job for Nodequeue or Flag and the Printer, e-mail and PDF versions Modules


drupal on postgresql vs mysql vs mariadb

The occasional issue you can hit, is that a contrib module is either just badly written because the author didn't know better, or, more rare, deliberately used mysql specific functionality for some reason, meaning that the module simply won't work on your site.

I've only had this on a single occasion though, and it caused issues during installation. A quick hack of the modules install file, and everything worked out well from there on.

It's unlikely to be much of an issue, and I'm myself running some personal things on postgresql just get familiar with it.

Drupal doesn't care if you use mysql or mariadb. They're the same thing to Drupal.


how can I remove registered .tpl.php file?

Simply clear the caches either on /admin/config/development/performance or via drush cc all if you've configured drush.


UI.selectmenu from jQuery is not imported!

Selectmenu Widget is added in jQuery UI 1.11, which is not supported by core and also jquery_update module. There is an issue on Drupal.org.

Tabs Widget is added since jQuery UI 1.9, you can have it if you installed latest version of jquery_update module with proper configuration.


How to refresh/update a Block or View after a form submit?

I think this might be the module you are looking for:-
https://www.drupal.org/project/views_nodejs

I has a few dependencies, and you will need to setup a node.js server, but aside from that it's pretty straightforward.


Why do I get 'access denied' when viewing nodes?

Things to try when you get inexplicable "Access denied" when non-admins try to view nodes and you're sure every role has the permission "View published content":

Clear all caches. Note that you need to both clear your browser's cache and the Drupal cache on the server. To clear your browser's cache, hold down Shift and reload the page. To clear the server cache, navigate to Administration → Configuration → Development → Performance → Clear all caches. If you use Views, clear Views' cache: Administration → Structure → Views → Settings Advanced → Clear Views' cache. If you've got drush installed (always a good thing to have around), a quick way to clean all caches on the server is drush cc all.
Rebuild permissions: append the path: admin/reports/status/rebuild to your site's base URL, or navigate to Administration → Reports → Status report and look for the link "Rebuild permissions".
Repair the Sessions table: Use phpMyAdmin or a similar tool, choose your Drupal database, check the box next to the {sessions} table, and find the "With selected" drop-down near the bottom of the page. Choose "Repair table".
If you've just installed a new module, make sure that you've executed a database update. To execute a database update, append the path update.php to you site's base URL.  (There will be a link to this page on the Status reports page if Drupal thinks you need to do it.)
Use the DNA module (part of Devel) to debug node access problems. DNA will display a block telling you exactly what permissions are enforced and where they come from.  Remember to give give the anonymous and authenticated user roles permission to "Access developer information" to use DNA to debug access problems for these roles. Report your findings here by editing your question if you don't understand the output of DNA.
If none of the above works, start disabling modules to see if one of those causes the problem.  Remember to clear caches after disabling a module.  You may also want to rebuild permissions (see pt. 2 above) after disabling a module, even if the module don't tell you to do it.


You have 3 simple options (And even more with preprocessors, but I won't go into that):

Most themes auto output the primary and secondary menu (configured in Appearance -> Global/THEMENAME -> Settings). You can turn it off on the theme settings, and use the Block system (Structure -> Blocks -> Main menu -> Configure) to put it on the pages (2 valid urls):

/user
/user/login

pages only.
(This is exactly the same as 1 except it's not database configuration, it's a code edit) Edit the page.tpl.php and comment out the lines that go something like:

if($primary_menu) { print $primary_menu; }

and again use the block system to output the main menu block on the login page (2 valid urls - see 1)
Or alternatively you can create a new custom menu, stick your form link there, and use the block system to assign it to the login page (2 valid urls - see 1). And leave your Main menu empty.


How to run code on every page request - after modules are loaded?

I'd need something that runs after all modules are loaded - but before cached pages are served.

You cannot, as loading all the modules is the last phase of Drupal bootstrap, while cached pages are served in the second bootstrap phase.

See the code used by drupal_bootstrap().

  switch ($current_phase) {
    case DRUPAL_BOOTSTRAP_CONFIGURATION:
      _drupal_bootstrap_configuration();
      break;

    case DRUPAL_BOOTSTRAP_PAGE_CACHE:
      _drupal_bootstrap_page_cache();
      break;

    case DRUPAL_BOOTSTRAP_DATABASE:
      _drupal_bootstrap_database();
      break;

    case DRUPAL_BOOTSTRAP_VARIABLES:
      _drupal_bootstrap_variables();
      break;

    case DRUPAL_BOOTSTRAP_SESSION:
      require_once DRUPAL_ROOT . '/' . variable_get('session_inc', 'includes/session.inc');
      drupal_session_initialize();
      break;

    case DRUPAL_BOOTSTRAP_PAGE_HEADER:
      _drupal_bootstrap_page_header();
      break;

    case DRUPAL_BOOTSTRAP_LANGUAGE:
      drupal_language_initialize();
      break;

    case DRUPAL_BOOTSTRAP_FULL:
      require_once DRUPAL_ROOT . '/includes/common.inc';
      _drupal_bootstrap_full();
      break;
  }

If you look at _drupal_bootstrap_page_cache(), you will notice that hook_boot() is eventually invoked before the page is served from the cached data, while hook_exit() is eventually invoked after the page is served from the cached data. Those hooks are invoked if the value of the Drupal variable "page_cache_invoke_hooks" is TRUE.

  if (variable_get('page_cache_invoke_hooks', TRUE)) {
    bootstrap_invoke_all('boot');
  }
  drupal_serve_page_from_cache($cache);
  // If the skipping of the bootstrap hooks is not enforced, call
  // hook_exit.
  if (variable_get('page_cache_invoke_hooks', TRUE)) {
    bootstrap_invoke_all('exit');
  }

Notice that in Drupal 8, hook_boot()has been removed and so does hook_exit(). This means Drupal 8 will never invoke those hooks.


How to move blog to a custom path in drupal?

For a 'permanent' move you'll need to write a custom module and implement hook_menu_alter(), to copy the settings for the original path over to the new one, and remove the old page from the system:

function MYMODULE_menu_alter(&$items) {
  if (isset($items['blog'])) {
    $items['share/blog'] = $items['blog'];
    unset($items['blog'];
  }
}

That will just do the core 'blog' page, the blog module defines 4 paths (see blog_menu()), each of which you'll need to override if you want make this change fully. You might also need to do some further digging into the code the blog module produces as I'm not sure if any of those paths are hard-coded into URLs or anything like that.


hook_entity_bundle_field_info_alter() only validates article bundle

You're using the bundle alter hook, which is only called on by-bundle fields.

Title is a base field but it can be overridden by a per-bundle through field override.. this is what happens if you chose a different title through the node type settings form. I guess that's why it's only available sometimes.

Try to use my_module_entity_base_field_info_alter(). Due to the override, which completely replaces the base field, you actually might need both hooks.. I don't know if the constraint is transported to the field override correctly and certainly not if the field override already exists when you add the alter hook. Not much that can be done about that I fear.


How to allow content editors to choose from Image Styles during content creation?

Luckily enough there's already a module that does exactly this, Formatter Field. The example use case given on the module page is exactly the same as yours:

The formatter field module provides a mechanism for specifying a formatter and formatter settings to be used for displaying a field, on a per-entity basis. By default, Drupal provides formatters and settings per entity bundle, but in certain situations it is necessary to choose the formatter at the entity level.
For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.


Probably you must not have given that specific user/role, the permission to "View Published Content". Verify that please.


What causes menu to stop querying for children half way through menu

this is what i see. There are no children missing. Have you cleared your Browser cache?

Some themes need the parent item set to "expanded". The setting is available (e.g. http://example.com/admin/structure/menu/manage/main-menu)for every menu item but only parents need it.

  Show as expanded. If selected and this menu link has children, the menu
  will always appear expanded.

This is the only wild guess i can take from your informations.


You can use simple jQuery to achieve this then. Try putting the following code in your JS file:

$("#fname").blur(function(){
  var fname = $("#fname").val();
$("#lname").val(fname);
});


Actually, Drupal Commerce fits this need perfectly as you can pretty much disable the entire notion of payments etc. no problem and the rest of the system won't mind at all.

The default "add to cart form" you use for adding stuff to your cart doesn't even display price.

Also, making a view out of the current user's shopping cart order (shopping cart contents are for Drupal Commerce "orders", just incomplete ones) to make a custom display of what the user has compiled and to make a rule for checkout that just sends the "order" to you(r) client.

I'd be happy to answer any more detailed questions you might run into, but in general, the answer is "yes" as the architecture of Drupal Commerce is very flexible and as it's fully entity-based, it integrates seamlessly with all other aspects of your Drupal site.