Creating a block with installation profile To create a block I am currently using this code:

$default_theme = variable_get('theme_default', getDefaultTheme());
$blocks = array(
  array(
    'module' => 'user',
    'delta' => 'login',
    'theme' => $default_theme,
    'status' => 1,
    'weight' => 0,
    'region' => 'sidebar_first',
    'pages' => '',
    'cache' => -1,
    ),
);

// Save blocks
$query = db_insert('block')->fields(array('module', 'delta', 'theme', 'status', 'weight', 'region', 'pages', 'cache'));
foreach ($blocks as $block) {
  $query->values($block);
}
$query->execute();

My question is what do the 'module' and 'delta' field exactly do? What can I fill in there if I made a custom block? And how do I define on which pages this block should be visible, should I add a page name or id?

I think that's not the correct way of creating the block as it won't fire the required api call for block creation and later on will cause issue.

Delta: This is a unique identifier for the block within the module. Delta values only need to be unique and is used in following purposes:

Passed into the other block hooks in your module as an argument to identify the block being configured or viewed.
Used to construct the default HTML ID of "block-MODULE-DELTA" applied to each block when it is rendered. This ID may then be used for CSS styling or JavaScript programming.
Used to define a theming template suggestion of block_MODULE_DELTA, for advanced theming possibilities.

Module: Name of module creating that block. E.g: If you are creating the block from custom module than it will take the value of that module name.

To programatically create the block, you need to use hook_block_info(), hook_block_view() in your custom module something like below:

/**
 * Implements hook_block_info().
 */
function MyModule_block_info() {
  $blocks['test1'] = array(
    'info' => t('Block info 1'),
  );
  $blocks['test'] = array(
    'info' => t('Block info 2'),
  );

  return $blocks;
}

/**
 * Implements hook_block_view().
 */
function MyModule_block_view($delta = '') {
  $block = array();

  switch ($delta) {
    case 'test1':
      $block['content'] = 'Required content 1';
      break;

    case 'test2':
      $block['content'] = 'Required content  2';
      break;
  }

  return $block;
}


How 2 set up a bunch of modules for sell per node access? I need to sell some nodes on my site, not type of content (subscription alredy exist) - only per node acess.
I think, that it is not cost-effective to create type of content for every good, cause number of goods can reach 100 units per day.
I know, that https://www.drupal.org/project/uc_node_access can resolve my trouble, but I develop my site under 7 version of Drupal, and uc_node_access for 7 has only sanbox now.
Dear experts, help me if u can, I'm not a professional developer.
P.S. - sorry if my post has grammar mistakes, I'm Russian.

I have done it successfully. Resolving my problem on https://www.drupal.org/node/2407311


Views - Rewrite Content:Link field based on content type I'm using Content:Link as a field in a view to make a link button in a list of content. How can I rewrite the results based on content type?

For instance, if the content type is an Article, it would say "Read More" but if it's a Product Display, it would say "Buy Now".

Thanks!
:)

I think you need Views Conditional Field module for this. Based on condition show other field which will output different text.

Module page explains :

  Views Conditional is a simple module that allows you to define
  conditionals (if xxx then yyy) with fields in views. Conditions
  include:

Equal To
Not Equal To
Greater Than
Less Than
Empty
Not Empty

  Views conditional allows you to output text based on the result of the
  condition.


Add to wishlist with ajax How can i make add to wishlist button with ajax like add to cart button using  Commerce ajax cart module .

Also in my view how to change the add to wishlist button text to already added if user has already added the product to wishlist.
I am using commerce wishlist module

There is a module called Commerce Wishlist

Alternatively, for ajax functionality, you could use the Flag module to replicate a similar sort of functionality


Drupal 8 CKeditor behaves LTR in an RTL site I've installed Drupal 8.0.2 in a standard installation process and in English.

I later changed The site's default language to Hebrew (Which is an RTL language) and my content type is now setted to the site's default language - Hebrew. I even determined my user's administration account, called "admin", to Hebrew (a new Drupal 8 feature that let's you pick a specific front-end language to a certain user).

After that I've organized the CKeditor full-profile edit-bar in an RTL manner at it's configuration page (and flushed all caches afterwards):

You saw - I did everything by the book, and yet:

I encounter two issues that comprise my whole problem:

1. The CKeditor edit-bar appears the opposite from how I arranged it (as can be seen one image up).

2. CKeditor input area typing cursor starts in the left instead of the right (I could easily manually flip the Edit-bar but the cursor will still appear in the left).

When I installed a test site in Hebrew from the start (instead of installing first in English and then add Hebrew and make it default), I didn't encounter that problem, and the edit-bar was RTL. I have no clue how to explain this! Maybe you can!

The default CKEditor text language direction is LTR.
To change it to RTL, you can try setting the JS config setting:

config.contentsLangDirection = 'rtl';

Reference: http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html#.contentsLangDirection

In D7, there was a config textarea that can be set:

In D8, you can set the CKEditor config settings in:

hook_editor_js_settings_alter

Something like:

/**
 * Implements hook_editor_js_settings_alter
 */
function MYMODULE_editor_js_settings_alter(array &$settings) {
  foreach ($settings['editor']['formats'] as $name => $value) {
    $settings['editor']['formats'][$name]['editorSettings']['contentsLangDirection'] = 'rtl';
  }
}

More info on creating Drupal 8 modules here: https://www.drupal.org/developing/modules/8

You can also set the config in JS, for example your theme

Something like:

(function ($, Drupal) {
  Drupal.behaviors.customCKEditorConfig = {
    attach: function (context, settings) {
      if (typeof CKEDITOR !== "undefined") {
        CKEDITOR.config.contentsLangDirection = 'rtl';
      }
    }
  }
})(jQuery, Drupal);

More info on adding theme assets here: https://www.drupal.org/theme-guide/8/assets

For your other question on the toolbar button ordering. That appears to work, just make sure you set the toolbar button order on all the "Text formats" that you want to use it with (e.g "Basic HTML", "Restricted HTML" and "Full HTML") in the CKEditor admin settings.


Drupal performance issue - too much time to establish a connection! My drupal site was working fine. Then i disabled access to public with some session thing, After a week or something , it is taking more than 12 second to establish a connection, then the loading is real quick.

79 requests  ❘  35.47KB transferred  ❘  14.87s (onload: 14.87s, DOMContentLoaded: 13.06s)
home
12.24s

css_6b268b79fc331b4fe1492e8a55b94a94.css
/sites/default/files/css
206ms

cometchatcss.php
394ms

........

another thing is its better for garland theme, so possibly theme problem , what what may cause this much waiting? not db_query as i checked even with blank page.tpl its taking 8+ sec!
Please help!

Finally found problem - panel templates in my theme

for those who experience same , can follow these steps

my site is optimized with APC and mod_deflate, so in pagespeed for chrome test, its 93/100
real problem was waiting time . chrome network analysis shows first GET took approx 18+ sec , then loading of other elements is real quick
after several test, i found my theme is causing delay. so i put a blank page.tpl in my theme. And you know it took 12+ sec to load that blank page! so it was not any db query problem!
so problem must be with .info, disabled css, then js, still no improvement
finally removed panel template declaration from .info , and now site took .3 sec to load!
next i tried with only one panel template in my theme, site took 1-2 sec

I have 10 panel templates in my theme.so panel templates affects site performance!


More efficient use of function by storing the result? So I have a custom module that is simply one function that during Commerce checkout goes through the order or cart to create an array saying how many "products" of type 'event','donation' and 'product' there are in the cart.

Now this all works great and I use it to do multiple things such as:

Change the title page of the checkout if someone is "donating" rather
than "purchasing"
Show or hide certain checkout panes depending on whether a 'donation' or 'event' is in the cart
Render a checkout progress bar which shows certain checkout pages, again dependent on the product types currently in the cart.

My issue now is that on render of the Checkout Details page I have this one function executing 4 separate time. How would I go about triggering it once for each load of a page and storing the array in a place that can be accessed by multiple modules and template files?

Seeing as how the data is not really an item that is cachable sitewide, you could quite easily use the $_SESSION variable.

Example:

function my_expensive_function($foo, $bar) {
  if (isset($_SESSION['my_really_cool_stuff'])) {
    return $_SESSION['my_really_cool_stuff'];
  }
  else {
    //Do what you would normally do to get everything you need
    //and put it in a $my_really_cool_stuff variable
    $_SESSION['my_really_cool_stuff'] = $my_really_cool_stuff;
    return $my_really_cool_stuff;
  }
}

This way, if the data already exists in the user session, it'll return that.  If not, then it'll generate it, put it in the session, and then return it.

You can put the $_SESSION data into a theme function and make it available to templates as well if you wish, but that's probably a separate question (and you'd have to make sure you had a fallback in case the session data had not been set).


How to display files in a web browsers? I have a new OA site spun up and have some content available for the few users I have. One of the requests from the user's is to be able to view (and most likely edit) the documents via the web browser.

I was able to open a Word document in the browser when using IE, however I was unable to edit the document. Also, opening project files was a no go.

I am pretty new to Drupal, however any research I did on this issue just brought me different file manager modules.

Is it possible to view/edit files in the browser with Drupal/Open Atrium?  I know it is possible with SharePoint but that utilizes a back end office.

Or is it possible to have it so people can open files automatically in their client side applications (Project, Word etc.) and have it save to the OA file system?

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.


Render menu in custom form-api module I've created a custom menu from the drupal admin panel, and have a custom module that uses drupal's form API. I'd like to render the custom menu in this module. Since this is using form API, I don't think it makes sense to use a template file, but I can't find any way to render a menu from the .module file itself. Not only would I like to render it, but I'd like to have control over which page region it's rendered in...How can this be done?

I am not sure if I got you right,but if you want to call a form on a menu item.Here is view for that
Implement

  hook_menu() - to build custom page page callback - return your custom
  form here

Some sample code

function mymodulename_menu() {
  $items = array();
  $items['custom-menu'] = array(
    'title' => 'Your Custom Form',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodulename_custom_form'),
    'access callback' => TRUE,
    'access arguments' => array('access content'),
  );
  return $items;
}

function mymodulename_custom_form() {
  $form = array();
  // your custom form code goes here
  return $form;
}


How to print url arguments in headers view I have a View and inside it I have and Attachment display. In this attachment I set a Header where I need to print the 2nd url argument. How can I do this? With globals?

Thanks

<?php print arg(1); ?>

See: arg

Arg can be used to get the url arguments. It's 0 indexed, so 0 will give the first url argument.

Notice, when using url aliases that arg will bring the internal url arguments (the original path).


Do Entity Field Queries respect grants and/or node access? "How to use Entity Field Queries" contatins the cryptic piece of information,

->addMetaData($key, $object)
Adds additional metadata to the query. One important usage of this method is to run the query as another user, since EntityFieldQuery's fieldCondition will take current user's permission into account[...]

and there is a DANGEROUS_ACCESS_CHECK_OPT_OUT query tag that bypasses access checks, implying that access checks are run by default when EFQs are run. But this issue suggests that access checks are NOT run, UNLESS one is using fields in EFQ, in which case the "field_sql_storage_field_storage_query() function will always add 'entity_field_access'".
So... what? Do EFQs respect node_access by default, or do you have to do something to invoke node_access?

EntityFieldQuery will always check the user has the permission to access the field, if "DANGEROUS_ACCESS_CHECK_OPT_OUT" is not between the tags added to the query, but that is not done directly. It is done by adding a tag to the query, as field_sql_storage_field_storage_query() does.

if (!isset($query->tags['DANGEROUS_ACCESS_CHECK_OPT_OUT'])) {
  $select_query->addTag('entity_field_access');
}

It is then an implementation of hook_query_TAG_alter() that alters the query to check the permission. The Node module implement that hook with node_query_entity_field_access_alter().

function node_query_entity_field_access_alter(QueryAlterableInterface $query) {
  _node_query_node_access_alter($query, 'entity');
}

That is the reason why, before Drupal 7.15 (which introduced the "DANGEROUS_ACCESS_CHECK_OPT_OUT" tag), it was suggested to use $query->addMetaData('account', user_load(1)). The user #1 always have any permission, and checking the permission to access a field would be always positive.

_node_query_node_access_alter() contains the following code.

  // If $account can bypass node access, or there are no node access modules,
  // or the operation is 'view' and the $acount has a global view grant (i.e.,
  // a view grant for node ID 0), we don't need to alter the query.
  if (user_access('bypass node access', $account)) {
    return;
  }
  if (!count(module_implements('node_grants'))) {
    return;
  }
  if ($op == 'view' && node_access_view_all_nodes($account)) {
    return;
  }

  // Omissis

  // Find all instances of the base table being joined -- could appear
  // more than once in the query, and could be aliased. Join each one to
  // the node_access table.

  $grants = node_access_grants($op, $account);
  if ($type == 'entity') {
    // The original query looked something like:
    // @code
    //  SELECT nid FROM sometable s
    //  INNER JOIN node_access na ON na.nid = s.nid
    //  WHERE ($node_access_conditions)
    // @endcode
    //
    // Our query will look like:
    // @code
    //  SELECT entity_type, entity_id
    //  FROM field_data_something s
    //  LEFT JOIN node_access na ON s.entity_id = na.nid
    //  WHERE (entity_type = 'node' AND $node_access_conditions) OR (entity_type <> 'node')
    // @endcode
    //
    // So instead of directly adding to the query object, we need to collect
    // all of the node access conditions in a separate db_and() object and
    // then add it to the query at the end.
    $node_conditions = db_and();
  }
  foreach ($tables as $nalias => $tableinfo) {
    $table = $tableinfo['table'];
    if (!($table instanceof SelectQueryInterface) && $table == $base_table) {
      // Set the subquery.
      $subquery = db_select('node_access', 'na')
       ->fields('na', array('nid'));

      $grant_conditions = db_or();
      // If any grant exists for the specified user, then user has access
      // to the node for the specified operation.
      foreach ($grants as $realm => $gids) {
        foreach ($gids as $gid) {
          $grant_conditions->condition(db_and()
            ->condition('na.gid', $gid)
            ->condition('na.realm', $realm)
          );
        }
      }

Definitively, the code checks the user has access to the node.


why &drupal_static is getting used with refernce? I am going through different modules and I found this &drupal_static function but exactly dont know why is getting used can any one please explain what is the purpose ?

function drupal_static

  Provides central static variable storage.

  All functions requiring a static variable to persist or cache data
  within a single page request are encouraged to use this function
  unless it is absolutely certain that the static variable will not need
  to be reset during the page request. By centralizing static variable
  storage through this function, other functions can rely on a
  consistent API for resetting any other function's static variables.

More with examples: https://api.drupal.org/api/drupal/includes%21bootstrap.inc/function/drupal_static/7


Changing the Login block HTML for D7 I want to change the form elements a bit in the login block for D7 to add the following to the input elements:

onblur="if(this.value=='') this.value='Username'" onfocus="if(this.value =='Username' ) this.value=''"

I would prefer not to create a new module just for this via hook form alter, and I did not see a user block to override in the User module.

Is there a template.php function that could be used?

You dont need to do access the form elements directly like that. You can use some unobtrusive JavaScript with jQuery to do the same thing.

;(function ($){
    Drupal.behaviors.YOUR_FUNCTION = {
        attach: function (context, settings) {
                    // your script goes here...
               };
    };
})(jQuery);

Create a scripts file and add the above. Add a reference to that file in your .info file.

Then add your script.

Some references if your not familiar with jQuery.

http://api.jquery.com/class-selector/
http://api.jquery.com/blur/
http://api.jquery.com/focus/
http://api.jquery.com/val/


How can I escape the brackets so they are seen as literal characters I am using clientside validation along with the field UI module in a Drupal 7 site to request some custom input fields on user registration. I need to set some custom error messages using the clientside validation modulename_clientside_validation_rule_alter() function. The problem is, the field UI module creates fields with brackets in the name attribute like so: field_first_name[und][0][value]. When I use this as the first argument of _clientside_validation_set_required(), the proper error message is not being shown. I believe this is because the brackets are not seen as part of the string. How can I make the brackets literally brackets and not look like an array to drupal?

The problem wasn't the brackets—I was able to set the rule by referencing the nested #name and #value keys:

_clientside_validation_set_required(
      $element['field_first_name']['und']['0']['value']['#name'],
      $element['field_first_name']['und']['0']['value']['#title'],
      isset($element['field_first_name']['und']['0']['value']['#required']) ? $element['field_first_name']['und']['0']['value']['#required'] : FALSE,
      $js_rules,
      t('Please enter your @field_name.', array('@field_name' => strtolower($element['field_first_name']['und']['0']['value']['#title'])))
    );


How do I declare my custom entities as non-multilingual? I have written a custom module providing two custom config entities holding data, that is not language-specific. But I can't seem to find a way to tell Drupal, that there is no need to "translate" these entities - in fact, I get this action offered on every entity listing.

Even all core entities I found so far implement translation, but some provide their own translation handler. (Is this maybe a way to do it? Implementing a custom translation handler that tells Drupal not to translate anything? But how?)

Is someone out there who can point me in the right direction please?

My actual annotation look like this (please notice the "translatable" option, which is not working):

@ConfigEntityType(
  id = "ad_tag",
  label = @Translation("Advertisement tag"),
  module = "field_vimeo",
  config_prefix = "field_vimeo.ad_tag",
  admin_permission = "administer site configuration",
  translatable = FALSE,
  handlers = {
    "storage" = "Drupal\field_vimeo\AdTagStorage",
    "list_builder" = "Drupal\field_vimeo\AdTagListBuilder",
    "form" = {
      "default" = "Drupal\field_vimeo\Form\AdTagForm",
      "delete" = "Drupal\field_vimeo\Form\AdTagDeleteForm"
    }
  },
  links = {
    "edit-form" = "/admin/structure/field_vimeo/ad_tags/manage/{ad_tag}",
    "delete-form" = "/admin/structure/field_vimeo/ad_tags/manage/{ad_tag}/delete"
  },
  entity_keys = {
    "id" = "id",
    "type" = "type",
    "label" = "label"
  },
  config_export = {
    "id" = "id",
    "type" = "type",
    "label" = "label",
    "data" = "data"
  }
)

Translatability for config and content entities is different. Translation handler is a content entity thing. Storage for translations needs to be explicitly enabled by adding a data table.

For config entities, it's different. Translatability works automatically there through config overrides. There's nothing that you need to do to opt-in to being translatable, but you also can't prevent it. What you can is control which properties are translatable through the config schema. Like the label,which is, technically, a translatable, user-provided string.

If you don't need it translated, just don't create any translations for it  or if you don't need any configuration translations, don't enable the config translation module.


submit handler not working when using hook_form_alter I am using hook_form_alter to add validation and submit handlers to the registration form:

<?php
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'user_register_form') {
    $form['#validate'][] = 'blah_register_validate';
    $form['#submit'][] = 'blah_register_submit';
  }
}
?>

They were both working fine until I added the following hook:

<?php
function MYMODULE_user_login(&$edit, $account) {
  drupal_goto('user');
}
?>

The validation function still works but the submit function gets bypassed completely - it doesn't get called at all by form_execute_handlers() in form.inc. As soon as I remove hook_user_login, it works again. Anyone have an idea why?

Update:

hook_user_login() gets called by user_login_finalize() in the User Module. Unfortunately,  this happens before my submit function gets called - so obviously when I use drupal_goto() the submit function will never get called. Can anyone confirm if I am adding the submit handler correctly, is there another way?

If you check out drupal_goto() you can see it calls drupal_exit() which is not something you want to do in a hook. The comments for hook_user_login() discuss this a little, finishing with this snippet:

function mymodule_user_login(&$edit, $account)
{
  // Your logic will set $redirection to the desired location
  $redirection = 'node/394';

  // Unless there is already a redirection going, or the user is trying to reset his password, we redirect to $redirection.
  if (empty($_GET['destination'])
    && !is_null($redirection)
    && (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset'))
  {
    $_GET['destination'] = $redirection; // Should we use $edit['redirect'] instead..?
  }
}

Also mentioned is the login destination module.


Hide error and warning in admin panel I want to hide error and warning message from admin panel. I have checked the option None in admin panel for error reporting and still it showing error and warning messages in admin  panel. let me how it can removed.

Although it is not a good idea to hide the errors (you may want to solve it; by watching the error log, debugging etc.), there is a way you can do it.

You can do it at theme level in template_process_page() function, in your theme's template.php file. (It should be placed in your admin theme's template.php)
Code: Edited according to @Chapabu 's comments :)
Used path_is_admin() and current_path().

<?php

function MYTHEME_process_page(&$variables) {
  if (path_is_admin(current_path())) {
    unset($variables['messages']);
  }
}

?>


Loop through child elements in Twig like Element::children() When dealing with a renderable array in PHP, I can use Element::children() to access the elements that are not # properties but subordinated renderable elements (form items inside a fieldset, items inside a field widget, etc). For instance, this snippet from file.module:

<?php
if ($element['#multiple']) {
  foreach (Element::children($element) as $name) {
    // ...
  }
}
?>

How can I do the same in a Twig template? If I do {% for child in element %}, it will include also #type, #cache etc.

{% for key, child in element if key|first != '#' %}
  <div>{{ child }}</div>
{% endfor %}


Security issues after authenticated user has been logged out I have a profile information page that is being displayed for an authenticated users. But after I log-out as that specific user,and then i click the back button of the browser,I could find the anonymous user landing on the profile information of the previously logged-in user.

How could I prevent such a behavior as I do have some confidential information on those profile information page.

Could someone please help me.

Once page is stored in browser's cache, there is nothing you can do about it. It's responsibility of an user who logs in and views confidential information to remove it from device he was reading it on.

You could try to prevent caching (as described in this question), but all you send to browsers and proxies in that regard is just an suggestion, not an order. It's a good idea to do this, but sadly you can't be sure of it.

You could use javascript to go to another page if logged out user tries to go back to page with sensitive data.

And you can and should use Secure Pages to enforce encryption and thus prevent proxies from reading you data.

At the end of the day once user will get that data, data security is his problem.


Ways to have lots of blocks on a site which is easy to manage I am building a new site and the client has about 400 pages under about 5 main categories. Each of these 5 sub-categories has further sub-categories.

My client want to put a block onto each page which has unique content, which is editable.

Let's say that the block is pulling in the content type 'news'. This would be about 400 (ish) blocks - if done just through the blocks UI.

I know about context and view relationships (although not a great deal), but I was wondering if there was anyone out there who had thought on the very best way to approach this idea.

What ways are there to curate this content and make it easy for the client to find what they want to edit?

Is there a whay which has worked for you to go about this set-up, something that experience shows is a good idea, that I might not have thought of?

You can use Nodeblock module - create a content type named "block", and then you can manage edit permissions like with any other node, using modules you want. It'll also support fields, translations et cetera. You can use taxonomy to keep track of what is where.


Suggested template file is not working for Custom Search's template I have installed Custom Search module for my drupal7 setup.

I am trying to modify template files for search-result and search-results.

By default its using template files from contrib module's theme itself which are as follows:

sites/all/modules/contrib/custom_search/theme/custom_search-results.tpl.php
sites/all/modules/contrib/custom_search/theme/custom_search-result.tpl.php

As per the theme-debug's hook suggestions I have created tpl files and have placed them within my sub-theme's templates directory, which are as follows:

sites/all/themes/bootstrap_sub/templates/custom-search-result.tpl.php
sites/all/themes/bootstrap_sub/templates/custom-search-results.tpl.php

I have cleared cache for several times, and still it uses template files from the module's theme directory.

Can anyone please help me out with this issue.

Thanks in advance.

This is a known issue with the Custom Search module for Drupal 7. Of note from the issue:

  Copy custom_search/theme/custom_search-result.tpl.php to your theme
  location (e.g, sites/themes//templates/search-result.tpl.php), modify
  accordingly and then refresh your caches.

  Tested on the current stable - custom_search 7.x-1.11

The solution is to rename custom_search-result.tpl.php from the module to search-result.tpl.php in your theme.


Find out the user's IP address given their UID? I'm running Drupal 7 web site with a Russian multiplayer card game and have to block some very annoying players every 4-5 days.

Before Drupal I was using phpBB 3. When these persons would come from a small city/village I'd just add their IP-network to the firewall rules, so that they can't re-register with a new mail address. This worked well in my case and my question is not about this policy.

My problem is that with Drupal, I can't find the last IP address used by a user id. I.e. the abuser is reported to me by other users and I know his uid, but I can't find his IP address in the logs, because:

I've enabled syslog-logging and see the Drupal messages in /var/log/messagess but there is rarely a message about a user logging in, probably because sessions are long by default, and I'd like to keep it this way for user comfort.
I've also enabled "database logging," but don't know where to see it (which database table).

If you have statistics module enabled, the "accesslog" table contains the IPs for all your visitors.

SELECT hostname FROM accesslog WHERE uid = %UID_FOR_YOUR_USER% LIMIT 1

If you do not have statistics enabled, I advise you to leave it off, even for this result, because enabling it, causes a severe performance-penalty.

In that case, you can use sessions table:

SELECT hostname FROM sessions WHERE uid = %UID_FOR_YOUR_USER% LIMIT 1

The benefit of the first over the latter, is that the first will always show you the latest hostname, whereas the latter might not always be up to date.


Automatic Login after Successful Registration Is there any way to automatic login user after a successful registration, it seems I can't find any tuts/solution how to do this.Thanks!!

Any replies are much appreciated....

in my template.php

function drupal_onrevue1_form_user_register_submit($form, &$form_state){

    //$form_state['rebuild'] = TRUE;
    $form_state['redirect'] = "user/login";
    //print_r($form_state);die();
   $edit = array(
          'name' => $form_state['values']['name'],
          'pass' => $form_state['values']['current_pass'],
          'field_first_name' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_first_name']))),
          'field_last_name' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_last_name']))),
          'field_middle_name' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_middle_name']))),
          'field_year_select' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_year_select']))),
          'field_month_select' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_month_select']))),
          'field_date_select' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_date_select']))),
          'field_gender' => array(LANGUAGE_NONE => array(array('value' => $form_state['values']['field_gender_select']))),
          'mail' => $form_state['values']['field_mail'],
          'init' => $form_state['values']['field_mail'],
          'status' => 1,
          'access' => REQUEST_TIME,
    );

    $account->is_new = TRUE;
    $hello = user_save($account, $edit);
    //print_r($hello);die();

}

Have a look at the Logintoboggan module. This offers you to login new users immediately.


How can I send mail containing rendered entity from referenced field? How do I code a function for sending mail containing a rendered entity that is referenced from a field?
I have content type A that contains static information, and content type B that users create and reference to the corresponding content type A node instead of writing everything manually. In a custom module I have some code for sending mail notifications containing info in a content type B node, but now the client wants some info from the referenced content type A node.
The line of code that I have a problem is this:
$avtal_id = $node->field_avtalsnummer['und'][0]['value'];

field_avtalsnummer is the reference field in content type B that points to a node of type A and $avtal_id is used in the mail (plain-text). All other fields in the custom module works fine, but for some reason that I don't fully understand I can't get this to work. If I change value to target_id i get the node ID but I can't get the value. Title does not work either. Do I need some code to load the entity first? The optimal solution for me would be to get the info from the referenced field and to display a custom view mode so that I can customise the mail notification accordingly to my clients demands, but I can't even get the value of of the referenced field to work so I'm running out of ideas. Help is very appreciated!

You need to use target_id to get the node id, then load the node and get the fields values you want.
$avtal_id = $node->field_avtalsnummer[LANGUAGE_NONE][0]['target_id'];
$avtal_node = node_load($avtal_id);


How to prevent ad blockers from restricting sections of my website (non google ads) I have a block towards the header, that is full width, and has some basic HTML with Full HTML Text format.

It is getting blocked by my user's ad blocker software. so far it is reported to be blocked with AdBlock and Adguard. I have tested and verified with AdBlock

My content isn't "spamy" at all. In fact it is a coupon code so they are missing out :)

Here's the content

50% OFF entire store. Use code AWESOMESALE50

The CSS class for the block is banner-advert

Could it be the inline CSS?

Thanks to No Sssweat's simple suggestion, it is fixed (as far as I can tell).

I changed my CSS class for the block from "banner-advert" to "sitewide-promo".

I'm assuming either banner or advert caused an issue, so I replaced both.


Custom template for specific vocabulary term Hi guys i hope you can help me with this, i made a vocabulary called Colors and inside this i have the terms: red, green, blue.

I was wondering, how can i make custom templates for each term, for example, for mysite.com/colors/red i want a different template than for mysite.com/colors/blue

I saw that it's possible for nodes, but don't know if it's possible for taxonomies. How can i do this?

Edit: for Drupal 7

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.


Problem with custom dropdown default value I've written a module that allows users to alter the display of a Date/Time object by allowing them to change their timezone via a front-end block.

It does it's primary function properly, changes the time display as expected, however, what is supposed to happen is that once you pick a timezone, the page reloads, and the dropdown form will default to the timezone you selected. Except it doesn't, it stays on a single default value

The array is the #options list for the dropdown item, and the single item underneath is the #default_value key for that dropdown.

As you can see, the default value should be set to Australia/Melbourne, but in the dropdown it's not, it's set to America/Creston Mountain time.

I cannot figure out what's going wrong, have I done the default value code incorrectly or something?

EDIT

This is the code for the select element

$timezone = mymodule_timezone_get_user_timezone();
$options = variable_get('mymodule_timezone_select', system_time_zones());
$options = array_filter($options);

// doing a dpm($timezone) comes back with Australia/Melbourne
// doing a dpm($options) comes back with the arrow shown above

$form['timezone_select'] = array(
  '#type' => 'select',
  '#title' => '',
  '#options' =>  $options,
  '#default_value' => $timezone,
  '#prefix' => t('
Please select your timezone from the drop down box below and click update to convert your viewing times accordingly.
'),
);
$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Update') ,
);

And the code referenced in this snippet

function mymodule_timezone_get_user_timezone() {
  $retrieved_timezone = session_cache_get('mymodule_timezone_user_timezone');
  if (empty($retrieved_timezone)) {
    $retrieved_timezone = drupal_get_user_timezone();
  }
  return $retrieved_timezone;
}

The variable for 'mymodule_timezone_select' is just from the default system_time_zones() but the admin has been given the option to delete ones they don't want the user to see (since they are several hundred options by default)

Are you providing #default_value when loading form? If yes, you need to make sure that you're providing what is selected by user first. Check example below:

global $user;
// Check if user has set the timezone,
// if yes use that else set to default 'America/Creston'

$timezone = isset($user->timezone) ? $user->timezone : 'America/Creston';
$form['timezone'] = array(
  '#type' => 'select',
  '#title' => 'Select Timezone',
  '#options' => $options,
  '#default_value' => $timezone,
);

As per Form API Reference Documentation, it says #default value is:

  The value of the form element that will be displayed or selected
  initially if the form has not been submitted yet.


Question regarding hook_user_presave() and setting roles When a new user is created, either via admin or by normal user registration, I need to assign a custom role to that user.  It works fine, but I'm not convinced I've checked the user status enough.

In my hook_user_presave() implementation, I check to make sure the administration role isn't set, and uid isn't 1.  To set my role:

if ($account->uid == 1 || array_search('administrator', $account->roles))
        return;

$account->roles[] = 'my_custom_role';

I only want to do this if it is a brand new user being created/inserted.  The documentation says hook_user_presave() is called if the user is being updated.  What is the best way to check if this is a brand new user creation?  Would uid be set to 0?

The documentation for hook_user_presave() says the hook is invoked when an user account is updated, or created, not just when the user account is updated.

If you look at user_save(), you will notice that $account->is_new is set before invoking hook_user_presave(), when the user account is being created. If the account is being updated, $account->is_new is not set, and $account->original contains the user object before any changes.

In Drupal 8, $user->is_new will be replaced with Entity::isNew().


Does request_uri() have to be filtered or escaped? Mind my ignorance, but I'm trying to understand whether or not calling request_uri(), and then echoing output from it into a link is safe.

What I'm doing is getting arguments from the URL, for example:

$exploded_url = explode('/', request_uri());
echo $exploded_url[3];

My questions: is this function's output being escaped/filtered already? Would it be overkill for me to do it again? What would be the way to ensure that it is safe? Is there another/better function I should or could use?

Thanks, any input is appreciated!

The short answer is yes, you need to sanitise the variable yourself.

All request_uri() does is pass the raw input from $_SERVER['REQUEST_URI'] (or from a different source if the server is not Apache). Apache/PHP does nothing by default to sanitise the $_SERVER variables on your behalf so they should be considered unsafe.

There's an excellent answer to Which $_SERVER variables are safe on StackOverflow that goes into a lot more detail, and actually notes that REQUEST_URI "may contain tainted data".


For content, what are the differences between nodes and terms I am debating whether to use nodes or terms to store a large amount of content in Drupal.

There are a lot of similarities between nodes and terms in Drupal 8/9:

Both can add any type of field.
Both can have URL aliases set automatically via Pathauto.
Both can have customized metatags via Metatag.
Both can have comments.
Both can have the displayed customized with Layout Builder, and both can be themed in the same way with Twig templates.
Both have content types (nodes have "content types", terms have "vocabularies").

They seem very much alike.  So what are the differences between terms and nodes?

Nodes are content. Terms are for categorization of content, they are not content themselves.

Terms are part of taxonomies. Taxonomy is the science of classification.

The relation between nodes and taxonomy terms is that you attach taxonomy terms to nodes, to categorize the node. So if you have a blog node, you may have topics or tags, that would be attached to the blog node. You can use that to find all blogs of a certain category, or tagged with a given term. You can think of hashtags on common SNS sites as being like taxonomy terms. When you click on the hashtag, you can see all posts with that hashtag. The hashtag essentially categorizes the post.

You have listed some ways in which nodes and terms share technical implementations, such as having revisions. But how they are used is entirely different.


Static resource URL in Drupal 8 theme I'm trying to place an image using a local resource in theme. Using the site url like

drupal.localhost/themes/customtheme/images/image.png

does give me access denied error. I understand that Drupal should generate a public url for the image, but how to ask Drupal to do so from the theme while still using relative URLs in src tag of img ?

edit: Changed question, made more clear

Check out file_create_url() function:

Example of usage in a preprocess hook:

$variables['image'] = file_create_url($variables['directory'] . '/images/image.png');

Example of usage in a twig template:

 <img src="{{ file_url(directory ~ '/images/image.png') }}"/>


How to change the labels TRUE and FALSE of a boolean field in views exposed filter I am using the flag module to toggle a node type 'Task' as Done.
I made a view that lists the tasks, and added a views exposed filter for the flag status, which is a boolean field.
In this way users can filter the view by selecting True or False for the flag status.

However, I want to change the labels 'True' and 'False' to 'Done' and 'Not Done'

I see no setting in the views exposed filter field that allows to change this setting. Is there another way to do this?

There is a number of ways how to do it, check out this thread for a lot of suggested options: Change the '- Any -' text in an exposed taxonomy filter.

You can change the themed output for that form and filter, you need a bit of custom code for that.

You could use Better Exposed Filters module, it lets you override each option text:

  Use this field to rewrite the filter options displayed. Use the format of current_text|replacement_text, one replacement per line. For example:

  Current|Replacement
    On|Yes
    Off|No

Without any additional modules or code changes you can use the Flagged Exposed filter Grouped filters option instead of the Single filter you're using now.

The Grouped filters allow you to enter a Label for each grouping. Only in your case you simply select "True" for the first grouping and "False" for the second grouping, which means you haven't grouped anything, you're just repeating the same options from the Single filter:


Open a link in a new tab in the menu I'm using Drupal 8 with Bootstrap theme, and I've created a sub-theme and different menus.

I've tried to edit the menu twig template but i am not really familiar with Twig.

How can I add a menu where links open in new tabs?

In my case I utilized hook_link_alter() to accomplish this.
Situation: in my menu links, I only need Contact Us to open in a new tab.

<?php
function MYMODULE_link_alter(&$variables) {
  if (!$variables['url']->isRouted()) {
    $uri = $variables['url']->getUri();
    // Only want the Contact Us to open in new tab.
    if ($uri == 'base:contact-us') {
      $variables['options']['attributes'] = ['target' => '_blank'];
    }
  }
}


Getting a better handle on APC Cache Bins / code for settings.php I've got APC up and running on my VPS and have installed the APC module on my Drupal 7 site. I followed the documentation here and added this code to my settings.php file:

$conf['cache_backends'] = array('sites/all/modules/apc/drupal_apc_cache.inc');
$conf['cache_default_class'] = 'DrupalAPCCache';
//$conf['apc_show_debug'] = TRUE;  // Remove the slashes to use debug mode.

However, on my site's status page under APC, it says:

APC has been running for 3 min 54 sec. Currently caching 0 entries (0 bytes).

To me the "0 entries" indicated that there was no cache being created / used. I did some digging around and it looks like there might be additional code I need to add but cannot find documentation anywhere.

I found this snippet but not really sure if I need it or what part it I am supposed to use and what it does, I could not find any documentation for this. I suspect this is what makes the cache work.

'page_cache_without_database' => TRUE,
        'page_cache_invoke_hooks'     => FALSE,
        'page_cache_maximum_age'      => 3600,
        'cache_lifetime'              => 0,
        /* my note -- noticed "cacherouter" in the path below
         so I am guessing this needs to be adapeted to the path for APC?? */
        'session_inc'      => './sites/all/modules/cacherouter/session.inc',
            'cache_default_class'               => 'DrupalAPCCache',
            'cache_class_cache'                 => 'DrupalAPCCache',
            'cache_class_cache_block'           => 'DrupalAPCCache',
            'cache_class_cache_bootstrap'       => 'DrupalAPCCache',
            'cache_class_cache_content'         => 'DrupalAPCCache',
            'cache_class_cache_filter'          => 'DrupalAPCCache',
            'cache_class_cache_form'            => 'DrupalAPCCache',
            'cache_class_cache_menu'            => 'DrupalAPCCache',
            'cache_class_cache_page'            => 'DrupalAPCCache',
            'cache_class_cache_pathdst'         => 'DrupalAPCCache',
            'cache_class_cache_pathsrc'         => 'DrupalAPCCache',
            'cache_class_cache_session'         => 'DrupalAPCCache',
            'cache_class_cache_session_user'    => 'DrupalAPCCache',
            'cache_class_cache_update'          => 'DrupalAPCCache',
            'cache_class_cache_users'           => 'DrupalAPCCache',
            'cache_class_cache_views'           => 'DrupalAPCCache',
            'cache_class_cache_views_data'      => 'DrupalAPCCache',
      );

Any help on this matter would be appreciated.

The information about the APC extension returned from phpinfo() are the following ones.

"APC has been running for 3 min 54 sec. Currently caching 0 entries (0
  bytes)."

This message suggests that your APC is running for each php request separately ultimately not caching anything at all.

I had a similar issue and it required to set up PHP once again but in a different mode.

APC works fine for multiple processes with apache/2 + php 5.3.x + php-fpm + fcgi in FPM/FastCGI mode.

PHP 5.3.x is configured with following options --enable-force-cgi-redirect --enable-fastcgi --enable-fpm

In APC section of my php info I can see:

APC Support = enabled
Serialization Support = php
MMAP File Mask = /tmp/apc.something  | where something is a random 6-character string

Please check your phpinfo

In PHP Configure Command you should have:
'--enable-fastcgi'
and
'--enable-fpm'

In Server API :
 FPM/FastCGI

Check if you have cgi-fcgi section and if you can find
php-fpm set to "active"

NOTE: There might be another solution if you use php 5.2.x or older.


How to partially upgrade a site? I'd like to redevelop a site on my  local machine (which takes a few days to accomplish) and then import to it only the nodes which are created on the production site during this period, so that importing new nodes does not undo changes made on the local version and then I can migrate the redeveloped version to production without loosing recent activities.

I am wondering whether it is possible, and how? I appreciate your hints.

Depending on the complexity of your nodes (if using custom fields or references) you might be able to use the node export module to export the nodes as CSV files and on the new upgraded site use Feeds to import them. Keep in mind that if the nodes NID are needed for an specific menu the NID might not match.

Note: you might also want to check the migrate module as well as the deploy module.


Drupal 7: Modifying the view page and edit form of a content type programmatically a Drupal newbie here trying to create his first module for Drupal 7.

In my site I've created a new content type (machine name: abstract) from the site's admin's front-end. A user can add a new instance of this content type by using a form I've defined using the FAPI. In this form's submit function I do the following:

function form_add_abstract_submit($form, &$form_state) {

  global $user;

  $node = new stdClass();
  $node->type = 'abstract';
  node_object_prepare($node);

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

  // ... fill the rest of the node's fields here [...]

  if($node = node_submit($node)) {
    node_save($node);
    // Not sure about this way of defining the path to the created node
    $path = 'abstract/' . $node->nid;
    $node->path = array('alias' => $path);
    node_save($node);
    drupal_set_message(t('Abstract submitted');
  } else {
    form_set_error('description', t('ERROR'));
  }

  $form_state['redirect'] = 'index.php';
}

As shown above, I define the path to these nodes to be 'abstract/[its-node-id]'. Then, when a user visits this URL I'd like to show two tabs, one allowing the user to see the node's fields and another linking to a form to edit it. I've tried to implement it by adding the following three menu items in my hook_menu function:

$items['abstract/%'] = array(
      'title callback' => 'abstract_page_title',
      'title arguments' => array(1),
      'page callback' => 'abstract_page_view',
      'page arguments' => array(1),
      'access callback' => TRUE,
      'type' => MENU_CALLBACK,
  );

  $items['abstract/%/view'] = array(
      'title' => 'View',
      'type' => MENU_DEFAULT_LOCAL_TASK,
      'weight' => -10,
  );

  $items['abstract/%/edit'] = array(
      'title' => 'Edit',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('my_module_form_abstract_edit', 1),
      'access callback' => TRUE,
      'file' => 'my_module_forms.inc',
      'type' => MENU_LOCAL_TASK,
  );

However, if I visit abstract/[a-node's-id], my abstract_page_view function is not being called and the default view for rendering my content type is displayed. The 'Edit' tab on this view also links to abstract/[the-node's-id]#overlay=node/[the-node's-id]/edit, not to abstract/[the-node's-id]/edit, as I'd like to.

What am I doing wrong? Should I programmatically define my content type instead of doing it from the admin's backend or is my problem somewhere else?

If I understand what you are trying to do, you want to customise the node add/edit page and the node view page for your 'abstract' content type.

It seems like you are trying to duplicate what drupal already does for you for no apparent reason. Your code doesn't seem to really be doing anything that drupal does not do for you already (from the code sample you provided).
(As a side note, what are you actually trying to achieve?)

If so, I wouldn't be creating fully custom pages. Drupal gives you hooks so you can modify what it gives you by default.

For example, the node add/edit page (node/add/abstract & node/[nid]/edit) can be modified by using hook_form_BASE_FORM_ID_alter() or hook_form_FORM_ID_alter().
While form altering these forms you can add your own custom validate and submit functions if you need to do additional submission.

For path aliases, use the pathauto module, which will allow you to set the path alias for your page to abstract/[nid] - although you would generally be better off doing something like abstract/[title] for the sake of SEO and more user-friendliness.

For the node add page you can add a path alias by going to admin/config/search/path. Then you can make it something like abstract/add instead of node/add/abstract.

Drupal fields should be able to handle pretty much any of the data you want to handle, especially with the help of modules like date, link, email, and many many more.

Now that I know you want to store some node data in an external database then this next part is of interest to you. These node hooks allow you to hook into the node CRUD system:

If you really really do need to have extra data (not so common, you can generally do what you need with fields), for example, data you custom store in a separate database table, you can use the hooks hook_node_view() for showing your custom data on the node view page, hook_node_load() to load your custom data into the node object each time it is loaded, hook_node_delete() to delete your custom data when a node is deleted, hook_node_insert() for inserting your custom data when a node is created, hook_node_update() for updating your custom data when a node is saved.

There are other hooks too, like revision related ones if you are using revisions and search index related ones, for adding data to search index & search results.
See them here - http://api.drupal.org/api/search/7/hook_node_

Also, if you are adding data to nodes from your external database that aren't in drupal fields, you might also be interested in the APIs that the Entity module provides. In particular, you can define your data as properties of the entity, so they can be easily handles by modules such as rules and search api (and other modules that utilise the entity api). See http://drupal.org/node/1021466

If you really must do it that way, your hook_menu() also has some issues:
The % characters in the menu paths should really be replaced with %node - which will then call node_load and properly validate the nid in the path. See http://drupal.org/node/224170 for more information on menu wildcard loaders.

abstract/% also should not be MENU_CALLBACK, it should be MENU_NORMAL_ITEM.

Basically, you are trying to replicate the node/% node/%/view node/%/edit pages so you should try copying what the node module has in node_menu() for those items, but just change the path. Then you can have your new paths doing what the node module would do at node/% node/%/view and node/%/edit.
However you will then have issues with other modules that add node/%/something paths (if you are using any such modules). In this case those extra tabs on the node page would not be present on your pages because their paths would not match.

So unless you really really have to have abstract/%/edit, I would leave the menu alone and just use path auto to have abstract/[nid] or abstract/[title] and leave the edit pages as node/[nid]/edit.

An alternative solution, depending on whether or not it suits your use case better, is to not use the node system at all and create your own custom entity type. So you would have an abstract entity type, like the user, node and taxonomy term ones.

If you aren't really using any of the features that the node system provides this might be a better solution. It is relatively straight forward to do but the downside is a lot of existing contrib modules work only with nodes, and not other entity types. So those additional functionalities you might require you would also have to code yourself.
So it depends on whether you have the time to do the additional custom work required or if you are better off utilising nodes, so you get compatibility out of the box.


Adding quantity to a Commerce product's attribute I have a D7 Commerce Store. It will be selling to wholesales.

I have a Product that has multiple attributes. An example of the attributes is as follows;

T-Shirt Printing (Product)

Size (S, M, L, XL, etc)
Sides (1 Side, 2 Side)
Service Type (All over, Spot)

How can I allow the customer to add that 1 product with multiple of a particular attribute?

Example; Customer should be able to order, 10 Small, 15 Medium, 20 Large of that one product "Tshirt Printing".

The Image below is an example from jakprints.com. I would like to do something similar. How can I replicate this in commerce? Or instead of using sliders... + or - buttons.

Please provide a few different ideas or POV's towards achieving this.

Use the Commerce Add to Cart Extras module. It provides a new product reference field display formatter that does exactly what you need.


Send view field in URL - Drupal I have a search page created with embedded filters in Drupal 8 View. In the list of fields I have a fields - [Field_program_id]. I also have a button 'Learn more' when clicking this button I want to pass the [field_program_id] and show the details of the Programs in that page. Not sure where to start. Any guidance?!

My view looks as below:

The '968' is the Program ID. Upon clicking the learn more, I want my url to be https://myproj/search?nodeid=[field_program_id]

and in this page I want to show the details again. Any help?!

In replacement to your "Learn more" add "Custom text" field after "Field_program_id" in your views. In "Text" add "a" tag like

Learn more

Take a look in "Replacement patterns" for available fields. Read description there too for a guidance.

(this is in Drupal 8)

It is the almost the same in Drupal 7, just with [] instead {{}}. Class for "button" depends of the theme.


How to create simple 'subsites'? I am creating a site for a company, which has multiple departments. Each department shall have a departments (sub/branch) site. Within each department site, there will be users of different roles, such as editors, approvers, administrators etc.  - each only allowed to edit content in its own branch site.

Apart from this permission, everything else will be the same - they will share the same theme and templates, content types, modules, workflow logic etc. Only the permissions need to be different

How to create these simple 'subsites'?

Here are the options in my head right now:

Using Organic Groups - a very steep learning curve (many settings) and seems like overkill
Subsites - requires additional databases, and installs
My idea - 1) Create a vocabulary containing all departments. 2) Create a content type for each content that will appear on any of the department sites. In the content type, have a field which allows the user to select the department (from taxonomy) to publish this under. However, I'd have to limit so that the user can only select the departments they are under

I am inexperienced and so do not know the potential pitfalls of choosing any of the options, anyone can give me some pointers?

Have a look at the domain access module.

I think it is what you're looking for.


Are custom content types a good way to model the classic entity relationship model? I have several content types which will store thousands of records each one.
Those content types will be related to each other as in a classic 1..N or N..M relationships I would like to query those content types taking this relationship into account.

I have searched for this on d.o but I am puzzled with the big quantity of modules available.
For instance is entity and entity reference any good for this ?

What is the best way to model the classic entity-relationship model of the database systems ?
Also, will I be able to tune the database (mainly create new indexes) to increase the performance of the queries ? I am asking this because I will need to tune the database because of the big amount of data, so this is something to take into account at the time of considering different approaches to the modeling decision.

In Drupal 7, you'll want the Entity module as it extends the core Entity API to do lots of useful things, and a lot of contributed modules depend on it.

To create relationships between entities (a "node reference" relationship, if you will) you'll want the Entity Reference module. Another more radical approach is the Relation module which provides two-way relationships – this is in early development stages and is a bit more complicated. I would recommend the Entity Reference module, as even though the initial relationship is 1-way, it's simple enough to find the referencing-entity on a referenced-entity when needed.

Regarding your question about tuning the database – the relationships are not setup as foreign keys or anything like that, as Drupal handles your database constraints in code and not within the database schema itself. That's a whole other conversation. The tables that contain fields for a specific node type, including the table that includes a reference to another node ID, are just joined with the node table on "entity_id". There are pros and cons to this – if you're a traditional database admin type, this may seem problematic, but it's the job of the CMS to maintain integrity in this model. I don't think you'll find ways to tune the database via new indexes, although you could certainly try. Thousands of nodes is not a lot of data and you should see Drupal 7 – in a properly tuned environment, with queries and views that do not contain extraneous joins – performs quite speedily.

My 2 cents.


Limiting term selection I have a few OG Groups and now I want to limit the taxonomy term selection for each group. For the first part I'm planning on checking if the user is a member of a certain group and then proceeding accordingly. So far, so good. The problem is, that I really have no idea how to actually limit the term selection. I tried something with the form api, but I just keep getting fatal errors when saving a node.

So... Can you guys help me limit the term selection? Telling me what do I actually need to do would really help. Thanks.

There is OG Vocabulary module for D6 (and just a basic D7 port) that

  "provides each Organic Group with its own vocabularies (i.e. taxonomy). This lets groups logically segregate their content into categories which make sense for them. This module is integrated with Token, Rules and Services modules."
  read more...


Display content having the taxonomy of the logged in user I need help creating a view in Drupal 7 with the following logic:

My users have taxonomy reference field.
My articles also have    taxonomy reference field.

When a user is logged in I want them to see only the articles that have the same term as the logged in user.  How to set the relationships and contextual filters in this view?

Create a view to display the article content, then add as relation for user and  add a contextual filter for UID for logged in user.

Add new filter for content taxonomy and it must be equal to user taxonomy.


How to place a role-aware "Add new" link at the top of a Views listing of media I've created a view that provides a listing of a particular media type on my site.  I'd like to place an "Add new" link at the top of this view and have it visible only to users who can actually add new media of that type.  Does anyone know a straightforward way of doing this?

What I've tried:

Adding a View header component of type "Text area":  Nope, can't restrict visibility
Using the menu's Menu block and trying to insert that as a Views header component: Nope, can't restrict visibility
Using the menu's Menu block and adding it to the Block layout with a specific "Show on this page" set to just the Views page I had created.  This worked, but with several of these links to create, I would be unacceptably cluttering up my Block layout with one-off menu blocks.
Creating a menu with one menu item and rendering it with the "Rendered entity: Custom menu item":  Nope, can't restrict visibility AND it renders in a useless way (unformatted data)

I find it strange that you can't create a Views header/footer element and specify its visibility based on roles/permissions.

Any ideas/solutions that won't be duplicative or hard to maintain?

A quick views only way you could:

Create an attachment with your link in a custom text or however you'd like to do it. Set the access permission for that attachment to your role and attach it to your main page display

If the user doesn't have that role the attachment should be empty/show the no results content


how to automatically select entity reference field value from url when adding a node I have a content type "Students" which has an entity reference field "Course".

Course field shows a list of course nodes titles from a view.

When adding a new student node, I need the course field to be automatically selected as per the URL value.

I will pass the course ID in the URL like this.

/node/add/student/COURSEID

Any idea how to get this done ?
thanks

I think the easiest way would be to use hook_form_alter() and set a default value for the field. You can use arg() to get the course ID


Upload an image in a form programmatically I'm doing a form programmatically. I need to give an option to upload an image and give an option to resize it ( like cropping option ).

I don't know how to do it,  I know that I need to upload the image to a directory and also I suppose that I need to show a relation between the node and the image in the database.

I've created a field called field_img.

So, how can I do it?

This is the form that I've done but I don't know how to give a relation in the database...

form['group_anuncio']['imagen'] = array(
        '#title' => t('Image'),
        '#type' => 'managed_file',
        '#upload_validators' => array('file_validate_extensions' => array('jpeg jpg png gif')),
        '#upload_location' => 'public://sites/default/files',
        '#progress_indicator' => 'throbber',
        '#status' => FILE_STATUS_PERMANENT,
        '#progress_message' => 'One moment while we save your file...',
);

I would strongly suggest to use nodes and one of these modules
Comparison of image cropping and resizing modules

If you dont want nodes then you still should be able to use one of crop modules which works with image fields if you use entities, you can use Entity Construction Kit (ECK) module  to create custom entity types


Email field does not show up when I view node, only when I edit I have an email field in an entity. The text field is there when I edit the entity but it does not display when I view the entity. How do I get it to display when viewing?

Check 'display fields' in your content type settings.


Auto approve an user after registration (Services) Is there some way to auto approve an user after registration? I don't want to send any email confirming the email or changing the password.

I'm trying to build a register/login for an app with REST services, but I don't want the user have to check the email to change the password, I want the user can use immediately the password it just filled in the registration.

I tried adding this line in settings.php $conf['user_mail_register_no_approval_required_notify'] = FALSE; but the user continues as (not verified).

Thanks!

Jose - Make sure you have "Require e-mail verification when a visitor creates an account" unchecked in your Drupal admin under /admin/config/people/accounts

Also, there seems to be a bug in the services module that doesn't set the password correctly if you send it through the REST service. If you apply this patch, you should be able to set the password and the user should be able to log in right away.

https://drupal.org/files/issues/user_create-2198005-1.patch


How can i add a page.tpl.php for a page type and a language? I want to match a page--type-receipe.tpl.php for a page type but it doesn't work. I think the reason is the multi-language.

The page.tpl.php work without any problems.

It doesn't work because page--type-receipe.tpl.php isn't a valid template suggestion. If you're looking to theme a page by node type & language, you can do something like this to create your own theme suggestions inside your theme's template.php.

function MYTHEME_preprocess_page(&$variables) {
  global $language;

  if(isset($language->language) && isset($variables['node'])) {
    $variables['theme_hook_suggestions'][] = 'page__'.$variables['node']->language.'__'.$variables['node']->type;
  }
}

This will let you make page--en--recipe.tpl.php a valid template file for a page showing a recipe node in english.


Is it safe to remove database tables of removed modules? I have disabled the 'mollom' module a long time ago but the tables ('mollom' and 'mollom_form') still exit in database and it takes time to repair them when I try to optimize the database. So I am wondering whether it is safe to remove these tables altogether?

Disabling a module doesn't mean uninstalling it. To uninstall a module, once you disabled it, you need to go to admin/build/modules/uninstall (Drupal 6), or admin/modules/uninstall (Drupal 7, and Drupal 8), select one of the module listed, and click on the button to uninstall them.

Since Drupal 7, every database table declared with hook_schema() is automatically deleted from Drupal. Modules still need to delete any Drupal variables they define, though.
Since Drupal 8, a module can just be uninstalled. You cannot anymore first disable it, and then uninstall; you just go to admin/modules/uninstall and uninstall the modules you need. If the module cannot be uninstalled for any reason, Drupal will show in that page the reason why it cannot be uninstalled.


Results table with form select for filtering I have a page set up via a custom module, which contains some data rendered in a table, not using views. I didn't use views because it requires some various calculations that views calc couldn't do.

The table works fine, however, I would like to add a dropdown above the table, so that is has the equivalent of exposed filters like you would see in views.

The trouble is, i haven't had any luck in rendering a form (for the filter widget) in the same page callback as the table.

Below is the code i have up to this point. I figured this would be a common use case and this information must exist somewhere, but i haven't had any luck in finding an answer to this.

<?php
function mymodule_reports_menu() {
  $items = array();
  $items['people'] = array(
    'title' => 'Members',
    'page callback' => 'mymodule_reports_page',
    'access arguments' => array('access content'),
    'weight' => 1,
  );
  $items['people/fees-by-month-paid'] = array(
    'title' => 'Members by Card Number',
    'page callback' => 'mymodule_fees_by_month_paid',
    'access arguments' => array('access statistics'),
    'weight' => 1,
  );
  $items['people/fees-by-card-number'] = array(
    'title' => 'Members by Card Number',
    'page callback' => 'mymodule_fees_by_card_number',
    'access arguments' => array('access statistics'),
    'weight' => 1,
  );
  return $items;
}

function mymodule_fees_by_card_number_form($form_state) {

  $form = array();

  $form['year'] = array(
    '#type' => 'select',
    '#title' => t('Year'),
    '#description' => t('Toggle the Year'),
    '#options' => array(
      '2015' => t('2015'),
      '2014' => t('2014'),
    ),
    '#required' => TRUE,
  );

  $form['buttons']['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
    '#submit' => array('mymodule_fees_by_card_number'),
    '#validate' => array(),
  );
  return $form;
}

function mymodule_fees_by_card_number($form_state) {

  // parameter that i will be setting up as the widget
  $year = '2015';

  $output = drupal_get_form('mymodule_fees_by_card_number_form');

  $members = array();

  $members = mymodule_get_membership_by_year($year);

  foreach($members as $key => $row) {
    $card_number[$key] = $row['card_number'];
    $name[$key] = $row['name'];
  }

  array_multisort($card_number, SORT_ASC, $name, SORT_ASC, $members);

  $yearly_sum = 0;

  $header = array('Card Number', 'Name', 'Paid');
  $rows = array();

  foreach($members as $member) {
    $rows[] = array($member['card_number'], $member['name'], $member['paid']);

    $yearly_sum += $member['paid'];

  }
  $rows[] = array('', '', 'Total:  $' . $yearly_sum);
  $output .= theme('table', array('header' => $header, 'rows' => $rows));

  return $output;
}

I don't see a render function anywhere after you create the form. If you didn't exclude it on purpose, after creating the form, it has to be rendered and printed.

in your function you call drupal_get_form()

  Return value

  The form array.

and later on you add to that with theme()

  Return value

  An HTML string representing the themed output.

it looks like you're trying to put together an array and string in the same variable. You need to either render the form first into a string and then add them together, or include the theme data into the form array and render it later on.


How to close modal after form submit? I am building an entity reference widget, which displays the reference link, next to the input field, to the target entity's edit form.
I make it to open in a modal, with the following attributes on the link:

 'class' => ['use-ajax'],
          'data-dialog-type' => 'modal',
          'data-dialog-options' => json_encode([
            'height' => 700,
            'width' => 900,
          ]),

That works perfectly. However when I click submit on the modal form, I got redirected to the referenced entity view page, instead of the modal being closed and stay on the original form, where this widget is being used.

Is there any special attributes (like "data-dialog-type") which tells to the modal form's submit button to close the modal instead of redirecting to the original view?

UPDATE

Adding this to the URL actually pretty much solves the problem:

    'query' => [
      'destination' => $this->requestStack->getCurrentRequest()->getRequestUri(),
    ],

This redirects the to the original page, with the potential values being updated (referenced item title), which is actually a pretty good thing!

That being said, I am still interested in the "ajax submit" version!

You need to implement and use your own EntityEditForm - is this the case ?
Then skip to the last code block :D

Otherwise you'll need to accomplish this first.
See this answer (Overriding an entity add/edit form through alterroute) for an approach to 'inject' a custom form. Here the crucial code to it (adapted to NodeForm):

modules/custom/form_overwrite/form_overwrite.services.yml

services:
    route_subscriber:
        class: Drupal\form_overwrite\Routing\RouteSubscriber
        tags:
 - {name: event_subscriber }

modules/custom/form_overwrite/src/Routing/RouteSubscriber.php

 <?php

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

namespace Drupal\form_overwrite\Routing;

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

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

  /**
   * {@inheritdoc}
   */
  protected function alterRoutes(RouteCollection $collection) {
     if ($route = $collection->get('entity.node.edit_form')) {
  $route->setDefault('_entity_form', '\Drupal\form_overwrite\Form\NewEditForm');
     }

   }
}

modules/custom/form_overwrite/src/Form/NewEditForm.php

<?php

namespace Drupal\form_overwrite\Form;

use Drupal\node\NodeForm;

/**
 * Form handler for the node edit forms.
 */
class NewEditForm extends NodeForm {}

There you make sure the #ajax is set, like:

<?php

public function form(array $form, FormStateInterface $form_state) {
   ...
   $form['actions']['DESIRED_EXISTING_ACTION'] = array(
      ...
      '#type' => 'submit',
      '#ajax' => array(
        'callback' => '::ajaxSubmit',
        'event' => 'click',
      ),
      ...
    );
   ...
}

and overwrite the ajaxSubmit function, adding the CloseModalDialogCommand, like:

public function ajaxSubmit(array &$form, FormStateInterface $form_state) {
    $response = new AjaxResponse();

    if ($form_state->getErrors()) {
      ...
    }
    else {
      ...
      $response->addCommand(new \Drupal\Core\Ajax\CloseModalDialogCommand\CloseModalDialogCommand());
    }

    return $response;
  }


menus and per page sub menus I have my primary navigation (which is hard-coded into the theme). What I want is for a sub-menu (depending on the page) to appear in the left sidebar.

For example, if they click on the primary link for "bears" then the left sidebar menu might have "black bears" and "brown bears". How can these sub menus be accomplished? I don't want sub-menus these hard coded (i.e. easily configured by the client)


Enable View Library tab for Media module The screen shot for the Media module  description shows the View Library tab. On my content type I can only see the first 3 tabs Uploads, Web and Library. The final tab "View Library" is not available. This site consists of 1000's of images thus such a tab is very useful. Let me know what is the way to enable this.

The image you've attached from the drupal.org media module page appears to be an outdated screenshot of the module. I believe you can use the "Library" tab. The "View Library" tab shouldn't be there in the latest version of the module.

There is more information on the tab title changes in this issue: https://www.drupal.org/node/1886994


Updating multiple node fields Is there a module that allows the user to update multiple node fields in one page?

I found a method using Views (http://eureka.ykyuen.info/2012/12/13/drupal-7-update-multiple-nodes-at-once-in-a-views/), but I prefer to use module approach. Probably something that utilizes function node_mass_update (https://api.drupal.org/api/drupal/modules!node!node.admin.inc/function/node_mass_update/7)

I guess my first question is how many nodes are you looking to update. If it's a relatively small amount, you should just use VBO (per the article you referenced). That is the easiest contributed module method of updating multiple nodes.

However, it is possible for you to create your own module (i.e. custom_node_update) and run the node_mass_update upon form submission (as recommended by the API documentation). This will be especially useful if you are updating a large number of nodes because it will batch it appropriately, however, you'll be required to write some custom code.

Does this answer your question?


How to modify the add node forms using hook_form_alter This is the $form_id of a content type: q_a_node_form. I'm trying to change its add/content form (the title field) using hook_form_alter. this is my code in template.php:

function MYTHEME_form_alter(&$form, &$form_state, $form_id){
switch ($form_id){
    case "q_a_node_form":
        $form['edit-title']['#size'] = 10;
        break;
    }
}

I'm sure that the case option happens, I already print something in it and it works. why it doesn't work?

See below code which works.. Form element is title instead of edit-title.. print $form array to investigate form elements...

function MYTHEME_form_alter(&$form, &$form_state, $form_id){
switch ($form_id){
    case "q_a_node_form":
        $form['title']['#size'] = 10;
        break;
    }
}

If you have installed devel module you can see elements using below code

dpm($form);


Render custom block by block name I have created a custom block in the Drupal CMS. Say it is called "test_block". Is there a way to render this block in a template file using the name of the block?

Thanks,

D7:

<?php
  $block = module_invoke('module_name', 'block_view', 'block_delta');
  print $block['content'];
?>

'module_name' = The machine name of the module (i.e. the module's folder name). This is true for core modules too, so for instance 'search', 'user' and 'comment' would all work here.

'block_delta' = The machine name of the block. You can determine what this is by visiting the block administration page and editing the block. The URL for editing a webform block, for instance, would be something like:

Drupal 7: admin/structure/block/manage/webform/client-block-11/configure

In this example, 'webform' is the module's name, 'client-block-11' is the block's delta.

Custom blocks will have module name of 'block' and a number for a delta, which you can also find by editing the block.

More information: http://drupal.org/node/26502

====== OR =============

<?php
//suppose 98 is the id of the block

   $block =block_load('block',98);
   $output = drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));
   print $output;
?>


Installing / updating modules in multi-site environment I am in the middle of configuring a Drupal 8 installation with multiple domains in a multi-site configuration. One thing that occurred to me, is if one domain/site updates a module, the other site that may use that module won't know of that update.

Should I either :
a) move the modules into the sites//site name//modules directory, or
b) make another drupal8 instance for each site

Or is there something else that i am missing. Recommendations most helpful.

You have described the options for multisite pretty well:

Lots of shared code by putting modules in /modules
Lots of copies of module code by moving to /sites/[sitename]/modules but only one copy of core to update.
Use multiple instances instead of multisite (lots of copies of the same code but the ability to update one without risk to others).

Multisite is most useful when there is low variation in the configuration between the sites and therefore you can safely use the same copies of core and the modules on most (if not all) sites.  The more variation you have between copies the more likely it makes sense to ditch multisite and move to multiple instances.

While there are some very large instances of multisite in use, there are also people in the community who feel pretty strongly that multisite brings more headaches than it is worth.


Computed Field display only if below 0 In my computed field I'm trying to make it display the field and it's label only if the value is negative.  If it is above 0 it should not display anything, not even field label.

So far in "Display Code (PHP)" I have:

if $entity_field_item['value'] < '0' { ;
$display_output = $entity_field_item['value'] . '%';
}else{$display_output = ''};

But it just returns the label with no value.

The classic

$display_output = $entity_field_item['value'] . '%';

works fine though.

Try this:

if ($entity_field_item['value'] != 0)
 {
 $display_output = $entity_field_item['value'] . 'pkt';
 }
 else($display_output = NULL);


Disable third-party modules before core update I have a D8 (8.5.6) installation which I have been trying to upgrade to 8.6 since it came out. It is on a shared hosting account which does not allow drush, so FTP it is. During the database update, it fails and I end up with the proverbial white screen of death. Before delving into detail troubleshooting, I want to disable all the third-party modules, and see if this works. If successful, I want to enable the third-party modules, one by one.

Is that a "good practice" type of approach?

The point is to quickly identify whether it is a contrib module which causes problems are the core install. Normal troubleshooting procedures would follow in any case.

The one and only way to solve your problem responsibly is the following.

Download all files to your local machine.
Where you have a web development setup. And Drush.
Download the database.
Setup the page on your local machine, import the database and re-do locally what you were currently trying to do on the live server.
Use your local Drush and whatever other tools you can get to check error messages, server logs, debug output etc.
Drop and re-import the local database and repeat every step until you have reproduced the problem often enough to know what went wrong in the first place.
Fix your live page.

And finally:

Never ever again update stuff untested on the live server. And have the database backed up let's say at least once a week. Good luck!


Documents as a node/block/field I'm working on my first Drupal site.

Using FileViewer I can load a PDF saved in a field, for viewing of various types. I haven't found something that does the same for Word Docs, Excel, etc.

Does anyone know of something that works in Drupal 7 to load documents other than PDF like FileViewer does inside a browser? Or like Scribd does (Scribd is hosted. I am behind a firewall with limited access for users. So I don't want to use a Scribd like service.)

It seems that FileViewer has been folded into a module called PDF, which uses JavaScript to render PDF files.

So the next logical question is: How do you render Word docs, like Google Docs? And the answer is: Google Docs Integration module, which lets you show a list of Google docs, but doesn't let you display the documents.

Web searches give up nothing else.

Good luck...


How to group by one field I have a view which shows the users subscribed to the website. Some users have multiple roles, therefore, on the results, there are some duplicates.

What I want to do is to remove these duplicates, so I've tried to enable the Aggregation in the view settings. This action reduced the repeated results, but it haven't erased them.
By looking at the query the GROUP BY is done for every field, but I want to enable for just one field, more specifically like this: GROUP BY users_name.

I've tried to achieve it by making a simple module with this function:

function alter_users_query_views_query_alter(&$view, &$query) {
    if ($view->name == 'all_users') {
        $query->add_groupby('users_name');
    }
}

Which adds the additional field in the GROUP BY, but it doesn't remove the others.
How can I achieve it? More specifically, how can I unset the other fields and group by just one?

I was able to find a solution by following this example. Here is the code in my case:

function alter_users_query_query_alter($query) {
    if (isset($query->alterMetaData)) {
        if (isset($query->alterMetaData['view'])) {
            if($query->alterMetaData['view']->name == 'all_users') {
                $fields =& $query->getGroupBy();

                unset($fields['field-you-want-to-remove']);
                $query->groupBy('users_name');
            }
        }
    }
}


Relation adding not working in Drupal 7.9 I am a adding a new relationaship type, when i add up its not adding up, it gives one more time asking for details for input of relationship type and when i give the details and add it an fatal error displays..

I am using Drupal 7.9 and latest versions of modules on Drupal.org
below is the error message

Fatal error: Call to undefined function ctools_export_crud_load_multiple() in R:\xampp\htdocs\sitename\sites\all\modules\relation\relation.module on line 397

There is a known incompatibility with CTools rc1; use the development snapshot, and it will work.


Problem in Recurring payment using money scirpts we offered 20% discount last year and I've just received a recurring payment and it should be for full amount but its the same payment as last year. It just means if people renew their membership we lose on 20% of each membership fee.

Am using MS Core 6.x-1.25 and Drupal Version 6.20

Any one can help?

Thanks

If you set it to 'Persistent' in scope, then it will remain discounted for all payments in the series. 'Initial' is what you want, where only the first payment is discounted, sort of like a Trial amount.


How to add twig template suggestions per display mode with custom module? I have a custom module where I am trying to use custom twig templates based on the user view mode. The templates files I am trying to add to my theme are:

user.html.twig
user--compact.html.twig
user--token.html.twig

These reside in a folder called MYMODULE/templates/.

This is my current module code:

module_name.module:

/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {

  return [
    'user' => [
      'template'  => 'user',
      'base hook' => 'user',
    ],
    'user__compact' => [
      'template'  => 'user--compact',
      'base hook' => 'user',
    ],
    'user__token' => [
      'template'  => 'user--token',
      'base hook' => 'user',
    ],
  ];

}

The fix was ensuring to add the theme suggestions via HOOK_theme_suggestions_HOOK_alter(), as well as switching one template from user to user__full. Below is the updated module code:

/**
 * Implements hook_theme_suggestions_HOOK_alter().
 */
function MYMODULE_theme_suggestions_user_alter(&$suggestions, $variables) {

  $view_mode = $variables['elements']['#view_mode'];
  $suggestions[] = 'user__' . $view_mode;
}

/**
 * Implements hook_theme().
 */
function MYMODULE_theme($existing, $type, $theme, $path) {

  return [
    'user__full'    => [
      'template'  => 'user--full',
      'base hook' => 'user',
    ],
    'user__compact' => [
      'template'  => 'user--compact',
      'base hook' => 'user',
    ],
    'user__token'   => [
      'template'  => 'user--token',
      'base hook' => 'user',
    ],
  ];
}


Prevent embedded video appearing above image overlay http://www.fareham.ac.uk/news/2011/10/17/skins-star-inspires-students

The above page includes an image gallery, powered by the Brilliant Gallery module.

The problem: when a thumbnail from the Gallery is clicked, the embedded YouTube video beneath the Gallery section appears above the image overlay (powered by the Lightbox2 module).

How can I prevent this from happening?


Drupal 7.x & GoDaddy Cron Jobs Has anyone successfully gotten cron jobs to work with GoDaddy shared hosting and Drupal 7.x?

This sort of thing is EASY if you have access to use wget or cURL but GoDaddy for some reason blocks access to their own shared servers through tools as wget and cURL. Why I don't know.

We are stuck with having to use

/web/cgi-bin/php "$HOME/html/drupal/cron.php"

but as described here: http://drupal.org/node/251481

that is bad since Drupal doesn't go through its bootstrap process and certain vars are not initalized. I also get the classic:

Status: 404
Content-type: text/html
No input file specified.

when I use this method. There is also the fact that D7.x requires a cron_key parameter passed along _cron.php?cron_key=XXXXXXXXXXXXX

Anyone have a solution...besides get the hell off GoDaddy?

Yes, I crated a cron.sh script and uploaded it on my server with the following content:

#!/bin/bash
# run drupal cron
echo "Start"
START=$(date +%s)
echo "Running Drupal Cron"
wget -O - -q -t 1 "http://<your-domain>.com/cron.php?cron_key=<your-key>"
END=$(date +%s)
DIFF=$(( $END - $START ))
echo "Total Time: $DIFF seconds"
echo "End"

I went into the GoDaddy hosting account and entered the cron command:

bash /home/content/00/00000000/cron.sh

NOTE: You will need to know the path of the location where the script resides on the server.  If you are using ssh you can get the path by typing "pwd" in the ssh command line.


Multisite and apple touch icons In a typical multisite D7 installation, I would like to set up apple touch icons. So that, when an agent requests http://example-1.com/apple-touch-icon.png then he receives the image appropriate for site example-1. And for site example-2, it should be a different image with the same name (and unfortunately at the exact same url, which is the multisite root directory). How can this be solved?

It doesn't totally help with the default paths, but I explicitly define them for each theme:

/**
 * Implements hook_preprocess_html().
 */
function MYTHEME_preprocess_html(&$variables) {
  $path = drupal_get_path('theme', 'MYTHEME');

  drupal_add_html_head(array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => $path . '/images/favicon.png',
      'rel' => 'icon',
      'type' => 'image/png'
    ),
  ), 'MYTHEME-favicon');

  drupal_add_html_head(array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => $path . '/images/touch-icon-iphone.png',
      'rel' => 'apple-touch-icon',
    ),
  ), 'MYTHEME-touch-icon-iphone');

  drupal_add_html_head(array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => $path . '/images/touch-icon-ipad.png',
      'sizes' => '72x72',
      'rel' => 'apple-touch-icon',
    ),
  ), 'MYTHEME-touch-icon-ipad');

  drupal_add_html_head(array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => $path . '/images/touch-icon-iphone-retina.png',
      'sizes' => '114x114',
      'rel' => 'apple-touch-icon',
    ),
  ), 'MYTHEME-touch-icon-iphone-retina');

  drupal_add_html_head(array(
    '#tag' => 'link',
    '#attributes' => array(
      'href' => $path . '/images/touch-icon-ipad-retina.png',
      'sizes' => '144x144',
      'rel' => 'apple-touch-icon',
    ),
  ), 'MYTHEME-touch-icon-ipad-retina');
}


What is the purpose of Translation field in form display mode? When editing the form display mode of a translatable content entity, there is a field called Translation in the UI. I thought this field would manage the weight/visibility of translation meta data fields (like content_translation_uid or content_translation_outdated) in the entity's edit form.

But moving that field around doesn't have any effect, it neither reorders the position, nore does it hide the Translation <details> element when I move it into the disabled section.

So, what is the real purpose of the field Translation in /admin/structure/ENTITY/manage/BUNDLE/form-display ?

(This is a follow-up of my question  Custom content entity: can't hide translation details in edit form)

This is an extra field (Drupal term for a pseudo field not stored in the database you can move around in UI), which is added when Content Translation is enabled:  content_translation_entity_extra_field_info()

See this issue:

  content_translation_entity_extra_field_info is obsolete

  Problem/Motivation

  content_translation_entity_extra_field_info is adding the extra field
  "Translation" but it is not used by content_translation in the form
  alter hooks and it only confuses when we are on the form display
  configuring the fields and reordering it doesn't change anything on
  the edit page.

  Proposed resolution

  Remove content_translation_entity_extra_field_info
  and remove the "translation" component from all saved form display
  configs.

https://www.drupal.org/project/drupal/issues/2856551


Is there a way to automatically have a copyright attribute when content is submitted? I have a website where all users submit content and that content is often also plagiarism, which I don't want.

Can this be done with rules? How would the copyright attribute fetching work?

What I want to accomplish and what I tried without luck in short:

After content is submitted, cross check websites database and look if there's some copyright attribution to be made, if positive add the copyright attribute to the end of the text.

Am I doing it right?

The only ready-made solution I know of is Plagiarism Checker - Authentication Framework.

  The module is a framework which supports various search APIs (plugins) to scour the net looking for possible plagiarized content. The framework provides support for 2 different types of APIs - Standard APIs (Google and Yahoo plugins are included here) and Custom APIs (such as the 3rd party paid authentication service from iThenticate (www.ithenticate.com)).

Note that these APIs are either not designed to plagiarism discovery, giving a lot of false positives, or may be paid. Also, low usage count and Development status: Maintenance fixes only should make you careful.


Drush alias doesn't work None of my site aliases defined in /home/peter/.drush/aliases.drushrc.php seems to work. When I ran:

drush sa @mysite.dk.local

I got

$aliases['mysite.dk.local'] = array (
 'uri' => 'mysite.dk',
 'root' => '/usr/share/nginx/www/drupal-7.16/sites/',
 'path-aliases' =>
 array (
   '%dump-dir' => '/usr/share/nginx/www/drupal-7.16/sites/drush.dbdumps',
   '%files' => '/usr/share/nginx/www/drupal-7.16/sites/files',
  ),
);

which looks ok, but when I do

drush @mysite.dk.local status

I get

PHP configuration     :  /etc/php5/cli/php.ini
Drush version         :  4.5
Drush configuration   :
Drush alias files     :  /home/peter/.drush/aliases.drushrc.php

So it seems that drush couldn't find  specified path, cause when I run second command in sites directory everything is showing up as expected. Can anybody point out what I'm missing?

If your settings.php file is at /usr/share/nginx/www/drupal-7.16/sites/default/settings.php, then you should change your 'root' line as follows:

'root' => '/usr/share/nginx/www/drupal-7.16',

The way you have it, Drush is expecting that your Drupal root is at /usr/share/nginx/www/drupal-7.16/sites, which is to say that it is also expecting to find your settings.php file at /usr/share/nginx/www/drupal-7.16/sites/sites/default/settings.php. Take out the extra 'sites' as shown above, and it should work fine.