File Upload to share storage I am trying to create a load balanced Drupal installation.  My setup has a shared storage that all the webservers can read write to.  At the moment I’m having trouble setting up the Drupal configuration at {mydomain}/admin/config/media/file-system/ to save our content to the correct file path.

The file path on the operating system that I’m trying to write content to is of the form:

\xx.xx.xx.xx\my\content\folder\

When I place this in the public file path I get the content written to the local path:

D:\myDrupalInstalation{mydomain}\sites\xx.xx.xx.xx\my\content\folder\

However I know the PHP has rights to write modify content on the shared storage because when I try the same path in private file path the content is written to the shared storage:

\xx.xx.xx.xx\my\content\folder\sites{mydomain}\allTheContent\

Which is what we require.

How can I configure the public file path to write to the same location?

P.S.  I think it is something due to the fact that the Drupal config page itself specifies "This directory must be relative to the Drupal installation directory and be accessible over the web." for public path and "* It should be writable by Drupal and not accessible over the web.*" for Private.

Thanks

In a Linux environment, this is done for NFS drives by creating a symbolic link under your Drupal webroot.

In the Windows environment, you can also create a symlink to a network drive path (e.g. \xx.xx.xx.xx\my\content\folder ).


Let the user change language with a select I need to let the user change language with a select. I need to do everything by hand because i'm putting that in a custom block. Do you have any idea on how I can accomplish that?

This is what i did in the end:

php

$path = drupal_is_front_page() ? '<front>' : $_GET['q'];
$type = 'language_url';
global $language ;
$lang_name = $language->language ;
$links = language_negotiation_get_switch_links($type, $path);
$languages =array();
$htmlSelect = "<select id='selezioneLingua'>";
foreach ($links->links as $id => $link) {
    $prefix = $link['language']->prefix;
    $selected = '';
    if ($lang_name == $prefix){
        fb('same');
        $selected = 'selected';
    }
    $htmlSelect .= "<option $selected value='$prefix'>$link[title]</option>";
    $href = ($link['href'] === '<front>') ? '' : '/'.$link['href'];
    $languages[$link['language']->prefix] = "?q=".$link['language']->prefix.$href;
}
$htmlSelect .= "</select>";
drupal_add_js(array ("languagepages" => $languages), 'setting')

javascript:

jQuery('#selezioneLingua').change(function(){
    var val = jQuery(this).val();
    var languages = Drupal.settings.languagepages;
    window.location.href = languages[val];
});


How to force a field to allow unlimited number of values using Field API? How do I force an unlimited number of values using code for a field I created using the Field API in Drupal 7? In this case it doesn't make sense to have any other setting so every time I create an instance of this field I have to set the number of values from 1 to unlimited.

You mean for a field type that you created yourself?

There is no real API to declare that, the only thing you can do is alter the add/edit field form.

I've already done this myself for the Properties module; here is the code (source):

function properties_form_field_ui_field_edit_form_alter(&$form, &$form_state) {
  if ($form['#field']['type'] == 'properties') {
    // Hide the cardinality setting on the field settings for properties fields.
    $form['field']['cardinality']['#default_value'] = FIELD_CARDINALITY_UNLIMITED;
    $form['field']['#access'] = FALSE;
  }
}

(Don't forget to flush the cache after changing form_alter hooks and, if it's an instance setting, delete and recreate the instance to remove the previous default)


What is the right way of loading a service? when trying to use a service in drupal actually there is 3 ways , what is the preferred way to use a service and why :

passing dependencies directly through the constructor:

public function __construct(AccountProxyInterface $current_user) {

}

passing the dependencies through the create() method wich look to me the same as injecting it through the __construct(), with the only difference , an instance will be created eah time (no singleton design pattern - not same instance will be reused)

      public static function create(ContainerInterface $container)
  {
    //1.getting service from the service container.
    $Door = $container->get('custom_service.door');
    //2.create a new object of current class, and Inject the dependency  object into the constructor
    return new static($Door);
  }

  //constructor receive the dependency set by the create() method
  public function __construct(Door $Door)
  {
    kint($Door);
  }

just get get the service from the service container and no need to inject it using :

$Door = \Drupal::service('custom_service.door')

The standard way to inject services in other services is passing dependencies directly through the constructor:

mymodule.services.yml:

services:
  mymodule.foo_service:
    class: Drupal\mymodule\FooService
    arguments: ['@current_user']

While you can define a factory method in *.services.yml, see
https://symfony.com/doc/current/service_container/factories.html,
in Drupal the most common places for this are Controllers and Plugins which implement ContainerInjectionInterface::create or ContainerFactoryPluginInterface::create. See How do I use dependency injection on \Drupal::moduleHandler() to a Controller?
\Drupal::service... is largely used from procedural code when not in an OOP context, like hooks or static callbacks. See the comment from @Kevin.


Including Part Template within a Custom Module I am writing a custom module that uses several twig templates in my modules /templates directory. I want to use part templates (https://www.drupal.org/node/2634166) so that I could reference the following:

{% include directory ~ 'includes/spr_table_selectors.twig' %}

The problem is my include keeps referencing my main site theme (themes/mytheme/...). Is there an easy way I can reference my includes directory within my custom module?

There should be a change to the theming documentation in this case. Namespace for twig is always set to MYTHEME/templates or MYMODULE/templates.

The directory variable is to ACTIVETHEME/templates.

So if you look at how the Symphony folks have been do things, you will find out they have their template parts in a subdirectory named parts rather then a sibling directory named includes. Use the subdirectory will fixed your problem. BONUS you can use @ to call the namespace of your module or theme like this:

<header>
  {% include '@MYMODULE/parts/header.html.twig' %}
</header>

Remember to keep your template part name(s) unique from the templates in use by your Drupal install to avoid them being used as a full template item that overrides something provided by core or another module.


'drush field-create' with type INTEGER from command line? drupal (ver 7.22) | drush (ver 6) tried to manage fields of tpye 'int' with drush (batch), without success!

working:
drush field-create user streetname,text,text_textfield --entity_type=user

not working:
drush field-create user streetnumber,integer,text_textfield --entity_type=user

workaround:
drush field-create streetnumber --entity_type=user
-> offers interactive dialog only
Field name: ...
Choose a field type ...
Choose a widget ...
--> '_http://default//fields/streetnumber'

Maybe there's another way to provide data, like

drush field-create user streetnumber < inputfile ??
drush field-create user streetnumber < 'fieldname_XYZ','6','1' ??

any ideas?

for an integer field type, try this :

drush field-create user streetnumber, number_integer, number_textfield

Or :

drush field-create user streetnumber, number_integer

(because you can ommit the widget type and the default one will be used).

If you are looking for the name of another field type, create the field in the admin panel, then look in your database, in table field_config, you will find it in the type column.


Modifying a module's function from another module A particular module has a theme function (theme_nice_menus_build()) that I'd like to give a slightly different output; I'd rather not modify the .module file to be able to continue updating the module when new versions are available.

Is it possible to modify that function from another custom module or from template.php?

All theme functions can be overwritten in template.php by replacing theme with phptemplate.
so your function in template.php should be like

phptemplate_nice_menu_build


views results differ from preview Working on my first Drupal project, I meet this problem for the second time. I can't figure why this happens and couldn't find any leed on the web.

1) A view with contextual filter Content: Has taxonomy term ID (with depth)

depth = 1
When argument not in the URL = Show all results
Vocabulary : the proper (hierarchical) taxonomy is selected

The view has path taxonomy/term/%

The preview is correct, both when entering as an argument a child term ou a parent term.

The view results are correct for any taxonomy/term/[child_term] path.

But for a taxonomy/term/[parent_term] path, I get a message "No content tagged with this term". The sentence is true, but it should return all content tagged with any of the child terms. So, it behaves as if there was no (with depth).

2) Adding to the same view a basic Filter criteria = Content: Type(=[TheRightContentType]).

The preview is ok. But again, the results are not filtered. Even when the argument is a child term, I get all results tagged with that term, but whatever their content type is.

I flushed the browser cache. Then I flushed Drupal's caches. In vain.

Any suggestions appreciated. Thanks.

Finally, the view has

• a path taxonomy/term/%/%

• a second contextual filter Content: Has taxonomy term ID depth modifier

and this solves problem 1 : with a parent tid as an argument the view produces every content that is tagged with one of its child terms.

But problem 2 remains.


How to create multiple user account types in drupal 7 I want to customize the default registration process in drupal 7 like Paypal.

Users can choose their account types to register and  each account type has some corresponding fields to fill information.

For example in Paypal have 3 account types : Personal, Premier, Business

In drupal I only see 2 account types(anonymous and authentication), how can I add more ?

Anonymous user, and authenticated user are two default roles used by Drupal (what other CMS's would call account types).

You can add custom roles from admin/people/permissions/roles.

Once you created the new role, you can change the permissions given to that role using the "edit permissions" link that appears to the right side.

If you then need to add new fields for user accounts having a specific role, you can use the Field Permissions module.
Drupal allows you to add new fields to the user accounts, from admin/config/people/accounts/fields, but the fields are visible for every user account, independently from the roles those accounts have.

The Field Permissions module allows you to set who can enter a value for a field, who can edit a value for a field, and who can view the value of that field.
For example, if you want a "Editor ID" field that needs to be filled only from users with the editor role, you can add the permission of creating a value for that field, and editing it to users with the editor role; other users should be allowed to see that field, as well as the users with the editor role.


How to pull parent taxonomy from nodes I have a taxonomy list like so...

Parent One
    Subitem One
    SubItem Two
       SubItem Three
Parent Two
    Subitem Four
Parent Three
    SubItem Five
    SubItem Six

I also have a content type that uses subitems in a field, along with other fields.

I need to have a view that will show the parent taxonomy terms in addition to the other fields in the CCK.  Something like

Parent Fields
      Title
      Book
      Subotem 1
   Parent Two - SubItemsTwo
      Title
      Book
      Subotem 3

Please advise

You should look into Relationships for this.


How to maintain a local mirror on my Mac? I have a personal Drupal 6 site being hosted commercially, and I would like to maintain a mirror of the site on my local MacBook for the purposes of developing custom modules and themes before deploying them.  My question has two parts:

How do I set up my Mac so that it's ready to install Drupal?
How do I mirror my live site locally?

First, download MAMP.

Then, use MAMP to run Drupal locally (great info here, on drupal.org). Another option is the Acquia Stack Installer, but that's only better if you plan on running Acquia Drupal (at least, in my experience). MAMP is pretty powerful (I even have it, or XAMPP on Windows) running a few Intranets here and there).

You can either grab the files using FTP, and put them in MAMP's htdocs folder (or configure MAMP better, so you can put the files into your ~/Sites/ folder, for instance, using virtual hosts), or you could use source control, like Git or SVN, to manage your drupal site codebase—then just do a git clone to your computer and you'll have the entire codebase.

Use PHPMyAdmin or some other tool to download the database for your website, and then, using MAMP's installation of PHPMyAdmin, import that database into a database on your local computer. You'll need to make sure the settings.php file for your site can authenticate to MySQL on your local computer.

You can either set up a user for your local MySQL installation with the same password and username as your live server, or you can customize settings.php so it uses a different database name and credentials on your local computer. See, for instance, Suggestions for settings.php - Local dev, Development server, Live server


How to make custom template for search results I have developed a custom search module that is working perfectly. Currently I am using the existing "search-results-tpl.php" and "search-result-tpl.php" for showing search results.

But I want to make my own custom template file for showing results and that template file should be inside my custom module directory. In this template I will be able to style my search results however I like.

Any suggestions on this?

Note: I have tried many contributed modules also, but they don't satisfy my requirements, so therefor I have started a custom module. But if you have any better solution, then feel free to point me to any of them.

By using the theme function I have got it working. Here is how it looks like:

/**
 * Implements hook_theme().
 *
 * Create custom theme and template files.
 */
function mymodule_theme() {
  $themes = array(
    'my_search_result' => array(
      'variables' => array('result' => NULL, 'module' => NULL),
      'file' => 'mymodule.pages.inc',
      'template' => 'my-search-result',
    ),
    'my_search_results' => array(
      'variables' => array('results' => NULL, 'module' => NULL),
      'file' => 'mymodule.pages.inc',
      'template' => 'my-search-results',
    ),
  );
  return $themes;
}


How to deal with SalesforceException: HTTP Method 'PATCH' not allowed I've the the Salesforce module mapping in place integrated with Commerce module and I've the following SalesforceException when purchasing the order:

SalesforceException: HTTP Method 'PATCH' not allowed. Allowed are HEAD,GET,POST

What's happening and how to deal with or debug this problem?

The format of the HTTP SFDC API callback for inserting/upserting records is:

/services/data/v20.0/sobjects/ObjectName/customExtIdField__c/Id

The ObjectName is the Name of an Salesforce table i.e. 'Contact' or 'Account'. And Id is the Id of a specific record you want to update in the table.

The possible cause of the error for that would be that you're calling SFDC API with the invalid data.

Please check if your REST URL is correct, probably your objectId is not passed through. E.g. If you have dependencies between the other objects, check if these were created in the first place, before creating your main object.

Related:

Update records using Salesforce REST API - Patch method not working


Where do I place hook_cron()? I think I need to use hook_cron() to cause my new module to be run each time cron runs, but in what file and directory do I place this code? Is it in my new module or some other place.

Logically, it would seem that it should go some place other than my module, but I don't know where even though I've looked at documentation from various web sources. It seems like the "chicken & the egg" problem. If I put hook_cron() in my module how does Drupal know to tell cron to run my module? Maybe it's magic?

I'm using Drupal 8.

All hooks by default go in the .module file, so it should go in the .module file.

It's not clear what you mean by "run my module", as modules aren't 'run', so I can't really give any more info.


How to attach a date field from another entity to a new form I am attaching a few fields from the user entity to a custom form with the following:

$account = user_load($user->uid);
foreach ($fields_to_collect as $field) {
  field_attach_form('user', $account, $form, $form_state, NULL, [
    'field_name' => $field
  ]);
}

This works fine except for date fields (I am using the date_popup widget but I haven't yet narrowed that down as responsible).  Attaching a date field results in the following error: Warning: implode(): Invalid arguments passed in date_limit_format() (line 2262 of sites/all/modules/date/date_api/date_api.module).  The date field is just shown as a text field with the text Format shown as a description.

The error is due to $granularity being NULL.  On, for example, the user account edit page which has this field, $granularity is something like:

[
  'month',
  'day',
  'year'
]

Thanks for any help/suggestions.

Unsurprisingly, it was my error.

Further up in my function I was building $form_state with form_state_defaults().  Once I provided a proper form_state everything worked as expected.


Unable to retrieve user id of edited user from $entity in hook_field_validate I have this little problem with a custom field that is bundled with user. In its validation function I need to have access to the user id of the user whose field is being edited.

What that means is, when I edit a user, I need to get his uid in the validation function.

The problem is that hook_field_validate provides just $entity variable that doesn't include uid.

I know I could load the user object using his email / name (and then retrieve the uid from it) but it wouldn't properly work when email/name was being changed (I could get only the changed values from $entity and therefore wouldn't be able to load the object properly).

Any ideas?

You can always get this information from the path, eg:

// you are sitting on user/#/edit

$uid=arg(1);                      // quick, or...
$account=menu_get_object('user'); // the full user object, eg the uid is in $account->uid


How can I apply logic in user registration welcome emails? I am trying to put some logic into user registration welcome emails. Simple "if-then" logic, based on tokens.

The tokens I use show up as expected, but both twig and php code gets sent as plain text.

Can I somehow make twig or php code execute before the email is sent to the new user?

UPDATE, to make the question more specific:

I have token module enabled.

I am trying to add this logic to the welcome email sent to new users at "/admin/config/people/accounts":

{% if [user:field_marketing_package] == "Yes" %}

Marketing selected

{% endif %}

The [user:field_marketing_package] field is filled out at user registration.

I would like to add logic like this. If I have the above twig code in the message, it just gets sent as plain text and does not execute.

Twig or php or any other solution is fine as long as I can include the token in the if statement.

Can you point me to the right direction?

Pretty ugly, but I have a solution. Please post if you have a better one that can be applied for more use cases.

So I installed the https://www.drupal.org/project/computed_field module.

I added a hidden computed filed to my user registration form with my logic.

Then I used the token module to include the value of that computed field in my user welcome email.

It does the job, but again, it is pretty ugly.
Hopefully this helps someone until someone posts a more direct solution.


Add redirection in submission handler How can I redirect users to a node in a form submission handler similarly to the following code?

In my form alter I have added an additional submit button:

$form['actions']['save_and_exit'] = array(
    '#type' => 'submit',
    '#value' => t('Save & Exit'),
    '#submit' => array('custom_submit'),
  );

function custom_submit(&$form, \Drupal\Core\Form\FormStateInterface
  $form_state) {
    $system_path = '/node/2';
    $url = \Drupal::service('path.alias_manager')->getAliasByPath($system_path);
    $form_state->setRedirect($url);
}

Then I'm getting following error:

  Symfony\Component\Routing\Exception\RouteNotFoundException: Route
  "/mypage" does not exist. in
  Drupal\Core\Routing\RouteProvider->getRouteByName() (line 190 of
  C:\wamp\www\www_assure_local_com\core\lib\Drupal\Core\Routing\RouteProvider.php).

where /mypage is the url alias of my /node/2.

A form submission handler never returns a RedirectResponse object to redirect users. (It actually doesn't return any value.)

A form submission handler calls FormState::setRedirect(), or FormState::setRedirectUrl() which accepts a Url object, for example the value returned from Url::fromUri('//my_node_url_alias').


How to filter views "node-changed-day is not node-created-day" I want to list node posts so, that only those ones will display which node-updated day is not the same as node-creaded day but at least next day or newer. How to filter it in Views? I'm using Drupal 6.

I just found a solution myself. There is  available ”Views PHP Filter” module for Drupal6. After installing I added new filter:  ”Node: Node ID PHP handler” for my Views. I left the filter options as default but filled PHP– textarea vith code below, and it worked.

$nodeids = array();

$result = db_query(db_rewrite_sql('SELECT DISTINCT(c.nid) FROM {node} c  WHERE c.status = 1  AND  c.changed >= c.created + 86400  - c.created % 86400  ORDER BY c.changed DESC'));

while ($node = db_fetch_object($result))  {
$nodeids[] = $node->nid;
};

return $nodeids;


What's the difference between the two-column layout and two-column bricks layout? I enabled the experimental Field Layout core module. There are two different two-column layouts available: one called "two column" and another called "two column bricks."

The dialog provides the diagrams below which don't clue me into their meaning. What is the difference between these layouts?

Layouts are defined in the Layout Discovery module and can be used by different layout modules.

The difference between those two layouts is the number of regions,  the Two Column Brick layout has three more. See the yaml layout definition:

/core/modules/layout_discovery/layout_discovery.layouts.yml

layout_twocol:
  label: 'Two column'
  path: layouts/twocol
  template: layout--twocol
  library: layout_discovery/twocol
  category: 'Columns: 2'
  default_region: first
  icon_map:
    - [top]
    - [first, second]
    - [bottom]
  regions:
    top:
      label: Top
    first:
      label: First
    second:
      label: Second
    bottom:
      label: Bottom

layout_twocol_bricks:
  label: 'Two column bricks'
  path: layouts/twocol_bricks
  template: layout--twocol-bricks
  library: layout_discovery/twocol_bricks
  category: 'Columns: 2'
  default_region: middle
  icon_map:
    - [top]
    - [first_above, second_above]
    - [middle]
    - [first_below, second_below]
    - [bottom]
  regions:
    top:
      label: Top
    first_above:
      label: 'First above'
    second_above:
      label: 'Second above'
    middle:
      label: Middle
    first_below:
      label: 'First below'
    second_below:
      label: 'Second below'
    bottom:
      label: Bottom


Drupal 7 & OpenLayers - Can see sample map under OpenLayers Admin: Preview but NOT under Views: Preview I'm stumped and seeking some direction.

I'm seeking to create a dynamic map using OpenLayers, Drupal 7, Views and Custom Content Type. I've read all the documentation I can find and so far I've been able to:

successfully create a content type (using "Geolocation Field" to
store geodata instead of GeoField),
create an OpenLayers Overlay in Views, and
create a custom map (clone of Google Map example) in OpenLayers Admin.

In OpenLayers Admin I can view the sample map ('MySample Map") under OpenLayers Admin: Maps: Edit Map: Preview.  This map successfully shows data points from content in the database.

However when I create a new View of format OpenLayer with style = MySample Map nothing shows - no datapoints and no map, only the title.

Any recommendations for debugging/resolving this problem?  Thanks in advance.

Openlayers is generated via JavaScript so wont display in the views admin. Save your view and check the page/block.

If it is still not working check the width of the map. Sometimes, when set to auto the map will collapse showing nothing. Set a fixed with and check again. If it works then some simple css will fix the rest.

Good luck :)


Twig attribues.addclass nesting issue Apologies if this has been asked before, but I'm on my first week working with drupal and twig.
I have the following code:
{%
  set container_classes = [
    'paragraph',
    'paragraph--type--' ~ paragraph.bundle|clean_class,
    view_mode ? 'paragraph--view-mode--' ~ view_mode|clean_class,
    not paragraph.isPublished() ? 'paragraph--unpublished',
    'container'
  ]
%}
{% set image_classes = [
  'col-12'
]
%}
{% block paragraph %}

  {% block content %}

          {{ content.field_two_column_image }}

          {{ content.field_two_column_copy }}

  {% endblock %}

{% endblock paragraph %}

My issue is the nested attributes.addClass. When I look at the HTML, I'm also seeing the container_classes classes, which is not what I'm looking for.
So how can I separate the two?

attributes is a variable containing attributes information (class, id, others..) for the main container of the template.
It should usually be used only once.
You can create a new attribute variable like this :
{% set my_attribute = create_attribute() %}|
And you can use it as usual :
<div{{ my_attribute.addClass(image_classes).setAttribute('data-type', 'image') }}>
  {{ content.field_two_column_image }}
</div>

More information about using the attributes variable in Twig templates :
https://www.drupal.org/docs/8/theming-drupal-8/using-attributes-in-templates
https://www.drupal.org/docs/8/theming-drupal-8/modifying-attributes-in-a-theme-file
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Template%21Attribute.php/class/Attribute/8.2.x


The curious case of a Drupal Button The code below is used to get the word count of a field (field_body) using ajax callback. It works great and everything functions as it should, well almost.
For some reason, the click of a button is also calling the default node form submit action.

So what happens is after I update count, and suppose I don't save the content. In fact, just go to another page or refresh the page, I get something like
Categories is required
Tags is required
Thumbnail is required....

Basically whatever I would get on form validation. It's just that the result is delayed as I am using ajax.

The problem is not with ajax, because even I comment the callback, and I click the button it tries to submit the form, when clearly it should not as executes submit callback is False.

function hook_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form' || $form_id == 'q_and_a_node_form' ) {

    $form['get_word_count'] = array(
     '#type' => 'button',
     '#value' => t('Update Count'),
     '#weight' => 5,
     '#executes_submit_callback' => FALSE,
     '#ajax' => array(
      'callback' => 'count_words',
      ),
    );

    $form['body_words'] = array(
     '#title' => t('Words in Body'),
     '#type' => 'textfield',
     '#disabled' => TRUE,
     '#weight' => 5,
     '#prefix' => '
',
     '#suffix' => '
',
    );
   $form['field_length_type']['#prefix'] = '
';
    $form['field_length_type']['#suffix'] = '
';
  }
}

function count_words($form, $form_state) {
  $str = $form['field_body']['und'][0]['value']['#value'];
  $count = preg_match_all("/\S+/", preg_replace('/(' . chr(160) .'|&nbsp;)/', ' ', strip_tags(str_replace('><', '> <', trim($str)))), $matches);
  $form['body_words']['#value'] = $count;
  if ($count < 500) {
    $form['field_length_type']['und']['#value'] = "short";
  }
  else if ($count > 500 && $count < 800 ) {
    $form['field_length_type']['und']['#value'] = "medium";
  }
  else {
    $form['field_length_type']['und']['#value'] = "long";
  }
  return array(
    '#type' => 'ajax',
    '#commands' => array(
      ajax_command_replace("#replace_body_words", $form['body_words']),
      ajax_command_replace("#replace_field_length_type", $form['field_length_type'])
     )
   );
 }
}

Any help would be much appreciated. Any workaround?

When using the #type => 'button' the submit callback is never executed, it already receives  a FALSE as default value.

Even if the submit callback is not executed, the validate callback is always executed (even on ajax posts). You can bypass this validation on a trigger element by using the #limit_validation_errors property.

In your case, you can set it on the body_words form element to only validate on this scope instead of the whole form.

$form['get_word_count'] = array(
    '#type' => 'button',
    '#value' => t('Update Count'),
    '#weight' => 5,
    '#limit_validation_errors' => array(
        array('body_words'),
    ),
    '#ajax' => array(
        'callback' => 'count_words',
    ),
);


How to anonymize IP logging by google analytics? I'm trying to achieve the implementation of:

gtag('config', 'UA-xxxxxxx-x');

to

gtag('config', 'UA-xxxxxxx-x', { 'anonymize_ip': true });

How to do this in D7?

I tried to add it to advance options in the google. Looked in some technical documents in ga but do not see how to fill in this field in drupal.
Any suggestion?

You can do that using the google analytics module. Enable the module and go to /admin/config/system/googleanalytics, there put your ga id in the textfield then there is a Privacy vertical tab. In that tab there is this checkbox which says Anonymize visitors IP address


Getting a 500 error with the Domain Access module I use Drupal 7.22 with 7.x-3.9 Domain Access Module for multiple subdomains website.
Making of subdomains works fine, but I cannot access to subfolders on subdomains.

example.com works
example.com/admin/ works
sub.example.com works
sub.example.com/admin/ internal server error 500

This error is showing on every sub-folder (content) in every sub-domain. The root domain is fine with all content. Also, theme changing on sub-domains works fine. Am I missing something in documentation?

To debug WSOD, you need info what exactly went wrong. There is a pretty neat article about fixing them - try to follow it. Around step 2a you should pretty much know what you need to look for in documentation.


I can't get date values using $_GET In my view, I have two filters: title (text box), and date (combobox); date has two values: year and month.

When I select the filters parameters in the view, and I click search, the filter values appears in the URL such as in mysite/views-path?title_filter=aaa&date_filter[year][value]=2012&date_filter[month][value]=3.

I used $_GET to get the value of the title filter, and it worked, but I can't get the date values using print $_GET['date_filter[year][value]'];.

Can anyone tell me how to get values like date using $_GET?

Arrays in query strings get converted into actual PHP arrays when you use $_GET.

To get the value in your case you'd use something like:

print $_GET['date_filter']['year']['value'];


Is 8.6.18 insecure? Will there be 8.6.19 etc.? I have a custom module that I think requires Drupal 8.6.x.

Is Drupal core 8.6.18 insecure? Will more 8.6.x versions be released?

According to the Drupal core release cycle documentation, the last month for security coverage for 8.6 was November 2019. There is no more planned security coverage for 8.6.

Security releases only last through the next minor release cycle. I.e. 1.0 will receive patch and security releases until 1.1 is released. Then 1.0 will continue to receive security coverage until 1.2 is released. Once 1.2 is released (the second minor release since 1.0), 1.0 is considered unsupported.


How to display the currently logged in user's details I am using D7 and views for one of my projects. I have created a view that displays the name, age, role and orders of the user. I would like these things to displayed only for the logged in user. For instance user/1 should get his name,age,role and orders only, he should not be able to see the other's details. Similarly each and every user must be able to see their own details. I know i can use the uid from the url, but not sure how to achieve this.

Thanks

Create a custom module and add following function.

function login_user_fn(){
   global $user;
   //print_r($user);
   $fid = $user->picture;
   $file = file_load($fid);
    if($file !=''){

    $user_pic  = theme('user_picture', array('account' => $user , 'path' => $file->uri,));

    return ('Hello '.$user->name.'<br/>'.$user_pic);
  }
}

And than call custom function " login_user_fn()" in our drupal custom block body.


Cannot add content using default content types I have Article and Basic Page, but when I try to add either of these to my Drupal Site I get the following error message.

  You have not created any content types yet. Go to the content type creation page to add a new content type.

If you go to Structure > Menus > Navigation, goto "list links" of Navigation menu, you'll see that all of your content types are disabled except for the actual "Add content" link. Just check the enabled box and save, then you should be good to go.


How to integrate custom code into a "Features" feature My specific problem:
In a Feature, I have a View. I want to use this View on several different sites. The View has a nid-argument, which validates Node:type == [node_type_1]. When the Feature get's exported, it outputs the filter settings like this:

'node_type_1' => 'node_type_1',
'node_type_2' => 0,
'node_type_3' => 0,

Problems ensue when the feature is used on site number 2, which, with exception of [node_type_1], has an entirely different list of content types. Thus the list becomes

'node_type_1' => 'node_type_1',
'node_type_4' => 0,
'node_type_5' => 0,

And suddently, I have an override, with a diff like:

< 'node_type_2' => 0,
< 'node_type_3' => 0,
> 'node_type_4' => 0,
> 'node_type_5' => 0,

Some background: At some point, I listened to an interview with a Features maintainer, who mentioned something interesting. It is both possible, and supported, to add custom code into features. I hope that can provide me with more dynamic means of handling this particular part of my problem.

My question is deliberately stated such that I hope someone can provide an answer to my specific problem, as well as similar problems, from other modules. I can easily imagine a similar problem showing up in many different situations. However, if it turns out that no-one can solve the problem in a general fashion, yet can solve this specific problem, I will re-phrase the question title to reflect that better.

I think I've been at your spot before with a single D6 codebase running on different sites and using Features for managing exportables such as Views.

In our example we had site sections running off taxonomies and firing off contexts (which got exported via Features). The problem was that although the name of most of our taxonomy terms was the same across sites, their tids changed, and there where exceptions as well, resulting in the problem you expose above.

Our solution was to go directly into the Feature and substitute the hard-coded, instance-specific variables with our own dynamic code. So we had a custom function in a custom module that would determine the contents of a particular variable in the exported feature. Then after exporting the feature initially, we would go into the array that we wanted to modify, and substitute it with a call to our dynamic function. When reverting features on each individual site the dynamic value would take the place of the hard-coded value. The only drawback to this solution is that you need to copy/paste the call to your custom function every time you recreate the feature. But overall the solution was straightforward, easy to implement, and reliable.


What instantiates a CacheBackendInterface? I am working on upgrading a module and there is a use statement

use Drupal\Core\Cache\CacheBackendInterface;

What is the point of using an interface like that?  Interfaces dont have actual code and this .module file doesnt inherit  from that interface.

Now when the module is in enabled i get

Error: Cannot instantiate interface Drupal\Core\Cache\CacheBackendInterface in /srv/www/mydev/current/core/lib/Drupal/Component/DependencyInjection/Container.php, line 265

and the only lines I can find relating to the cache interface are

\Drupal::cache('libraries')->deleteAll();
\Drupal::cache('libraries')->set($name, $library);

So I am confused as to why this is supposed to clear the cache?

Or is it that it is not supposed work and the latest version of the module is not complete yet?

You're using an old version of libraries module it seems. There was a core change that changed how the cache backends are defined.

Update it, clear caches and it should work.


Drush installation problem - Non-empty values for magic_quotes_gpc I have successfully installed and configured Drush and i am able to work with it.

Unfortunately, I am getting an error like this:

  The following restricted PHP modes have non-empty values:
  magic_quotes_gpc. This configuration is incompatible with drush.

I have tried this

magic_quotes_gpc = Off
magic_quotes_runtime = Off
magic_quotes_sybase = Off

in my php.ini and still I am getting the error. What could be the reason? How can I fix this?

Be sure you are editing the right php.ini file. As far as I recall the file used from PHP CLI could be different from the one used from PHP when running as Apache module; plus, Drush could use a completely different file, basing on its options, or settings.

To see which php.ini file Drush is using, use drush status. Drush can use a php.ini file that is saved in the $HOME/.drush, or /etc/drush directory; it can also use a drush.ini file present in the same directories. Alternatively, the path of a php.ini, or drush.ini file to use are taken respectively from the PHP_INI, and DRUSH_INI environment variables. (See the content of the README.txt file for more information.)

The function that checks the PHP settings in the php.ini file is _drush_environment_check_php_ini(), which contains the following code.

  // Test to insure that certain php ini restrictions have not been enabled
  $prohibited_list = array();
  foreach ($ini_checks as $prohibited_mode => $disallowed_value) {
    $ini_value = ini_get($prohibited_mode);
    $invalid_value = FALSE;
    if (empty($disallowed_value)) {
      $invalid_value = !empty($ini_value);
    }
    else {
      foreach ($disallowed_value as $test_value) {
        if (strstr($ini_value, $test_value) !== FALSE) {
          $invalid_value = TRUE;
        }
      }
    }
    if ($invalid_value) {
      $prohibited_list[] = $prohibited_mode;
    }
  }

On my computer, the directive for which the error message is reported is set with the following line.

magic_quotes_gpc = Off

When I execute dpm(ini_get('magic_quotes_gpc')); I get 0 as output.


Create a node programmatically on installing a module I would like to have my module to create new nodes (page) when being installed and removing these pages on uninstall.

I tried the following with no success in my mymodule.install file:

<?php

function mymodule_install() {

  $node = new stdClass(); // We create a new node object
  $node->type = "page"; // Or any other content type you want
  $node->title = "Your title goes jere";
  $node->language = LANGUAGE_NONE; // Or any language code if Locale module is enabled. More on this below *
  $node->uid = 1; // Or any id you wish
  $node->path = array('alias' => 'your_node_path'); // Setting a node path
  node_object_prepare($node); // Set some default values.

  // Let's add standard body field
  $node->body[$node->language][0]['value'] = 'This is a body text';
  $node->body[$node->language][0]['summary'] = 'Here goes a summary';
  $node->body[$node->language][0]['format'] = 'filtered_html'; // If field has a format, you need to define it. Here we define a default filtered_html format for a body field

  $node = node_submit($node); // Prepare node for a submit
  node_save($node); // After this call we'll get a nid

}

This code is cut n' paste from this page.

When I disable/enable the module, the page is not created (at least it does not appear in Content and in the node table of the database).

How should I do it please?

The problem is that install/uninstall and enable/disable are two separate things in Drupal.

When you enable or disable a module, hook_enable() and hook_disable() are invoked respectively.

When you install or uninstall a module, hook_install() and hook_uninstall() are invoked respectively.

If you want to keep your code in hook_install() / hook_uninstall() you'll need to disable the module, and then uninstall it at http://mysite.com/admin/modules/uninstall. Once you re-install it (which will also enable it), your code will be run.

It might be worth having a think if this code would be better served in hook_enable() / hook_disable(), but it will depend on your particular situation.


Using setAttributes() returns a fatal error I have the following code in a rule:

$imgpath = file_load(($node->field_image[LANGUAGE_NONE][0]['fid']))->uri;
$image = theme('image_style', array('path' => $imgpath, 'style_name' => 'thumbnail'));

$link = l($image, "node/$node->nid", array('html' => TRUE));
print $link;

I need to add a class to the thumbnail picture. I change the code as follows, but I get a fatal error about calling a member function on a non-object.

$imgpath = file_load(($node->field_image[LANGUAGE_NONE][0]['fid']))->uri;
$image = theme('image_style', array('path' => $imgpath, 'style_name' => 'thumbnail'));
$image->setAttribute("class", "AnyClass");

$link = l($image, "node/$node->nid", array('html' => TRUE));
print $link;

What am I doing wrong?

The error is simply caused from the fact you are trying to access a member function for something that is an object; in fact, theme_image_style() is returning a string, not an object. This is true also for Drupal 8.

  Returns HTML for an image using a specific image style.

To set attributes, just use the following code.

$imgpath = file_load(($node->field_image[LANGUAGE_NONE][0]['fid']))->uri;
$image = theme('image_style', array('path' => $imgpath, 'style_name' => 'thumbnail', 'attributes' => array('class' => array('AnyClass'))));

$link = l($image, "node/$node->nid", array('html' => TRUE));
print $link;

It works because theme_image_style(), as theme_image(), accepts a list of attributes to add to the image tag.


Webform no duplicate selections with multiple select lists I have a webform (7.x-4) with two selection lists, with the same content, like

A
B
C
D

so I would like to prevent users, who fill out this form, from using the same options in both lists.

i.e., if they check A they should get an error when they check A on the the second list.

what is the best way to do that?

You can do it by writing custom module. If you want to go for a contributed module, the Webform Validation module does that

This module adds an extra tab to each Webform node, allowing you to specify validation rules for your Webform components. You can create one or more of the predefined validation rules, and select which Webform component(s) should be validated against those. By using the hooks provided by this module, you can also define your own validation rules in your own modules.
The following validation rules are currently included:
Numeric values (optionally specify min and/or max value)
Minimum length Maximum length Minimum number of
words Maximum number of words Equal values on
multiple fields Unique values on multiple fields
Specific value Require at least one of two fields
Require at least one of several fields Minimum number of
selections required Maximum number of selections allowed
Exact number of selections required Plain text (disallow
tags) Regular expression Must be empty (anti-spam:
Hide with CSS) Words blacklist Must match a
username


Migrate media with alternative text I'm trying to import image with new media module on core 8.5.

I've a json source and on my .yml I've:

  field_media_image:
    target_id:
      plugin: migration
      migration: immagini
      source: fid

This works, immagini is another importer that imports files.

In the new media there is also an "alt" (mandatory) and "title" attribute on the media entity.
But if I try to add something like this, it doesn't work (alt_text is the correct source for alternative text). The media is created but is not referenced to the correct id:

  field_media_image:
    alt: alt_text
    target_id:
      plugin: migration
      migration: immagini
      source: fid

How should I pass the alt attribute to this field?
I also tried to use a syntax like:

  field_media_image:
    target_id:
      plugin: migration
      migration: immagini
      source: fid
  'field_media_image/alt': alt_text

But it doesn't work, the media is created but there is no reference to the correct id.

field_media_image/alt belongs in the immagini migration, not in the node migration.

In migration that creates the media item (destination plugin entity:media) you can map the media item's fields:

  # Image field see media_entity.bundle.image.yml.
  field_media_image/target_id: fid
  field_media_image/alt: field_file_image_alt_text/0/value
  field_media_image/title: field_file_image_title_text/0/value

  # Description field.
  field_description: field_image_description
  # Caption field.
  field_caption: field_caption

destination:
  plugin: entity:media

See https://www.previousnext.com.au/blog/migrating-drupal-7-file-entities-drupal-8-media-entities


How do I assign a view to a panel node in drupal I have a panel that shows a teaser of a bunch of nodes of a certain content type. I am attempting to replicate this for a new content type.

I have created a similar content type with the exact same fields. I have cloned the view(type = content pane) and changed the filter to the correct content type. I have now created a page of content type panel.

Question: How do I assign the view to that page(node)? Does it have something to do with display suite and the layout?

I am using Drupal 6.

EDIT: To put the above in another way:

I have a panel and I don't know how to apply a view to it. So I have my view that basically aggregates a bunch of nodes based on content type. I'm not sure how to add panel content to the panel. But the panel content being the query the view execute

If you are display the panel on a node then you need to add a variant of the node/%node page. In Drupal 7 you would

Edit the node_view (node/%node) page.
Press Clone to create a variant of your current page.
Under Selection rules add Node:type and select your new content type.
Ensure that the new variant is above your current variant, or add Selection rules to your current variant too.
In your new variant under Content replace the old View with the new View.

Note: If the only change to the View (and Page) is the Content type then you could have used the Content type of the node being viewed as a Contextual filter on the View. Then there would be no need for a Panel variant or another View.


Is it possible to update module provided configuration schema in an hook_update_N()? So I have a custom module with a module.schema file, defining a configuration schema for that module, not talking about database/field schema.

module.settings:
type: config_object
label: 'Settings for Module'
mapping:
  my_ids:
   type: sequence
   label: 'Ids from config'
   sequence:
    type: string
    label: 'ids'

I provided a module.settings file like:

my_ids:
 - 1
 - 2
 - 3
 - 4

As you can see, my mistake is that I needed a type: int in my schema not type: string.

On the configuration synchronization page I see Drupal has taken care of this and corrected this in its active configuration, by setting string values for "my_ids", and of course producing a diff between the staged and active configuration. The active conf has now strings:

my_ids:
 - "1"
 - "2"
 - "3"
 - "4"

I would like to update the schema of that configuration to int, without re-installing that module.Is this possible.

Tried to write to schema service in an update hook like:

  $name = 'module.schema';
  $path = '/home/user/Drupal/docroot/modules/module/config/schema';
  $source = new FileStorage($path);
  /** @var \Drupal\Core\Config\ExtensionInstallStorage $active_schema */
  $active_schema = \Drupal::service('config.storage.schema');
  $active_schema->write($name, $source->read($name));

But it turns out that "Write operation is not allowed." and that does not sound like a surprise.. :)

So is there another solution for this schema update, except re-installing the module?

Thank you.

Well it turns out I spent some time here because I tried to update the schema file, by typing int not integer LOL.
All I needed was integer and clear caches after all :)


How to remove link from around the rendered entity inside view header I use rendered entity inside my view header. It is a page. When the view displays, the rendered page title in the header has link around it.

I've tried to prepare my own display mode for page type of content and remove link items from them, moved them to hidden. Nothing helped.

Any suggestions appreciated.

Here's the How:

 {% set headline %}
   {{ label }}
 {% endset %}
 {{ headline|striptags }}

as found here


After adding new content type, drupal (7) returns to same window without any notification As in the title, every time I add a new content type Drupal returns to the same page and provides no notifications.

Also, the overlay window is full screen width. Any ideas? No error logs.

What do you mean by adding content type?
It Is normal that drupal return to the front page after creating a new content type...

Do you mean creating a node?Where does drupal returns?


Why my hook_filter not work in Drupal 6? I'm having a hard time trying to make my hook_filter work on Drupal 6.

Here's my filter function.

function arb_question_filter($op, $delta = 0, $format = -1, $text = '') {

  drupal_set_message($op);

  switch($op){

  case 'list':
    return array(t('My filter name here'));

  case 'description':
    return t('Description my filter here');

  case 'settings':
    break;

  case 'no cache':
    return false;

  case 'prepare':
    return $text;

  case 'process':
    return preg_replace("|\[support!\]|i", 'hello world', $text);

  default:
    return $text;
  }
}

I can see my filter name on the filter option below the content textarea, but when I add my testing for example " this is a test [support!]"

When I view the content, it just show [support!], which is suppose to show "hello world" according to my filter.

I did put a drupal_set_message($op) on my hook filter, but it seems to only show "list" not process or prepare or the rest of the $op.

What I'm doing wrong?

Welcome your advice

Given that you are only seeing 'list', I would make sure that your filter is added to an existing Input Format (check at admin/settings/filters and click on configure next to the appropriate input format) and also that all caches are cleared.  Sometimes if you start entering/coding a filter and it runs before you've got all the kinks worked out, the case 'no cache' gets in the way and stores the initial/wrong result.  Until you are sure of everything, you may want to change that to return TRUE; as well.


How to hide some administer option from all users? I want to hide some administer options (such us: Actions, File system, etc) from all users, including admin (user='1').

How can I do that?

Thanks

User #1 is special.  This user bypass all access control, so the only way to make sure that no user have access at this level is to disable user #1.  However, disabling user #1 is not a good idea.  At one point, you may need to have access to a special user account that can access all areas in order to fix some serious problem with your site - and in some cases, the all-powerful user #1 is the last resort.

However, you can approach this by creating a second admin user account (name it lesser_admin) and give this user account all the administration rights except Administer users and other rights you want to withhold.  You then stop using user #1 as admin and instead log on as lesser_admin when you (or someone else) want to perform admin tasks.

To make sure, you may give user #1 as very long and impossible to remember password and  write this password down and put in a sealed envelope in a bank vault.  That way, neither you or anyone will have access to the user #1 account.  However, when the day comes when you regret doing this, you can go to the bank vault and retrieve the envelope.


Autosave form fields example I have a form with 3 textareas and some other fields. I would like to put in an autosave functionality and found the Autosave module. But that seems to be specifically for editing nodes and is also too advanced for what I need. I just need to save the contents every 3 seconds or so, no revision support or anything fancy like that.

I'm thinking about a silent form submit that the user doesn't notice or a specific page that receives the contents of the form posted with JavaScript.

But something like this must have been done before, so is there an example or some pointers on how to implement this? I'm using Drupal 7.

Try the Save Form State module. Here is a quote about it (from the module's project page):

... provides a way to autosave data entered in any Drupal form without actually submitting the form, which helps if the user is writing an article or a comment and the browser crashed or the power went down, or even if the window was closed accidently.
It works using the jQuery Sisyphus plugin, which is a lightweight jQuery plugin that uses Local Storage to save form fields every specific time span that is configurable from the module settings page.


Using CCK Date with Date Repeat on Calendar I have a content type named Event.  It has a field name Date, which uses the jQuery pop-up with Repeat options.  It uses the To and From date, both of which are required.  The time zone conversion uses the Site time zone.

On the Calendar view, I've modified it to use as the Argument, the Date field from the Event content type.  This is also added to the Fields, as it's required to match the Argument.  On Filters, I've got Node Type=Event and Published=Yes.

Now, I create an Event and set the Date field for 3/17/2011 03:00 pm to 3/17/2011 05:00pm.  I then put on the Repeat a repeat for Every Day until March 20, 2011, with no exceptions or anything else.

Immediately after submitting it, I see that the node display only has repeats for March 17, March 18, and March 19.  This is also reflected on the Calendar.  But, then when I open the node in edit mode, it says the Repeat Until is set to March 21 now.  If I save it now, March 20 shows up on the node display, but now the edit form shows March 22.

Any ideas what might be going on?  I've tried playing with the time zone settings, and no luck.  Any help would be appreciated!

Here is a very recent issue thread that seems to match your problem:

http://drupal.org/node/1014664

The issue is very recent and it looks like a working patch has been rolled into the newest version of the module, so a quick update of the Date module, (specifically the Date-Repeat submodule) should fix you up.


When building a SelectQuery, why can't I use the alias from addExpression() in a condition()? I'm trying to search for nodes with field values that satisfy a mathematical formula. I can build a SelectQuery that will find all nodes and return the value of the computation for each result using addExpression(), but I cannot seem to accomplish the final step of only returning the correct nodes using condition().

Here is a simplified example:

$myquery = db_select('node', 'n');

// Use innerJoin() since node field values are stored in separate tables
$myquery->innerJoin('field_data_field_number_one', 'one', 'n.nid = one.entity_id');
$myquery->innerJoin('field_data_field_number_two', 'two', 'n.nid = two.entity_id');

// Add basic node fields and the two value fields so they will be available in the results
$myquery->fields('n');
$myquery->addField('one', 'field_number_one_value', 'one');
$myquery->addField('two', 'field_number_two_value', 'two');

// Add the computation using addExpression()
// In this example the computation has been reduced to a simple sum
$myquery->addExpression('(one.field_number_one_value + two.field_number_two_value)', 'sumcalc');

// Only return nodes of type desired_type
$myquery->condition('n.type', 'desired_type');

// The query will execute properly without the following line
$myquery->condition('sumcalc', 5, '<');

$prex = $myquery->preExecute();

if ($prex) {
  $qresult = $myquery->execute();
  foreach ($qresult as $qrecord) {
    // Without the erroneous condition above, this line will print each result
    // and each result will contain the value of the calculation added via addExpression()
    dpm($qrecord);
  }
}

If I try to execute the code above, I get the following error:

PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'sumcalc' in 'where clause'

What am I doing wrong here?

The MySQL you're trying to build is invalid - you can't refer to an expression field in a WHERE clause.

You need a HAVING clause for that, which in Drupal-ese is:

$myquery->havingCondition('sumcalc', 5, '<');


How can I see the created date of a node in a view? How can I see the created date of a node in a view? I don't see it as an option.

choose revision, created date as the field to add in the view


Form error messages appearing in the middle of the form I've got a hopefully EASY question. I'm using a Drupal Commerce-based form in my Drupal 7 site. The form has some required fields. When a user clicks the button to 'continue registration' at the bottom, and they hadn't filled out all the required fields, the form, of course, throws error messages in an error block that tells the user certain fields are required.

But the error messages are not showing up in the correct location. Please see the image below. The main error that there are problems with the form is displaying correctly at the top of the form, but then the problems with individual fields are displaying in THE MIDDLE OF THE FORM. Obviously, not ideal.

So, how do I make all the errors display at the top of the page?

I've already checked my tpl file for the page and the $messages variable is at the top.

This is actually due to the way the checkout module has been written (and is in line with recommended best practices for checkout form submission). The idea is to place the actual error message as close to the form element that generated it to reduce confusion in correcting errors on the form. There is no simple way to undo this behavior in the checkout module.

However, the fact that these are appearing halfway down the page is a good thing - what you really need to do is figure out what it is about your CSS that's causing the messages to float weirdly relative to your form elements.


Allow tinymce in WYSIWYG to load different skins per content type I want to user a different default tinymce editor styles per content type. I basically want to use a different default font in the editor area of tinymce per content type.

I have discovered that the editor of tinymce has some default settings that are not configurable through the WYSIWYG module, but it can by modifying the file
jscripts/tiny_mce/themes/advanced/skins/default/content.css

However, that would apply to all content types.

Is there a way to set a skin for a content type?

This would be a start, but does not apply it per content type:

/**
 * Implements hook_wysiwyg_editor_settings_alter().
 */
function custom_wysiwyg_editor_settings_alter(&$settings, $context) {
  if ($context['profile']->editor == 'tinymce') {
  $settings['skin'] = 'o2k7';
  $settings['skin_variant'] = 'silver';
  }
}

I think you're on the right track, but from memory, I don't think you'll have info about the content type or the node form in the $settings and $context variables, As Darvanen suggests.

I'd implement hook_form_alter() to match node forms, then read the content type being used, and store it as a static variable through drupal_static() function. That way you can access the content type info from the snippet you pasted above, using that same drupal_static() function, and then choose which skin to use.


views and contextual filter with entity reference to current user I have a view that I need to filter based on the current logged in user, however a secondary entity reference is in-between the two.  Pretty sure I need to add in PHP contextual filter code but not exactly sure what is needed.

Scenario:

inventory has an entity reference to retail_location.
retail_location has an entity reference to users.
I need to display inventory based on the retail_location of the logged in user.

D7.

Was able to get it working using the following code, it does however only allow for one retail location, which is all I need for this scenario.

  global $user;
  $query = new EntityFieldQuery;
  $query->entityCondition('entity_type', 'node')
      ->entityCondition('bundle', 'rnm_principal')
      ->fieldCondition('field_principal_retailer', 'target_id', array($user->uid));
  $results = $query->execute();
  return current($results['node'])->nid;


Fallback values for OG Meta Tags / hiding some unused OG fields I'm using D7 and the Open Graph Meta Tag module to allow open graph meta tags to be set for various content types.

With the OG:summary field if not specified it falls back to the first 200 characters of the article body. Can anyone suggest how to change this fallback behaviour so that it instead uses a different field from the content_type as the fallback if not set?

Also is there a good way to hide some of the OG tags that are not going to be used? (location, type and contact sections specifically).

Also is there a good way to hide some of the OG tags that are not
  going to be used? (location, type and contact sections specifically).

You can use common css selector to do that:

.form-item-metatags-ru-og\:type-value,
.form-item-metatags-ru-og\:latitude-value,
.form-item-metatags-ru-og\:longitude-value,
.form-item-metatags-ru-og\:street-address-value,
.form-item-metatags-ru-og\:locality-value,
.form-item-metatags-ru-og\:region-value,
.form-item-metatags-ru-og\:postal-code-value,
.form-item-metatags-ru-og\:country-name-value,
.form-item-metatags-ru-og\:email-value,
.form-item-metatags-ru-og\:phone-number-value,
.form-item-metatags-ru-og\:fax-number-value {
  display:none;
}


Drush affected by El Capitan? After updating my Mac from Yosemite to El Capitan, I am noticing drush does not run properly on any of my sites. Doing a simple:

drush status-report

Command core-requirements needs a higher bootstrap level to run - you[error]
will need to invoke drush from a more functional Drupal environment
to run this command.
The drush command 'status-report' could not be executed.             [error]
Drush was not able to start (bootstrap) the Drupal database.         [error]
Hint: This may occur when Drush is trying to:
  * bootstrap a site that has not been installed or does not have a
configured database. In this case you can select another site with a
working database setup by specifying the URI to use with the --uri
parameter on the command line. See `drush topic docs-aliases` for
details.
  * connect the database through a socket. The socket file may be
wrong or the php-cli may have no access to it in a jailed shell. See
http://drupal.org/node/1428638 for details.

This is now happening on all my Drupal sites locally, and yes, I am at the root of the Drupal install directory where this command would normally work. I've updated Composer and made sure that stable Drush 7.0.0 is running. Has anyone else come across this behaviour?

Fortunately, I made a full bootable backup of Yosemite so I will 'simply' roll my Mac back to how it was setup prior to the so-called upgrade of El Capitan. Normally I wait at least a month or two before upgrading to Apple's latest release but I got reckless and now this is the price. Sometimes I just want to switch to Ubuntu full time and say goodbye to the Mac OS.

Using:

Mac OS 10.11
MAMP PRO 3.2.1
Little Snitch 3.6 (mentioning this because of this thread)
Composer version 1.0-dev
Drush 7.0.0

2015-10-17 - Update #################################

First off, thank you for the folks who commented on the original issue. I have decided for better or worse to try again. I updated Yosemite, where Drush, Mamp and everything was working fine, to El Capitan.

I removed drush by editing the .json file for composer by removing the lines for drush and then running composer global update which then finished the job by removing the actual drush files. Composer is up to date, and then drush7 was installed successfully with

composer global require drush/drush:7.0.0

However, once I navigate to a directory with a Drupal install, I am told after running some commands that 'No drupal site was found' and yet, the commands seem to complete regardless. Here are some examples:

drush cron results in the following:

 No Drupal site found, only 'drush' cache was cleared.
 'all' cache was cleared.

drush updb results in the following:

 No database updates required
 No Drupal site found, only 'drush' cache was cleared.
 'all' cache was cleared.

drush dl hacked results in the following:

 Project hacked (7.x-2.0-beta5) downloaded to
 /Users/[me]/Sites/[path]/drupal/sites/all/modules/contrib/hacked

Note there was no 'drupal not found' message on the last command. So, my concern is why the 'No Drupal site found' message is showing up. Here is what my .bash_profile looks like:

export PATH="/Applications/MAMP/bin/php/php5.4.42/bin:$HOME/.composer/vendor/bin:$PATH"
export PATH

export DRUSH_PHP='/Applications/MAMP/bin/php/php5.4.42/bin/php'

export PATH=/usr/local/bin:$PATH

None of these settings were changed from how it was in Yosemite. If anyone can shed some light on these issues, I'd really appreciate it. Thanks again.

Homebrew

Install Drush by Homebrew:

brew install drush

via Phar binary

sudo wget -O /usr/local/bin/drush http://files.drush.org/drush.phar
sudo chmod +x /usr/local/bin/drush


Allow specific HTML tags inside a text field of a custom content type using CKEditor I would like to add a new content type with a field which supports some HTML tags. So far, I added a text editor format and there I chose CKEditor as the editor and edited the list of allowed tags according to what I want to achieve. Then I added a new content type with a field of type formatted text. If I now add new content, CKEditor shows up where I expect it, but when I edit the source code and enter, for instance, an <h2> tag, it becomes a <p> tag after saving. The specific problem I'm facing is that I can't figure out how to "connect" an editor format to a field and make it selectable for the one who adds a field to a content type (for example inside the drop down menu where one can select the field type). Do you know any good documentation or tutorial which deals with this topic? Thanks in advance for your help!

I can't figure out how to "connect" an editor format to a field and
make it selectable for the one who adds a field to a content type.

The text formats are shown in order here:
/admin/config/content/formats
The format at the top of the list is the default format.  To change the order of the formats, drag the arrow icon on the leftmost side and then press save.
Users can only see formats for which they have permission. The roles with permission are listed in the Roles column of the table at /admin/config/content/formats.  To change the permissions, click "Configure" for the relevant format and add the correct roles.


struggling with template_preprocess in module I know there is a lot of documentation on this function on google, but I am still not able to get this hook to run for my holidayautosxml_carsearch_form. Could anyone advise on what I am doing wrong.

The Theme function is running fine. If I put exit(); in that function I get white screen of death. However if I put exit(); in the template_preprocess function nothing happens.

I have cleared all the caches.

my template is called holidayautosxml-carsearch.tpl.php and it is located in the module folder.

Here is my theme function

function holidayautosxml_theme(){
return array(
            'holidayautosxml_carsearch' => array(
                    'template'=>'holidayautosxml-carsearch',
                    'render element'=>'form',
            ),

    'halocationresults' => array(
        'template' => 'halocationresults',
        'variables' => array('haresults' => NULL,),
    ),
    'hapriceslist' => array(
        'template' => 'hapriceslist',
        'variables' => array('haprices' => NULL,),
    ),
);
}

Here is my template_preprocess function

function template_preprocess_holidayautosxml_carsearch(&$variables){

$variables['holidayautosxml_carsearch'] = array();
$hidden = array();
//Provide variabels named after the form keys so themers can print each element independently.
foreach (element_children($variables['form']) as $key){
    $type = $variables['form'][$key]['#type'];
    if ($type == 'hidden' || $type == 'token'){
        $hidden[] = drupal_render($variables['form'][$key]);
    }
    else{
        $variables['holidayautosxml_carsearch'][$key] = drupal_render($variables['form'][$key]);
    }
}
//Hidden form elements have no value to Themers. no need for seperation.
$variables['holidayautosxml_carsearch']['hidden'] = implode($hidden);
//collect all form elementsto make it easier to print the whole form
$variables['holidayautosxml_carsearch'] = implode($variables['holidayautosxml_carsearch']);
}

and here is my form function

function holidayautosxml_carsearch_form($node, &$form_state){

    $country_list = _get_country_list();
    $form['country'] = array(
            '#type'=>'select',
            '#title'=>'Select Country',
            //'#description'=>'Select the country where you want to collect the car',
            '#options'=>$country_list,
            '#ajax' => array(
                'callback' => 'update_officename_autocomplete',
                'wrapper' => 'haofficename',
            ),
    );

    $citylist = _get_city_list($form_state['values']['country']);

$form['officename'] = array(
    '#type'=>'select',
    '#title'=> t('Location'),
    //'#description' => t('Select the location where you want to pick up the car'),
    '#required' => TRUE,
            '#options' => $citylist,
            '#width' => 50,
            //'#autocomplete_path'=>'location-autocomplete',
            '#prefix' => '
',
            '#suffix' => '
',
);

    if (!empty($form_state['values']['country'])){
        $form['officename']['#autocomplete_path'] = 'location-autocomplete/' . "{$form_state['values']['country']}";
    }
    $dateformat = 'd-m-Y H:i';
    $form['datefrom'] = array(
        '#required'=>TRUE,
        '#type'=>'date_popup',
        '#date_format'=>$dateformat,
        '#title'=>t("Pickup date"),
        //'#description'=>t("The date you are picking up the car"),

        );

    $form['dateto'] = array(
        '#required'=>TRUE,
        '#type'=>'date_popup',
        '#date_format'=>$dateformat,
        '#title'=>t("Dropoff date"),
        //'#description'=>t("The date you are bringing the car back"),
    );

$form['submit'] = array(
'#type'=>'submit',
'#value'=>'Search Now',
'#submit'=>array('holidayautosxml_carsearch_form_submit'),
);

return $form;
}

I think it should be  holidayautosxml_preprocess_holidayautosxml_carsearch(&$variables).
Basically the syntax is [yourModuleName|yourThemeName]_preprocess_[themeFunctionName](&$variables).

Also you need to flush your cache after you make the change.


Form loaded with ajax call not having autocomplete enabled I have a form (loaded by obiumap function) that have a section loaded ( by function obiumap_addobj() ) with a $.ajax call from jQuery script (addobj.js) by clicking a button (addobj_btn). This new section is loaded in an

existing div (addobj-container) but without autocomplete functionality and also without default_value.

This is main form:

function obiumap($form, &$form_state) {
drupal_add_js(drupal_get_path('module', $this->modName) . '/addobj.js');
global $user;

$form=array();
$form['uid'] = array(
'#type' => 'hidden',
'#title' => 'uid',
'#default_value' => '3',
'#id' => 'uid',
);
$form=array();
$form['name'] = array(
'#type' => 'textfield',
'#title' => 'name',
'#id' => 'name',
);
$form['addobj_btn'] = array(
     '#type' => 'button',
     '#value' => t('Add new objects'),
     '#id' => 'addobj_btn'
);
$form['addobj-container'] = array(
        '#markup' =>  '

'
);
die(drupal_render_children($form));
}

This is section definition loaded via ajax:

function obiumap_addobj($form, &$form_state){
global $user;
$form=array();
$form['uid'] = array(
'#type' => 'textfield',
'#title' => 'uid',
'#default_value' => '10',
'#id' => 'uid',
);
$form['fldset_addobj'] = array(
'#type' => 'fieldset',
'#title' => t('Add new object'),
'#collapsible' => TRUE,
'#collapsed' => FALSE,
);
$form['fldset_addobj']['objname'] = array(
'#type' => 'textfield',
'#id' => 'objname',
'#title' => t('Object name'),
'#autocomplete_path' => 'obimap/obiumap_addobj',
'#required' => TRUE,
);
 $form['fldset_addobj']['submit'] = array(
'#type' => 'submit',
'#value' => 'Add object',
'#id' => 'addobj_btn'
);
die(drupal_render_children($form));
}

and this is addobj.js

function addItems(arg1, arg2) {
jQuery(document).ready(function() {
jQuery('#addobj_btn').click(function() {
var formURL = 'obiumap_addobj';
jQuery("#obiumap").submit(function(){
 return false;
 });
    jQuery.ajax(
    {
        url : formURL,
        type: "GET",
        data : { uid: jQuery('input[name=uid]').val() },
        success:function(data, textStatus, jqXHR)
        {
            jQuery('#addobj-container').html(data);
            console.log("###### Drupal.attach #####");
            Drupal.attachBehaviors("#addobj-container");
        },
        error: function(jqXHR, textStatus, errorThrown)
        {
        }
    });

});

});
}

I really need autocomplete for that field but I don't now how to activate it.

If you want Drupal's autocomplete, you need to modify form using Form API '#ajax'. If you are doing it with your custom scripts, Form API will not know that field really belongs to your form, and will not handle field's calls.1

The way you should do it is:

In your form building function, create element with '#ajax' property, that will be responsible for loading your form part, or add it to existing element.
Also in your form building function, add an if that will check triggering element ($form_state['triggering_element']), and if that was your button, add entry in $form_state that new section should be visible.
If there is an entry mentioned in 2., output form part you want to be loaded with AJAX.
Use AJAX callback function only to select and return proper part of the form.

1 Simplified explanation, of course.


Programmatically create a new node from an existing NID Essentially I want to take a node and duplicate it. Take a node ID and programmatically create a copy of the node.
I want to be able to edit the newly created node, and maintain the data on the old node.

On entities, you can use is_new to signify a new entity to save, but you still need to unset nid (iirc), vid, and tnid manually. This saves unsetting log.

$new = clone $node;
$new->is_new = true;
unset($new->nid);
unset($new->vid);
unset($new->tnid);
node_save($new);

Interestingly, the node_clone module incorrectly sets the properties to null, which is significant for databases that support NULL and DEFAULT separately (e.g. PostgreSQL).


Content list menus translation I have a multilingual site and the content list view can be accessed like this:
htttp://www.website.com/{country_code}/{language_code}/admin/content
There are only two administration page languages: English and Japanese, and the
toolbar is displayed only in these 2 languages regardless the language_code.
However, the content list menus are displayed in according to the language_code.
For example, in case of French (fr) it looks like this:

What I want to do is to display content list menus only in the administration page language.
So I want that the language_code in the path to be ignored and I have the menus
shown only in English or Japanese.
Could you please advise some approaches to solve the issue?

This can be changed on the Detection and selection page of the Language settings: /admin/config/regional/language/detection.
This page lists the detection methods, and by default, Drupal 8/9 prioritizes the path.
But, here you have two options.
Option 1: You can enable User (Follow the user's language preference) and then drag User above Path, which should give the admin pages in the admin language. This is simple, but the drawback to this approach is that users on the site will see content based on the language set in their account, not the site, which may not be what you want.
Option 2: You can enabled Account administration pages and then drag Account administration pages above Path.  This will create a new setting on the user account edit page to set the admin language, so you may have to check all the admin accounts and set the language appropriately.  This approach is more complex than the first, but limits the change to admin content only, which is probably what you want.


Can we use panels for header and footer? I have a few different top menus which I want to display in certain contexts, and ideally this should go in the header region. However, I have found that Panels can only take over the content region, and the right and left sidebars.

Is there a way to make panels for the header (and footer) regions?

EDIT:
I am using the Bootstrap theme, so I'm not sure if this plays well with the Panels Everywhere theme.

Panels takes over the "Content" region.

Panels everywhere takes over the entire page, and is the module that does what you want.

Some themes are listed on the PE page as "compatible", but all that means is that they ship with appropriate templates, which makes it easier to get started.

You can use any theme you want with PE, but you will likely want to provide your own site-template as alternative to the regular page.tpl.php which PE will disregard. Look at one or two of the themes that are listed on the PE page and their use of template to get started.


Image in View with Lightbox2 formatter lacking alternative text tag I have a page view for image gallery. It has only 1 Photo field of Photo which has a field of type Image. In view it use "Lightbox2: lightshow: small-square -> large" as formatter. small-square is a custom image style.

The rendered page doesn't show any alt tag:

<img typeof="foaf:Image" src="http://www.example.com/sites/default/files/styles/small-square/public/6486388587_61846b6d84_1323732945.jpg" width="240" height="240">

I need to add alt tag to images. What do I have to change?

My drupal installation has these versions:

Drupal 7.10
Lightbox2 7.x-1.0-beta1
Views 7.x-3.0-rc3

looking at Lightbox2 modules's file lightbox2.formatter.inc it seems that alt tab should be forced to show, using image title.

  // Set up the title.
  $image_title = $item_data['description'];
  $image_title = (!empty($image_title) ? $image_title : $item_data['title']);
  $image_title = (!empty($image_title) ? $image_title : $item_data['alt']);
  if (empty($image_title) || variable_get('lightbox2_imagefield_use_node_title', FALSE)) {
    $node = node_load($node->nid);
    $image_title = $node->title;
  }

  $image_tag_title = '';
  if (!empty($item_data['title'])) {
    $image_tag_title = $item_data['title'];
  }

  // Enforce image alt.
  if (!empty($item_data['alt'])) {
    $image_tag_alt = $item_data['alt'];
  }
  elseif (!empty($image_title)) {
    $image_tag_alt = $image_title;
  }  $image_tag_alt = '';
  if (!empty($item_data['alt'])) {
    $image_tag_alt = $item_data['alt'];
  }
  elseif (!empty($image_title)) {
    $image_tag_alt = $image_title;
  }

So... where is the error?

For people coming to this page...I wanted to use the title of the node containing the image as the caption on the lightbox2 image, which I was displaying in a view, but I didn't want to modify the module, which I think is the issue with the above technique.

What I ended up doing was making my own image formatter.  Basically I cut and pasted the hook_field_formatter_info and hook_field_formatter_view from the lightbox2 module and modified them.   There may be a better way, but it works, solved my problem, and I can upgrade lightbox2 without worrying about breaking my site.

/**
 * Implementation of hook_field_formatter_info().
 */
function mymod_field_formatter_info() {
  $formatters = array();
  if (module_exists('image')) {
    $formatters["mymod_custom_formatter"] = array(
      "label" => "Field formatter for my Photos",
      "field types" => array("image"),
    );
  }
  return $formatters;
}

/**
 * Implements hook_field_formatter_view().
 */
function mymod_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();
  $pieces = explode('__', "lightbox2__lightbox__thumbnail__large"); // forced this, you could do something trickier, but it solved my issue

  ... untouched ...
  foreach ($items as $delta => $item) {
    // here is the bit I added which sets the node title to be the image caption
    if ($entity_type == 'node') {
      $item["title"] = $entity->title;
    }

    $uri = array(
    ... etc ...


How to disable default extension validation in Drupal's #managed_file Form API element? I wrote validation function that tests file's mimetype. I commented out my old validators to avoid validation by extension:

'DownloadFile' => array(
  '#type' => 'managed_file',
  '#title' => t("Download"),
  '#title_display' => 'invisible',
  //'#description' => t('Allowed extensions: pdf zip exe.'),
  '#upload_validators' => array(
    //'file_validate_extensions' => array('pdf zip exe'),
    'file_validate_size' => array(variable_get('mymodule_image_size', 2 * 1024 * 1024)),
  ),
  '#upload_location' => 'public://mymodule/download',
  '#default_value' => $item->DownloadFile,
  '#required' => TRUE,
  '#theme' => 'preview_upload',
),

Now when I'm trying to upload exe, I get:

  The specified file putty.exe could not be uploaded. Only files with the following extensions are allowed: jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp.

Now, I will have files without extensions there. And with extensions I cannot predict. And all I want sometimes is to test for a proper MIME type match, not even an exact mimetypes sometimes. So, how can I get rid of extension validation and turn it into "everything goes"?

I managed to find issue that seemed to be about this problem, but it tells to unset($element['#upload_validators']['file_validate_extensions']); - does not make sense to me as I'm creating brand new array and this isn't set at all.

I tried to use #process property to add a function that will unset default validators later, like shown there in issue,  but dpr($element) shows there is nothing to unset:

[#upload_validators] => Array
    (
        [file_validate_size] => Array
            (
                [0] => 2097152
            )

    )

The answer comes from the following code used by file_save_upload().

  if (isset($validators['file_validate_extensions'])) {
    if (isset($validators['file_validate_extensions'][0])) {
      // Build the list of non-munged extensions if the caller provided them.
      $extensions = $validators['file_validate_extensions'][0];
    }
    else {
      // If 'file_validate_extensions' is set and the list is empty then the
      // caller wants to allow any extension. In this case we have to remove the
      // validator or else it will reject all extensions.
      unset($validators['file_validate_extensions']);
    }
  }
  else {
    // No validator was provided, so add one using the default list.
    // Build a default non-munged safe list for file_munge_filename().
    $extensions = 'jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp';
    $validators['file_validate_extensions'] = array();
    $validators['file_validate_extensions'][0] = $extensions;
  }

In your case you should use the following array.

  'DownloadFile' => array(
    '#upload_validators' => array(
      'file_validate_extensions' => array(),
      'file_validate_size' => array(variable_get('mymodule_image_size', 2 * 1024 * 1024)),
    ),
  );

In that way $validators['file_validate_extensions'] is set, but $validators['file_validate_extensions'][0] is not. As result, the code will not set $extensions, and the following code will not be executed either.

  if (!empty($extensions)) {
    // Munge the filename to protect against possible malicious extension hiding
    // within an unknown file type (ie: filename.html.foo).
    $file->filename = file_munge_filename($file->filename, $extensions);
  }

The code has a strange way to check if the list is empty; it assumes the array is empty of there isn't an item with index equal to 0.
I would have rather used the following one, which would not make assumptions about the lower array index being used.

  if (isset($validators['file_validate_extensions'])) {
    if (empty($validators['file_validate_extensions'])) {
      // If 'file_validate_extensions' is set and the list is empty then the
      // caller wants to allow any extension. In this case we have to remove the
      // validator or else it will reject all extensions.
      unset($validators['file_validate_extensions']);
    }
    else {
      // Build the list of non-munged extensions if the caller provided them.
      $extensions = array_shift($validators['file_validate_extensions']);
    }
  }


Using content type fields within page.html.twig I am new to Drupal 8, and relatively new to Drupal templating in general.

Here's what I am trying to do:
I have a content type, called "Property" with a "header_color" field.  When I add a property, I set the color that I want for that property's header.
When I then navigate to that node, the background color of the page's header would be whatever I set the color to.

My understanding is that this needs to take place in page.html.twig, and that there is a way to grab the data from the content type and use it within page.html.twig, using:

{{ node.field_header_color.value }}.

This is the tag I have in my page.html.twig:

<header id="header" class="header" role="banner" aria-label="{{ 'Site header'|t }}" style='background-color:{{ node.field_header_color.value }}'>

When I inspect it in the Chrome Dev, it shows:

"style='background-color:''"

Can someone give me some guidance on what I am doing wrong here?

I am using Drupal 8.6.4

In the preprocess_page set up the variable

if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) {
 $variables['bg_color'] = $node->field_header_color->value;

}
     and use this in ur twig file

<header id="header" class="header" role="banner" aria-label="{{ 'Site header'|t }}" style='background-color:{{bg_color}}'>


Is using Views overkill to display a single image above the footer of all pages on my site? I would like to add a banner type image above the footer. I'd like it to be present on every page. Would adding a gallery, and then creating a block using Views be overkill for just a single image?
Should I just include it as a block and then add the image via the ckeditor? Or should I add a content type and field specific for this block/image?

If you need a static image, just use a block.  If you want a slideshow or something, Views is better.

Unless your site is going to get a huge amount of traffic, I wouldn't worry about the performance differences between these two options.  The main concern is how much harder is it going to be for you to set up a view versus setting up a block.

I don't know why you would created a content type and field specific for the image.  If you just want to stick a piece of content in the same place on every page, that is one of the things that the blocks system was designed to do.


Drupal CKeditor image-upload plugins don't delete unused files In my Drupal travels, I've used a number of CKeditor instant image-upload plugins; IMCE, Media, and another one (don't recall the name).

The three of them doesn't delete unused files (Like Drupal imagefield does automatically) and thus I sometimes need to upload the same file with them 6 or seven times and these duplicated can whey much gb's in a cumulative way.

Is there any way to make one of the CKeditor instant image-upload plugins delete the files automatically? or at least? Have you cam across something that does delete unused image files automatically? Thanks,

Try to check out the Fancy File Delete module. One of the things it can do based on the module page is

  Deleting unused files from the whole install that are no longer attached to nodes & the file usage table. AKA deleting all the orphaned files.

I think this would require a manual process of deletion but this may solve the issue of deleting orphaned or unused duplicate images in your site.


Drupal 7: Is hook_update_N() called when a module is updated between minor versions? Say I'm trying to update a module from version 7.03 to 7.04, and version 7.04 has a function called mymodule_update_7704() which updates the module's schema.

If I go to the modules page and update mymodule, will the mymodule_update_7704() function run, and update the module's schema?

Also, if the above is correct and mymodule_update_7704() does run, will the user have to click to run the update, or is it silent?

Sorry if this question seems elementary, I just can't test this without releasing my module, and I'd rather know first before I do release.

hook_update_N is only invoked when:

The update process is running (via /update.php, drush, etc).
The current schema version for the module is less than the update hook's schema version (The N in hook_update_N).

No updates are run when you visit the modules admin page, the process will always be invoked by an administrator (or perhaps an automated task, but never silently/automatically by Drupal itself).

As an aside (in case it comes to bite you at some point), no update hooks are invoked when installing a module, only for already-installed modules during the update process. The update hooks are only for getting older installations up to speed with what the current release offers upon installation anyway.

As another aside, your schema numbering looks a bit suspect if you want to stay within common practice; have a read through the hook_update_N docs for more info, but your numbering should probably be in the 7100s at this point.


File_managed URI change not working Is there a way i can make file_managed URI changes in the database?

I the database i have a list of files and there is append a _1 or _2 to the URI file name.i wanted to clean these up and remove the _number so there will be only one file but when i change it i get an error unable to write row duplicate entry for uri key.

Doing this directly in the database can be messy given the way Drupal abstracts its managed files. It is usually better to try and find a solution that works with the Drupal file API directly so you're not forgetting some entry somewhere and leaving extra cruft in your database. You could roll your own solution using the file API and file_delete() but I would suggest that you're better off doing this using an interface like IMCE and combining that with a solution like this module:
http://drupal.org/project/upload_replace
which would resolve this problem for you going forwards:

The problem with drupal is if you have a file called "mydoc.doc" upload it to a node, then make changes to "mydoc.doc" and upload the newer version, the newer version will be renamed to "mydoc_0.doc" because at the time of upload the old file was blocking the desired path name.
This module solves that problem by swapping the names of the older and newer file so that the newly uploaded file will retain its original name.


Why is my Language Switcher Dropdown block NOT displayed in my site? I have a multi-language site in Drupal 7. And I use the Language Switcher Dropdown module in it. I enabled all the settings required by this module, as described in the module's readme.txt. I have also assigned the block to new region. But still the Language Switcher Dropdown block is not displayed anywhere in my site.

What are the other settings I may have to review/configure? Or maybe there is a possible plugin which conflicts with this one that causes the block not to be displayed?

make sure that:

add few languages to site here - admin/config/regional/language
enable one of Detection Methods here - admin/config/regional/language/configure
clear cache


Add drop down selection to shipping method I need to add an additional drop down field when a particular shipping method is selected, on the order information page during checkout. I only found how to add additional plugin option when adding a new shipping method through the UI.
This is for a custom omniva parcel machine location implementation. Can anyone help me out where to get started with this?
EDIT: im using drupal 8 and commerce 2.
UPDATE: i tried creating a custom pane, thanks to the suggestion of Berry Dingle. I added the drop down and managed to pass the value to the summary page but i can't figure out how to get the value in the email receipt.
I saved the selected value like this but how can i access it in the email template?
This is how i saved the value.
$form = $form_state->getValue($pane_form['#parents']);
$val = $pane_form['omniva_parcel_machines']['#options'][$form['omniva_parcel_machines']];
$this->order->setData('omniva_parcel_machines', $val);

This is how i built the summary pane.
public function buildPaneSummary()
{
    if ($parcel_machine = $this->order->getData('omniva_parcel_machines')) {
        return [
            '#plain_text' => $parcel_machine,
        ];
    }
    return [];
}

Is it even possible to access the value in the email receipt twig template or i have to pass it somehow?
I tried using
{{ order_entity.getData('omniva_parcel_machines') }}

as well as
{{ order_item.getData('omniva_parcel_machines') }}

but so far nothing.

I resolved the issue by adding a field to the order type and then instead of using
Order interface
$this->order->setData('field_omniva_parcel_machines', $val);

i used FieldableEntityInterfaces' set
$this->order->set('field_omniva_parcel_machines', $val);

and i accessed the value in the commerce-order-receipt.html.twig by using
      {% if order_entity.field_omniva_parcel_machines.value %}
         {{ order_entity.field_omniva_parcel_machines.value }}
      {% endif %}

Thanks again, Berry, for getting me started with this!


Set a views path to base URL I am using view.

Every view needs path and i want to set that path to my base url.

For example i want to make a view which will take a Car as a argument and show result at

www.example.com/Car

Any help will be appreciated.

I think what you are looking for is contextual filters.

You should add a contextual filter to your view and set the path to %.
What kind of filter you should use depends on if Car a taxonomy term or a node and so on.

In the following example I have set my path to stores/% and a store is a node with a associated taxonomy term. I can display stores marked with a specific term by going to http://example.com/stores/england or http://example.com/stores/sweden.

You find the contextual filters under the advanced tab.

Here are the settings for the filter. Arguments from the url will be transformed into Term ID.

* EDIT * Perhaps this link will help you Views contextual filters taxonomy name


tabledrag: React on drag event I'd like to create a form with tabledrag, with some fancy client-side behavior when (after) a row is being dragged.

More specifically: If row A is being dragged, I want to change an indicators on row B, depending on the new position of row A.

The classical solution would be a jQuery event that fires when a row is dragged. But which event is that, and to which element does it bind?

UPDATE

2pha pointed me to this page, which is nice:
http://drupalapi.attiks.com/api/drupal/misc!tabledrag.js/7

So the remaining question is, how to use these commands?

$('table#the-table').onDrag(..)

would that be it?

Got the answer for you! Check out the core tabledrag.js lines 862, 869, 1150, 1160. These are all functions that you can overwrite to react to tabledrag events! Here's a code example I wrote for you:

Drupal.tableDrag.prototype.row.prototype.onSwap = function (swappedRow) {
      (function ($) { // Important as this allows $ for jQuery.
        alert('React to tabledrag!');
        return NULL;
      }(jQuery));
    }