How do I conditionally override views cache using preview?

ADDITION:

This works:

$view=views_get_view('to_c_or_not_to_c'); // or whatever your name of your view is
$view->display['cached']->display_options['cache']=array('type' => 'none'); // 'cached' is the display name of the view that is normally cached but here we are going to set it to none
return $view->preview('cached'); // returns the rendered html of that display (if you need arguments, they can be passed here as an array in a second argument

ORIGINAL:

May the great drupal gods strike me down for this answer, but....

$view_object->live_preview=TRUE;

will cause drupal to ignore any cache()ing that may be set and a very quick look doesn't seem to show much other side effects (other than some query capturing)


Hide certain views fields only on particular content type

Controlling the rendering of information at the views level is preferable. If you control it at template.php it's just one step before the information is going to be displayed to the end user. So, it will be an overload. Just try to render the $data object, you can easily get the required information. Yes, $row has issue of returning nid in D7.

Hope it helps


Disable payment if Drupal Commerce Order Balance Total is <250

Actually the correct condition is called: Price Comparison and not Balance total

see here:


Corrupted mysql cache_rules table - dropped the table and now I cannot create it anymore!? Stuck

I tried dropping the database multiple ways. via command line and phpmyadmin. none of that worked.

What did work was going into the database files directory and deleting it manually. These mysql database tables are just regular files you can delete. Mine were located here: /var/lib/mysql/

here's what i did:

After that I was able to recreate the table via mysql command line. just copy and paste this to recreate the table with the schema:

CREATE TABLE `cache_rules` (`cid` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique cache ID.', `data` longblob COMMENT 'A collection of data to cache.', `expire` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry should expire, or 0 for never.', `created` int(11) NOT NULL DEFAULT '0' COMMENT 'A Unix timestamp indicating when the cache entry was created.', `serialized` smallint(6) NOT NULL DEFAULT '0' COMMENT 'A flag to indicate whether content is serialized (1) or not (0).', PRIMARY KEY (`cid`), KEY `expire` (`expire`)) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Cache table for the rules engine to store configured items.';


Why does Drupal say I need to upgrade to 8.0.0 beta 6 when I'm already checked out on that tag?

update.module doesn't know about git.

It only understands .info(.yml in D8) files. And .info.yml files only get their version as part of the package building process. If you look at your system.info.yml, it doesn't say anywhere that it is beta6.

There is a module called git deploy, that is trying to fill that gap and extracts version information from git and tells update.module about it, there is a Drupal 8 release but I don't know if it works with the current version.


I'm not aware of any web based file browser that "opens files in the client site applications" like Project, Word, etc. and saves them.

Some ideas:

However, this could be possible if you open your files with a FTP manager, as they will be opening from your client's computer, therefore using its applications.

Another option might be the download / re-upload approach, for what you could use a module like elfinder, which does allow you to edit text based files (note that we are not talking about propietary software like Microsoft Word).

Disclaimer: I'm not endorsing any of these methods, just offering alternative ideas.


drupal 7.12 : multiple taxonomy vocabularies in a single view exposed filter

I recently did the exact same thing for a client. The website is http://www.buyagainbaby.com.

You will notice there are 9 primary categories each with subcategories.  I achieved this by creating 9 different taxonomies. After researching this for weeks, I found this was the best solution. Here is how I did it.

9 taxonomies, each named for the product category you want, Footwear, Trousers, etc, then add as many terms as needed to each vocabulary. Now create one content type for each corresponding category and then assign that vocabulary to that managed fields area. At least this is how I did it.  It was a bit of a chore to get setup, but, bit was worth it. All the search functionality is done with views filters and having it architectured like that lets me do some very complicated things with filters and views.  Let me know if you have questions.  Oh one more thing, keep the content type name the same as the vocabulary name, and that will help tremendously in simplified complicated views to return products, etc.


When you setup a node field, there's a default value in the form.

Simply write down the default value there, and each time a new content is created, this field will be loaded with that default value.


In case someone's interested, I finally got it fixed implementing a simplenews hook :

function MY_MODULE_simplenews_subscribe_user() {
  drupal_get_messages('status'); // Flush default simplenews status message
  drupal_set_message(t('My custom message'), 'status'); // Set my own message
}


how to upload multile user profile pics at a time?

You can use something like profile2 module and create image upload filed that allows multiple files.


What are the most appropriate users and permission levels for Drupal sites on shared hosting?

Hosting options

Hosting options for a website site is generally one of the following:

dedicated server
virtual private server (VPS)
shared hosting

With a dedicated server, only one site is hosted on a physical computer, and the configuration is as secure as the computer itself.

With a VPS, your software runs on the same physical computer as other users' virtual machines. However, it is functionally equivalent to a dedicated server. Most important, a VPS has the privacy and security of a dedicated server.

With shared hosting, your web site resides on a file system shared with other users.  This, unfortunately, makes it less secure than when it is running on a dedicated server or VPS.  The rest of this article discusses the security of a WCMS in shared hosting environment.

Environment

A shared hosting environment can be regarded as consisting of a web server, a file system, a settings file, a database, and some users.

In the following examples, it is assumed that the owner account is "tom", and that the settings file (holding database credentials) is named "settings.php".

The web server process may run with the user permissions of the owner account "tom", or with group permissions of the group "www", depending upon the configuration.

Also, a standard Gnu/Linux or Unix environment is assumed, and it is assumed that the reader understands the Unix access control system with separate read (r), write (w) and execute/access directory (x) permissions split into three blocks (user, group, other).

Before I go on to discuss specific settings, it may be helpful to list the conditions we want to satisfy:

For a web-site to be operational, the web server must have read access to all the files that make up the site, and access  directory access to all the directories that make up the site.
For secure operation, web server must not have write access to any of the files it handles.
For secure operation, a web script run by a rogue user must not have read access to the files owned by another user.
For the owner to work on his own site using the CLI, the user must have read and write access to his own files.
To protect the files from being accessed by other users using the CLI, the "other" block should have no permissions set.

Unfortunately, on a shared host, you can only have 4 out of 5.  I know of no way you can  satisfy all five conditions on a shared host.

As far as I know, two different configurations are used by shared host providers.  Both are discussed below, along with the permissions to use to best protect files and directories, and what condition the configuration fails to satisfy.

Config 1: Web server is running as owner

This is AFAIK the most widely used configuration.  The web server is running as owner of the files.  This means that a rogue user cannot use his web server user to run a script to read another user's files.  This type of configuration also protects users from each other in the CLI.

However, it also means that we can't have separate permissions for the owner and the web server. To satisfy condition 2 with this type of setup, you need to restrict write permissions for the owner in order to prevent write access for the web server to everything except the upload directory.

Permissions:

Directories:  500 r-x --- --- tom.tom
Files:        400 r-- --- --- tom.tom
settings.php: 400 r-- --- --- tom.tom
Upload Dir.:  700 rwx --- --- tom.tom

Unfortunately, this means that condition 4 cannot be satisfied.  I.e. the site cannot be maintained through the CLI. The owner will be constrained to use some sort of web-based dashboard to access the site (my recommendation is that the owner maintains a copy on some staging server where he has unrestricted access, and mirror changes made on the staging server to the shared host).

Config 2: Web server is running as a member of the www group

This configuration is used by some (IMHO) less professional providers of a shared host solution.  The web server is running as a member of the www group, and is given the required read access through the group block:

Permissions:

Directories:  750 rwx r-x --- tom.www
Files:        640 rw- r-- --- tom.www
settings.php: 640 rw- r-- --- tom.www
Upload Dir.:  770 rwx rwx --- tom.www

These settings have the advantage of giving the owner full access to his files through the CLI, and restricts the web server to read access only.

However, it also fails to satisfy condition 3.  I.e. it allows a rogue user on the shared host (or a hacker that as compromised the site of another user sharing the host) to run a script to read any file that can be read by the web server.  This gives the rogue script access to the file settings.php with the database credentials, which makes it trivial to completely take over the site.

My recommendation is to avoid this type of configuration.

Addendum: How dangerous is it to use a shared host?

I certainly would not put anything sensitive, such as credit card numbers or medical records, on a shared host.  But shared hosting is cheap, and there is an attraction in that.  I use shared hosting myself for several of my sites.  I haven't been hacked yet, but I know that the risk exists and I am prepared for the day when it happens.  If I am hacked, I will simply delete everything on the shared host, and reinstall the site from a mirror copy I keep on a secure staging server.

With "config 2", the main problem is the others.  If some other website that you share the host with gets compromised, your website is also lunch.  Making security depend upon another party you don't know and have no control over is not a good idea.  This is why my recommendation is to avoid "config 2"-type hosting arrangements.

With "config 1", you alone control your web site's security. This is better (in particular if you know what you're doing).  But it is not fool-proof.  Nobody's perfect, and  if you goof up and your site is compromised, the attacker will have access to every file stored on that host that belongs to you.  In other words, to minimize the damange when you're hacked, do not keep anything on that host that will cause harm if someone else gains access to it.  In particular, do not keep your email on that shared host.  There is usually tons of sensitive data in email, so you do not want it anywhere near a web server executing as "you".

And if your web applicaton is handling sensitive data, make sure your budget allows for a dedicated host or a VPS.

You may also want to see this guide to Securing file permissions and ownership at Drupal.org.


Display images filed in views slideshow in node content page

Create slideshow view block.
In view configuration, provide contextual filter of field "Content: Nid" and then provide default value "Content ID from URL".
Now place this block into Content region.


You just need to define them in your .info file...

regions[four_first]   = Footer panel (first)
regions[four_second]  = Footer panel (second)
regions[four_third]   = Footer panel (third)
regions[four_fourth]  = Footer panel (fourth)

Then add them to your page.tpl...

<?php if ($page['four_first'] || $page['four_second'] || $page['four_third'] || $page['four_fourth']): ?>
    <div id="footer-panels-wrapper">
       <?php print render($page['four_first']); ?>
       <?php print render($page['four_second']); ?>
       <?php print render($page['four_third']); ?>
       <?php print render($page['four_fourth']); ?>
    </div>
<?php endif; ?>

When you have done this they will appear in /structure/blocks

The rest is down to CSS...


How can I provide an optional link to a Forum from a node (D7)?

Use entityreference. Create a rule that generates the forum on node creation and then an action that creates an entity reference in the original node.


Drupal 8:

$table = [
  '#type' => 'table',
  '#header' => ['ab', 'cd', 'ef'],
  [
    [
      '#plain_text' => 'rowspan',
      '#wrapper_attributes' => ['rowspan' => 2],
    ],
    ['#markup' => '1'],
    ['#markup' => '1'],
  ],
  [['#markup' => '1'], ['#markup' => '1']],
];

Result:

See Drupal Documentation for a colspan example


My solution was to turn off the layout ('Manage display' --> 'Select a layout' --> 'none').
Now the debug mode FILE NAME SUGGESTIONS showed the correct suggestions.
I was able to override the 'node.html.twig' in my subtheme (in my case with 'node--CONTENT-TYPE--full.html.twig')from 'themes/bootstrap_barrio/templates/content/'.
Neither the FILE NAME SUGGESTIONS for the DS (8.x-3.9) nor the Bootstrap Layouts (8.x-5.2) were working (the one you see in debug mode, when one of those layouts is selected in 'Manage display').
Maybe there is a better way ...


How do I require the user submitted content to be approved before it is published?

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

From the Workbench project page:

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

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

From the Workbench Moderation project page:

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


What might cause my "User error" in Watchdog?

This is not connected to the Token module.

You should not try to render a non existing entity. Your code should throw an exception instead:

use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;

  throw new NotFoundHttpException();

Or configure the route so that when you have a non existing entity as parameter in the route, drupal will throw this exception automatically. See the answer from Berdir to your last question:

https://drupal.stackexchange.com/a/205054/47547


Update database with data from dev site?

Jordan.

Unfortunately, this is not something that Drupal does very well.

You can try using the Deploy module, but in my experience as a professional developer, I have never met anybody who has found a good way to export nodes in a way that is thorough, consistent, and safe.

More specifically, Deploy may not support all field types, and sometimes field definitions are hard to find, and can be inconsistent (for example, taxonomy terms are exported as TIDs, which change if the term is deleted and then added again).

Sorry for the bad news.


How do I get request parameters when using fragment AND query with drupal_goto

I'm guessing you're trying to access the $_GET from the page that's loaded in the overlay (admin/vendor/auth-stripe).  If that's the case, then you've constructed the url wrong.  It should be:
http://mydrupalsite/#overlay=admin/vendor/auth-stripe%3fcode%3dsuccess

That said: where are you actually constructing this URL?  If you're doing it properly, all of that should be taken care of for you automatically.


Using form_set_error in the submit handler

In case it's useful to anyone else, I have a unsatisfactory work around;

Store the error in form_state, and look for them in the form callback.

function example_form($form, &$form_state) {
  // if we had an error in the submit handler, trigger it now
  if(isset($form_state['error']) && $form_state['error']){
    form_set_error('test', 'test');
  }
  if(!isset($form_state['step'])){
    $form_state['step'] = 1;
  }
  $form['test'] = array('#markup' => '
Step: ' . $form_state['step'] . '
');

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'go'
  );
  return $form;
}

function example_submit($form, &$form_state) {

  $form_state['rebuild'] = TRUE;
  if($form_state['step'] > 5){
    //store error and return before the step is increased
    $form_state['error'] = true;
    return;
  }

  $form_state['step']++;
}


Correct way to append value to serialized array in key_value table

The best way to go about doing this is by using config API. If somehow this option is not suitable for your use case. You can also use the DB API to update the desired congratulation table records. In both cases, you will need to unserialize the blob then change the data and serialize it back before inserting it into the database.

https://www.drupal.org/docs/8/api/configuration-api/configuration-api-overview


Writing Drupal 7 queries using drupals DB abstract. (Similar to an entity wrapper)

If by level of abstraction close to the one given by entity wrappers, you mean a module/library that would allow to write code similar to the following, no, there isn't anything like that.

$field_value = database_wrapper('table')->table_field;
database_wrapper('table')->set('table_field', $new_value)->save();

The level of abstraction that would offer, in the case of reading the database, would not be worth the code you would write to implement it, and it would just save a few method calls. In fact, $field_value = database_wrapper('table')->table_field; would be equivalent to the following Drupal 7 code.

$result = db_query("SELECT table_field FROM {table}");
foreach ($result as $record) {
  // Use $record->table_field;
}

Also for writing, the Drupal 7 code is not much complicated to require a wrapper.

db_insert('table')
  ->fields(array(
    'table_field' => $new_value,
    ))
  ->execute();

Real code would be more complicated than this, but a wrapper that should consider every case would be even more complicated.


Private filesystem does fire 403 on every role and file

If you need to debug access at the Drupal application level, then look at FileDownloadController::download; it's the controller method for the /system/files/{filepath} path; you can use your tool of choice to inspect the execution flow from request to the returned response object.
If the issue is outside the Drupal application level (e.g. web server, varnish) then it will require further stack troubleshooting.


The process callback is generally called from the check_markup() function.

That function blindly passes the $langcode value through to the process function, so it is up to the caller of the check_markup() function to send through the appropriate language.

You can see the list of functions that call check_markup() here.

The main one that you will encounter would be the text module's _text_sanitize() function, which is what formats the text for text fields that user input filters.

As you can see, it also passes through the language of the field.

Going up another level we have hook_field_load(), which also passes through the langcode.

Back again we get field_attach_load(), which calls hook_field_load() via _field_invoke_multiple().

All these are passing through langcode.

field_attach_load() is called by all these functions.

So basically you can scour the API site and see that is calling check_markup() in your case and see why there is no langcode being passed in.

Alternatively, you can install the devel module and put

dpm(debug_backtrace());

in your format process function.

Then load the page where your text is printing out and you will get a backtrace on the screen.

The backtrace will give you all the functions that have been called to get to your code. It shows you all the parameters that have been passed into function along the way.

This way you can more quickly isolate the point where the language becomes LANGUAGE_NONE (UND) - In theory :)


how to count the results from the exposed filter

You can get that in the view itself.

view->Header->"Global: Result summary"


I think the problem might be the source on the skip_on_empty plugin. It looks like you're trying to refer to the result of the previous plugin to obtain the destination uid; I don't think you can do that until after all plugins have run on the field.

Even if you can make that reference, there's a special syntax for referring to destination fields on the source side, which is an @ symbol plus the field name (e.g. '@uid').

A solution that should remove all doubt would be to load the uid in a fake field, and re-use it for the proper destination field. For example:

process:
  _uid:
    plugin: user_lookup
    source: EMPNO
    value_key: field_employee_id
    entity_type: user
    bundle: 1
    bundle_key: status
    ignore_case: true
  uid:
    plugin: skip_on_empty
    method: row
    source: '@_uid'
    message: 'no empno found'

Of course that might be wrong, and you may just have meant to use EMPNO instead of uid for the source, in which case you should just fix that and move the skip_on_empty plugin so it runs first, saving yourself DB queries with empty conditions.


How can I make a block that holds all the information about an articles author?

You should investigate the Views Module.  Watch the series at Nodeone.se regarding using the views module called "Taming the Beast" to learn how.


References lost when a content type is renamed

why not name it back, and then only changing the displayname, not the machinename would maybe sufficent for you ?

else do an export and import - as suggestes via features module.


Breadcrumbs for a view page with arguments

I believe when you are creating a view that has an argument you can the opportunity to set a breadcrumb from within views itself.

Substitutions will also be available based on the arguments present.

For example, if you view is

/blogs/2011

Where blogs is the path to the page, and 2011 is the argument, you could set the breadcrumb of the page with the argument to be:

%1

This would leave breadcrumbs that would look like:

Blogs > 2011


How to get administration views to work?

I'm sure your problem is already gone by now but for those who might be searching for ways to make Admin Views and VBO work, the versions I'm using are 7.x-1.3 and 7.x-3.2 respectively.

You would need to clear Drupal cache for the default admin pages to be overridden by the newly added Admin Views.


I am unable to show the access denied message of the premium content module. How can I do this?

I have included this code within the teaser in node--content-type.tpl.php:

<?php print $content['body'][0]['#markup']; ?>

And I have included this code in template.php:

function  mimooc_premium_body($arguments) {
  $node = $arguments['node'];
  node_build_content($node, 'teaser');
  unset($node->content['links']);
  $level = premium_level_load($node->premium);
  if ($level->denied_message) {
    $denied_message = $level->denied_message;
    $denied_message_format = $level->denied_message_format;
  }
  else {
    $denied_message = variable_get('premium_message', t('Full text available to premium subscribers only.'));
    $denied_message_format = variable_get('premium_format');
  }
  // Only display the premium message, if we actual have any content.
  if (!empty($node->content)) {
    return '

' . check_markup($denied_message, $denied_message_format) . '

' . l('Click here to sign in', 'user') . '

';
  }
}

Now, when I access the full view mode of the node, I get the teaser of that node with the access denied message.


How to handle duplicate .module files that live in 2 places?

There shouldn't be a job.module in the includes directory at all, your module files for your job module should all be in sites/all/modules/jobs.

You generally shouldn't put anything in (or modify anything in) the includes directory or you will make it harder for yourself to upgrade drupal core in future.

I would say you should:

check for any differences between the two files.
If they are different determine whether or not anything in includes/jobs.module should be in sites/all/modules/jobs/jobs.module. If so add it.
Delete includes/jobs.module


Custom template for specific vocabulary term

You can go with the following:

taxonomy-term--[term id].tpl.php You can get the term id number when you hover the edit button.


How to filter the options from a select list field according to a previous select list?

Take a look at Conditional Fields module to define dependencies between fields based on their states and values. Conditional Fields allows you to manage sets of dependencies between fields. When a field is “dependent”, it will only be available for editing and displayed if the state of the “dependee” field matches the right condition. When editing a node (or any other entity type that supports fields, like users, terms and files), the dependent fields are dynamically modified with the States API.


How to make user profile page display extra fields in drupal 7?

You most likely added the fields through this admin page:
admin/config/people/accounts/fields

To control which fields are actually displayed on the view page, go here:
admin/config/people/accounts/display

Also if you have the Field Permissions module enabled, make sure all necessary roles have the permission to view the fields you've added.


Since you are setting 'access callback' to TRUE, you are actually giving access to those routes to every user, including the anonymous users.
You could easily set the access callback to a function in your module 'access callback' => 'ibbr_inv_access_callback' and check the roles the global $user variable has, but that would be a bad idea, since every time you need to give access to those routes to a new role, you would need to change the code of your access callback. Plus, since you are hard-coding the roles in your code, the module could not easily be adapted to different needs, such as sites using totally different roles.

The Drupal way is to assign permissions to the roles that should be able to access the routes you define, and use user_permission() as access callback for your routes. In this way, the code would check for the same permission, which could be given to new roles, or to totally different roles; any change in the roles having that permission would not reflect on your code, which would still work in any case.

As permission, you could use one that Drupal already use, or (if that is not restrictive enough) define a new permission.

function ibbr_inv_menu() {
  $items['inventory_scan'] = array(
    'title' => 'Inventory items',
    'page callback' => 'ibbr_inv_menu_page_callback',
    'access arguments' => array('administer inventory items'),
    'type'=> MENU_CALLBACK,
  );
  $items['inventory_scan/add_item'] = array(
    'title' => 'Add new item',
    'page callback' => 'ibbr_inv_add_new_item_callback',
    'access arguments' => array('administer inventory items'),
    'type'=> MENU_CALLBACK,
  );
  return $items;
}

function ibbr_inv_permission() {
  $permissions['administer inventory items'] = array(
    'title' => t('Administer inventory items'),
    'description' => t('Creates/deletes inventory items.'),
  );
  return $permissions;
}

To use a access callback that checks the roles the currently logged-in user has, I would use the following code. It's not the code I would use, but if you need to use such code for any reason, this is what I would suggest.

function ibbr_inv_menu() {
  $items['inventory_scan'] = array(
    'title' => 'Inventory Items',
    'page callback' => 'ibbr_inv_menu_page_callback',
    'access callback' => 'ibbr_inv_access_callback',
    'access arguments' => array('the role the user needs to have'),
    'type'=> MENU_CALLBACK,
  );
  $items['inventory_scan/add_item'] = array(
    'title' => 'Add new item',
    'page callback' => 'ibbr_inv_add_new_item_callback',
    'access callback' => 'ibbr_inv_access_callback',
    'access arguments' => array('the role the user needs to have'),
    'type'=> MENU_CALLBACK,
  );
  return $items;
}

function ibbr_inv_access_callback($role_name) {
  if ($role = user_role_load_by_name($role_name)) {
    return user_has_role($role->rid);
  }

  // The role doesn't exists; return FALSE as safe value.
  return FALSE;
}

The code works on Drupal 7.36 and higher, since it is using a function that previous versions didn't implement (user_has_role()).

As side note, since for inventory_scan/add_item you are using array(1, 2) as page arguments, the page callback would receive 'add_item' as argument, which doesn't make much sense; it would make sense if you were using the same page callback for different routes, and you would use 'add_item' to make the page callback know which action to perform.
In the same way, it doesn't make much sense to use array(1, 2) as page arguments for a route like inventory_scan; if you are not visiting inventory_scan/first_value/second_value, the page callback will not receive any arguments at all.


You have the Theme Developer module enabled, which adds <span thmr="foo"> tags to everything. Theme Developer uses a bit of brute forcing when it comes to adding those tags that can cause problems with complex themes that don't go out of their way to support it.

Disable it and they'll go away: you should only have Theme Developer enabled during development/debugging anyway.


Show menu items with limit access to anonymous users

Your problem is quite common.

Here is discussion how to implement such trick in Drupal 6 and 7 and 8: http://drupal.org/node/300607

  Drupal 6 (and 7) removed the ability to display menu items the user doesn't have access to. However, in some cases it is desirable to show a menu item even though the user doesn't have access to the menu item. For example, if you use an authentication mechanism that tries to acquire authentication when a 403 would be displayed, you still want to display the menu item so that users get a chance to provide credentials to log in.

Solution for Drupal 7 can be found here: http://drupal.org/node/300607#comment-4450062

If you prefer ready module - you can download it here https://github.com/systemseed/always_visible


Yeah, it sounds like you need to create a view to output submissions.

Webform helps you here by integrating fully with views so you can pull out whatever data you need. You can also create a view per webform which will enable you to have a separate page for each.

Failing that, if you go to Content Management > Webforms it gives you a summary of all webforms on the site with links to view submissions, export them, etc.

Hope this helps.


sort a view by Most Viewed, Most Favorited, Latest

Create three different views, Most Viewed, Latest, Most favourite with display type block.
For sorting by views, You need to enable statistics module.
For sorting by latest, use post date sort filter in views.
For sorting by favourite, flag module has integration with views. You can able to create a filter to sort by number of flags.
Use Quick Tabs module to group above three different view blocks as a single block and display it where ever needed.


Search index as custom view for taxonomy term with hierarchy. Showing all children results in term parent in taxonomy menu

If I'm understanding correctly what you're asking, here are some tips.

Under your defined search index, go to Fields. If you have "Products" taxonomy defined, uncheck the taxonomy term, then go to the bottom and open "Add Related Fields" and add "Products", then save changes. When it reloads, you'll now have more taxonomy options. Check "Products >> All parent terms". You should now have additional facets for parent/child terms.

Use in conjunction with Facet API Pretty Paths for even more powerful usage. Take a look at one of my other response about how to use that.


In a tableselect form element with '#js_select' => FALSE, how can I re-use the column header for a label?

For doing this you have to change the "theme_tableselect" core code. See this documentation code part. If you do not set "select all" then the header is assigned to null


A couple things here:

hook_init() will be run on the first hit on the page, eg, if it's not in cache already, it will be run and then the page will be cached.  But...
A page will not be cached if there are any drupal messages, so, when you call drupal_set_message() it sets drupal_page_is_cacheable(FALSE); and the page isn't cached.

ADDITION:

Regarding your additional code with respect to Javascript:  adding this code in verbatim here does not exhibit the random behavior you see on your site; eg; here the same number appears until the cache is refreshed.

Which made me think about this.  Check your cache times:

If the times are set to <none> I see the behavior you seem to experience, but when they are set to anything else, eg:

then I don't.


How to create a view that lists all groups and their respective contents?

Create a view that lists all content of type "Group Content"
Add a relationship OG membership: Group Node from OG membership and make it mandatory

 - Add field Group Title and exclude it from display choose relationship above

Use Group By Option in Display settings and group by Group Title

And the output will be

Find view export below.. Content type names are group and group_content

$view = new view();
$view->name = 'group_group_content';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'node';
$view->human_name = 'Group - Group Content';
$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'] = 'Group - Group Content';
$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['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'full';
$handler->display->display_options['pager']['options']['items_per_page'] = '10';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['style_options']['grouping'] = array(
  0 => array(
    'field' => 'title_1',
    'rendered' => 1,
    'rendered_strip' => 0,
  ),
);
$handler->display->display_options['row_plugin'] = 'fields';
/* Relationship: OG membership: Group Node from OG membership */
$handler->display->display_options['relationships']['og_membership_related_node_group']['id'] = 'og_membership_related_node_group';
$handler->display->display_options['relationships']['og_membership_related_node_group']['table'] = 'og_membership';
$handler->display->display_options['relationships']['og_membership_related_node_group']['field'] = 'og_membership_related_node_group';
$handler->display->display_options['relationships']['og_membership_related_node_group']['required'] = TRUE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title']['id'] = 'title';
$handler->display->display_options['fields']['title']['table'] = 'node';
$handler->display->display_options['fields']['title']['field'] = 'title';
$handler->display->display_options['fields']['title']['label'] = '';
$handler->display->display_options['fields']['title']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['title']['alter']['ellipsis'] = FALSE;
/* Field: Content: Title */
$handler->display->display_options['fields']['title_1']['id'] = 'title_1';
$handler->display->display_options['fields']['title_1']['table'] = 'node';
$handler->display->display_options['fields']['title_1']['field'] = 'title';
$handler->display->display_options['fields']['title_1']['relationship'] = 'og_membership_related_node_group';
$handler->display->display_options['fields']['title_1']['label'] = 'Group';
$handler->display->display_options['fields']['title_1']['exclude'] = TRUE;
/* 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;
/* Filter criterion: Content: Type */
$handler->display->display_options['filters']['type']['id'] = 'type';
$handler->display->display_options['filters']['type']['table'] = 'node';
$handler->display->display_options['filters']['type']['field'] = 'type';
$handler->display->display_options['filters']['type']['value'] = array(
  'group_content' => 'group_content',
);

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


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

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

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


How to show files with lighbox/colorbox effect?

My first problem is to get lightbox or Colorbox to display the file on click on the page

For this you need to set either lightbox or colorbox module. Once you install and enable the site you will see the option in file field to show the file in lightbox.

    he second one is to remove certain content type files from the views display

Add a filter criteria File Usage: Entity type or File Usage: Entity Id and exclude user entity.

    Thirdly, i want to create a menu to sort the file per type

For this you need to add a sort criteria based on your File:Mime Type


For your revisions, I assume you're using the revisioning module.

Why not just remove the Content: Published filter entirely?  Any node with a pending revision should be moderated.

On my site, when I unpublish a node, unpublishing it alone does not cause it to have a pending revision.  In other words, if the most recent version of a node is published, unpublishing that node does not create a pending revision.

However, if you unpublish a node with a pending revision, that node will still have a pending revision after it is unpublished.  There is no way to use views alone to distinguish between a node with a pending revision that was "set" to unpublished and one that isn't published yet.

To implement such a workflow, I would suggest using the flag and rules modules.  Roughly, the steps I would take would be:

Create a global flag called "Intentionally unpublished."
Create a rule that automatically flags nodes when they are unpublished.
Add the flag as a relationship to your view and filter based on the existence of the flag.


How do I programmatically create a file and write it in the private:// folder?

If anyone need it, I make it work:

use Drupal\Core\File\FileSystemInterface;

...

  /**
   * @var \Drupal\Core\File\FileSystemInterface
   */
  protected $fileSystem;

  public function __construct(FileSystemInterface $fileSystem) {
    $this->fileSystem = $fileSystem;
  }

  public function testCreation() {
    $request = 'test content';
    $path = 'private://gmt/';
    if ($this->fileSystem->prepareDirectory($path, FileSystemInterface::CREATE_DIRECTORY)) {
      /** @var \Drupal\file\FileInterface $file */
      $file = file_save_data(
        $request,
        $path . 'requests.txt'
      );
    }
  }


Loop through a multi value entity reference field working only on the first selected item

foreach ($Articles as $Article) {

  // Get the "Article Country" Value from the loaded article.
  $ArticleCountry = $Article->field_article_country->target_id; // shorter way

  // Set the 'User Country' value on the user account.
  $CurrentUser->field_user_article_countries[] = ['target_id' => $ArticleCountry]; // use array

}


Generated: not cached yet (either no one has visited the page recently, or something is preventing the cache from being generated).

Please logout, visit same page as anoymous user then login and visit again. I think you can see cached page message.


footer block through custom module and fetch node image field in Drupal 7

To accomplish this I would probably use a combination of hook_cron() to check in every hour, persistent variables to track the last loaded image (see variable_set and variable_get) and the great Ajax Blocks module so that your block is refreshed without having to rebuild the entire page each time.


That error has nothing to do with your form.

You need to provide a config schema for your config entity, see examples in node.schema.yml and many other places.

See also the configuration schema documetation.


Using Views and Date module in Drupal 7 - Limiting Filter Options

currently "date" module doesn't allow to satisfy this needs

I see two solutions for the first question:

1) Develop a custom module in order to create this type of interaction.

2) A quick and dirty alternative is to alter the dropdown content using JS, but a custom module would be miles better.

Sincerely I'll suggest the first one.

About the second question you could expose the day filter and populate it substituting the form filter with a custom one, for example hiding the original form filter with CSS (display:none) and adding some hand crafted links with the URL parameters on the views header area.

Good work!


I use the drush qd command and add the --root parameter. You can use it to download the Drupal installation into /Applications/MAMP/htdocs


If you are looking to delete children as well with parent menu items seems like Delete menu options address this issue..

Project page says

  On the 'Delete menu item' confirmation page you can choose to delete
  child menu items and decide if the linking nodes should be deleted as
  well. When the checkbox 'Delete all children of this menu.' is
  checked, all child menu items of the parent menu item to delete, will
  be deleted as well. When the checkbox 'Delete nodes of the deleted
  menu items (only orphaned nodes).' is checked, the nodes to which the
  child menu items link will be deleted too. When other menu items link
  to same nodes or aliases as the nodes which were set out to be
  deleted, those nodes will not be deleted.


According to this Stackoverflow question you might need to add this to your server configuration:

AddType application/x-httpd-php .php

Another possibility is an encoding problem, according to this other Stackoverflow question.


Alter granularity in date exposed filter from Y-m to Y if only year is selected

So, I ended up going the very ugly way.

First, my module is now reduced to:

    function lezoo_views_query_alter(&$view, &$query) {
  //If a date was selected in the exposed filter, ignore the default date filter '> today'
  $conditions = $view->query->where['1']['conditions'];
  $date_index = 3;
  dpm($conditions);
  if(isset($view->query->where['1']['conditions'][$date_index]) &&
    //if a date exposed filter was set
   $view->query->where['1']['conditions'][$date_index]['field'] != 'node.nid')
  {
    unset($view->query->where['1']['conditions'][2]);
  }
}

which is needed because the default filter on dates(not exposed) is after today, but if you select a date, then ignore that filter.

And I added a second date_exposed_filter, so that I now have date1->granularity:Y, and date2->granularity:Y-m. I then use css to hide the Y of Y-m, and js to mirror both Year fields. if anyone is interested, here is the code I use:

            var year = $('.views-widget-filter-field_date_value_2 select.date-year');
            var ymonth = $('.views-widget-filter-field_date_value_1 select.date-month');
            var yearm = $('.views-widget-filter-field_date_value_1 select.date-year');

            ymonth.change(function(e){
                var value = $(this).val();
                //var value = e.target.value;
                var empty = value == "";
                if(!empty)
                {
                    yearm.val(year.val()).trigger("chosen:updated");
                }
                else
                {
                    yearm.val("");
                }
            });

            year.change(function(e){
                if(ymonth.val() != '')
                {
                    yearm.val(year.val()).trigger('chosen:updated');
                }
                else
                {
                    month.val('');
                }
            })


different templates for print and deafult version of the node

load a print only CSS file and "display:none" for that div in it:


How to restrict users to certain Content Types?

It looks like you should give it a try to use the Group module.
You'd enable the gnode submodule, and for each group type you would define the appropriate permissions (view, edit, delete, etc) for the various Content Types.

From the details included in your question, it seems that possibly you'd only need 1 group type. And if you then would create 1 group for each of the Content Types involved, you might be close to a working solution.

More info: What's the purpose of the Group module and how to get started with it?


Can't translate the messages of the flag module

See this from the Flag module issue queue

  Each string you enter as an administrator is available in the Translate Interface section, but you first have to switch to a different language, then view a page that contains that message (such as trying to flag/unflag a piece of content). Afterwards, the string will be flagged as needing a translation and you can find it in the Translate Interface section.


in views row-template, how to obtain rendered output of each item in multi-valued field?

If the field is multi-valued, then $view->render_field($fieldname, $view->row_index) returns a comma-separated string of the individual rendered items:

rendered_item0,rendered_item1,rendered_item2,...

To generate the array $field_output_array where $field_output_array[2] = rendered_item2, explode the string:

$field_output_string = $view->render_field($fieldname, $view->row_index);
$separator = ',';
$field_output_array = explode($separator, $field_output_string);


Determine if menu link is current/active

Have you tried to combine it with item.below? I suppose (not tested) that this could be used to only apply the class to the deepest item within the active trail. The code could look something like this:

{% for item in items %}
  {% if item.in_active_trail and not item.below %}
    set classes = [
       'is-active',
    ]
  {% endif %}
{% endfor %}


What is the difference between "content type" and "custom content type"?

A content type is a type of node. Node types (aka content types) are generally created through the browser UI. However, they can also be created through code, which people refer generally refer to as a custom content type.


Print user uploaded logo in twig template

All of you need to do is to Add New Regions to your Theme like logo_region and then print the site logo on desired twig template with below code:

{% if logo_region %}
  <div class="my-style">
    {{ page.logo_region }}
  </div>
{% endif %}

And finally enable/place your site brand in created region (logo_region) on Block layout page:admin/structure/block


add ajax form-like functionality inside node

Build your webform, or Form api form, grab its ID and then follow my answer to insert this form into node's content through a custom module of yours

Cleaner way to do it.


Get an image with style url from an URI in twig

You could put the php code in the preprocess function of the field template. You have all information you need in your question.

But then you would do coding, that is already in drupal. If you have #image-style set in the image render element, then the image field should be configured for the preprocess functions that come later in the image-formatter and image-style templates to put the right src attribute in the variables for image-style.html.twig. So you can use the code that is already there by overriding this template.

See the code in /core/module/image/image.module:

function template_preprocess_image_style(&$variables) {
  $style = ImageStyle::load($variables['style_name']);

  // Determine the dimensions of the styled image.
  $dimensions = array(
    'width' => $variables['width'],
    'height' => $variables['height'],
  );

  $style->transformDimensions($dimensions, $variables['uri']);

  $variables['image'] = array(
    '#theme' => 'image',
    '#width' => $dimensions['width'],
    '#height' => $dimensions['height'],
    '#attributes' => $variables['attributes'],
    '#uri' => $style->buildUrl($variables['uri']),
    '#style_name' => $variables['style_name'],
  );


What options exist for search result weighting (e.g. promoting same score results higher in the results)

Although Search API / Apache Solr Search Integration are popular modules with more flexible control over boosting, the core Search module allows you to add custom scoring via hook_ranking().

There is a code snippet in a comment in the documentation referenced above that at least hints how to do the boosting fpr content types. Boosting on a specific taxonomy term might be a little more tricky because the scoring logic is done in the "score" key, which is effectively a SQL clause. Therefore you have to either get fancy with joining a custom table that has some of your custom scoring logic pre-calculated when the node is indexed, or you will have to add you logic directly in the SQL clause to generate it on the fly. The latter could get messy if you have a lot of conditions.


hook_node_access() is a standalone hook and has nothing to do with the node_access table.

hook_node_access_records() and hook_node_grants() go together and are different to hook_node_access(). These hooks use the node_access table.

Basically, the node_access table stores all the access grants for nodes.
These grants can then be queried and joined to other queries to check the access rules for a node.

hook_node_access_records() is invoked when writing access rules to the node_access table and hook_node_grants() is invoked when reading them out again.

To give you a better idea of how the hooks work, look at the code where they get invoked from.

For hook_node_access_records() this is node_access_acquire_grants().
It invokes the hook and then writes all the returned grants to the node_access table.

hook_node_grants() is called from a few places, but generally via the node_access_grants() function, which is called from a few places. Take a look at the node_access() function as an example.

It queries the node_access table, adding to the query conditions any access grants returned by modules that implement hook_node_access_grants(). Note that grants are also alterable via hook_node_grants_alter().

While you are looking at the node_access() function you can also see how hook_node_access() is called and you'll see how it is different and why it's not as flexible a solution to access control.

In case you haven't seen it, this is a good article on the topic: http://www.phase2technology.com/blog/drupal-7-node-access-grants-locks-and-keys/


Providing translations for custom modules

I had a similar problem that it didn't work but it turned out that my problem was with file permissions that weren't set correctly on the PO file I was trying to import.

I debugged it as follows:

On the following url admin/reports/translations you can see where it looks and what it looks for. (handy for debugging the tokens) Expand the status information for the available language.

Every time you change your info.yml file don't forget to rebuild cache and trigger the translation update manually.


Thanks a lot molot

the problem was a wrong implementation to the views hooks as this post

and hook_views_query_alter

This hook should be placed in MODULENAME.views.inc and it will be auto-loaded. MODULENAME.views.inc must be in the directory specified by the 'path' key returned by MODULENAME_views_api(), or the same directory as the .module file, if 'path' is unspecified.


We also solved this task with the user_multiple_role_edit() function.
In our usecase we didn't react on the register-form but on a special menu-callback to create users on the fly.

First: Create a user

$user = new stdClass();
$user->name = $name;
$user->status = 1;
user_save($user);

Second: Assign the user to the role

$role = user_role_load_by_name("my custom role");
user_multiple_role_edit(array($user->uid), 'add_role', $role->rid);


I think you are looking for the function which returns the access denied page; that is  drupal_access_denied(). Just call this function inside your conditional statement.


You can combine multiple field values into one (hidden) field using Computed Field. Be sure to save the value to the database, so that it can be used as a Views exposed filter. You'll also need to re-save each existing node in order to populate the computed field (VBO can do that in bulk).

This is another interesting idea (I haven't tried it): http://drupal.org/node/732458#comment-4750574


How to handle simultaneous editing and deletion of nodes?

A better solution may be to use content locking to prevent double editing.

for example: http://drupal.org/project/content_lock


Is it possible to combine two filter criteria exposed filter into one dropdown

Even with Better Exposed Filters you will not achieve what you need. As I understood you want one selectbox for the end user which merges three different fields of your content type?
This is not possible out of the box. When filtering the name of the selectboxes and the chosen values will be added to the URL like "?selectbox1=123&selectbox2=abc&selectbox3=xyz" (not exactly, but this is not important). Views does it for you to translate these URL parameters into the field names and the database query.
For your idea you need a way to tell Drupal that "?my_merged_selectbox[]=123&my_merged_selectbox[]=abc&my_merged_selectbox[]=xyz" needs to be somehow translated into the seperated filters / field names and values like above.
The only way would be to write your own views filter plugin. Helpful link: https://zanzarra.com/blog/custom-views-filter-plugin-drupal-8-bounding-box-geofield
I do not know if you have programming skills but what you want to achieve will need custom programming and is not trivial.


Content types with a field that get data from my custom table

Did you already try the Entity reference module? If I understand your question correctly, you could create a content type Writer and add a reference field on your Book content type. This reference field can be used to select (i.e., use the 'Select list' widget) the appropriate Writer for your Book. No need to create a custom table yourself.

With permissions you can control who's allowed to create/edit/delete each of the content types.


How do I remove a DIV from the rendered result of a BEF exposed form?

why not just write CSS that targets this item and removes any css applied by the default bootstrap .form-group ?

For example the rule could look like:

div.from-type-bef-checkbox.form-group {
  /* then "undo" whatever .form-group is doing -- you can see whatever it's
     doing by using Firebug or Google Chrome and inspecting the Element
     on the page.

     for example:
  */
  margin: 0 0 0 0;
}

By fixing just the CSS and not removing the css class or the div entirely you dont break or worry about upgrading these modules (of course you'll still have to check this CSS fix works in newer versions of the theme).

You can do this in your theme by adding or using a default custom stylesheet provided by your theme.


Change Add to cart button text in Drupal 7

The string overrides module is handy for these kind of things.

Provides a quick and easy way to replace any text on the site.

  Features

  Easily replace anything that's passed through t()
  Locale support, allowing you to override strings in any language
  Ability to import/export *.po files, for easy migration from the Locale module
  Note that this is not a replacement to Locale as having thousands of overrides can cause more pain then benefit. Use this only if you
  need a few easy text changes.


To use state for checkboxes element, you should target the specific element by JQuery selector, all elements they have the name="field_select_shipping" with value attribute different so try to target the input with both attributes try with the following to show adresse_home only if home and colissimo checkbox checked:

$form['input']['adresse_home'] = [
      '#type'     => 'textfield',
      '#title'    => 'Adresse',
      '#required' => FALSE,
      '#states'   => [
        'visible' => [
         ':input[name="field_select_shipping"][value="home"]' => ['checked'   => TRUE],
         // This like AND so the input show if home and colissimo checked
        ':input[name="field_select_shipping"][value="colissimo"]' => ['checked'   => TRUE],
        ],
      ]
    ];


Calling /user page with username instead of uid results in database exception due to failed string to int conversion

There are two sides to this question.
First, you should not get this error message. It should be good old 404 page or Drupal's error message about invalid argument. It's either a bug in database backend for MS SQL and belogs to their queue, or in your version of MS SQL RDBMS and belongs to Microsoft technical support. Or you simply need updates.
Second part is - out of the box only numerical URLs works.You neet to create aliases with username. It can be done automatically, Pathauto's default setting is exactly:

Pattern for user account page paths
users/[user:name]

Sadly, unless you get the first part fixed, it will only help with valid users, people will still get ugly message if they'll hit a name that does not exist, by typo in their address bar for example.


Rules Conditions being evaluated after schedule time elapsed?

Give this a try

Create a New Component

1) Add Compotent of Rule.

2) For Data Type: select Node. Name, Label and Machine name use whatever you want.

3) Add condition of Content is of type

For Data Selector: put your Node Data Type machine name. Ex: if you gave the node data type a machine name of test you put test
Select your content type

4) Click on Add and select Data Comparison and select your boolean field.

Example: When creating the component, if you gave the Node Data Type a machine name of test and your boolean field is named hello. For your boolean field you need use test:field-hello as your data selector.

5) Add action of Send Mail.

Now Create a new Rule

1) For action use after content is created

2) Leave the condition empty (no need for condition here)

3) for Action add the scheduled component evaluation and select the component you just created.

use node as your data selector

  I believe this will evaluate your rule component only when the schedule time hits.


Disable double confirmation for Simplenews

There's a considerably easier way to do this, which is also documented in the README.txt for 6.x-2.x, but apparently not in 7.x-1.x.

In short, just change the confirmation mail templates and append /ok to the URL token.


How to troubleshoot general module issues?

My first port of call is usually the reports in /admin/reports, in particular 'recent log entries' (use the filters) and 'status report'. Also the PHP error logs on the server can be useful.

Also, keep an eye on Javascript errors by using your web browser's javascript console/log, as you attempt to do the broken activity.


You could load external content replacing your href by

javascript:void jQuery.colorbox({html:''})

It will be something like:

<a href="javascript:void jQuery.colorbox({html:''})">colorbox-load external link


In multisite environment can you have a default site?

For sure you can have a default site to use i case if the requested site was not available some reason the default site will be open to user. to do that you need to setup the default site setting under sites/default/setting.php

lets assume we have 3 website

mysite1.com
mysite1.com
mysite3.com
defultsite.com

In that case your file structure needs to be :

/sites/mysite1.com folder which will have setting.php file for mysite1
/sites/mysite2.com folder which will have setting.php file for mysite2
/sites/mysite3.com folder which will have setting.php file for mysite3
/sites/default folder which will have setting.php file for default site

You need to setup your .htaccess file in your root of server to point every Domain to the main drupal folder. to learn more about .htaccess please read here.

No to test if your default site is working simply rename mysite1.com folder to xxxxx and now try to access your mysite1.com using any browser it shoud take you to default site because mysite1.come folder cant be found anymore.


Only render translated nodes, prevent rendering of base language node

One way to think about it is to disable language fallback mechanism in Drupal. Although there are 3 different modules which handle language fallback priority, none of them provide such functionality.
However, the module Disable Language allows admin to disable an entire language entirely without deleting the content itself.
I think you can use its code to implement an EventSubscriber which checks whether the node has a translation for the current site language then return a NotFoundException in this case. This will cover direct node access.
I'm not entirely sure how to deal with nodes loaded via DB. I think you can use hook_entity_load for this case.


Why are my menu items not showing under the top level menu item?

According to Drupal menu item types you need to designate which item is the parent and designate the children as such. So in your case, I believe setting your 3 links as MENU_LOCAL_ACTION should resolve the issue. You might have to designate the top level menu item as MENU_DEFAULT_LOCAL_TASK to make it work depending on your settings.


I need a Drupal workflow solution where I can edit live/published nodes and save without the edits going live until commited

Try the Workbench module. If I'm not mistaken you can make draft versions of nodes that have been published.

From the module page:

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

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


Displaying parts of main menu in separate blocks

Consider using menu_block and defining 2 blocks with the depths you desire within the main-menu for each block; and then place them in the drupal Regions you want. The menu_blocks I believe will play nicely with Nice Menus if you have "expand all child elements" of this menu option checked.


Using the Context module you can achieve your required feature.

This module will help you to place all your blocks in multiple regions on same or multiple page.


subscribe to nodes with entity reference

Try flags + Rules + Views

I use something similar on a jobs site to allow users to subscribe to 'industries' (taxonomy) and be notified when a new job tagged with the industry is created.

In short:
install the Flag module, and create a flag for taxonomy terms.
This flag, when clicked, would fire a rule saying "Subscribe the user to this term" and this would happen with a nice Ajax link that does not reload the page.

Create another rule, saying something like "When new content is posted in X term, email all users who have flagged (subscribed to) that term."

Then build a couple of views:
A page of all the terms (if you need this!), showing the Flag links (these can be text, or you can style them as nice images using CSS).
The second view: A block, emulating a Subscriptions block - basically this block would appear on your 'Artists' pages, and it would show the terms together with their flag/subscribe links.

You could build a third block, to be shown on the user's profile page, listing the terms they're subscribed to.
You might want to use the Context module to control the logic of where the blocks appear.


The URL you're building is taking the query (e.g. "word1 word2 word3") and replacing it with literal "+" chars for spaces. Hence, the %2B encoding in the string.

You don't need to parse/encode $form_state->getValue('textBox'). Per the documentation of Url::fromUri() for the $options param:

  'query': An array of query key/value-pairs (without any URL-encoding) to append to the URL.

$options['query'] expects its key/value pairs to have the literal strings.

You needn't worry about +/%20 encoding differences. They are different ways to encode the space character. (the + is an older space-encoding spec which you can do if absolutely needed, see rawurlencode, urlencode, & http_build_query in the PHP docs).


Architecture advice for site with lessons that belong to courses

How about this unproven setup.

Create a third content type, Sections. Courses reference sections with a mutli-value entity reference field, which you can drag/drop the order of this field from the node edit form. You can use inline entity form to assist with content creation.

Then, reference Lessons from Sections with a multi-value entity reference field, also allowing you to drag/drop the order of the field values. Not sure if you can use the inline entity form within an inline entity form...maybe.

Then, you can continue to use EVA on both the courses and sections to display view results, using a node id contextual filter...I assume.

Or, you could just render the referenced entity, selecting a custom display mode, which you theme accordingly. This may offer better performance.


Preventing a duplicate node from being created

There is the Unique Field module that does this.


If the page content needs to be fetched via an API request, you can use

hook_menu

to define a URL path to function callback to generate the page content.

Basically your own path to the content.

The page callback will fetch the API response from cache or perform the request, cache the response and display it.


How to ensure successful update after system failure during updb causing the site to remain in maintenance mode?

When running subsequent drush updb that says "no updates required" does this guarantee the previous updates were successful.

When Drush queues up batch items to be processed for drush updb, it adds these operations:

Any module schema updates
Any entity definition updates (off by default, not supported after 8.7)
A cache clear & post hook update functions (on by default)
Toggle off maintenance mode (if it not already enabled)

If the only updates were module schema updates then you might be in a scenario where things are ok; there are no post-update hooks needed (e.g. some batch data ops following a schema change) and only the last step of toggling off maintenance mode didn't complete.

How do I ensure the integrity of the system when this happens without restoring a backup and running the updates again?

You'd have to audit the list of updated modules to double-check each schema update was applied and there were no post-update hooks missed in the update.
Depending on your update scenario this may or may not be easy, hence the best practice is doing a DB rollback and re-applying updates to ensure data integrity when uncertain.


You can use the Table theme. Example :-

$form['data_field'] = array(
'#type' => 'textfield',
'#title' => t('Search!'),
'#id'   => 'search',
'#maxlength' => 1024,
'#description' => t('Search by using tags and free text'),
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Go!!',
);
...
...
fill $table
...
...
if(sizeof($form_state['input'])!=0) {

$form['table'] = array(
'#theme' => 'table',
'#header' => $header,
'#rows' => $rows,
'#empty' => t('Empty Rows')
);
}
return $form.


Clear Varnish Cache (and maybe Views?) for Home Page when new story posted

Install the varnish module and set the minimum cache lifetime to none at admin/config/development/performance Also be sure to add the tweaks to the settings.php from the varnish module page.

This should ensure that the cache is flushed when new content is added.  You may want things to be a little more granular (if a complete cache clear at every content update would overload your server and cause performance problems) so using here are some other steps you can take:

I found a nice article about using varnish which you might consider checking out.

The author recommends:

Go to the Varnish settings page (admin/config/development/varnish) and select "None" under "Varnish Cache Clearing". This will make sure that all pages are not flushed when content is altered.

Enable the Cache actions and the Rules UI module
Go to Administration => Workflow => Rules and click "Create a new rule"
Select "After updating existing content" under "Node" as the reacting event
Add the "Clear a specific cache cid" action
Select cache_page as your cache bin.
Put "node/[node:nid]" in the value text area.

Try to edit one of your nodes, everything should still work. The difference now is that we are actually only purging the entry of the particular node that has been edited not the whole page. You can try this by visiting another node, notice that it is still cached by looking at the Varnish headers.

You will probably also want to clear the views cache (for your relevant views) so they are updated instantly.  Testing should be relatively easy by adding new content in a browser and refreshing another browser window that isn't logged in.  You should see your new content appear immediately at refresh.


Try this:
in '/admin/structure/block' find your block, click on configure link beside it  then in Language setting tab Check "Make this block's title translatable"
Then Go to Translate interface admin/config/regional/translate/translate
Then enter the block title above and limit search to "block"


Suppress certain content types from taxonomy term list display (D6)

use a view for taxonomy/term/* (it is created by default, you just need to enable it) and set a filter for it to exclude the blog_post node types


How can I tell to the rule I am writing that the value of region field is the value coming from webform data?

If I switch to data selection I can't find submitted values, so how can I tell to the rule I am writing that the value of region field is the value coming from webform data?

You can use a technique similar to what is described in my answer to "How to do a data comparison to submitted webform data when using the Rules module?". For short:

Add an extra Rules Action to Add a variable (call it whatever you want), with a value assigned to it equal to your [data:ComponentFieldName-value-raw] (with a data type which equals the data type of your Webform component), and with ComponentFieldName whatever you're using for that region field in your Webform).
In your subsequent Rules Actions you can refer to the value of this variable you just added (that's the clue!).


Set the Contextual Filter: Author uid. to a default user?

In contextual filters instead of selecting User ID from Logged in user select php code and write some code like

global $user;
if($user->uid > 0){
$uid = user_load($user->uid);

$roles = $uid->roles;
if(in_array('administrator', $roles)){
return 'uid of the logged in user';
//print_r($uid->roles['3']);exit;
}
else{
return FALSE;
}
}
else {
return 'return here person1 uid';
}


Try customising the Scroll to Top module. Which provides a similar functionality.


Your code should work fine from what I see. You can print the $url value to see what really is passed to API. Please note that $form_state['storage']['Title'] will contain the key, not value - maybe that's the problem?

Plus, you don't need to use storage in this case. When using $form_state['rebuild'] you can just use $form_state to pass variables, like this:

function mymodule_form($form, &$form_state) {
  $storage_val = isset($form_state['values']['title']) ? $form_state['values']['title'] : 'nothing stored yet';

  $form['message'] = array(
    '#markup' => t('Stored value: %storage_val', array('%storage_val' => $storage_val)),
  );

  $options = array(
    'opt1' => 'option1',
    'opt2' => 'option2',
    'opt3' => 'another option',
  );

  $form['title'] = array(
    '#title' => 'Select option',
    '#type' => 'select',
    '#options' => $options,
    '#default_value' => isset($form_state['values']['title']) ? $form_state['values']['title'] : '',
  );

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

  return $form;
}

function mymodule_form_submit($form, &$form_state) {
  $form_state['rebuild'] = TRUE;
}


Set default value for Enity Reference using View and Entity Reference View Widget Checkbox

Did you try casting the value to a string?  I had to do that when I was setting default values for a user reference field type.  It wouldn't work otherwise. Something like

 $form['line_item_fields']['field_pesonal_data']['und'][0]['field_cover']['#default_value']=(string)6;

Also, I noticed that you had a spelling error.  You had 'field_pesonal_data' It should probably be 'field_personal_data'

Also, I was a little confused by your use of terminology.  You described that the user is configuring the entity reference field on the product.  Did you mean configuring the entity on the line item?  I just wanted to clarify, because if you are modifying the form that governs the adding of products (or product variations in Commerce Kickstart 2.0), you need to use a different form alter call because the product variation creation form uses the inline_entity_form module to manage the specific product variations.

That call is:

function hook_inline_entity_form_entity_form_alter(&$entity_form, &$form_state)

Look at the inline_entity_form.api in the contrib/inline_entity_form folder in Commerce Kickstart 2.0

for modifying a user reference on a product, I did the following:

function bh_vendor_inline_entity_form_entity_form_alter(&$entity_form, &$form_state) {
  global $user;
  if ($entity_form['#entity_type'] == 'commerce_product') {
    $entity_form['vendor_user_reference']['und']['#default_value'] = (string)$user->uid;
  }
}

My widget I used was a option list.
You have to have the ['und'] or it won't work either.


Recovering from a WSOD related to hierarchical select module

The _hierarchical_select_setup_js() function is defined in the hierarchical_select.module so this is one of those "it should work" situations.  Since it isn't, a quick workaround would be to copy it out of there and into, oh, say, your template.php file, wrapped in a "if !function_exists()" so it doesn't WSOD when it does :)


How to set the breadcrumb for view defined pages

You can set with hook_page_alter()

if (request_path() == 'your/page/path') {
    $breadcrumb[] = l(t('Home'), NULL);
    $breadcrumb[] = l('Whatever', 'whatever');
    drupal_set_breadcrumb($breadcrumb);
}


How do I link drush to my drupal site thats hosted via localhost?

There are several ways to tell Drush which Drupal site you would like it to operate on.

Run Drush from the directory that contains the Drupal site's settings.php file.

$ cd /path/to/drupal_root/sites/default
$ drush status

Pass --root and --uri options that identify the site:

$ drush --root=/path/to/drupal_root --uri=http://mysite.dev status

Create a site alias, and use that

$ drush @mysite status

In order to use the last option, you must define the mysite alias as described in the example aliases file.

UPDATE:

The --uri option is used (a) to select which settings.php to use, and (b) to set the $_SERVER superglobal. If your settings.php file is in the default directory, then --uri is not necessary to bootstrap. However, some modules will expect the URI to be set up correctly; in some instances, you will not get the correct results if this setting is omitted.


Drupal 7 Commerce - What permissions do I need to set to give access to a specific role to view ANY order for administration?

This is how my permission look like --

As you can see, Site Admin & Shop Keeper can manage orders along with administrator(I have several kind of users). Site Admin & Shop Keeper doesn't have access to toolbar, so I have created a menu with name "Manage Order" & set it to the path "admin/commerce/orders"(I have several menu items of this kind).

Placed this menu in one region with permission set to be viewed only by these users type who are intended to use it. These users have permission to use admin theme, so they access it just like administer do by clicking on those menu item.


Manage 2 separate page cache for the same URI

This assumes that the theme is changing.

Settings.php file:

// Check if cookie is set.
if (!empty($_COOKIE['custom_theme'])) {
  // Add theme name to page cache id.
  $_SERVER['REQUEST_URI'] .= '#' . $_COOKIE['custom_theme'];
  // Set Theme.
  $conf['theme_default'] = $_COOKIE['custom_theme'];
}
// Disable page cache if cookie not set so hook_init code can set the cookie.
else {
  $conf['cache'] = CACHE_DISABLED;
}

hook_init():

  // If no cookie is set set a cookie with the value of theme_default.
  if (empty($_COOKIE['custom_theme'])) {
    $temp = empty($custom_theme) ? variable_get('theme_default') : $custom_theme;
    setcookie('custom_theme', $temp, time() + 60*60*24*30, ini_get('session.cookie_path'), ini_get('session.cookie_domain'));
  }


Select options not loading when using callback function

Your select_user_dropdown_options() function needs to return an array of options, not a block of HTML. See the #options section of the Form API documentation -- you should find yourself re-reading that Form API page a lot.

Your array will be in the form

array(
  'group_1' => 'Group 1',
  'group_2' => 'Group 2',
);

A pedantic note -- I believe that's really a function call as opposed to a callback. That's fine; I mention it mostly because you don't include the parentheses when providing the names of callback functions.


Using Views' Contextual filters in a Panel for one taxonomy term

If you want to display a different view for a country, I think what you probably want to do is use the Taxonomy Term override page rather than using contextual filters.

To do this, go to the pages admin screen (/admin/structure/pages).  Then, enable the Taxonomy term template panel to override the display of taxonomy terms using Panels.

To show a custom view, you can edit the Taxonomy term template panel.  This will allow you to use the taxonomy term as arguments for your view, because Panels understands that you are overriding the taxonomy term display.


Display price in add to cart form BEFORE add to cart button

I spent weeks on trying to find a clean solution using the commerce-product.html.twig template but to no avail. The problem is the fact that the variation fields and add-to-cart button are packed together into one component (product.variations) in a way that is difficult to decompose. I cannot think of a way to insert the price in there somewhere. Someone should create an issue about this.

Here is a hacky CSS-workaround.

First, create some space above the add-to-cart button:

.commerce-order-item-add-to-cart-form .form-actions {
   margin-top: 4em;
}

Now place the price div into the created space:

article .field--type-commerce-price {
   position: absolute;
   bottom: 2.5em;
}

This also works when the price is updated.

Still looking for a cleaner solution.


Pricing rules was the right track. In order to configure 2 main prices for a single product :
Add a 2nd price field to the product type:

Add a boolean field to the corresponding line item type:

In the Add to Cart form settings of this field (admin/commerce/config/line-items/CUSTOM-line-item/fields/field_avec_aerien), check  Include this field on Add to Cart forms for line items of this type.
Finally, in admin/commerce/config/product-pricing/rules/manage/, create (or clone & edit) a new pricing rule which set the unit price to 2nd price amount, when the boolean is checked by the customer in the add to cart form.

Pricing rules are very powerful, indeed !


Retain content while deleting user using services

Answering my own question,

I have updated the default account setting of when cancelling a user account in the path /admin/config/people/accounts to Delete the account and make its content belong to the Anonymous user

Resolves my query.


How merge two different views on single page?

Views Global Filter

  Use Views Global Filter on sites that feature multiple Views. You want
  the views to be driven by the same filter selection, for instance a
  country, a date range, a search term or even proximity to a post code.
  These views may be on the same page or scattered across several pages
  on your site, however you want to offer the visitor the convenience of
  setting the filter for all these views only once, for instance when
  they first land on your site. Views Global Filter implements the
  picked once, operates site-wide (POOS) principle. This means you can
  place anywhere on your site a selection widget (drop-down, check boxes
  etc) to globally filter all or some of your views. When the user picks
  a value from the global selector, the value is invisibly passed as a
  contextual filter to whatever views you like, even when these reside
  across multiple pages. This avoids you having to duplicate filters and
  avoids the visitor having to re-select their choice as they go from
  page to page.

Combine two views on one page


I am afraid you need to edit drush files to achieve it.. Currently label support is not there if you see below code in contributions/drush/commands/core/field.drush.inc

function drush_field_create($bundle) {
  $entity_type = drush_get_option('entity_type', 'node');

  $args = func_get_args();
  array_shift($args);
  if (empty($args)) {
    // Just one item in this array for now.
    $args[] = drush_field_create_wizard();
  }

  // Iterate over each field spec.
  foreach ($args as $string) {
    list($name, $type, $widget) = explode(',', $string);
    $info = field_info_field($name);
    if (empty($info)) {
      // Field does not exist already. Create it.
      $field = array(
        'field_name' => $name,
        'type' => $type,
      );
      drush_op('field_create_field', $field);
    }

    // Create the instance.
    $instance = array(
      'field_name' => $name,
      'entity_type' => $entity_type,
      'bundle' => $bundle,
    );
    if ($widget) {
      $instance['widget'] = array('type' => $widget);
    }
    drush_op('field_create_instance', $instance);

    $urls[] = url(drush_field_ui_bundle_admin_path($entity_type, $bundle) . '/fields/' . $name, array('absolute' => TRUE));
  }
  drush_print(implode(' ', $urls));
}
?>

As you see above only field_name and type is taken from args.. To create label also you need to change code to below

function drush_field_create($bundle) {
  $entity_type = drush_get_option('entity_type', 'node');

  $args = func_get_args();
  array_shift($args);
  if (empty($args)) {
    // Just one item in this array for now.
    $args[] = drush_field_create_wizard();
  }

  // Iterate over each field spec.
  foreach ($args as $string) {
    list($name, $label, $type, $widget) = explode(',', $string);
    $info = field_info_field($name);
    if (empty($info)) {
      // Field does not exist already. Create it.
      $field = array(
        'field_name' => $name,
        'type' => $type,
        'label' => $label,
      );
      drush_op('field_create_field', $field);
    }

    // Create the instance.
    $instance = array(
      'field_name' => $name,
      'entity_type' => $entity_type,
      'bundle' => $bundle,
    );
    if ($widget) {
      $instance['widget'] = array('type' => $widget);
    }
    drush_op('field_create_instance', $instance);

    $urls[] = url(drush_field_ui_bundle_admin_path($entity_type, $bundle) . '/fields/' . $name, array('absolute' => TRUE));
  }
  drush_print(implode(' ', $urls));
}
?>

and use command like

drush field-create [content-type] [field-machine-name],[field-label],[field-type],[field-widget-type]


The Drupal way was easier than I thought.

I changed it to direct input and used

now +7 days 18:00:00

and it's working.


Why aren't nodes indexed when they are saved?

I believe it is in the interest of scalability. Imagine you had a large, popular site with user-generated content. Imagine you had users saving a node (say, posted a question or answer) every 20 seconds. Imagine a node being indexed as well as submitted every 20 seconds. The site would become unusable very quickly. So it's much better to allow the indexing to happen independently of node submission.


How to Disable Whole Form from hook_form_alter?

Drupal doesn't cope with the form being removed in such a way because it is expecting certain things in the form array after you have altered it.

That's why you are getting that error, because form_builder() does this:

if (!isset($element['#id'])) {
  $element['#id'] = drupal_html_id('edit-' . implode('-', $element['#parents']));
}

but you have removed $element['#parents'] when you looped through unsetting everything, including #parents.

If you want to loop through all form elements are remove them the correct way would be to use element_children(), which will loop through the keys of child elements but skip properties of the current element.

So to loop though child elements you would do this:

// Remove all elements from this form.
foreach (element_children($form) as $key) {
  unset($form[$key]);
}

Alternatively you could restrict access like this, which could cause you less side effects if other modules are expecting form elements that you have deleted.

// Restrict access to all elements in this form.
foreach (element_children($form) as $key) {
  $form[$key]['#access'] = FALSE;
}

If the form is a page though, not in a block or something, then it might be better to use hook_menu_alter() to block it as Shawn said in his answer.


Drupal 7 - Add two menu items with the same path but different query string

What I did is add the redirect module.

Then I created custom redirects for those menu items, e.g. "node/add/alert/kind/regular" goes to "node/add/alert?kind=regular".

No need for custom hook_menu programming.
It worked! But why doesn't drupal provide it work out of the box???


How to display the related node content in a block?

You can use the Featured Content module for that.

Alternatively, you can also use the Views module by filtering your content using the node of the current page as an argument and using taxonomy or node reference to relate the content.


How to set the visibility rule for pane to not show up when any user is logged in?

While adding a Visibility rule to the pane, select User:Role and then select "anonymous". This way the pane will be shown only to anonymous (not logged in) users.


What causes 'You are not authorized to access this page' during create/edit of any menu?

Make sure you flush caches and rebuild permissions (from status page) and run cron.
If these fail check if any custom module implements hook_node_access
A rogue Rule could also be the culprit


is there any possible conflict for fields with the same machine name?

Machine names for fields must be unique per entity type.

The means that with nodes, fields must be unique across all content types. So you can't create two fields with the same machine name on different content types, as both content types are nodes, and machine names must be unique for the entity type. (Edit - you can however re-use the same field on multiple content types, but it will be the same field, not two fields with the same machine name).

You can have a field_image on a node, and field_image on a taxonomy term. Here, the machine name is the same, but unique to each entity type, so there is no problem.


MY PROBLEM :
When the {{ drupal_view('accueil_page_liste_des_taches_boutique', 'block_1') }} block is rendered on my home page, the blocks in the
commerce-store--professionnel--tasks-frontpage.html.twig templates
do not work. This is normal because I think it searches for the store
ID in the URL.
How do I fix this ? There is an EVA module, but is there another way
to do this directly with TWIG ?

If you don't want context filters getting IDs from the current path or current user you have to pass arguments to the View:
{{ drupal_view('accueil_page_liste_des_taches_boutique', 'block_1', store_entity.id()) }}

The arguments can be an array or a scalar if it is only one argument.


Change the expiry time for welcome user notification message

In Drupal 7:
Set user_password_reset_timeout variable (i.e. in settings.php, or strongarm):
i.e. in settings.php:

$conf['user_password_reset_timeout'] = '604800';

source : https://www.drupal.org/node/246029


How to change value a field of preproces

You should preprocess the field output and add a class based on the value. Then to theme in css. It's a good idea to keep the images separate and business logic separate.

<?php

/**
 * Implements template_preprocess_field().
 */
function acTheme_preprocess_field(&$vars) {
  $element = &$vars['element'];
  if ($element['#field_infraestructura'] == 'field_infraestructura') {
    $value = $vars['element']['#items'][0]['value'];
    $vars['classes_array'][] = 'type-' . drupal_clean_css_identifier($value);
  }
}

?>

Take this qwith a grain of salt - I don't see the actual code and values in my debugger, but if you replace myfield_name with the name of the field, and mytheme with the theme name (all these machine names), then it should assign the classes based on the values.

Sadly, there may be some need of tweaking this code if some mapping does not fit - so, I hope you know at least some PHP to do that.

The output classes should be somehting like class="type-agua", and then you can theme it. You need to know css, of course - there are samples in the comments under your question.


How to stop the script drush if previous command failed?

Checkout the run_cmd function in this file: base_functions, which wraps any command and terminates the script if it fails.

You should also be able to do something like:

drush cc all || exit;

where exit will only run if the previous command fails, and you could replace exit with a call to a function that outputs a more meaningful error message. You may also add a number between 1 and 255 after exit to have your script emit an exit status that can be used further using $? in any other script calling this one.


Preventing other sites from embedding Drupal page

The technique that you want to employ is called framebusting (or framekilling).

The Frameprevention does this.  However, I typically do this manually, as I want it to happen as soon as possible, or I need to do it a certain way to pass an automated test.

Typically, I will edit html.tpl.php to add a no-js class onto the <html> tag, then then add this code bit directly after the opening <head>:

<head<?php print $rdf->profile; ?>>
  <script>
    // http://www.456bereastreet.com/archive/201209/tell_css_that_javascript_is_available_asap/
    document.documentElement.className = document.documentElement.className.replace(/(\s|^)no-js(\s|$)/, '$1js$2');
  </script>
  <?php // bypass render array so this is guaranteed to be very first thing ?>
  <style>html.js { display:none }</style>
  <script>
    if (self == top) {
      document.documentElement.style.display = 'block';
    } else {
      top.location = self.location;
    }
  </script>

This does force users to have Javascript enabled in their browsers, which is a common problem with framebusting.  I cannot find the exact reference for the technique above, but I think it came from OWASP.

You can also implement X-Frame-Options:

function MYTHEME_html_head_alter(&$head_elements) {
  $head_elements['mytheme_x_frame_options'] = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'X-Frame-Options',
      'content' => 'DENY',
    ),
  );

  $head_elements['mytheme_x_frame_options']['#attached']['drupal_add_http_header'][] =
    array('X-Frame-Options', $head_elements['mytheme_x_frame_options']['#attributes']['content']);
}

Keep in mind that you may need additional logic to account for legitimate <iframe> elements in your site.  Some ctools modals come to mind, as well as some WYSIWYG situations.


Content type adding page is not displaying properly

For admin users you can change this at the bottom of theme settings:

/admin/appearance

☑  Use the administration theme when editing or creating content

On the staging server you probably testing this with a non admin user account, so you won't see a difference there.


Given a File ID (fid) how can I get the HTML that represents that fid?

This works for me. For videos via the media module:

<?php
  $file = file_load($fid);
  if (strpos($file->filemime, 'video/') !== 0) {
    return;
  }
  $key = 'media_' . substr($file->filemime, 6) . '_video';
  $formatter_info = file_info_formatter_types($key);
  $content = array();
  $content['#theme'] = $key;
  $content['#uri'] = $file->uri;
  if (isset($formatter_info['default settings'])) {
    $content['#options'] = $formatter_info['default settings'];
  }

  $rendered = drupal_render($content);
  return $rendered;
?>

And for images; this shows you what presets are available (#style_name)

<?php
$styles = image_styles();
echo '<pre>' . print_r($styles, TRUE) . '</pre>';
?>

And this will render the file

<?php
$file = file_load($fid);
$image = image_load($file->uri);
$content = array(
  'file' => array(
    '#theme' => 'image_style',
    '#style_name' => 'large',
    '#path' => $image->source,
    '#width' => $image->info['width'],
    '#height' => $image->info['height'],
  ),
);
echo drupal_render($content);
?>

Note that image_load performs I/O.

And for the reverse; given a filename get a fid.

<?php
$query = new EntityFieldQuery();
$result = $query
  ->entityCondition('entity_type', 'file')
  ->propertyCondition('filename', basename($filename))
  ->execute();
foreach ($result['file'] as $values) {
  $fid = $values->fid;
  break;
}
echo $fid
?>

Given media embed code, get a FID.

<?php
$file = media_parse_to_file($embed_code);
if (empty($file->fid)) {
  return FALSE;
}
return $file->fid;
?>


Finding all nodes not referenced by a menu entry or another node

I needed this for a clients request, so i decided to try and do it without any additional modules, and push my MySQL a bit. This is what i ended up with.

For clarity, this will only provide a list of NID's that DO NOT have an associated menu item.

I've also added a WHERE clause to limit content types, as some content types will naturally be excluded because of the way they was architected.

SELECT n.nid, n.type, n.title, n.status
FROM node AS n
WHERE (n.type = 'article' OR n.type = 'page')
AND n.nid NOT IN (
  SELECT REPLACE(link_path, "node/", "") AS nid
  FROM menu_links
  WHERE SUBSTRING(link_path, 6, LENGTH(link_path)) REGEXP "^[0-9]+$"
);


function template_preprocess_node(&$variables)

makes available in your node.tpl the variable $title, so you can wrap this as you like in your node.tpl theme file.


How long will the previous core version supported?

Drupal 7 is currently on LTS.
  Drupal 7 LTS will end when Drupal 8 enters LTS, at which point Drupal 7 enters security fixes only mode.
  Drupal 7 security fixes only mode ends when Drupal 8 enters security fixes only mode, and Drupal 9 enters LTS.
  Essentially: Drupal 7 won't be EOL before development has started on Drupal 10.

Source: Has the EOL (end of life) for Drupal 7 been announced?

The simple answer is: We don't know, yet, exactly.

Check out the following articles:

When is Drupal 7 End-of-Life?
Understanding the Drupal 8 and 9 Release Cycle.

  Drupal 7 will likely get bug-fixes until October 2017, and official
  security support until 2019 or 2020 at least.