Replace URL query string with slash for a cleaner URL I have created a new content type with a body and multiple fields.

I use the following query string

?article=referral-partners

to change the content of the node's body according to the value of the value of article.

The full URL looks like this (with my path alias I created):

http://localhost/userguides/contacts/my-first-user-guide?article=referral-partners

I would like to clean up the url to look like this instead:

http://localhost/userguides/contacts/my-first-user-guide/article/referral-partners

How can I do this with Drupal 7?

You can use something like this on your custom module for the redirects with the query strings.

/*
 * custom redirect with query string
 * module implements hook_init()
 */

function MyModule_init() {
  if ($_GET['q'] == 'userguides/contacts/my-first-user-guide/article/referral-partners') {
    drupal_goto('userguides/contacts/my-first-user-guide', array('query' => array('article' => 'referral-partners')));
  }
}


views stripping html tags I am using views to create a table in which I display blogs title and body. Blog is a content type in which body field can be any of plain text, HTML and full HTML. I want to display only two lines of the body for which I use trim option under Rewrite results tag, and set maximum length to 300 which serves the purpose for paragraphs. But if there is a line break then this doesn't work and the text appears in three lines. Please refer to snapshot below :

The output in row number 2 is desired one. How do I go about it?

In the "Rewrite results" section, when you checked check-box "Trim this field to a maximum length", there is check-box "Field can contain HTML" in this section. If you check check-box ""Field can contain HTML", then Drupal will maintain your HTML with content.


Programmatically submit form / save all nodes After migrating all the content from a drupal 6 installation to a drupal 7 one, I ended up with empty fields in my nodes, that are displayed when viewing the node.

However if I edit the node without changing anything and save it, the empty fields are gone (at that point the save function populates the database with the proper null values).

Obviously I can't do that by hand and the solution proposed here: Load and Save nodes with script? doesn't remove the empty fields, even if I actually edit one of the fields. I would like to do this with a php script as I am not familiar at all with Python and the selenium script proposed here: How to programmatically iterate over nodes, load into form, and save the form?.

Now as far as Drupal's form_submit method, how does it actually populate the $form, $form_state variables since I won't be changing anything.

Thanks in advance.

I don't think trying to fake form submissions is a good idea - there is a lot that goes on behind the scenes, and it is easy to get something wrong.

I would suggest instead you implement a script similar to the one you pointed out in Load and Save nodes with script? in which you actually set the missing values to the empty data you require. In that script, after the node_load (and before the node_save) you could do something like:

$empty_value = array(
  'value' => ''
);
$node->field_my_custom_field[$node->language] = array(
  0 => $empty_value
);

You would need to do this for each field that needs fixing. The value you need for $empty_value will depend on the field type. You could work it out dynamically by calling field_info_field ;  however as your script is a one-off, it's simpler to just set the right value for each field. To know what the right empty value should be, just create a node with the right empty value and then inspect it (eg. using var_dump, dpm, etc.)


Uploaded image width After uploading an image, it is re-sized to a width of 904 pixels; I need to keep the original file (1080 pixels).

It was my problem: I took the original dimensions wrong, then Drupal resized the original image to fit the max dimensions.


Changing the default "View" page when user logs in? In Drupal 6 when a user logs in, they are presented with a completely useless page that has no information other than how long the user account has existed.

How do you edit this? Can you embed a view or something there? How would I make a Homebox the default tab? (I've tried using Tab Tamer to hide and disable the tab, but no effect -- still has the lousy "History" info.).

Thanks!

I think the Login Destination module may help you.


How to display forum on a custom URL on my site? The default URL of forum is ./forum but I want it to move to ./discuss/forum
How can i accomplish same?

You can use pathauto, url alias to  your forums to achieve the same.  if it is a custom menu you can use hook_menu_alter(). or an .htaccess re-direct if it is a permanent change


Why isn't my custom Form API #states applied in my webform yaml editor working? I have the need to set visibility state of a checkbox option in one question (Table checkbox select) based on the value of another checkbox in the same table. I also have other scenarios where I would need same functionality but across different questions in the same webform.

I know I can easily do it between two different questions ( 2 different elements) with the built-in conditional logic UI in webform but no such UI option for my case now (afaik) so I'm trying to set it via the custom one and this is my first time with form states and custom condition in webform so I appreciate your kind help so greatly.

I went through trials and errors and the code wasn't being saved till I, thanks to @jrockowitz 's tip, learnt that I was using php code where I need to use yaml code since I'm using the yaml source editor (shown in the screenshot below). When I fixed that, my custom code would save and it reflects as entered in the webform source yaml. However, the custom condition is still not working as expected and I'm still not sure why.

I'm adding the code in the Edit source box accessible via clicking its link on the form "Conditions" tab.

I got the selectors for the involved question options from the "Available selectors" list by clicking on the "Help" link under "Learn more about Drupal's Form API #states." on the "Conditional Logic" for the element editing tab in my webform.

This is a sample full yaml code for the form with a sample question and what I want to achieve but not yet working:

some_question:
  '#type': tableselect
  '#title': 'some question'
  '#options':
    q1: 'q1 (hide if q2 is checked)'
    q2: 'q2 (hide if q1 is checked)'
    q3: q3
    q4: q4
    q5: q5
    q6: q6
    q7: q7
  '#states':
    ':input[name="some_question[q2]"]':
      invisible:
        ':input[name="some_question[q1]"]':
          checked: true
    ':input[name="some_question[q1]"]':
      invisible:
        ':input[name="some_question[q2]"]':
          checked: true

What am I missing here ?!

For those who maybe aren't familiar with the UI edit source, this is a link with info and screenshots : https://www.drupal.org/node/3012686
Note: As per @leymannx 's kind advice, I re-wrote the whole question to rid it of my dump of updates with my trials and errors. I hope it's now cleaner, clearer and more worthy of up-votes :)

For the simple case where Question 2 is shown only if Question 1 is left unchecked, your YAML doesn't look right to me. If you're editing YAML in the conditions tab for the Question 2 checkbox, then just the last 3 lines should suffice:

invisible:
  ':input[name="some_question[q1]"]':
    checked: true

I don't think you want the "#states" key to be in there anywhere, nor do you want to include any selector information for Question 2.

That's if the YAML is part of Question 2's Condition source. If on the other hand the YAML you're showing is part of the form's source, then it should probably look something like this:

q2:
  '#type': checkbox
  '#title': 'Question 2'
  '#states':
    invisible:
      ':input[name="some_question[q1]"]':
        checked: true

Note that the #states key is shown here, but only once - we're omitting 2 out of 3 of the same lines as above.


How to set conditional edit permissions on webforms? I need to extend a Drupal6 based system. I'm not too familiar with it since I overtook administration from another group. It has a product registration system wich uses webforms and a custom module. The user have to be able to edit the their own submitted webform but only until the status is set to accepted.

I switched on permissions for users to edit their content, and it works fine, but I need to revoke this permission based on a field in the webform. When the field value is set to "new" or "pending" the user must be able to edit the content, but when the business owner sets that field to "accepted", the user shouldn't be able to edit that submission any more.

How can I catch user permissions and only let users edit certain content when I want?

Just place a hook_form_alter() or a hook_form_FORM_ID_alter() (just for your webform) in your module.

Then inside the code check that the webform status is valid before committing the update or redirect to to an error page.


jquery script on view not working when filtering with (ajax on) 'better_exposed_filters' module i have a script for dealing with node images hover

(function ($) {
    $(function(){

    $('.node-photos-teaser').mouseenter(function() {
        $(this).addClass('photos-hover');
    }).mouseleave(function() {
        $(this).removeClass('photos-hover');
    });

});
})(jQuery);

when clicking on a node filter set by 'better_exposed_filters' using ajax,
the POST drupal/views/ajax?field_tags_tid_1=4 is loaded and filter out nodes fine but the JQuery behaviour is working nomore.

Ajax breaks jquery

Any help?

Thanks to Clive answer i have solved out the problem embedding to my theme script file :

 Drupal.behaviors.betterExposedFilters = {
    attach: function(context) {  }}

now having:

 (function ($) {
Drupal.behaviors.betterExposedFilters = {
        attach: function(context) {

    $('.node-photos-teaser').mouseenter(function() {
        $(this).addClass('photos-hover');
    }).mouseleave(function() {
        $(this).removeClass('photos-hover');
    });

        }}
})(jQuery);

renders compatible the JQuery from my theme with ajax from betterExposedFilter module


How to make my new administration page use my administration theme? I’ve created a user role of accountant and for this role have created a single page using Views. This page started out as a clone of another admin views page.

Unfortunately this page is using the website’s main theme CSS instead of the admin CSS and is causing some real problems.

I’ve been looking how to have this page NOT load the theme CSS, and use the admin CSS instead.

The accountant role has very limited permissions.

How can I correct this??

There's a permission named View the administration theme. This should be given to the accountant role to allow users with that role to view the admin theme instead of the site theme.

If that permission is granted, then check the URL for the page you've created. A last resort would be to check out the documentation for hook_admin_paths(). This hook allows you to specify paths that should use the admin theme and/or use the Overlay (if you've got it enabled). Something like the following would work:

/**
 * Implements hook_admin_paths().
 */
function MY_MODULE_admin_paths() {

  $admin_paths = [
    'my/new/admin/view' => TRUE,
  ];

  return $admin_paths;

}


Best way to show another site's page via Drupal? I have a somewhat odd request and, while I hate asking vague questions, I just don't know where to start with this one.

I am developing a website (Drupal 6) for a user that also has a seperate website with some very particular server side apps that allow their staff to do data entry.

The request is that they would like to show a certain data entry form from within the new site. The data entry form can span several pages but once done shows a very definitive End of Form marker. I am thinking that to simply show the form can be done using iFrames, perhaps. But this requested level of integration of having the current site recognize the end of form marker puzzles me.

Any advice on how to:

Show the data entry form from the other site.
Have Drupal recognize the "End of Form" marker (just some text that says Done, basically) would be very much appreciated.

Googling things like "Drupal show another page" and such doesn't yield much.

You should be able to use this.  Enable PHP code mode and paste it into a page:

<?php
  $curl_handle = curl_init();
  curl_setopt($curl_handle,CURLOPT_URL,"http://www.google.com");
  curl_setopt($curl_handle,CURLOPT_CONNECTTIMEOUT,2);
  curl_setopt($curl_handle,CURLOPT_RETURNTRANSFER,1);
  $html = curl_exec($curl_handle);
  curl_close($curl_handle);
  print $html;
?>


(solved) send mail with Rules when a term in multi value vocabulary is selected Trying to get an mail-update when a tag is selected (if a node is inserted or updated).

The debug shows that 'till the second condition, everything is working fine. The second condition should be comparing if tid = 22 is selected. And i can't get this working ..

The name of the vocabulary is 'zichtbaarheid' (dutch for visibility).

{ "rules_vinkje_k_n_mail" : {
    "LABEL" : "Vinkje K\u0026N \u003E mail",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_zichtbaarheid" } },
      { "data_is" : {
          "data" : [ "node:field-zichtbaarheid" ],
          "value" : { "value" : { "22" : "22" } }
        }
      }
    ],
    "DO" : [
      { "mail" : {
          "to" : "\u003Cfoo@bar.com\u003E",
          "subject" : "[node:title]",
          "message" : "[site:current-date]\r\n\r\n[node:body]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

The debug shows

...
10.619 ms The condition entity_has_field evaluated to TRUE [edit]
11.293 ms The condition data_is evaluated to FALSE [edit]
...

=== EDIT ===

The correct config is as following.
Events: after saving new content & after updating

First condition (to 'load' the terms): [entity has field] > in Data
selector [node] & in Field the correct vocabulary
Second condition: [List contains items] > Data selector: node:[fieldname]. In next screen, switch to [direct input mode]. Terms should be visible in a dropdown-menu. Choose the right value

And the export is (you should alter some settings, like the name):

{ "rules_twee_vinkje_k_n_mail" : {
    "LABEL" : "TWEE Vinkje K\u0026N \u003E mail",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert" : [], "node_update" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_zichtbaarheid" } },
      { "list_contains" : { "list" : [ "node:field-zichtbaarheid" ], "item" : "22" } }
    ],
    "DO" : [
      { "mail" : {
          "to" : "\u003Cfoo@bar.com\u003E",
          "subject" : "[node:title]",
          "message" : "[site:current-date]\r\n\r\n[node:body]",
          "language" : [ "" ]
        }
      }
    ]
  }
}

(replace node:field-zichtbaarheid with your term-name, like field-tags)

And, as bonus to prevent recursion:
I've added the term 'mail send' in the vocabulary. This term is hidden, but updated with an action. When firing the rule, the second condition is now to check if the term 'mail send' is checked or not. If checked, the output is false and the rule is not further executed.

I see 2 possible reasons that may cause your problem:

Maybe it's a data type conversion issue. You may be more lucky to get that 2nd condition to work if you'd use a text comparison (= "text_matches")  instead of a data comparison (= "data_is").
Maybe your zichtbaarheids-field is a multi value field?

To further investigate this, just add a "Display a message" (within System) as your very first Rules Action, to display the actual value (using an appropriate token for your field), after you temporary remove that 2nd rules condition (to ensure the Rules Actions are performed). If that doesn't help either, you may also want to (temporary) enable the Devel module, so that you can (temporary) add a Rules Action like "Display a value".


8 - How to Get Values From $variables hook_preprocess_commerce_order_receipt? So thankful for all the help on here, but still so baffled as to how Im not able to just quickly determine how to pull these values out of certain arrays and objects.

Trying to get the order id (and other values) from the frickin $variables array in hook_preprocess_hook

Code
afc.theme

function afc_preprocess_commerce_order_receipt(&$variables) {
  dpm($variables['order_entity']);
  \Drupal::logger('afc_theme')->notice('running');
}

Some of the Output

stdClass Object
(
    [__CLASS__] => Drupal\commerce_order\Entity\Order
    [values:protected] => Array
        (
            [order_id] => Array
                (
                    [x-default] => 182
                )

            [type] => Array
                (
                    [x-default] => default
                )

            [uuid] => Array
                (
                    [x-default] => c8b1c210-0e6e-4efb-a59d-84b28d4dadfe
                )

            [order_number] => Array
                (
                    [x-default] =>
                )

            [store_id] => Array
                (
                    [x-default] => 1
                )

            [uid] => Array
                (
                    [x-default] => Array
                        (
                            [0] => Array
                                (
                                    [target_id] => 1
                                )

                        )

                )

Ive tried various wrong things like:

$variables['order_entity'] = $order;
dpm($order->get("order_id")->getValue());
dpm($variables->get("order_id")->getValue());
dpm($variables['order_entity']['order_id'];

1. How do I get the order_id from this $variables object?

2. How/where did you find this information telling you how to get this value out?

How do I get the order_id from this $variables object?

All entities have an id method, inherited (or perhaps overridden) from Entity::id. From your debug output $variables['order_entity'] appears to be one such entity, so:

$order_id = $variables['order_entity']->id();

  How/where did you find this information telling you how to get this value out?

Short answer, in the source and the docs (following/finding isn't always straightforward though). For example if you've read the Introduction to Entity API in Drupal 8, you'll intuitively know that a Drupal\commerce_order\Entity\Order is an entity type, both by the folder structure and its annotation, and you can start thinking about how to address an object of that type in more generic terms.

That leads to searches like "Drupal 8 get entity id" or "Drupal 8 get entity field value programatically", and Google will dutifully tell you everything you need to know.

If you can spare a bit of time to follow the class hierarchy up the chain, and get at least a broad idea of what each class does and how it works, that will probably take some pain out of future encounters with the entity API too.


How do I add a menu subtitle to field sets displayed as vertical tabs? I have formatted my field sets in a form builder function to display as vertical tabs. Here's a snippet of my code. It works fine:

$form['vertical_tabs'] = array(
    '#type' => 'vertical_tabs',
);

// * Form elements: fieldset tree.
$form['episode'] = array(
    '#title' => t('Episode details'),
    '#type' => 'fieldset',
    '#tree' => TRUE,
    '#collapsible' => TRUE,
    '#group' => 'vertical_tabs',
);

I see a lot of vertical tabs with, let's call it, a menu subtitle just below the menu title. It's the grey text under the blue anchor text in this pic from the vertical_tabs module page - the top one reads 'Create new revision':

I guessed, wrongly, that adding a #description attribute with my menu subtitle would add it in, but is just appears at the top the field sets' tab contents. Does anyone know how this is done?

Thanks

SOLUTION

Some may consider this not to be the 'correct' Drupal way, but this is simple, requires hardly any code, resides in the Sites folder (so it won't be over written on update), and does not require editing any core files. Just a bit of CSS. This is what I did:

.vertical-tabs ul.vertical-tabs-list li:nth-child(1) .summary:after {
  content: 'Menu subtitle 1';
}
.vertical-tabs ul.vertical-tabs-list li:nth-child(2) .summary:after {
  content: 'Menu subtitle 2';
}

Clive's answer (see below) may be a better option if you're handy with JavaScipt.

ANOTHER SOLUTION

Here, is a jQuery solution I've developed:

Add this jQuery file to your module directory, call it jquery.YOURFILE.js:

/**
 * Vertical tabs summary setters.
 */
(function( $ ) {
  $(function() {
    $( ".summary:gt(0)" ).html( "Foo" );
    $( ".summary:gt(2)" ).html( "Bar" );
  });
})( jQuery );

Here I used the .gt method, but you could target tabs individually with the .eq method. In your form element definition, where you define your fieldsets, add:

'#attached' => array(
  'js' => array(drupal_get_path('module', 'YOURMODULE') . '/jquery.YOURFILE.js'),
),

MORE SOURCES OF INFORMATION

See the vertical_tabs examples module for another way to do this.

Look in content_types.inc and content_types.js in the node module too.

This is an update of the jQuery file above. It uses Drupal.behaviors and the eq method. Probably more 'correct' than the one above.

(function ($) {

Drupal.behaviors.yourModule = {
  attach: function (context) {
    $( ".summary:eq(0)" ).html( "Foo" );
    $( ".summary:eq(1)" ).html( "Bar" );
    $( ".summary:eq(2)" ).html( "Baz" );
  }
};

})(jQuery);

The tab summary is set by JavaScript (I don't think you can do it in PHP), per the comments in misc/vertical-tabs.js:

  Each tab may have a summary which can be updated by another script. For that to work, each fieldset has an associated 'verticalTabCallback' (with jQuery.data() attached to the fieldset), which is called every time the user performs an update to a form element inside the tab pane.

The node module has a good example of how to do this, the code in node.js should be pretty easy to adapt for your own module:

Drupal.behaviors.nodeFieldsetSummaries = {
  attach: function (context) {
    $('fieldset.node-form-revision-information', context).drupalSetSummary(function (context) {
      var revisionCheckbox = $('.form-item-revision input', context);

      // Return 'New revision' if the 'Create new revision' checkbox is checked,
      // or if the checkbox doesn't exist, but the revision log does. For users
      // without the "Administer content" permission the checkbox won't appear,
      // but the revision log will if the content type is set to auto-revision.
      if (revisionCheckbox.is(':checked') || (!revisionCheckbox.length && $('.form-item-log textarea', context).length)) {
        return Drupal.t('New revision');
      }

      return Drupal.t('No revision');
    });

    ...

I think the only PHP change you'll need to make is to add a specific class to the fieldset so the JS can target it:

$form['episode'] = array(
  '#title' => t('Episode details'),
  '#type' => 'fieldset',
  '#tree' => TRUE,
  '#collapsible' => TRUE,
  '#group' => 'vertical_tabs',
  '#attributes' => array('class' => array('mymodule-node-options')),
);


How do I set up a default value for a text field? I am trying to setup a default value according to drupal API (http://take.ms/sSbow) in case if the form is empty (before use filled any data) and not successful.
In hook_form_alter() I already added the code via
$form['#info']['filter-field_geoaddress_proximity']['label'] = t('Distance'); and it works well. Hovewer if I try like these

$form['#info']['filter-field_geoaddress_proximity']['value']['#default_value'] = 21;
$form['field_geoaddress_proximity']['widget'][0]['value']['#default_value'] = 21;

nothing happens.

This my debug info:

Array
(
    [operator] => field_geoaddress_proximity_op
    [value] => 2ield_geoaddress_proximity
    [label] => Drupal\Core\StringTranslation\TranslatableMarkup Object
        (
            [string:protected] => Distance
            [translatedMarkup:protected] =>
            [options:protected] => Array
                (
                )

            [stringTranslation:protected] =>
            [arguments:protected] => Array
                (
                )

        )

    [description] =>
)

Could somebody help me? Doesn't matter it is in hook_form_alter() or any other hook.

Thank you.

Usually you setup the default value when configuring the filter -- if you've got an exposed content:type filter, then you set the default values by selecting one or more content types in the Configure filter criterion dialog.

I wouldn't do this via hook_form_alter (or similar) as you'll be fighting Views the whole way.


Add 2 flag fields of 2 types of flag to views field I have two kinds of flags. Each flag has a field that gets a value. I want to add these field in one field of views. Any user can flag a content by two kinds of flags.

Should I use "views field view"? What is the instruction?

You may be able to do this with native views.

Using field rewriting in views you can insert values into field display originating from other fields in the same row if they are ordered to appear above it. You can also use a "Global: Custom Text" field and add values and HTML to construct complex output.

Add the fields you want to be displayed as part of the rewritten/global field should be ordered to appear above it by clicking the reorder button and using the handle bars to drag fields up and down.

Those fields you want to merge should be set to exclude from display.

Those hidden fields will be available as a token value you will be able to use elsewhere in the view row in the global custom text field, or combined field.


How to use pager_default_initialize with entity field query? In order to apply pagination on nodes which get rendered into block, I am using pager_default_initialize method. Basically I have written a query, execute that query and after that write pager_default_initialize() function. But it is not applying limit to content per page. i.e. "paging" is not working.

    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node')
          ->entityCondition('bundle', $content_type)
          ->propertyCondition('status',1);
  $results = $query->execute();
pager_default_initialize(count($results['node']), 2);

here, the count of nodes is 4 and I want to display only 2 nodes with pagination.

return theme('calender', array('calender' => $output)).theme('pager');

Here I'm using theme('pager') for pagination interface.

Pagination UI is displayed, but I'm not able to put limit "2" to the no. of count of nodes. Any suggestion where I went wrong?

If your motive is to create a pager for those results, I suggest you to use ->pager() on your EntityFieldQuery.

See this question EntityFieldQuery display pager

if ($type == 21) {
  $query = new EntityFieldQuery();

  $entities = $query->entityCondition('entity_type', 'node')
    ->propertyCondition('type', 'product')
    ->fieldCondition('field_razred', 'tid', array (607,608,609,610), 'IN')
    ->pager(10) // this is the bit you're missing
    ->execute();

  $nodes = node_load_multiple(array_keys($entities['node']));
  print render(node_view_multiple($nodes, 'teaser')) . theme('pager');
}

If you necessarily want to use pager_default_initialize(), see this post Creating pager in Drupal (without db_select() and PagerDefault)

$per_page = 10;
// Initialize the pager
$current_page = pager_default_initialize(count($rows), $per_page);
// Split your list into page sized chunks
$chunks = array_chunk($rows, $per_page, TRUE);
// Show the appropriate items from the list
$output = theme('table', array('header' => $header, 'rows' => $chunks[$current_page]));
// Show the pager
$output .= theme('pager', array('quantity',count($rows)));

Hope these examples will help you.


Different permissions after node publishing I have a role (Creators) where users can create/edit/delete nodes of some content types but they can't publish it, publication is done by other role (Publishers), I'm using Workbench and Workbench Moderation modules.

Now I need to disable Creators role to edit/delete content (even their own) after someone from Publishers role published node, so if user from Creators role create node and user from Publishers role publish that node, than node creator from Creators node can't edit or delete it.

How can I achieve something like this?

I resolve this with small custom module. I checking user role as well because I need to apply this only on one role.

There is my code:

/**
 * Implements hook_node_access().
 */
function MODULE_node_access($node, $op, $account = NULL) {
    global $user;
  if (
    // The $node argument can be either a $node object or a machine name of
    // node's content type. It is called multiple times during a page load
    // so it is enough if you perform the check once you get the object.
      is_object($node) && array_key_exists(6, $user->roles) &&
      // Operation on which you want to act: "create", "delete", "update", "view".
      ($op == 'update' || $op == 'delete')
  ) {
    // Check if the node is published.
    if ($node->status == 1) {
      return NODE_ACCESS_DENY;
    }
  }
}

My role's ID is 6, so I used this part array_key_exists(6, $user->roles) because of that.


How do I set a tag via cookie and filter content on the whole site based on that tag? I have a site which has different tags for different cities. Most of the content on the site is either for all cities or a set of specific cities. I am planning to have all the content pieces taggable via taxonomy references. Within my template I want a dropdown which sets the current city. What is the easiest way to only show correct content based on this drop down througout the site?

you can build a view to show your content, then add a "filter" for the city term and "expose it" to your visitors. There is an option to remember the selection for each user.


What is best way to integrate external jQuery plugin? What is best way to integrate external jQuery plugin? can i use it without libraries module?

Perhaps the simplest way is to add it to your theme.info file

e.g, in mytheme.info

scripts[] = js/jquery.cycle.min.js

That will add it globally sitewide.

For more selective control, use drupal_add_js

e.g, in template.php

/**
 * Implements hook_preprocess_html
 */
function mytheme_preprocess_html($variables){

  $valid_path = ''; // TODO, check arg(), current_path() etc.. for valid_path
  if ($valid_path){
    drupal_add_js(drupal_get_path('theme', 'mytheme'). '/js/jquery.cycle.min.js');
  }

}

An advanced method is to use the Libraries API and hook_libraries_info however any of these methods will work.


Pass offset and limit in Drupal embed view I am having below code to embed a view

$view=views_get_view('questions');
$view->set_display('block');

// execute view
$view->execute();
$viewArray = $view->result;

How do I set an offset in this? So that I can get the content I need?

I will be displaying a set of content in a page after processing it. I will need to skip first contents sometime. Like skip first 1 sometime or first 3 some other time.

| skip first 1 sometime or first 3 some other time.

Is there a reason you can't do this in the view? If you use a pager you can specify an on offset in pager options.

If you need to do this in code, you do something like:

$view=views_get_view('questions');
$view->display['block']->display_options['pager']['options']['offset'] = 'OFFSET NUMBER';
$view->execute_display('block'));


Customise Drupal 7 Taxonomy View / Template (without module) How would I go about changing a custom taxonomy view / template without using a module?

i.e. I have a taxonomy named 'tutorials' which has three posts.

How would I modify the HTML output for 'tutorials?

From what I've heard, you can create a file named 'taxonomy--name.tpl.php' to override the default taxonomy template?

Thanks!

As described in Drupal 7 Theme Hook Suggestions, the template files that Drupal looks for a taxonomy term page are the following:

taxonomy-term--[tid].tpl.php
taxonomy-term--[vocabulary-machine-name].tpl.php
taxonomy-term.tpl.php

Replace [tid] with the taxonomy term ID, and [vocabulary-machine-name] with the machine name set for the vocabulary. Supposing that the machine name is programming_languages, then the template filename that Drupal looks is taxonomy-term--programming-languages.tpl.php. (The underscores are replaced with hyphens.)

The first file that is found is the one that Drupal uses.


Allow node creation only via services Is there a way to allow the creation of nodes only via services and not via node/add?
I want that nodes are created by the users of a mobile application, and not using the web interface.

Is this possible?

I have created a module that only allows logins through services.. therefore, you can only create a node through services if you use it in conjuction with a Session Limit, or other module which prevents multiple sessions.

http://drupal.org/sandbox/tpainton/1851382

Still experimental but please try, and if you find bugs, report.  Hope it works for you.


trusted host patterns in web hosting Do I need to add my IP in settings.php and change settings.local.php if I'm only doing web host? Because I would like to fix the status report about no trusted host patterns. Thank you all for helping

No, you only need to add the hostname patterns in settings.php for how the site is being accessed, which normally isn't by IP. settings.local.php shouldn't be involved, as that is typically just for local development (I never adjust trusted patterns for local dev, just staging and production).

Essentially, the portion of code that handles this looks at the HTTP Host header, which is the hostname portion of the URL you requested (unless your webserver does canonical Host normalization, which is different that the rewrite rule for canonical URL).  The IP address never comes into play, unless you browse directly to the a URL where the "hostname" portion is the IP.


Zebra striping on custom panels layout Is there a way to get zebra striping on a custom panels layout?  I've been looking hook_preprocess_panels, but I don't see a way to tell if I'm a certain layout is being used.  I don't want it on all layouts, just one in particular.  I have the layout made, and I figure if I can add a css even/odd class to a node in the panel, I should be able to get what I need.

If you use even/odd pseudo-classes, you don't need even/odd classes

:nth-child(even)
:nth-child(odd)

Example:

.parent_class > div:nth-child(even) {background: #CCC}
.parent_class > div:nth-child(odd) {background: #FFF}

or

ul.yourclass li:nth-child(even) {background: #CCC}
ul.yourclass li:nth-child(odd) {background: #FFF}


Drupal 7 multisite domain without www. not working I have moved a site (www.example.com) to a multisite installation.  The path is 'sites/www.example.com'.  I am reading that adding the 'www' to the sites folder is a no-no.

www.example.com - Works but..

example.com - Doesn't.

I tried creating a symlink 'example.com -> /home1/username/public_html/sites/www.example.com/

also, tried adding "$sites['example.com'] = 'www.example.com';" to my sites.php, but..nothing.

If I rename the folder to 'example.com' all of the paths in the database will be broken.  Any ideas?

Rename the folder to example.com, create a 'sites.php' file in /sites, then add the following:

<?php
$sites = array (
  'www.example.com' => 'example.com',
);


what is the equivalent for category in wordpress in drupal websites? to boost the ranking for a specific keyword we should create categories in wordpress. how should I make a category in drupal?
There are only tags. Are tags in drupal the same as categories in wordpress? If so it means that I should implement all the SEO considerations to set up the keywords?
for exp not using a keyword both for meta keyword and tag or assigning two tags to a simple article.

Everything you mention in your question is a Taxonomy, a way to sort your content into meaningful groups. This mostly helps to improve site navigation, discoverability and consequently clarifies what the website it about (boosting a keyword ranking might be too strong of a claim).

In WordPress, it's custom to name the main Taxonomy Vocabulary as Categories (they can be hierarchical) and to have additional Taxonomy Vocabulary tags that are optional and sort the content into categories that aren't necessarily closely related to the website main topics.

In Drupal, Taxonomy module allows you to create your own Vocabularies and use them as you see fit. You get the Vocabulary named Tags out of the box, but don't let that name confuse you. You can use Tags as your main Categories Vocabulary. You can also rename the label "Tags" into "Categories" (machine name will remain tags but that isn't user-facing).

Or simply don't use Tags Vocabulary anywhere, delete the field from Articles content type that references it. Create all new Vocabularies, name them as you like (Categories, and Tags, with different machine name) and use them the same way as you did in WordPress.

There are no technical differences between terms coming from different Vocabularies. A term from Categories, and a term from Tags is linked to an article in the same way technically.

The SEO value of using Taxonomy is in how smart you are about categorizing your content, knowing your visitors and offering them what they expect/want/value.


How can I theme profile field forms in an HTML table? I put this code in Drupal 6, and made a template file called "user-register.tpl.php" to override the default registration page.

function my_theme_theme(){
  return array(
    'user_register' => array(
      'arguments' => array('form' => NULL),
      'template' => 'user-register',
    ),
  );
}

With this, I could print profile user name, email and password.

<?php print drupal_render($form['account']['name']); // prints the username field ?>
<?php print drupal_render($form['account']['mail']); // print the email field ?>
<?php print drupal_render($form['account']['pass']); // print the password field ?>

This code doesn't print the profile field form.

<?php print drupal_render($form['profile_category_name']['profile_field_name'] ); ?>

Ideally I would like to print the form itself separately from the title, and the description so that I can arrange them with <table> tags.

I found out why it didn't work. Because my category name was not ASCII characters and it now works after changing them to ASCII characters with the code above.


data selector not working in custom Module I am working in a module and I have added custom date data attribute to ubercart order.

Now, I would like to create a data selector in rules for custom date attribute of the order.

I have implemented hook_rules_data_info() into my custom module but its not showing in data selector in rules.

/**
 * Implements hook_rules_data_info().
 */
function uc_datepicker_rules_data_info() {

  $entities['uc_datepicker'] = array(
    'label' => t('Ubercart Delivery Date'),
    'group' => t('Ubercart'),
    'wrap' => TRUE,
    'token type' => FALSE,
  );

  return $entities;
}

I have also added implemented hook_rules_condition_info() hook and its showing date condition into rules correctly.

Please suggest, how can I add data selector in rules for date attribute of the order in my custom module.

Thanks,

Have you tried with the options as 'getter callback' & 'setter callback'? It seems that these data selectors that you are creating needs to pass the values to the already implemented hook_rules_condition_info as parameters.


Date display differences in node templates In a node template, if I use the following:

{{ content.field_event_start_date }}

The correct localized date and time will be displayed.  For example:

Tuesday, February 14, 2017 @ 9:00am EDT

However, if I only want to display the time part and use the following:

{{ node.field_event_start_date.value|date("g:ia") }}

The incorrect time is displayed:

1:00pm

There appears to be a +4h offset when using the TWIG date() filter.

Drupal's Timezone is set to "America/New York".

How can I display only the time part so that it correctly displays the following?

9:00am

Also, can you please explain what conversion Drupal is performing on the time under the covers?

Thank you.

The proper thing to do here is to configure your field output to use the proper formatter.  On the Manage Display for your content type, eg admin/structure/types/manage/page/display, change the formatter for your field_event_start_date field to Custom, then click on the gear and change the format to 'g:ia'.  You should then be able to use {{ content.field_event_start_date }} in your template.

The standard Twig date() filter doesn't use the date.formatter service, so timezones and localization settings will not be honored.

TwigExtension defines a custom filter for Drupal that will call out to DateFormatter::format() called format_date().  This should work

{{ node.field_event_start_date.value|format_date("custom", "g:ia") }}

This apparently only works for Timestamp fields and not datetime or daterange fields.


Hide Edit View link in Newsletter I have created a view and sending the view as newsletter to users. But received mail contains EDIT VIEW link. How to remove the edit view link from newsletter. I have added the screenshot of received email. I am using Mime Mail for sending email.

Remove permission for anonymous users to edit views from yoursitesname.com/admin/people/permissions

It kind of a long page, so try "ctrl+f" and there type "administer Views" and uncheck the right permission.

If it's not helping, try using another Newsletter module (It's maybe a bug since there is no logical reason to give to email subscribers edit your views, of course).

Please update in comment what worked for you.


What is the purpose of Master Display in Views module of Drupal 7? Why is it not present in every Drupal 7 installation? I have been using Views on Drupal 7 a lot and I enjoy it every time. Great module. I have always noticed the existence of "Master" display while creating views but, never bothered about its existence until today when I noticed that there is no "Master" display in my another server running the same instance of Drupal 7 (same version of Views and Views UI modules)? The two servers differ only in OS, Apache, MySQ and PHP versions, shown as follow:

Core      : 7.31
Views     : 7.x-3.8
Views UI  : 7.x-3.8
PHP       : 5.3.3 and 5.4.16
Apache    : Apache/2.2.15 and Apache/2.4.6 (CentOS)
Database  : 5.1.73 (MySQL) and 5.5.37-MariaDB
Centos    : 6.5 & 7.0

I am a bit confused why "Master" display is not present in recent server but, is available in my other server even though both run same instance/version of Drupal 7? I would greatly appreciate if you could share your knowledge/understanding of "Master" display and its existence/use/purpose (in theory or practical examples if you got any).

To always see the Master Display you need to set the 'Always show the master display' setting at

admin/structure/views/settings

The Master Display is a convenience and time saver when you have a set of related displays (block, page, feed etc.). You create the master view and then all of the other displays are 'clones' of the master that you then customize individually. Also, when you revert a setting in an overridden display it will revert to that of the master. I also think that the master display is fully saved in the database, and for all the other displays on the same view only the overridden parts are saved, hence less storage.

The Master Display has no associated menu and is therefore good when you need a view but do not want to unnecessarily create a menu entry (ie page) or block or other views resource. It is typically used in this fashion when embedding a view in code, or by other modules that take a view as a parameter, ie Answers, and Views Field View.


How to override prepareTranslation method in Drupal\content_translation\Controller in drupal 8? I want to override prepareTranslation method using my custom module in drupal 8. You can find this function here(Drupal\core\modules\content_translation\src\Controller\ContentTranslationController.php).

You can use hook_entity_prepare_form() to override the values from prepareTranslation() on $form_state.


Best APC settings to reduce page execution time I have Drupal 7, apc with php-fpm and apache behind varnish and512 MB RAM.

I measure page execution time with devel module.

Database query time is low (62ms) compared to page execution time which is 854 ms.
That means there is problem with PHP and APC settings.

My current settings are just

apc.shm_size = 64
apc.stat=1

How I can improve?

What are the best settings for Drupal given the above configuration?

Thanks

We run in a SVN push environment so we only clear the apc file cache with a script.

APC settings:

apc.ttl=604800
apc.user_ttl=3600
apc.shm_size=192M
apc.include_once_override=1
auto_globals_jit=Off
apc.num_files_hint = 2048

apc.stat_ctime = 0
apc.file_update_protection = 2
apc.stat = 0

PHP Script:

<?php
$return = apc_clear_cache('opcode');
echo var_export($return);

604800 = 1 week.

After this, getting xdebug/xhprof up and running and doing a cache grind of the site should let you know what's slowing down the site. In short analyzing the cache grind output is the best way to speed up Drupal. Below I'm listing what patches and modules we use to speed it up; in your case it will be different most likely.

Drupal 6 Specific Answer Below

Once you get past this point and realize the APC isn't going to give you what your looking for, switch to pressflow and give these patches a whirl:

Core - Cache module_implements()
Imagecache - use lock.inc instead of a file lock
Views - views_get_default_view() - race conditions and memory usage
Views - Persistent caching for unpack_options() calls from building displays

Also try some of these modules as they improved our sites speed in a big way:

Imageinfo Cache
Advanced CSS/JS Aggregation


See which context is used on a page when looking at the page When you are watching a page, is there a quick way for seeing all of the contexts that are being applied? Ideally I would like to be able to see which context is responsible per the blocks.

You can use the active context api to get this done.,

$contexts = context_active_contexts();
print_r (array_keys($contexts));

Place the above code in your form_alter or in any hook_node_view. This will list the active context in the page.


Allow anonymous user to search custom account field I have a custom account field called license number.

How do I allow anonymous users to search for that license number and, after they select it, view that user's profile?

This can be covered by the Views module in a few steps.

Make sure anonymous users have the Access User Profiles permission.
Create a user view with a page display in the Views UI.
Add a exposed filter on your view for your license number field. Set the Operator  to Is equal to if you want a search by full account number only, or set it to Contains if you want a partial/full account number search.
Adjust the display how you see fit. The display can contain links to the user profile page.
Save the View.

From this point you should now have a page from which to search for user profiles with your custom account number field.


Table with Add row option for external users I am trying to build a training website. If the external user is booking a slot for a training class for 10 people he should be able to add 10 people details like the Name, address etc., at checkout. I am thinking to provide the ability to add each attendee details to the table with an "Add row" option dynamically by the external user.

Is this possible? Do we have any modules for this? I checked with datatable module I didn't find this option. Could anyone please suggest me on this.

Example View:

Thanks in advance!!!

I got it. We can use Matrix webform component module(https://www.drupal.org/project/webform_matrix_component) to achieve this.


Pass title of current node to subsequent node created in modal I need to pass the title of the current node to the title field of an add node form that pops up in a modal using. I am using auto node title which allows the use of tokens as replacement patterns but [current-page:title] results in the title 'Create User Photos', the title of the add node form. Can anyone tell me how to pass the title of the review node either through auto node title or by changing the form's title to match the review node?

I am using the form block module to render the add node form as a block then using js to display it as a modal. I am trying to pass the title to make the nodes related if you will.

I am open to other ways to relate the nodes.

A little context: I've got restaurant review nodes with photo galleries. Users can add photos to a reviews gallery via a modal form that creates a new node containing the photos. I would like the title of the new photo node to match the review node's title but I haven't been able to do that.

If your form is not loaded via ajax then you can write a form alter hook in your module and alter the photo node form and provide a default value for the title field of the photo node form. You can either query or do node_load() of the current review node to get the title. You can retrieve the nid of the current node by the arg(1) function.

When you have the title of the review node you can assign it as the default value of the photo node.


Expose only a specific content type to Views I've been playing with Views in trying to expose only a certain content type to the View, but I cannot find a way to do so.

For example:

I have a content type called Regions and I have 3 nodes of type Regions.

When I create my View, is there a way to only expose the 3 nodes of type Regions?

Currently, it displays all the entries in my node table, which is not what I want.

You want to add a filter to your view that is a content type filter, and then select "only show" and check off "Region" in the checkbox list.

So, edit your view, and on the left under "Filter criteria" click add.  Then, scroll through the list of available fields to filter on and find "Content: Type", check that off, click "Apply".  Then, on the left, select "Is one of" and on the right in the checkbox list select "Region", click "Apply".

After you've done that you can save your view.  The changes should be applied and should be showing only nodes in the view that are of type Region.


I am unable to get 'file' #type to appear in my form I am building a custom module where the user needs to upload an image.  Here is the code for my form:

function floor_map_form($form, &$form_state) {
        $form['file'] = array(
            '#type '        => 'file',
            '#title'        => t('Choose a file'),
        );
        $form['center'] = array(
            '#type'     => 'textfield',
            '#title'        => t('Center'),
            );
        $form['country'] = array(
            '#type'     => 'textfield',
            '#title'        => t('Country'),
            );
        $form['region'] = array(
            '#type'     => 'textfield',
            '#title'        => t('Region'),
            );
        $form['submit'] = array(
            '#type'     => 'submit',
            '#value'    => t('Submit'),
            );

        return $form;
    }

The only thing that shows in the browser are the text fields and submit button, the file upload field is nowhere in the page or html for the page.

Does this look wrong to you:

  '#type '        => 'file',

it's not '#type'


copies of installations for each client I have built a Drupal based web app product that I want to give (a trimmed down version) for free. I am expecting 100s and 1000s of subscribers. Each one should get an exclusive code base (drupal files) and database- thats my product's need.
I plan to use AWS- amazon web services.

1). I want users to visit my company site and click and install the product(the web app site) for themselves. This should automatically
       a. create a sub-domain,
       b. copy my main code base and database. How to do these?

2). For maintenance and upgrades management, I want to have a single
parent code base (probably at private github) and would want each of these sites to replicate that. This is to avoid upgrading 1000s of sites individually. How to do this?

3). Some of my subscribers may want to upgrade to paid version. So I may have to customize their instance. How to ensure the custom changes are not overridden on maintenance acts of above point.

I have a low budget so I cannot buy any service to do this. I am hoping that a module or some Drush way can solve this.

You may be able to use Aegir (Hostmaster): https://www.drupal.org/project/hostmaster


Can we access paragraph field in views-view-unformatted.twig? Is there a way to access the fields in paragraph in views-view-unformatted.twig.
I want to perform checking on field of paragraph before print the row
something like this

{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  {% if paragraph_field is not null %}
     <div {{ row.attributes.addClass(row_classes) }}>
        {{ row.content }}
     </div>
  {% endif %}
{% endfor %}

I don't think you can get the value of field from paragraph field inside views-view-unformatted.twig all you can get is the target_id of referenced paragraph using view.result[key]._entity:

I suggest to use template_preprocess_views_view_unformatted like the following:

function YOURTHEME_preprocess_views_view_unformatted(&$variables) {
  $view = $variables['view'];
  $rows = $variables['rows'];
  if ($view->id() === 'YOUR_VIEW_ID') {
    $paragraph_storage = \Drupal::entityTypeManager()->getStorage('paragraph');
    foreach ($rows as $id => $row) {
      /** @var \Drupal\node\Entity\Node $node */
      $node = $view->result[$id]->_entity;
      // Get paragraph field.
      // Change field_paragraph by your filed ref to paragraph.
      if ($node->hasField('field_paragraph')) {
        $paragraph_ref_id = $node->field_paragraph->getValue()[0]['target_id'] ?? NULL;
        if ($paragraph_ref_id) {
          /** @var \Drupal\paragraphs\Entity\Paragraph $paragraph_entity */
          $paragraph_entity = $paragraph_storage->load($paragraph_ref_id);
          // Get the value of your field.
          // Change field_paragraph_text by your field.
          // And set another variable to use in twig.
          $variables['rows'][$id]['should_display_row'] = ($paragraph_entity->field_paragraph_text->value !== NULL) ? TRUE : FALSE;
        }
      }
    }
  }
}

Now in your views-view-unformatted.twig you can check on row.should_display_row like the following:

{% for row in rows %}
  {%
    set row_classes = [
      default_row_class ? 'views-row',
    ]
  %}
  {% if row.should_display_row %}
    <div{{ row.attributes.addClass(row_classes) }}>
      {{- row.content -}}
    </div>
  {% endif %}
{% endfor %}


Views: how to achieve automatic pagination? I currently have a view that shows some content displayed in the right sidebar but now I have a pager that shows 4 items on every page. The user has to click next every time he wants to see the next 4 items but I want that this paging goes automatically. So instead of clicking next each time, the next page has to show after 30seconds for example.

Any ideas?

Try Views infinite scroll module.

  Views Infinite Scroll provides a #586668: Pluggable pagers that enables views infinite scrolling ( autopaging, depaging, endless pages ...you name it) by using jquery.autopager plugin. using this module with views page display will load another page whenever the user reaches bottom of the page.


Cannot load ctools automodal associated menu call from another module I have several modules that make extensive use of the Ctools Automodal modal to activate custom-driven modals. These Link references live in their own module, example_item_modals:

/**
 * Implements hook_menu()
 */
function example_item_modals_menu() {
  $items['product/product1'] = array(
    'page callback' => 'product_order_modal_1',
    "access arguments" => array('interact with orders'),
    'type' => MENU_LOCAL_TASK,
    'modal' => TRUE
  );

  $items['product/product2'] = array(
    'page callback' => 'product_order_modal_2',
    "access arguments" => array('interact with orders'),
    'type' => MENU_LOCAL_TASK,
    'modal' => TRUE
  );

  return $items;
}

We have another module that loads in a User Profile (developed by another third party) and the requirements call for loading some of the products here, and interacting with the modal. Actually displaying the links are done using a tpl.php call to those menu calls with an l().

    <?php echo l("View Product", "product/product1"); ?>

So when we eventually load the template call in this custom user profile module, this link should load and have the necessary logic to fire the modals. Except, its not. Here, it treats it like a backpage link. Is there something I am missing for this link to function as a modal? Do I need to explicitly include the parent module the links are defined with, and if so, what API call accomplishes that? (I looked at module_load_include() but i'm importing settings thrown in the .module, not a .inc file).

I think you need specific class for your link to be preprocessed as a modal link (but i don't know the 'automodal' feature so maybe im wrong)


What is the purpose of the tabs div when logged out? I am using a Bartik theme and am getting some extra padding in between the breadcrumbs and page title. Using firebug I discovered that there is an empty div which is displayed when I am logged out.

What is the purpose of this div? I thought it's only used in logged in mode... Is there a way to remove it from logged out mode?

The tabs div will contain links even when logged out on some pages, such as the user page, where logged-out users can choose to either "Create new account" "Login" or "Request new password" by using the tabs.

Instead of removing it you can prevent it from taking up space when empty using CSS to remove the padding and margins on the div.


Autopublish content from drupal to wordpress My question is that i am having a drupal blog and wordpress on different different domains. I am looking for a module so that whenever i publish some content in drupal it should also published in wordpress.

This is more of a Wordpress question, but on drupal side you could expose the new content with a feed or JSON View and after that use some WP module to import the data.

Edit
And here's something that you can use on WP side to autopost from a feed: https://wordpress.org/plugins/wp-rss-multi-importer/


How do I maintain persistent information over a multi-step input process? I don't have a multi-step form. I have many forms that are presented over many steps depending on decisions made in previous forms and user role. How do I best store persistent information across all forms? Should I use some type of ctools cache, store the information in a cookie or should I attach the information as a query string to each URL request? I am currently using Rules and Rules link for this. Also, I intend to use hook_form_alter() to manage the information through the steps but I not sure how to securely maintain persistent information.

Easiest is just save to $_SESSION which effectively stores it using the cookie for you. Are these anonymous users? Care may need to be taken if cookies are disabled in that case.


Remove Classes from Menu I know that this isn't a really big priority but with the default Drupal menu you get css classes like .first or .last or .active.

.first and .last are being provided by CSS3 and .active only needs to be on the <a> link not on the <li> due to the way my CSS works.

All these classes are unneeded and I'd like to remove them, so I can create a clean and efficient template.

Does anyone have any ideas how to do this (and if possible provide a small code sample)?

Thanks :)

I will get so downvoted for this but are you sure this is the last thing you need to make your site awesome? You are wasting your time on microoptimization.


Views REST Endpoint With paragraph field I've created a REST export view to get a paragraph field in a JSON format but I cannot get the result properly, so I used Rest Views module but I got the results including something like these characters \u003Ca href=\u0022\/colors\/gray-metallic\u0022 hreflang=\u0022en\u0022\u003EGray Metallic\u003C\/a\u003E

Also, this paragraph field includes a term reference field.

So I want to render the data properly without these characters and as a plain text

I have solved by using jQuery.parseHTML() or you can use Javascript DOMParser

Something like this

$.ajax({
    type: 'GET',
    url: drupalSettings.path.baseUrl + 'REST_VIEW_PATH/' + nid,
    success: function (data) {
        {
            var paragraphField = data[0]['FIELD_NAME'];
            $.each(paragraphField, function (index, item) {
                var fieldItem = $.parseHTML(item.FIELD_ID_IN_PARAGRAPH);
                console.log(fieldItem[0]['innerText']);
            });
        }
    }
});


Increase label max length The default max length for all labels of all field types is 128. The DB can handle 255. So no schema change. How can I change the default max length to 250?

I've seen this module https://www.drupal.org/project/remove_field_label_length_limit

  Removes field label length limit (which is 128 characters). The module
  supports entity field labels, field group labels, and views field
  labels.

it was working on Drupl7 very well. but there is no version for Drupal 8.

I'm looking for a way to increase all Label length in a specified content type.

use Change Label Length limit module.

it lets users change the maximum limit of label fields.


How to figure which function(s) are triggered upon file download to check permissions I am experimenting with private file system, done custom way :) .

There is file system/files/test.txt (That is, private://test.txt).

When I try to access the file, I get access denied from Drupal, as expected (site redirects to Access denied page, and dblog shows that accesss have been denied).

But now I want to know what module/function have blocked access to the file. I am blindly trying to check hook_file_download or hook_file_download_access, but as far as I can see it does not go through that functions.

All that in attempt to solve this.

If the Drupal log shows you that the access has been denied, then you have a simple way to debug this: if you have a debugger, simply set a breakpoint in drupal_set_message. Skip calls to that function (there shouldn't be too many) until you get the one with the access denied message - and then look at the backtrace. This should show you which function denied the access.

If you don't have a debugger, you can simply (temporarily) add some extra code in that function to test for the relevant error message, and then output a backtrace using debug_backtrace. You can output the data on the screen, to a log file using drupal_debug (if you have the devel module enabled), add it to the generated error message, etc.


How can I display filter guidelines/tips below field for text formats? I want reverse of these
https://www.drupal.org/project/drupal/issues/2098071
https://www.drupal.org/project/drupal/issues/1340860
It can be achieved by hacking core i,e removing line

$element['format']['guidelines'][$format_id]['#access'] = FALSE;

in Element.php but I want proper drupal solution.

namespace Drupal\my_module;

use Drupal\editor\Entity\Editor;
use Drupal\editor\Element;

/**
 * Defines a service for Text Editor's render elements.
 */
class CustomElement extends Element {

  /**
   * Additional #pre_render callback for 'text_format' elements.
   */
  public function preRenderTextFormat(array $element) {

    $element = parent::preRenderTextFormat($element);

    $format_ids = array_keys($element['format']['format']['#options']);

    // Early-return if no text editor is associated with any of the text formats.
    $editors = Editor::loadMultiple($format_ids);

    // Hide the text format's filters' guidelines of those text formats that have
    // a text editor associated: they're rather useless when using a text editor.
    foreach ($editors as $format_id => $editor) {
      // Display filter guidelines.
      $element['format']['guidelines'][$format_id]['#access'] = TRUE;
    }

    return $element;

function my_module_core_element_info_alter(&$types) {

  $types['text_format']['#pre_render'][] = 'my_module.element.editor:preRenderTextFormat';
}

function my_module_module_implements_alter(&$implementations, $hook) {
  switch ($hook) {
    case 'element_info_alter':
      $group = $implementations['my_module'];
      unset($implementations['my_module']);
      $implementations['my_module'] = $group;
      break;
  }
}

Above piece of code worked me and defined this service.


Are there any quality of life add ons for Content Admin page? Easier sorting, searching, etc I think the words make it vague for a google search since I'm not really finding anything. Looking for enhancements to the Content screen in Admin (that lists all of your content items). You can search for things and sort by a few select fields but looking to expand this and make it more specific to our content types. Thanks!

The content page is actual just a view.  You can just edit it to make it do what you want to.  This is set up via the initial site creation so you will not loose your changes when core is updated.


Allow two html tags in node titles How I can allow two html tags <sup> and <sub> in node title of all content types.

Or may be is there some module for BB tags which allow using BB-codes in title?

Or my ba is there some hook for preprocess all titles?

function template_preprocess_node(&$variables)

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


How do I install the commerceguys libraries? While installing Drupal Commerce 8.x-2.x-dev on Drupal 8.0.0-rc4, I'm greeted by the announcements.

Commerce Price requires the commerceguys/intl library.
Commerce Tax requires the commerceguys/tax library.
Address requires the commerceguys/addressing library.

How do I that? It's probably so obvious that I'm overlooking it.

Download composer_manager into your modules directory.

From the Drupal root directory, initialize composer_manager, and run it for the first time:

php modules/composer_manager/scripts/init.php

composer drupal-update

composer dump-autoload

This will download the required libraries into the root vendor/ directory.

Enable modules now.


Open Layers map not showing pointers drupal7 I have created a content type in drupal 7 and added a reference to a taxonomy term.The taxonomy term has geofield data i.e Longitude and Latitude.
The challenge is when I create a view and use an Openlayers data overlay following what is provided in the open layers documentation I do not have a pointer on my map. Could there be anything I am not doing right here?

I had the same problem when I used a non-default PIN image, the URL it then used was incorrect, it included '?q', so the pin image didnt display. This was using openlayers-7.x-2.0-beta1, and when I applied the openlayers-fix-marker-lang-path-1404912-3.patch (http://drupal.org/node/1404912) it was fixed and worked for me. Hope this helps.


How to customize the webform field validation message? there is a huge issue where when a Phone number field is validated on a webform, we get the following error message:

North American Phone numbers should only contain numbers and + and - and ( and ) and spaces and be like 999-999-9999. Please enter a valid ten-digit phone number with optional extension.

In reality we need an ability to customize this and we were looking into the hook_form_alter, but we hit a snag and cannot find ways to modify the error message. How would we be able to modify the validation messages?

One solution here is the String Overrides module.

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

  Features

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

For your case, you can override the Phone module's default error message. By placing this string in this string:

  "%value" is not a valid North American phone numberNorth American
  Phone numbers should only contain numbers and + and - and ( and ) and
  spaces and be like 999-999-9999. Please enter a valid ten-digit phone
  number with optional extension.

And substituting whatever you need it to display.


How to db_select DISTINCT on a particular field in Drupal 7? I understand that you can specify ->distinct() on the db_select statement so that it only returns distinct values when looking at ALL fields. But what I want is to return distinct values by only looking at ONE field. Here's my code:

$event_table = db_select('my_table', 'e')
    ->distinct()
    ->orderBy('e.time', 'ASC');//ORDER BY
$event_table->join('node', 'n', 'e.nid = n.nid'); //JOIN node with events
$event_table->groupBy('e.time');//GROUP BY time
$event_table->fields('e')//SELECT the fields from events
    ->fields('n',array('type','status','title'))//SELECT the fields from node
    ->orderBy('e.time', 'ASC');//ORDER BY

$result_event_table = $event_table->execute();
$result_event_table = $result_event_table->fetchAllAssoc('time');

Suppose I want the distinct column to be e.nid. You'd think  ->distinct('e.nid') would work but it still returns distinct values based on all fields (i.e. distinct(columns1, column2, column3, etc).

Assuming you're trying to get to roughly this query:

SELECT DISTINCT e.nid AS nid, e.time AS time, n.type AS type, n.status AS status, n.title AS title
FROM
{my_table} e
INNER JOIN {node} n ON n.nid = e.nid
GROUP BY e.time
ORDER BY e.time ASC

You would use:

$query = db_select('my_table', 'e')
  ->distinct()
  ->fields('e', array('nid', 'time', 'foo', 'bar'))
  ->fields('n', array('type', 'status', 'title'))
  ->groupBy('e.time')
  ->orderBy('e.time');

$query->join('node', 'n', 'n.nid = e.nid');


Is there a Drupal Wiki documentation site? Like on other Drupal support sites, there are many questions and very few answers here.  The community appears to divide into two Drupal groups, coders and users.  I am a user trying to make a website out of the tools available, not invent a new module.

One problem here is that a question quickly gets lost and answers harder to find. I am finding parts of answers at various sites and would be happy to contribute them to a central depository.  Anyone know where that might be?

Added Related Question:
I see a checkbox below the answers box for a Community Wiki. Does this option tag items for use in a Wiki about Drupal?  If so, How do I filter to see them?

http://drupal.org/documentation is home to our documentation.  While not usually referred to as a "wiki", most pages are editable by anyone with a drupal.org account.

Also consider connecting with the Documentation Team - there are other users who can help you get started.


math functions inside views 3 On my commerce site I give free shipping for users with total order over €100.
Now I would like to create a view that would say, "spend [x] euros more to get free shipping," where [x] is simply 100 - $total_order.

Is there a way to accomplish this in Views, or do I need to use PHP?

It really all depends on where $total_order is defined/declared etc.  You might be able to use the http://drupal.org/project/computed_field module to do the math and just rewrite the field with the text "spend [field] euros more...." to do it, or, if that doesn't work, or adds too much complexity, just create a views template for the field that does the math in php there and displays the field.


Making sort links on views better exposed filters toggle I was able to create sort links on views using better exposed filters. I configured the sort filter sin such a way so I have one link that is ascending and another one descending, based on post date. This works very well. What would be amazing is if I could have one link that toggles achieving the behavior of the previously explained sort links. So for example when  I'm first looking at the view sorted by ascending date I would get one exposed sort link that would sort by descending (most recent ↓). Then when I would be looking at the view sorted by descending date I would only get one exposed sort link that would sort by ascending (most recent ↑).

So in conclusion I want to combine the two views sort links that I have: most recent asc and most recent desc into one link that toggles between most recent ↑ and most recent ↓

Is there a way to do this with jQuery for example?

Right now, BEF doesn't have a lot of extra classes or IDs that would facilitate this. You could post a feature request in the BEF issue queue requesting the necessary additional markup that would make this fairly simple using jQuery.

At a minimum, you'd need some sort of "active" designation so you knew which link reflected the current sort options.  Currently the active sort option is displayed as plain text (rather than a link) but there's an issue requesting the active sort be displayed as a link.

However, I should point out that I'll be out of town most of Aug and wont' be on the issue queue much... (I'm the BEF maintainer).

I'm always open to bounties!  :)


Operations between the same field of a content type I feel like this is a very basic question, but after a couple of years it is the first time I need something like this and I cannot wrap my mind around the structure and get an idea of how to acomplish it.

Lets say I have a content type called "Fruit" where I store data in the fields "Name" (text), "Description" (text), "Price" (integer), "Date" (date).
In a view I'd like to select the fruit with names "Pear" and "Apple" with their respective prices for the dates inserted, but also make mathematical operations on the prices of the fruit (Like, "The price of apples was the 3/4 of the price of pears"). I cannot think of a way to do this since it is actually the same field, only grouped by some other field.

Any suggestions?

Install views_php module. This module adds a field to the view and it also provides a few tokens. You can use the current row values. Note that you have to insert the main fields before the PHP field and exclude the Price field from display, Then the $results,$data,$row objects will give you the value of the row, Do the mathematical calculations and output the result.


Is it important to assign CSS injector and JS injector code snippets to specific pages instead of site wide? Is it important to assign CSS injector and JS injector code snippets to specific pages instead of site wide?

If the code is a few lines, is there a REAL performance benefit to assign css and JS to only some pages?

Or does it only matter for very large code?

I'm just wondering if it's over kill to target the specific pages all the time?

An example code snippet combo I'm using is the first word for JS

$('p').each(function() {
var word = $(this).html();
var index = word.indexOf(' ');
if(index == -1) {
    index = word.length;
}
$(this).html('' + word.substring(0, index) +    '' + word.substring(index, word.length));
});

And CSS:

.first-word { font-style:italic; }

So less than 10 lines of code...

For those amount of lines, it's no biggie, specially if you're caching, as those lines gets cached as HTML.

An alternative, the good practice, would be to add the css to your theme's style.css file and the JS to your theme.info file. That way you can aggregate and compress them along with your other files.

Aggregating and compressing makes a huge difference. You should do that if you aren't already. (speaking of all your css and js files).


Generate new bearer token with simple_oauth programmatically? I have a custom service and in the custom service, I want to generate a new Bearer token for the current user ( it's logged in) with simple_oauth module. in its documentation is has not mentioned how can I generate new a new token for current logged in user. So, how can I generate a new Bearer token for current logged in user?

POST request to /oauth/token generates a new token (don't forget to add proper body params)

You can also use a refresh token to generate a new access token by using grant_type 'refresh_token'


How do I disable APC caching just changing any Drupal setting? Is it possible to disable APC caching completely in Drupal 8 without modifying the php.ini settings (i.e. only by modifying the Drupal settings)?

There are multiple settings necessary to do so:

in active settings.php:

/**
 * Class Loader.
 *
 * If the APC extension is detected, the Symfony APC class loader is used for
 * performance reasons. Detection can be prevented by setting
 * class_loader_auto_detect to false, as in the example below.
 */
$settings['class_loader_auto_detect'] = FALSE;

// Default cache backend.
$settings['cache']['default'] = 'cache.backend.database'; // or any other alternative cache backend

After looking at Berdirs comment and diving further into code and looking at more usages of apcu within Drupal it appears to be pretty much impossible to catch every usage / and even if you manage to find all of them - disabling at some points is not possible (e.g. no configuration options present).


Drupal forum posts with images dilema I want to use Drupal to make a forum where users can post either as text or upload images. This can be achieved with the Comment Upload module.

However if you attach an image and try to post without any text, you get an error message saying 'Comment field is required.'.

Are there any solutions to this? Is it possible to remove the validation causing this issue?

Seems like 'Comment Field is required' when clicking the Attach is similar (identical?) to the issue you encountered.

That issue has status Closed (fixed), and also contains a patch for it.


include social media in view page I'm using theSocial media module to share in linkedin, facebook. I have installed the Widgets module. I want to include this to created field 'Linkedin_share'(image type).

Shall I need to add separate field for share? How to include this social media in view page.

There is sharethis contrib module. You can use this module to share contents in lots of social media.

Also, this module can be used as block, content field and links area.

So, you can put a sharethis block in a view.

Here's what you need to do.

Install & enable module.
Under Configuration > web services, configure sharethis settings. (For the view, you should check block under content at the bottom)
In block settings, place sharethis block on content region.
Configure the sharethis block to only show it on the view.


Exposed date filter doesn't work with 'greater than' or 'less than' and 'is equal to' I'm working on a Drupal 8 site where I use a exposed filter to filter on date. I created a simple version of what I want on simplytest.me.
In this example I created a article with a start and end date.
Start date is 28-02-2018 01:00:00
End date is 28-02-2018 10:00:00

I also created a view with two exposed filters to filter on date range.
Exposed filter 1: >= Startdate
Exposed filter 2: <= Enddate

When I add 28-02-2018 in both filters the result is null. When I look in the query, I see it says 2018-02-27 instead of 2018-02-28
What is going wrong? It looks like it doesn't see the is equal to part of my filter.

Is this normal? How do I make this filter work as I expect?
I tried to fix it with https://www.drupal.org/project/drupal/issues/2627512#comment-12382345, but this only adds an hour, not a full day.

A friend of mine helped me out, the problem was me not adding time to the search query. I found this already along the way in finding a solution but I didn't understand it at that moment. Now I do.

By not entering a time in the search field (so searching for 28-02-2018) the search will go to 28-02-2018 00:00:00 which is the same as 27-02-2018 23:59:59.

So what I had to do was search for 28-02-2018 23:59:59 instead, when entering this in the search field, the right items do show.


How to display the user picture on the search page? I want to show the user picture on the search page. Currently only its show the user email or name, but I want to show the user profile picture.

How can I do that?

Note: the search page is about the user type, so when I search some users their picture should be displayed on the search result page.

Copy the file YOUR_SITE/modules/search/search-result.tpl.php to your theme and modify the code inside with this:

<?php
//obtaining the username
$username = explode('(', $title);
$username = trim($username[0]);
//getting the user object
$user = user_load_by_name($username);
?>
<li class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php print render($title_prefix); ?>

  <?php
  /*
   * The following line will print the user picture
   */
  print theme('user_picture', array('account' =>$user));
  ?>

  <h3 class="title"<?php print $title_attributes; ?>>
    <a href="<?php print $url; ?>"><?php print $title; ?>

  <?php print render($title_suffix); ?>

    <?php if ($snippet): ?>
      <p class="search-snippet"<?php print $content_attributes; ?>><?php print $snippet; ?>

    <?php endif; ?>
    <?php if ($info): ?>

<?php print $info; ?>

    <?php endif; ?>

This will be the output:

EDIT: If you want follow another way you can read this: How to access to the user info on the search page?


There is no language option in drupal 7 site When I hit

  Administration > Configuration > Regional and language

There is no language option in drupal 7 site. Could I need to install modules? Which modules can I install?

It is be because you've installed Drupal with English. You can make Drupal Multi-lingual after it is installed, using the quick steps provided on HowTo: Basic Internationalization setup.

You can also have a look at the Multilingual guide for detailed information.


Theme output of submenu I have a menu that should look like this:

xx

xx

xx

You can see, that the first ul has a class and the submenu ul doesn't have.

I am using this code to add class to the ul.

function mytheme_menu_tree__menu_mymenu($variables) {
    return '
' . $variables['tree'] . '
';
}

But it adds that class to the all submenus.

xx

xx

xx

Is there any way to theme the sub menu? Thank you.

function mytheme_menu_tree__menu_mymenu($variables) {
  return '
' . $variables['tree'] . '
';
}

function mytheme_menu_tree__menu_mymenu_second($variables) {
  return '
' . $variables['tree'] . '
';
}

function mytheme_menu_link__menu_mymenu($variables) {
  $element = $variables['element'];

  $submenu = '';
  if ($element['#below']) {
    // You can set a theme wrapper here or put an empty array() only
    // and theme the second level directly by adding

 one line below.
    $element['#below']['#theme_wrappers'] = array('menu_tree__menu_mymenu_second');
    $submenu = drupal_render($element['#below']);
  }

  $output = l($element['#title'], $element['#href'], $element['#localized_options']);
  return '
' . $output . $submenu . "
\n";
}


Turn Drupal into a USER API I'm developing the main website (A) for an organisation in D7 but for other reasons there are microsites (B) related to this website using CMSs.

I need to give this other users an endpoint in which they can check if the user and password given to them are correct in my drupal instance and of course be able to verify the request only comes from a trusted source (in another physical server without a fixed IP)

So this would be something like:

User enters credentials in website B
Website B's server sends those credentials to my endpoint (A)
Website A check if they are correct and return either ok and the
role that user has or error is there's no user matching them

I looked into Open ID and OAuth approaches but those require user interaction and rely on the users authorizing, etc. What we need is to make it all transparent to the end user so they don't have to know in which of the CMS he/she is in and make an authorization for each one.

Install and configure services module in site A, and on site B you will have to write a custom php post method,

POST http://example.com/rest/user/login

Content-Type: application/json
{
"username":"user_1",
"password":"password"
}

If the response you get from this post method is status 200 then you can verify that the username and password are matching.

Some useful resources:

Services installation doc: https://drupal.stackexchange.com/a/15718

Also found php-curl example here: https://www.drupal.org/node/1334758


How to load a user field in template_preprocess_comment() I added a country field to users and want to show it below the username on comments (in the Bartik theme).
How can I load that field into the bartik_preprocess_comment() function?

Drupal already loads the user object. You can see the user object on that function:

function bartik_preprocess_comment($variables) {
  $user = $variables['user'];
  // Full load user
  $user = user_load($user->uid);
  // Now access your field
  $country = field_get_items('user', $user, 'field_country');
  if ($country) {
    $variables['author_country'] = $country[0]['safe_value'];
  }
  else {
    $variables['author_country'] = '';
  }
  // On your comment.tpl.php using $author_country
}


Ideas for implementing a shift scheduler? calendar? custom content type? for our NPO we need the following feature: We have a bar, hotel and restaurant, and there are some fixed shifts ie. 7am to 12am, 12am to 7pm and so on, the whole week;

People enter their wanted work shift themselves;
There has to be an overview what shifts are set and which ones miss workers. A table for the current and next week, coloured with the user names;

I thought about a custom content type in a module, where the time (start, end) are set by the admin and can be changed from time to time. On click in the calendar resp. the overview panel, the node is prepopulated with auto_title and the times and the entityreference to the user.

And ideas if there is a view plugin which could do the overview, or do i need to code that myself?

I am aware of : shift_scheduler module (sandbox)

Maybe you are aware of the calendar module https://drupal.org/project/calendar
It has a very nice integration with views, and you could create a calender from template for a specific content type that has date fields in seconds (that generates also a view of it per week).
Of course for the case you have described you will need custom coding, surely the Drupal Ajax Framework and some other stuff... but that sounds more like fun :)


HOOK_menu_alter to remove Main Menu items for specific user roles I'm trying to add a menu link (admin/people/create?operator=1) to the Main Menu only for the user role of 'Supervisor.'

I have tried to do this:

function mymodule_menu_alter(&$items) {

 if(in_array('Supervisor', array_values($user->roles)))
   $items['admin/people/create?operator=1']['type'] = {idk what goes here};

}

But I'm not sure I am on the right track.

I take you added a link to the main menu, and you want to make it appear only when the user has the right permission. In that case, hook_menu_alter() is not the right hook to implement because:

It is not used to override the links added to that menu
It is not possible to use admin/people/create?operator=1 as path for the menu link in hook_menu() or hook_menu_alter()

What you should do, after you added the link to the main menu, is to enable a module that contains the following code.

function mymodule_menu_link_alter(&$link) {
  if ($link['link_path'] == 'admin/people/create?operator=1' && $link['module'] == 'menu') {
    $link['options']['alter'] = TRUE;
  }
}

function mymodule_translated_menu_link_alter(&$link) {
  if ($link['link_path'] == 'admin/people/create?operator=1' && $link['module'] == 'menu' && user_access('use advanced user creation link')) {
    $link['hidden'] = 1;
  }
}

function mymodule_permission() {
  return array(
    'use advanced user creation link' => array(
      'title' => t('Use advanced user creation link'),
    ),
  );
}

The $link['module'] == 'menu' part allows to alter the link that you manually added in the main menu, and not other links (i.e. added from a module). In the first function, $link['options']['alter'] = TRUE tells Drupal to invoke hook_translated_menu_link_alter() for that link; in the second function, which is actually an implementation of hook_translated_menu_link_alter(), while the first function is the implementation of hook_menu_link_alter(), $link['hidden'] = 1 actually hides the menu to the currently logged-in user.
Instead of "use advanced user creation link," you can use another permission string; as long as the permission is only given to the roles that need it, and it is unique, you can use any string you want.

I didn't find one, but if there is a module that makes the links added to the main menu visible to users with specific roles, I would use that, instead.

As side note, checking for a permission is preferable to checking for the roles the logged-in user has. The reason is that when you check for permissions, the code is always similar to if (user_access('permission to check')) {} whatever roles have that permission, while when you check for roles, the code could change from if (in_array('supervisor', array_values($user->roles))) {} to if (in_array('supervisor', array_values($user->roles)) || in_array('another role', array_values($user->roles))) {}; in other words, you are hardcoding something that you could change in the future.


List of all bookings in the next 3 days In a content type i have a field date which has a start date and end date. using views i want to put filter in such a way that it display results in a date range form now to next 3 days. In a fields i can see content:dates and in filter i can see start and end like this.

After selecting content:start date i dont know waht to do screen shot like this

Try to change your "Date selection" in your second screenshot to "Text". If I remember correctly, you can now provide a text as paramaters.
There you can add things like
from: now and till: now +3 days


Apache AddDefaultCharset utf-8 - filename not saving in utf-8 Using file field to upload image which has utf-8 filename, but when it is uploaded to site filename is not saving in utf-8 format.But original name is saved as link in database making it not found when accessed.

AddDefaultCharset utf-8 is added to httpd.conf and server restarted before testing.

original filename - noëlle_châtelet.jpg(same is saved in database)
saved filename -noÃ«lle_chÃ¢telet.jpg

According detailed explanation at https://bugs.php.net/bug.php?id=47096 temporary solution would be, explicitly converting filename encoding using iconv().Now it raising new warning message(shall I have to open another issue thread for this?)

Warning: filesize() [function.filesize]: stat failed for public://noëlle_châtelet12.jpg in file_save() (line 566 of C:\server\www\drup_dlist_mys\includes\file.inc)

temporary solution until it is fixed in php move_uploaded_file() function.
In file.inc I added the line in drupal_move_uploaded_file function block

+$uri= iconv("UTF-8","ISO-8859-1//TRANSLIT", $uri);
$result = @move_uploaded_file($filename, $uri);
// PHP's move_uploaded_file() does not properly support streams if safe_mode
// or open_basedir are enabled so if the move failed, try finding a real path
// and retry the move operation.
.
.

This is only happening in WAMP and working fine in linux. I don't know how this new iconv statement will affect in unix/linux environment.Can it be possible to check whether the current locale supports for utf-8 just before iconv() statement?.


How do I change assigned redirect url to drupal root url? Sorry I really don't know how to actually ask this.... But let me explain....
I have my drupal installed in a subdirectory (www.mydomain.com/my-drupal-install). If I type that in the browser url address bar it works fine - drupal loads and I can navigate all links within the domain and the user and admin configuration loads as well. I have set a domain name to that directory in godaddy shared hosting so if I now type (www.my-drupal-install.com) the first page loads but it will not allow me to navigate to any links not even the user or admin login links. I get a 504 error... How can I fix this?

Fixed.........
You just have to reset the base url ($base_url = 'http://www.example.com';) in your main settings.php file to whatever your desired url is and refresh the page... It should work fine afterwards.

Thanks anyways.


How to troubleshoot errors after successful Drupal update? Recently, I updated a Drupal core website from 7.31 to 7.34 and the process was successful, without any error during the upgrade.

It's showing the latest version of 7.34 core in the Status Report, BUT if I visit the home page or any other pages, then it's showing different different errors.

I can access the Administration pages BUT I don't know how to solve these issues.

Here you can see the details about it:

http://cityguest.norrwing.ro/en
http://cityguest.norrwing.ro/en/privacy-policy

I appreciate your help in advance!

According to this comment you should re-upload common.inc file in includes folder.

  I don't use Drupal Commons, but I got the same error when upgrading
  Drupal Crore from 7.20 to 7.34.

  This function was added in Drupal Core 7.33 so check your core version
  is later than that. https://www.drupal.org/node/2369141

  I then fixed it by reuploading common.inc in the includes folder. Must
  have not uploaded correctly the first time.


Brackets in URL Field Get Reformatted to %5B%5D I have a Drupal 7 site with a content type that includes a link field.  The intention is for staff to add a link that can link to an outside website. But if that link contains brackets [ ], the module uses %5B %5D instead. It also, cuts out parts of the URL.

So, ....

...Search/Results?lookfor=&basicType=Keyword&type=Keyword&filter[]=local_time_since_added

would translate to

...Search/Results?type=Keyword&filter%5B%5D=local_time_since_added

Would anyone be able to advise me as to why the link field in a content type would not only remove parts of my URL but also replace brackets?

I see a lot of chatter about this with views, but not on a link field in a content type.

Though I have not come up with an answer to my question, the easy work-around I created was to add a text field instead of a URL field in my content type.

I then used the Linked Field Module to link the text field to the outside website.  This preserved all of the crazy characters that were needed.

For those not familiar with the Linked Field Module, after you have added a text field to your content type, go into:

Manage Display for your content type
Set the Format to Default
Click on the Gear Symbol
Say No to link to content
Check the box to Link the field
For Destination use the field item name with dashes, like this [node:field-online-link-to-resource]
Use the Advanced section to add a title, link text, etc.

FYI that I would only allow trusted content editors to add data to this type of field.


Will a Fields form with many submissions make an overload of nodes? I need to create some user submission forms, and I'm debating the merits of using a custom content type Fields API forms, or a custom module form like the ones in Examples module.

As I understand it, Fields API forms will create a new node for each submission. These forms will have hundreds of submissions every day all year long, and this will create a lot of nodes. I am wondering if this would present a problem in terms of database performance, and site management.

Generally, the bigger the database the potentially slower it can get. If you get 200 nodes submitted every day that's 73,000 nodes a year. A lot of news sites or forums or w/e that run on Drupal easily surpass numbers like that.

You can use the Form API to capture content in a custom table of your creation, there's absolutely nothing wrong with that. If you need everything that comes along with nodes, fields, contrib modules that plug into nodes, etc., than you may want to just use nodes. Then there's the ability in D7 to just create a custom fieldable entity (not a node but "like" a node in that it's a piece of content that Views and other things can hook into) and save overhead by keeping things lean.


Prevent file renaming I have a user who is uploading a number of files with the same file name. It is important to them that the files are never renamed. However, the files are getting _1, _2, etc on the end.

Is there a way I can ask Drupal to make a new directory for duplicate file names so that a rename is not necessary?

There are two ways you can do this:

The Upload File Replace module. A small utility module that automatically stops Drupal from renaming new files upload via filefield CCK. When 2 files with the same name exist, the older files will be renamed.
Specify an optional subdirectory within the field setting where files will be stored using a unique token in the file path settings. (e.g. [current-date:raw])


How to install required packages for feeds spreadsheet module as shown required by Composer Manager? Modules being used
Composer Manager
Feeds Spreadsheet
Requirement

I need to install the package as mentioned in the configuration page of module composer manager.
The error shown is as given below.

Composer's install command must be run to generate the autoloader and install the required packages.
Refer to the instructions on the Composer Manager project page for installing packages.

I have access to Cpanel but don't have command line access right now, how can I install the required packages?

You essentially have 2 options:

Ask your hosting provider to let you install and run Composer, and access it via the command line
Run the Composer install locally, then push all the files up (including the vendor folder)