You can use Menu Attributes Module to add classes.

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

To custom code it, you can add class to menu links using hook_menu_link_alter . Try something like this:

$item['options']['attributes']['class'] = array('class-one' , 'class-two');


You can create form by develop custom module then you use developed form any where in node or block.

Create a custom module

Create a file sites/all/modules/own/form_test/form_test.info
Create a file sites/all/modules/own/form_test/form_test.module

(start it with <?php tag, but don't add ending ?> tag)

function form_test_form($form,&$form_submit) {
  $form['firstname'] = array(
    '#title' => t('Firstname'),
    '#type' => 'textfield',
    '#required' => TRUE,
  );
  $form['lastname'] = array(
    '#title' => t('Lastname'),
    '#type' => 'textfield',
  );
  $form['submit'] = array(
    '#value' => 'Submit',
    '#type' => 'submit',
    );
  return $form;
}

More details


How to programmatically access the allowed HTML tags in Filtered HTML

$filters = filter_list_format('filtered_html'); // put your filter name here
$tags = isset($filters['filter_html']) ? $filters['filter_html']->settings['allowed_html'] : FALSE;


CKEditor oEmbed Plugin Shows up in config but not in actual Editor instance

I figured it out. On the Drupal side, everything was configured correctly. The error was in the Javascript. The original plugin.js file has the following:

editor.ui.addButton('oembed', {
                    label: editor.lang.oembed.button,
                    command: 'oembed',
                    toolbar: 'insert,10'
                });

I modified this to

editor.ui.addButton('OEmbed', {
                    label: editor.lang.oembed.button,
                    command: 'oembed',
                    toolbar: 'insert,10'
                });

Note the name passed to addButton() from oembed to OEmbed. I think there was some conflict in naming it oembed, possibly from some existing functionality. Not sure, but that was the fix for me.

In addition, I should note that for the Basic Editor, I had to modify the HTML filter to allow tags that the oEmbed plugin added to the source view. Hope this helps someone.


Sounds like a case for a jquery.ui accordion fieldgroup setup instead.

e.g: If you install https://drupal.org/project/field_group

I believe you can also use those group styles in custom FAPI forms. At least, I've done that for vertical tab, but maybe that's core now...

You could also add the javascript manually with

drupal_add_library('system', 'ui.accordion');

and use it as per: http://jqueryui.com/accordion/


How do I change the field title on the "Generate automatic URL alias" checkbox in pathautho?

One option is to utilize the String Overrides module. Depending on exactly what you are trying to do, it may be a bit easier to administer and manage this change via the admin rather than in code.


creating "live search" from database text field in Profile Content field Drupal 6

You're asking how to make an Ajax search request from a textfield.

I'm not going to answer your exact question but you need some javascript to fill in the results from your sql query into the search field. Here is an example which fills in an HTML <options> list from a Drupal sql search:

jQuery(function($) {

  $('#edit-field-survey-program-und option:gt(0)').remove();
  $('#edit-field-survey-program-und').attr('disabled', 'disabled');

  // When a country is selected. Find the Academic Programs within that
  // country from an SQL lookup. Then fill in the options values and
  // make that options list enabled for the site visitor.
  $("#edit-field-survey-country-und").click(function() {
    var selected_country = $("#edit-field-survey-country-und").val();
    if (selected_country != '_none') {
      // Do our SQL lookup from a service enpoint with a search parameter.
      $.ajax({
        type:'GET',
        url: '/eap-ajax/eap-country-programs/' + selected_country,
        data: '',
          success:function(data){
          // Replace values of target form element with found results.
          // Enable for enduser.
          $('#edit-field-survey-program-und option:gt(0)').remove();
          $.each(data, function(key, value) {
            $('#edit-field-survey-program-und').append(
              '<option value="' + key + '">' + value + '</option>'
            );
          });
          $('#edit-field-survey-program-und').removeAttr('disabled');
        }
      });
    }
  });
});

The above example is the same 3 pieces for any AJAX thing.

Make a click event listener function
Do your SQL business logic
Inject your results somewhere back into the page

For a full writeup feel free to see my more complete writeup:
http://blog.arvixe.com/drupal-ajax-autocomplete-dependant-form-elements-using-jquery/

I suggest googling how to fill in results to an <input> text field using jQuery.


It's possible that "op" is a default that gets applied if there's nothing already there.

Try:

$form['#submit']['#attributes']['name'] = 'thing-you-want-to-call-it';


Slider for Select List (Text, Numbers etc) in Views Exposed Filters

There is another module called Views Contextual Range Filter

Views Contextual Range Filter is a simple plugin for Views that adds the option to contextually filter not just by a single value, but also by range.


How to convert a stdClass object to a SimpleXMLElement object

Using the XML Serializer package, you can use the following code to make the conversion, as reported in this answer on Stack Overflow.

function json_to_xml($json) {
  $serializer = new XML_Serializer();
  $obj = json_decode($json);

  if ($serializer->serialize($obj)) {
    return $serializer->getSerializedData();
  }
  else {
    return NULL;
  }
}

Alternatively, you can use the following code give in this answer for the same question.

require_once 'XML/Serializer.php';

$data = json_decode($json, true)

// An array of serializer options.
$serializer_options = array (
  'addDecl' => TRUE,
  'encoding' => 'ISO-8859-1',
  'indent' => '  ',
  'rootName' => 'json',
  'mode' => 'simplexml'
);

$Serializer = &new XML_Serializer($serializer_options);
$status = $Serializer->serialize($data);

if (PEAR::isError($status)) {
  die($status->getMessage());
}

echo '<pre>';
echo htmlspecialchars($Serializer->getSerializedData());
echo '</pre>';


Display all Nodes associated to a Taxonomy term?

You could accomplish this by writing code (in a custom module) to ajaxify the relevant select fields. Check out the Examples module (ajax examples -> dependent dropdown) for implementation help. Here's what needs to be done roughly:

Use hook_form_alter or hook_form_FORM_ID_alter to add necessary #ajax options (callback and wrapper at minimum) to the taxonomy select field. The node reference field needs a wrapper (via #prefix, #suffix) and #options changed when a term has been selected (value set in $form_state['values']).
A function for the ajax callback returning the node reference form field.
Custom functionality checking which nodes are associated with the selected term to set the right options for node reference. Easiest way might be by querying them directly from the taxonomy_index database table (if you need other data (like type) include the node table as well).


How to order search results based on author field content

You are almost have done it.

I made a relationship between the content and the author. I can access field "x" in the fields part of views, but it does not show up in the "filter" or "order by" parts.

add that fix "X" in sort section and sort it as Descending. when you make it descending contents with null values appear after those that have value.


Module to view node in a grid layout with the ability to quickly change the reference

You don't really need a module - just some css.
If you are using the views module to create your html then something like this should suffice:

.view-content .views-row {
    display: inline-block;
    margin: 0 20px 10px 0;
    vertical-align: top;
    width: 207px;
    font-size: 0.8em;
}
.view-content .views-row img {
    width: 170px;
}
.view-content .views-row-1 {
    font-size: 1em;
    width: 439px;
}
.view-content .views-row-1 img {
    width: 350px;
}

Here is an example in jsfiddle: http://jsfiddle.net/42LHW/3/


What to do with hidden files in Drupal 8 minor core upgrade?

TL:DR;
You should delete all files hidden and not hidden that you didn't place there yourself.

Drupal core has a lot of hidden files, which are used when developing Drupal itself (git, lint and possibly more) but none of those are needed or relevant for running a Drupal site in production. They are highly relevant when you are working on Drupal itself.

The only hidden file you need for a production site is the .htaccess, if you have more than that they are safe to delete.


It's a hook used from the Features module. Truly, the feature.api.php file, which should contain a description of all the hooks used by a module, contains a description for hook_field_default_fields_alter().

Deprecated as of 7.x-2.0.
Alter the default fields right before they are cached into the database.
@param array[] &$fields
By reference. The fields that have been declared by another feature.
@deprecated

Usually an alter hook is paired with a "normal" hook, but that is not always the case.
If you see that the hook is always invoked with drupal_alter('field_default_fields', /* the other arguments */), the module uses only the alter hook. Checking if the module itself implements hook_field_default_fields() or hook_field_default_fields_alter() would also help to understand which hook is used from the module. Unfortunately, in this case, the module doesn't implement neither one or the other hook. This is easily explained from the fact the hook has been deprecated. (A module should be the first one not to implement its own deprecated hooks.)


How to change the order of form elements in a modal user login form

@jags: Always make sure to mention what version of Drupal you are working on as the answers could be sightly different for different Drupal versions.

You essentially have to change the HTML that gets generated to render the form. Such 'theme override' can be done at multiple places. In your case a good place to do so is the theme layer. Assuming that you are on version 7, the below is what you will need to do -

In your theme's directory edit the file called 'template.php' to register a new theme function

/**
 * Implementation of HOOK_theme().
 */
function THEME_NAME_theme(&$existing, $type, $theme, $path) {
  $hooks = array();
  // Add your theme hooks like this:
  $hooks['FORM_ID_FOR_THE_FORM_YOU_WISH_TO_EDIT'] = array(
      'arguments' => array('form' => NULL),
    );
  return $hooks;
}

Now create the new theme function and make changes to the '#weight' property of the desired elements to change the order in which they appear in the form

function cio_st_FORM_ID_FOR_THE_FORM_YOU_WISH_TO_EDIT($form) {
  dsm($form); // This line will show you the content of $form and help you know which attribute you would like to edit. You will be able to use this function only if the devel module is turned on.

  // Make the changes in the '#weight' attribute of the desired elements to change the order in which they get rendered.

  return drupal_render($form);
}

The line dsm($form) is just for your help. Do not forget to remove/comment it once you are done with the changes.
NOTE You will be required to clear you sites theme registry cache to see the changes take affect.

Hope this helps :-)


Maybe this is the solution... doesn't create the node, sends them to a blank 403 page.

function _utils_photo_nodeapi(&$node, $op, $teaser = NULL, $page = NULL) {
  switch($op){
    case 'presave':
      if(empty($node->field_image[0]['fid'])){
        _utils_check_spammer($node->uid);
        //try again?
        die(header('Location: /node/add/photo', TRUE));
      }
      break;
  }
}
//meta code
function _utils_check_spammer($uid){
    if (in_spam_table && spam_count > spam_limit_for_today)
        //nice knowing you...
        ban_user($uid);
    else
        //you get some more chances
        increment_spam_count($uid)
    endif;
}


You should extend your contenttype with a weight field for this and use it as sort parameter. If your drupalversion is 6 you could use the CCK module for that.


You need to do the logic in the form function not the callback. The callback should only return the relevant part of the form. If you add options or change form structure in a callback then you get these illegal choice errors (it's a security feature to stop people from tampering with the forms).

function test_ajax_form($form, &$form_state){
  $form['school'] = array(
    '#type'             => 'textfield',
    '#title'            => t('School'),
    '#required'         => True,
    '#ajax' => array(
      'callback' => 'get_formations',
      'wrapper' => 'formationsWrapper',
    ),
  );

  $form['formations'] = array(
    '#type'             => 'select',
    '#title'            => t('Formations'),
    '#required'         => True,
    '#options'           => array(),
    '#prefix'           => '
',
    '#suffix'           => '
',
    //'#access'           => empty($form['values']['formations']['#options']) ? False : True,   );

  if($form_state['triggering_element']['#name'] == 'school') {
    $formations = array(
      0 => t('No'),
      1 => t('Yes'),
    );

    $form['formations']['#options'] = $formations;
  }

  return $form;
}

And the callback:

function get_formations($form, &$form_state) {
  return $form['formations'];
}


Comments not showing up when set to open and assigned a region in manage display in drupal 7

My issue was that comments was "CLOSED" for the nodes I already created as the default setting initially was set as "CLOSED". Even thought I set the comment settings to OPEN on the content type, this doesn't affect previously created work.

Solution was to bulk update all the nodes types to open comments with the following sql:

UPDATE node SET comment = 0 WHERE type LIKE "MY_NODE_TYPE_HERE";


Couple of important issues before I migrate into Drupal

Taxonomies and pathauto/token will solve your first two questions. Use a taxonomy to categorise your nodes, then use a token such as [term] or [termpath] to add it to the start of the automatically generated URL paths.

The sections module will solve your last question. You can assign different themes based on paths, or for individual nodes, and some other ways too. Unfortunately, it looks like it doesn't currently have a released D7 port. There may be one in the works, or you may need to try to port it (likely not hard from my understanding of how it works). Possibly related project is taxonomy_theme, which seems to have a -dev D7 release. I haven't used this module in either D6 or D7 personally though; I know sections works fabulously though in D6 despite not having an update in 2 years now.


Input formats and WYSIWYG editor problem

Check your permission page, and make sure you have the right permissions.  Also make sure there is no conflicting permissions


If you use Views to provide it then you can limit it by role/ permission (which will tie your user to a REST login process), else the Views RSS Feed Authentication module allows you to utilise basic auth or oauth.
There are plenty of options, but what you do will depend on how you intend to implement the feed.


SQL query to access a field collection's data? At them moment, I'm only getting field_collection_item returned

You can use the field_collection_field_get_entity() function to obtain the desired result without writing SQL, like this:

$node = node_load(12);
$items = field_get_items('node', $node, 'field_fc_field');
foreach ($items as $item) {
$fc = field_collection_field_get_entity($item);
// Do something with $fc
dpm($fc);
}


Webform does not submit when a file field is added

I discovered the issue: I had added a script to my theme to prevent double form submissions: a simple "if the submit button is clicked, disable submit buttons in the form" jquery script.

This script prevented the submit button of the field field from being activated at the same time the main submit button was pressed. This confused Drupal to a sufficient degree that nothing worked anymore.

I fixed it by wrapping the disabling of submit buttons in a window.setTimeout(function yada yada ... , 50).


In case you know exactly when something changes (it is your own code doing it), you can also use a cache tag.

'tags' => ['my-tag'] within #cache and then when it changes, you invalidate it with \Drupal\Core\Cache\Cache::invalidateTags(['my-tag']).

The advantage is that your data is cached as long as possible and also immediately updated when it changes.

If you have constant changes, and that tag would actually result in shorter cache times, then setting a max-age might be more efficient, but that's usually not the case.


How do you make entity fields appear in Rules when converting a Webform submission to node?

Assuming you are using Webform Rules, you should move 3 and 4 to a Rules Component, but unfortunately Webform Rules does not allow to expose webform data (transfer submission between rules and components) without the patch from here https://www.drupal.org/node/2020149 Without it the data is only available using tokens, and you can not even set the webform data to the variable.

There is another solution, you can extract the Webform SID ([data:sid]) and send it to your Component together with newly created entity and webform itself, then inside your component you can convert received [data:sid] to integer and fetch the submission (Rule Action: Fetch Webform Submissions) and access it using PHP. You will also be able to use Entity:has field inside your component to access all the fields from your newly created entity.

Something like that (component):

The component parameters has:


Try this.

 $sql = 'SELECT sid, score FROM {search_index} WHERE word LIKE :term';
 $result = db_query($sql, array(':term' => '%' . db_like($search_term)));


DB query for tabular results of all a db table's info

Use this table theming, next code created from comments below with some fixes:

  $header = array(
    array('data' => t('Age'), 'field' => 'age', 'sort' => 'asc'),
    array('data' => t('Savings'), 'field' => 'savingvalues'),
  );

  $result = pager_query("SELECT age, savingvalues FROM {savingvalues} " . tablesort_sql($header), 30);

  $data = array();
  while ($row = db_fetch_array($result)) {
    $data[] = $row;
  }
  $output .= theme('table', $header, $data);
  $output .= theme('pager');
?>


Why am I getting "Your browser does not support iframes" in multiple browsers?

I figured out that it's because I'm using CKEditor.

When editing the page, I had to click on Switch to plain text editor in order to get the iframe to load. CKEditor would convert that HTML into a misleading string of Your browser does not support iframes.


SQL error for anonymous users on Views Nivo Slider block

When you enable content_permissions together with the rest of cck submodules, the fields you created aren't visible to anonymous users per default. Due to this, views doesn't add any columns to the select statement and you end up with a faulty select. So the solution is to either setup some permissions or switch content_permissions off.
In case you need to setup permissions on fields, i think Field Permissions is nicer - you can select the fields that will be affected, by default all is shown.


Try the notifications framework:

  This is a complete Subscriptions/Notifications Framework aiming at extendability and scalability. It allows any number of plug-ins defining new event types or subscription types or a different user interface.

Its a full featured module with a number of companion modules for sending messages via different channels depending on different events but what you're probably looking for is the 'Web messaging' submodule:

  Sending Method: Show messages on user's page


Output block in particular region from custom module drupal 7

The way you are trying wouldn't work as you are creating a page by
creating a menu item. Rather you should visit your block administration
page at www.example.com/admin/structure/block. Here you will see the list
of all your blocks and available regions in your theme to assign
the blocks.

Here is a screenshot:

In the screenshot where you are seeing the select list with none as selected. This list will let you place your block in the available region.


Apache URL aliases not working with the visibility settings for blocks

If example.com/product/efg is a path alias, then you need to use the path that uses that alias in the block visibility settings.

For example, if example.com/product/efg is the alias for example.com/node/1, then you need to add node/1 in the list of pages where the block should not be shown.

If you have more path aliases for the same internal URL, then instead of setting the pages where the block should not be shown, you need to use PHP code that returns TRUE when the block needs to be shown. Code similar to the following one should work:

<?php
  return request_uri() != '/product/efg';
?>

If Drupal is executed in a subdirectory of the web server root directory, e.g. dr6, the code needs to be modified as follows:

<?php
  return request_uri() != '/dr61/product/efg';
?>

The reason I didn't use drupal_get_path_alias() is that the function returns just one of the path aliases existing for the internal path passed as argument; in the case there are more path aliases, this would be a problem.


The recieving end doesn't require any configuration that's specific to Views field view. The arguments are passed on as if they came from the URL, so they are used just like regular arguments/contextual filters.

It's important to note that it's easy to completely wreak your server performance with this module. A medium-sized site could suddently execute a thousand views or so if this module is (ab)used.


Upload a drupal site to the server to test

I suggest you instead use any other unused domain. In that case robots.txt, .httaccess will work normally. And also there is risk of Googlebot indexing this content.

Just add "Disallow:/" in the robots.txt as a first rule.


How can I make kint() load faster when debugging twig templates?

There are two other ways other users have mentioned for setting the max output levels in addition to the settings.php method mentioned in the question, plus a couple other ideas below:

Create a /modules/contrib/devel/kint/kint/config.php file and add / modify the line $_kintSettings['maxLevels'] = 3; (by @mdrummond on Slack)
In a preprocess function, add the following: (by @thpoul on Slack)

kint_require();
Kint::$maxLevels = 3;

Be sure to never click the + sign, that shows the entire tree. Click the block instead. You can click the right arrow to open the output in a new window for easier viewing (like when the output is in a block). (by @cwightrun on Slack)
Instead of using kint(), create a preprocess function and use a debugger to explore the variables. (by @danny_englander on Slack)
Pass kint() a specific variable instead of making it roll through the whole tree (by @No Sssweat below).
If you just need to know what variables exist, you can just view the keys by doing a {% for key, value in _context  %} loop (by @mortendk below)


I guess Simplenews Roles modules can help you for creating the groups.

You can assign users to a specific role and then based on this roles you can send Simplenews.

For Eg.

User 1 and User 2 can be assigned to role A

And

User 3 and User 4 can be assigned to role B

Now you can use role A and B for sending Simplenews.

I guess this helps.


How to use URL parameter and page callbacks for tab menus correctly?

A couple of things seem to be missing here. The main confusion seems to be around page callback which should be a function not a URL. The URL is the key to your $items array.

Your first menu item has no 'page callback'. This would be inherited from the parent item (keyed as $items['vehicle_info/%'] and a type of MENU_NORMAL_ITEM) if you had one, but you don't.
Your second item menu seems to be confusing URL with callback as well. If you want it handled by a view then your page display on your view should handle the URL path vehicle_info/%/history, i.e. it will have a contextual filter. Does your view work like this?


Show the latest post from multiple content types

This would probably best be fixed by creating view blocks and creating a separate view for each of the content types.  Then display the blocks in the region as needed.  Or you can create a custom page template and embed the views inside that


Recommended modules for managing Content access?

Recommended modules

Here is what I consider as the "shortlist" for such modules (quotes are from their project pages):

Content Access.

  This module allows you to manage permissions for content types by role and author. It allows you to specifiy custom view, edit and delete permissions for each content type. Optionally you can enable per content access settings, so you can customize the access for each content node.

Taxonomy Access Control:

  Access control for user roles based on taxonomy categories (vocabulary, terms).

  Automatically controls access to nodes (based on their taxonomy terms).
  Configuration page for each user role.
  Three node access permission types: View, Update, Delete.
  Two term access types: View tag, Add tag.

Simple Access (RC4 version only for D7):

  This module allows administrators to make some nodes private and/or editable by certain user roles. It can manage viewability, editability, and/or deletability and provides an easy way to make nodes accessible by only a group (or groups) of users. It is perfectly suited for making private nodes that are only viewable to certain 'access groups'.

  Access groups are based on roles. So for example, my site has roles entitled "Coach Level 1", "Coach Level 2", and "Coach Level 3". I can create an access group called "Coaches" and assign all of these roles to it. Then when I assign a node to be viewable only by "Coaches", only users who are a member of these roles will be able to view.

  Nodes that are not assigned to any access groups will remain viewable by all users, so all nodes will remain viewable when activating this module. And nodes only become private when they are assigned to an access group. The end result is that this module can be enabled for a site with existing nodes without making them all invisible.

Special case: Organic Groups, which provides 'Groups' for Drupal users, and management of Access Control based on these groups. A great resource for learning about Organic Groups is the (free) video training about Learn Organic groups, a set of 14 videos.

My "recommended" module is Content Access ... Also because of al sorts of integrations with the Rules module.

For more details, refer to Access Control modules.

Rebuilding permissions

About "Rebuild permissions": any time the "Access" rules are changed (via admin settings), Drupal needs to ensure that these rules are applied to all impacted content (nodes). That's why Drupal then re-applies the updated access rules. A special case is the "installation" (actually "enable") of a module, when rebuilding permissions is also required. Makes sense? Clear enough?


For reference, this is in the comment_view() function.

It is equivalent to this, which makes it a little easier to understand:

if ($is_threaded) {
  if ($comment->divs <= 0) {
    $prefix .= str_repeat('
', abs($comment->divs));
  }
  else {
    $prefix .= "\n" . '
';
  }
}

$is_threaded is a boolean value for whether or not threading has been enabledfor comments in the settings for this content type.

$comment->divs is set in comment_prepare_thread() and is a count of the indentation divs required to have this comment in the right place in terms of the comment's depth. So this value will either be 1 if a new indentation div needs to be added to make sure the comment is at the correct depth, or a negative number, which is how many indentation divs need to be closed to have the comment at the correct depth.

So if comment threading is enabled, then if $comment->divs is less than or equal to zero then close zero or more indentation divs by appending str_repeat('
', abs($comment->divs)) to the markup otherwise, if $comment->divs is 1 then open a new indentation div by adding '
' to the markup.

For example if you had these comments:

Comment 1
-Comment 2
--Comment 3
---Comment 4
--Comment 5
---Comment 6
----Comment 7
-----Comment 8
-----Comment 9
Comment 10
Comment 11
-Comment 12
Comment 13
Comment 14

Then for each comment, $comment->divs would be:

Comment 1: 0
Comment 2: 1
Comment 3: 1
Comment 4: 1
Comment 5: -1
Comment 6: 1
Comment 7: 1
Comment 8: 1
Comment 9: 0
Comment 10: -5
Comment 11: 0
Comment 12: 1
Comment 13: -1
Comment 14: 0


drupal module defines front page using hook_menu...What does it need to return?

Yes, if you return either a string or a render array from a page callback function, it will be rendered in the main content region on the front end (well, under normal circumstances anyway. There are possible exceptions).

There's an in-depth description of page callback in the hook_menu() docs which is a bit long to reproduce here. I'd recommend giving it a read through.


What is the good way to pass a value from form creation function to its submit handler?

It is easy to do by using $form_state['storage'],

Just define $form_state['storage']['something'] = ;
This value will not show in browser and You will get this value in submit handler. see this code you will understand.

/**
 * Returns the form.
 */
function my_module_form() {
  return drupal_get_form('my_module_my_form');
}

/**
 * Returns the render array for the form.
 */
function my_module_my_form($form_state) {

  $form_state['storage']['product_nid'] = 12;

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

/**
 * Add a submit handler/function to the form.
 *
 * This will add a completion message to the screen when the
 * form successfully processes
 */
function my_module_my_form_submit($form, &$form_state) {
  $product_nid = $form_state['storage']['product_nid'];
}


htaccess settings to allow access to special non-drupal page

add in your .htaccess.

RewriteCond %{HTTP_HOST} ^special.mysite.com$
RewriteRule ^/?$ "http\:\/\/mysite\.com\/special" [R=301,L]


How do you properly render the body when pulling it from the database using db_select?

I think the 'proper' way to do this is not to get the data directly from the database at all, but to use the built-in field API:

// Get an entity (node in this case).
$node = node_load(1);

// Get the view for the body field
$view = field_view_field('node', $node, 'body');

Doing it this way you won't have to bother negotiating languages or anything that, and the field will be outputted exactly as it is when it's attached to a node display.

If you do want to do it manually, though, you need to use the check_markup() function:

$text = check_markup($body_value, $body_format);

It might be worth taking note of the comments in that function, you need to be careful about accepting an arbitrary filter format without validating it:

  Note: Because filters can inject JavaScript or execute PHP code, security is vital here. When a user supplies a text format, you should validate it using filter_access() before accepting/using it. This is normally done in the validation stage of the Form API. You should for example never make a preview of content in a disallowed format.


My content type has a string of words, how do I make them tags?

You can do it using the Feeds module, you probably could have done it when importing the data for the first time.

Create the Taxonomy you need with all the terms.

Export the relevant nodes information containing the text field, in the CSV copy the text field column and manipulate it so you can use it to import the terms into a multi-value Term reference field.

This requires a bit of Excel/Calc magic. It will probably be term IDs separated by semicolons IIRC.

Then use a Feeds importer to update the existing nodes (the same ones you exported), make sure to map the correct column to the Term reference field for the new Taxonomy.


When is using --package-handler=git_drupalorg appropriate with drush?

The second half of your question is easiest to answer: yes, if you are planning on creating a patch for drupal.org, --package-handler=git_drupalorg is a good option to use, as you may then easily create patches with git diff.  For an additional tool to help create and apply patches, see drush_iq.

The answer to the rest of your question is more subjective.  How you download projects for inclusion on a production site depends on your strategy for managing your code.  There are many options, but it's important to pick one that will work for you, because Drupal will commonly WSOD on you if you miss-match your code and your database -- that is, you must use any particular database snapshot with the version of the code that created it.  If you ever end up with an older database with newer code, you can just run updatedb; however, you can never use a newer database with older code.

Sometimes, I check in my entire Drupal source code tree into git.  When I do this, I do not use --package-handler=git_drupalorg to download modules; I just update them with drush pm-updatecode, and commit the result to my repository after testing.  When I do this, sometimes I deploy with git (git pull on production), and sometimes I keep my .git files on dev/stage only, and push just the code to production with drush rsync, leaving the .git files behind.

Using submodules might be a viable option.  There is a project to help manage Drupal submodules in your repository:  see Drupal on Git, aka "dog".  I don't really use submodules or dog myself yet.

Another option is to build an installation profile from your code, and commit just that to your repository.  The advantage here is that there's less in your repository, and it is easier to understand how versions change by tracking a makefile than trying to parse and understand the history of an entire Drupal tree committed to a repository.  See http://drupal.org/node/1368242.  I am just starting to use this, and have not really adopted it as a standard practice yet.


How do I add the "cancel" button to a managed file

if you redirect your browser I'm 99.9% sure it will cancel the upload.

how you handle that redirection is up to you.  I'd probably just show a hidden div when the upload starts with a Cancel upload

hopefully what I wrote above helps, but I'd like to mention the other alternative:

don't put a cancel button in.  I would say that this is a useless "feature" and really why add things to your UI when you don't have to?

the user has to step through quite a few things, it'd be pretty odd if they selected the wrong file.


Those are variables, not tokens. They're arbitrary, and can/will change depending on what template you're in, what modules/themes you have installed, and how you have them configured.

The easiest way to see what variables you have available in context is to use the dump() method:

{{ dump() }}

See Discovering and Inspecting Variables in Twig Templates for full details.


How to print alt or title field image in twig node template?

The alt and title properties are stored in the image field, not in the file entity. You can access them by replacing the entity property with alt or title:

{{ node.field_image.title }}
{{ node.field_image.alt }}


Show or hide fields in view based on a user relationships

The Views Conditional module works for me! Thank you J. Reynolds!
I have the price field set to be hidden, and created a conditional field that shows the price field (with the token), if the relationship field (also hidden),   haves the value of "the name of the relationship". If it has not that value it shows "----".
I am going to fine tune some things around the relationships module but this is exactly what I needed. Thanks again!


DI requires a bit more effort than that - you haven't told the system about your class; the DI container doesn't know that you've called new MyClass(), and it can't get involved.

You need to create a Service, which you can make depend on other available services, instances of which will be passed to your class using the static create method pattern you're already using.

In this case, that's probably as simple as providing your mymodule.services.yml and adding:

my_service:
    class: Drupal\my_module\MyClass
    arguments: ['@file_system']

When you've correctly registered the class with the system, you'll get an instance of it like so (if you need it in a global function):

$foo = Drupal::service('my_service');

Or if you're consuming it in a container aware class, then you can inject it just like any other service.


How do i use a template file for my content type?

function THEME_preprocess_node(&$variables) {
  print_r($variables['theme_hook_suggestions']);
}

put this code into you template.php this will give you the suggestions to make your tpl file.

And for your answer you just can print anything in you page.tpl.php file it prints then you just have to change in your page.tpl.php file


You can change this in Ubercart settings using no extra modules...

Go to /admin/store/settings/products/edit/general, which is in Store administration -> Configuration -> Product settings -> Edit -> Product settings in the menu.

The text for 'Add to cart' is editable in the Add to cart button text section.


How to show how many hits has got one page

check the Statistics module. Its already there in drupal, just need to enable it


How do I override an endpoint provided by a module in a feature?

I found a smooth way to do this without overriding anything.

Create a new services endpoint by cloning the Drupalgap endpoint.
Add the new endpoint to a feature to keep it in code.
In Drupalgap's settings.js, change the endpoint to the new custom endpoint. The relevant line is:

// Default Services Endpoint Path

Drupal.settings.endpoint = 'drupalgap';


Phising warnings (in gmail) when using a gmail address as the website email address. How to avoid it?

I have been using this module for a long time without problems. You need to authenticate once, and then all your site emails are sent through the google smtp server.

http://drupal.org/project/smtp


How to show thumbnail preview in node display for uploaded video in file field

Go to your content type >> MANAGE DISPLAY settings and set FORMAT as Rendered file and view mode: perview


How to remove 'Message log' tab from profile page?

It's part of the Messages modules; it has nothing to do with Private messages.

It's not a glitch, it's what this module does: a simple example of a way to deliver messages (notifications) to users.


Entity Reference | View - Display content based on a entity reference field's value that is randomized?

you just have to configure a view that:

shows 1 breed, sorted random.
has another display that shows dogs based on a contextual filter on the breed nid
Install views field view
use the block from step 2 as a field in your first display and give the nid of the breed as a contextual filter to your views field.

So this views will show one random breed and has a view field to show the dogs that are of that breed. Hope this helps you out.


Getting errors trying to upgrade Commerce Kickstart 1.24 to 1.34

I always did this manually.
You don't need to replace whole profiles folder. Replace commerce_kickstart folder inside profiles only if you have not hacked or changed any file within. If you have changed any module or theme file. First move the folder to sites/all/modules or sites/all/themes folder, then replace that and run update.php.


How do I view the user registration form (as a page/node) while signed in as Admin.

The user/register path in Drupal only displays a form for anonymous users. If you wish to view it as you're changing form elements, open up an anonymous tab (e.g. Igcognito in Chrome, Private Browsing in Safari, etc.) and reload the page as you make updates.


Body class padding top, where is it coming from

It is being done by the core toolbar module. See updateToolbarHeight in  core/modules/toolbar/js/views/ToolbarVisualView.js.

updateToolbarHeight: function updateToolbarHeight() {
  var toolbarTabOuterHeight = $('#toolbar-bar').find('.toolbar-tab').outerHeight() || 0;
  var toolbarTrayHorizontalOuterHeight = $('.is-active.toolbar-tray-horizontal').outerHeight() || 0;
  this.model.set('height', toolbarTabOuterHeight + toolbarTrayHorizontalOuterHeight);

  $('body').css({
    'padding-top': this.model.get('height')
  });

  this.triggerDisplace();
},


The only way i found to fix this was preventing the conflicting hook from running:

function myModule_module_implements_alter(&$implementations, $hook) {

    if ($hook == 'node_access') {

      unset($implementations['conflicting_module']); // Not any more
    }
}

As it contains useful functionality, i'm running it in my own code, should my conditions for allowed not apply:

function myModule_node_access(NodeInterface $node, $op, AccountInterface $account) {

  if ($account->isAuthenticated() and myConditionIsTrue()) {

      return AccessResult::allowed();
  }

  // Run removed hook

  if (function_exists('conflicting_module_node_access')) {

    return conflicting_module_node_access($node, $op, $account);
  }

  return AccessResult::neutral();
}

This is less than ideal and i would prefer an alternative.


Since you did not specify a version I am assuming Drupal 8, but the hooks are nearly the same for Drupal 7. (You can navigate to them from the linked documentation pages).

The problem is that a user can have multiple roles and they can be assigned in a random order. This way you can never be sure that the correct role is shown.

You could try to provide Drupal with some custom tokens for these roles. This means you'll have to create a small custom module, but that is really not that hard.

Create a folder with your module name.
Create a <modulename>.info.yml file within that folder. (<modulename>.info for Drupal 7)
Create a <modulename>.module file within that folder.

Then you'll have to implement 2 hooks in your .module file:

hook_token_info_alter(). This allows for the tokens to show up in the token browser.

hook_tokens_alter(). The code could look something like this:

function <modulename>_token_info_alter(&$data) {
  // Add description of user tokens.
  $data['tokens']['user']['actor-role'] = array(
    'name' => t("Actor role"),
    'description' => t("Role if the user is an actor."),
  );
  $data['tokens']['user']['author-role'] = array(
    'name' => t("Author role"),
    'description' => t("Role if the user is an actor"),
  );

  // Add as much as you like (need).

}

function <modulename>_tokens_alter(array &$replacements, array $context, \Drupal\Core\Render\BubbleableMetadata $bubbleable_metadata) {
  $options = $context['options'];

  if ($context['type'] == 'user' && !empty($context['data']['user'])) {
    $user = $context['data']['user'];

    if (isset($context['tokens']['actor-role'])) {
      // PHP logic to determine the role. Below is an assumption and might not work.
      // Set the value to the actor-role token to 'Actor' or nothing.
      $actor-role = $user->hasRole('actor_role_id') ? t('Actor') : '';
      $actress-role = $user->hasRole('actress_role_id') ? t('Actress') : '';

      // Combine them (one should be empty leaving the other)
      $actor-role-to-show = $actor-role . $actress-role

      $title = $node->field_title->view('default');
      $replacements[$context['tokens']['actor-role']] = $actor-role-to-show;
    }

    // Again add as many as you like.
  }
}

Now you should be able to use [user:author-role] and any other tokens you have defined.


Change stylesheet for just one page in Drupal 7

Try adding this code snippet in a custom module :

function MYMODULE_init() {
  // You can verify actual page by using arg() function. Example for targeting node with nid 123
  if (arg(0) == 'node' && arg(1) == '123') {
    drupal_add_css(base_path() . drupal_get_path('theme', 'mytheme') . '/path/to/css/file.css');
  }
  // You can verify actual page by using the actual alias
  // Supposing your page alias is : http://www.example.com/first-part/second-part
  $args = arg(NULL, drupal_get_path_alias());
  if ($args[0] == 'first-part' && $args[1] == 'second-part') {
    drupal_add_css(base_path() . drupal_get_path('theme', 'mytheme') . '/path/to/css/file.css');
  }
}

Don't forget to change MYMODULE by your module machine name


Your CSS in style.css line 432 is overwriting the CSS that the module is trying to use. You should probably comment that CSS out or edit/remove it's background property.


Custom template for custom page in custom module in D6

Your custom callback functions still use url aliases so you would just need to define a preprocess_hook that adds template files if that particular alias is being served. Here is a basic function you can use in your template.php file, modified from this handbook page:

function YOURTHEMENAME_preprocess_page(&$vars) {

    $alias = drupal_get_path_alias(str_replace('/edit','',$_GET['q']));

    if (($alias != $_GET['q']) && ($alias == 'YOUR CUSTOM HOOK')) {;
      $template_filename = 'page' . '-' . 'YOUR CUSTOM TEMPLATE';
      $vars['template_files'][] = $template_filename;
    }

}

So, for example, if your menu hook was /trigger/awesome then the code could look like this:

function YOURTHEMENAME_preprocess_page(&$vars) {

    $alias = drupal_get_path_alias(str_replace('/edit','',$_GET['q']));

    if (($alias != $_GET['q']) && ($alias == 'trigger/awesome')) {;
      $template_filename = 'page' . '-' . 'awesome';
      $vars['template_files'][] = $template_filename;
    }

}

and the theme would now look to serve this page using the page-awesome.tpl.php file in your theme folder.


drupal_json_output actually echos out the code its self so you don't need to return it's output, but you do need to exit after calling it:

drupal_json_output($output);
drupal_exit();

I'm not sure if this will fix your problem but certainly won't hurt...


Changing the title of the Answers add answer form

Since you have the node object, you can find its author via $node->uid. Then load the account and wrap it in format_username():

$uid = $node->uid;
$account = user_load($uid);
$account_name = format_username($account);

The hook you need depends on the function in which your snippet was found. In your case it is in hook_node_view, so you need hook_node_view_alter()

From there it is as simple as redefining the value. Something like this:

MODULENAME_node_view_alter(&$build) {
  $node = &$build['#node'];

  $new_title = t("Give @author your answer", array('@author' => $account_name));

  $node->content['new_answer_form']['new_answer_form_title']['#value'] = $new_title.
}


Visibility problem with 'restricted to certain pages'

Of course! Now that Drupal 8 returns URL aliases with the leading slashes, I needed to update my rules to:

/news/
/news/*

to get it working as in D6


Drupal 7 + Services 3 : anonymous user can't access user/register endpoint (401 access denied)

Well, apparently the 401 is a false error message.

I had an error in the data structure I posted to user/register, when I fixed it the 401 disappeared.

I still have an error on my user registration but this is now a 500.


I'm going to preface this answer by saying doing this en-masse presents a potential security risk, especially if you are changing the format to a more lenient set of filters. Text formats modify field output during display, not during save. So for example, any previously-escaped HTML or PHP submitted to a field will straight up render/run if you accidentally or intentionally set the filter to Full HTML or PHP code.

It's for this reason that Drupal doesn't automatically update all existing nodes when you change a text format. The behavior of text formats in similar scenarios is still an open issue.

So again: beware, there be dragons.

With that said, each field stores the text as a column named field_foo_format, where field_foo is the machine name of the field. You'll need to update that column on the tables field_revision_field_foo and field_data_field_foo.

The value for the column is a machine name defined as the column format in the filter_format table. So, updating all the fields would be a matter of a query like:

UPDATE field_revision_foo SET field_foo_format = 'new_format';
UPDATE field_data_foo SET field_foo_format = 'new_format';

for each field that needs changing.

You can determine new_format value here: http://YOURSITE.com/admin/config/content/formats - configure link - number or string in URL is your new_format. Clear cache after updating.


Custom module to alter display value of field

The example you're using in the hook_page_alter() docs isn't a valid example but a demonstration. The problem here is the variable $nid isn't defined in your hook invocation. The expression:

$page['content']['system_main']['nodes'][$nid]['body']

isn't valid. $page['content']['system_main']['nodes'] contains an associated array of nid/node data.

This can be one or many nodes depending on the context (e.g. front page vs. a node page). You'll need build your logic accordingly (e.g. $nid = reset($page['content']['system_main']['nodes']) to retrieve the specific node that you want then make the altercation as you need it.


Problems with accessing private files uploaded via file field in a webform

If you are using private file system every module can prevent you from downloading a file. It comes from file_download_header function:

function file_download_headers($uri) {
  // Let other modules provide headers and control access to the file.
  // module_invoke_all() uses array_merge_recursive() which merges header
  // values into a new array. To avoid that and allow modules to override
  // headers instead, use array_merge() to merge the returned arrays.
  $headers = array();
  foreach (module_implements('file_download') as $module) {
    $function = $module . '_file_download';
    $result = $function($uri);
    if ($result == -1) {
      // Throw away the headers received so far.
      $headers = array();
      break;
    }
    if (isset($result) && is_array($result)) {
      $headers = array_merge($headers, $result);
    }
  }
  return $headers;
}

So basically you should discover which implementation of hook_file_download returns -1. You can do that by printing (or writing into watchdog) value of $function variable inside if ($result == -1) { statement (so you will know that this function is responsible for giving -1 result).

However, there is also other case when you'll get access_denied() - if none implementation of hook_file_download will return file headers.

So try to figure out which function (=> module) prevents you from downloading file, then debug that function and try to deduct why.


Omega 4 Sub-Theme problem with file_get_contents(make.libraries) failed to open stream

It's a known bug of Omega theme, so you should follow Drupal issue queue for details: Invalid or empty make file: libraries.make.

As workaround, you may to navigate to subtheme's folder (e.g. fifth_avenue subtheme dir) and run:

drush make libraries.make --no-core --contrib-destination=.


Create config object with array containing key-value pairs

To add an add more button you'll need to create a callback function that will increase the number of fields necessary and rebuild that part of the form based on that information. You can make a new config variable based on some sort of index as you do a loop through all the necessary fields.

I haven't tested this so the syntax might be off but here's the basic idea in an example I wrote.

public function buildForm(array $form, FormStateInterface $form_state) {
        if (empty($number_of_member_fields)) {
            $number_of_member_fields = $form_state->set('number_of_member_fields', 1);
        }
        $forms['members_fieldset'] = [
            '#type' => 'fieldset',
            '#title' => t('Member types'),
            '#attributes' => [
                'id' => 'names-fieldset-wrapper'
            ],
        ];
        for ($i = 0; $i < $number_of_member_fields; $i++) {
            $form['members_fieldset']['memberType'.$i] = [
                '#type'          => 'textfield',
                '#title'         => t('Name'),
                '#default_value' => $config->get('memberType'.$i),
            ];
        }
        $form['members_fieldset']['actions']['add_name'] = [
            '#type'     => 'submit',
            '#value'    => t('Add one more'),
            '#submit'   => array('::addOne'),
            '#ajax'     => [
                'callback' => '::addmoreCallback',
                'wrapper'  => 'names-fieldset-wrapper',
            ],
        ];
    }
    public function addmoreCallback(array&$form, FormStateInterface $form_state) {
        return $form['members_fieldset'];
    }
    public function addOne(array&$form, FormStateInterface $form_state) {
        $number_of_member_fields = $form_state->get('number_of_member_fields');
        $number_of_member_fields++;
        $form_state->set('number_of_member_fields', $number_of_member_fields);
        $form_state->setRebuild();
    }


Hiding a View if empty when contextual filter is already used

I found a very simple answer to this question.

The problem I was having was two contextual filters, Content:NID from URL, and Global:Null Hide If empty, which stopped the view displaying even if full.

Instead, I simply added a Filter Criteria for one of the fields in my view, with :fid on the end. In my case, it was Content: Sidebar Images:fid (not empty)

Now the view shows if it has content, and hides completely, including block region if empty.


Alter Commerce Line Item Order Edit Form

If you want to add an editable column, you cannot do that just through the theme layer (though I think the same would hold true even for a non-editable column). Instead you need to alter the form element that gets created, even if it's just through an order edit form level alteration. First you need to create the elements you need in the form array and then you can override the theme function to ensure they get rendered into the table in the right column.

You should also look up documentation on how to override theme functions in general. You shouldn't need to alter the theme registry, just place the theme function in your theme's template.php, copy the functionality of the default theme function, and alter it to your need.


how to add the "add content" to menu drupal

Navigate to 'Add Content" page from admin menu & copy the path after $base_url.

Example - If it looks like "http://example.com/node/add/product" then copy "node/add/product".

Go to your menu and add one more menu item with the Menu link title of your choice & put this node/add/product in Path over there. All the user will have access to this menu item who ever have permission for adding content of this particular content type.


after one day, i finnaly figured out how to :)

I've first found some help on those both discutions :

a)https://www.drupal.org/node/1920682 (see kenorb answer)

b)Create a new user in LDAP, not wherever Drupal normally creates it (see kernorb answer again)

HOW TO :

1) from LDAP server create manually an inetOrgPerson account (in phpldapadmin it is called a "Courier Mail Account") , let's call it 'myuser'

next steps will be done in drupal admin=>configuration=>people=>LDAP configuration

2) setup LDAP server, and test it (see links above for further details)

3) again in server test page, set myuser into 'Testing Drupal Username' field.
Start the test, then copy somewhere 'testing_drupal_user_dn' value from test result.

4) now 2 things must be done :

a) choose a user schema, inetOrgPerson is a good schema for drupal as it contains email, username, and password fields

b) find witch fields are requiered by your LDAP server for this schema

so search on google [NameOfTheSchema] [NameOfYourLdapServer] attributes

(e.g : "inetorgperson openldap attributes")

then note witch fields are marked as requiered.

for example i found this :
http://www.openldap.org/lists/openldap-software/200001/msg00079.html

there we see that

objectClass, sn, and  cn are marked as required

To resume, you have now noted somewhere: the dn (step 3) and the required field (this step)

c) now, how to set objectclass?
get back to phpldapadmin, display 'myuser' account that you have manually created, then click on export =>LDIF

as example here my result :

# Entry 1: uid=myuser,ou=drupal,dc=mydomain,dc=lan
dn: uid=test1,ou=drupal,dc=mydomain,dc=lan
cn: myuser
description: my description
mail: email@email.com
objectclass: inetOrgPerson
objectclass: top
sn: myuser
uid: myuser
userpassword: mypassword

it is important to respect the order of objectclass fields. In my case i'll have to set in drupal :
UserToken => inetOrgPerson=> [objectclass:0]
UserToken => top => [objectclass:1]

5) go to admin=>configuration => LDAP configuration => user
then "Basic Provisioning to LDAP Settings" section

Check all checkbox into "LDAP Entry Provisioning Events "

Now fill the table bellow

For each line created, you'll have to check both "ON LDAP ENTRY CREATION" and "ON SYNC TO LDAP ENTRY" collumns

a) You MUST have a line with [dn] as target, this is here that you use the dn retreived in step 3.

Example :
i had this : testing_drupal_user_dn = uid=myuser,ou=drupal,dc=mydomain,dc=lan

so i add this line :

--user tokens-- => uid=[property.name],ou=drupal,dc=mydomain,dc=lan => [dn]

b) You MUST set objectclass lines . If we refere to my result in step 4) c) , i have to add 2 lines :

--user tokens-- => inetOrgPerson => [objectclass:0]
--user tokens-- => top => [objectclass:1]

c) you MUST add as many lines as there is required fields in the schema. If we refere to my case step 4) b) i have to setup objectclass , sn and cn, so i have to add two more lines :

Property:UserName => => [cn]
Property:UserName => => [sn]

To Resume :

3 steps to follow :

Setup connection to LDAP server then test it
Give a correct path to user entries (path is called DN with lpda)
Choose a user schema (inetOrgPerson is a good one) and fill all fields required by this schema (this is specific of your LDAP server so refere to its doc)

How to test :

in admin=>configuration=>people=>LDAP configuration=>Settings , check " Enabled Detailed LDAP Watchdog logging.", then edit a user in drupal to trigger the sync with LDAP (assuming you followed my howto). when you save an user in drupal, you'll see an LDAP error message if something goes wrong.


Are Drupal .php files associated with a module cached?

To answer it literally - probably, yes, on many levels:

Filesystem cache
Opcode cache
Possible other caches, depends on your configuration

Above caches should not create the effect you are seeing, but outout of the whole page is also cached, in your browser. Inspect headers to make sure it was not the case, and if so, clear caches and try again. If you have any proxy or reverse proxy, make sure they are not interfering, too.

If you are sure pages are not cached at output, and you didn't make Drupal to cache your variable, it shouldn't be cached. So there are two options:

Problems with include path:

  Files are included based on the file path given or, if none is given, the include_path specified. If the file isn't found in the include_path, include will finally check in the calling script's own directory and the current working directory before failing.

Maybe there is another instance of this file somewhere, one that gets higher priority in including? That's one of the reasons to use module_load_include instead.
Problems with uploading. You know what you sent to your server. But have you inspected (from console, for example) what really is there? Maybe you are looking for something that isn't even there.


try something like

#search-block-form input[type="submit"] {
background-color: white;
padding: 15px 25px;
color: black;
border-radius: 0px;
border: 1px grey dotted;
background-image: url(http://cashbin.win/sites/default/files/favicon.ico);
background-size: 30px 30px;
background-repeat: no-repeat;
background-position: left;
padding-left: 30px;
}

This is an example obviously replace the image and/or border, color, background, position, and padding options.

Add this into you /sites/all/themes/CURRENT_THEME/css/style.css

Hope this helps, God Bless!


Appending string causing link to render as plain html

The toString method of Link returns the HTML string for the link object.

HTML strings in the table render array are wrapped in a markup element which escapes many HTML tags for security concerns.

You can, however, pass your own render array in the row as follows:

$table['#rows'][0]['item']['data'] = [
  '#type' => 'inline_template',
  '#template' => '{{ link1 }}, {{ link2 }}, {{ link3 }}',
  '#context' => [
    'link1' => $link1->toRenderable(),
    'link2' => $link2->toRenderable(),
    'link3' => $link3->toRenderable(),
  ]
];


Maximum flexibility:

I would use the Migrate module. It has CSV support, and there's even direct spreadsheet support in the works. Migrate documentation.

It will require some coding, yes, and Migrate module is not the easiest module to get a grip on, so if you're new to coding, you may need some help with that, but I think it's by far the best solution.

Easier implementation:

The Feeds module claims that it can

  Import or aggregate CSV files

I haven't used that particular piece of functionality myself, but from previous use of Feeds, I'm under the impression that this could be configured from the UI, and thus wouldn't require any code. Feeds documentation.


Why am I getting a "page not found" error for this implementation of hook_menu()?

I believe you cannot define a hook_menu() implementation in a theme; it should be defined in a module.

When you make changes to a hook_menu() implementation, you need to ensure that you rebuild the menu router, as well. To that end you can manually look at your database's "menu_router" table to see if the callback is being registered.


Taxonomy List in node/add Capitalize all letters in the parent only

You can use hook_form_alter to alter the node form. This way you don't alter the data in the vocabulary.

function modulename_form_alter(&$form, &$form_state, $form_id) {
  // For 'article' content type.
  if ($form_id === 'article_node_form') {
    $lang_code = $form['language']['#value'];
    foreach ($form['field_dd'][$lang_code]['#options'] as $key => $value) {
      // Check if option starts with '-' sign. Only child starts with '-' sign.
      // If yes, then continue.
      if (strpos($value, '-') === 0) {
        continue;
      }
      // Else capitalize all the characters.
      $form['field_dd'][$lang_code]['#options'][$key] = strtoupper($value);
      // $form['field_dd'][$lang_code]['#options'][$key]['#attributes'] = array('class' => array('option-blue'));
    }
  }
}

Note:

Refer this link for your new use case: https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#attributes


Simply print your json stuff in your page callback instead of returning it, then Drupal isn't going to add anything around it. In fact, there is a helper function for that, called drupal_json_output(), see user_autocomplete() for an example of that.

That's the official way to deal with this currently, Drupal 8 will hopefully add proper handling for different types of content directly into the routing system (which will be heavily reworked and built upon Simfony2 components).


How do I reference an image from text/description field?

Unless the location of your Drupal install changes (sub directory versus root directory), the easiest way would be to use a relative path from the site root to the image.

You could get the file path with a PHP snippet. Note that the PHP filter module needs to be enabled, and the PHP code text format selected, for this to work.

<?php $path = base_path() . path_to_theme() . '/images'; ?>
<img src="<?php print $path; ?>/imagefilename.jpg" />


Webform A partially-completed form was found. Please complete the remaining portions

This is shown if you have the Show "Save draft" button option ticked in any webform and is hardcoded into the Webform form builder. If you want to override the message display the Disable Message module can help you here.

  Gives a site owner options to disable specific messages shown to end
  users. The core drupal message system as offered by drupal_set_message
  is an excellent way for modules to send out messages to the end users.
  However not all drupal site owners are keen to show all the messages
  sent out by drupal core and all modules to their users. This module
  gives site administrators a reasonably powerful way to filter out
  messages shown to the end users.


I think one of your problem is with this:

$element = &$variables['element'];

I don't think you can assign a reference to an array element (the &), so try changing it to:

$element = $variables['element'];

and I don't see a 'element' element, so unless I'm blind you're trying to access an element that isn't there, so it will always return NULL;


Is it possible to programmaticaly change the HTML rendered by Drupal 7?

If you want to alter the rendered content of a page, you start by adding a post_render function to the node:

/**
 * Implements hook_node_view_alter().
 */
function MODULE_node_view_alter(&$build) {
  $build['#post_render'][] = 'MODULE_wrap_images';
}

And then in that post render function, you can do what you need to do. In the example below, I am replacing float:left and float:right with a wrapper div:

function MODULE_wrap_images($content) {
  // Find all links within the content and extract the complete  tag.
  if (preg_match_all('##i', $content, $matches)) {

    // Loop matches and process.
    foreach ($matches[0] as $index => $match) {

      // Align images left.
      if (stripos($match, 'float: left;')) {
        $new = '
' . str_ireplace('float: left;', '', $match) . '
';
        $content = str_ireplace($match, $new, $content);
      }

      // Align images right.
      if (stripos($match, 'float: right;')) {
        $new = '
' . str_ireplace('float: right;', '', $match) . '
';
        $content = str_ireplace($match, $new, $content);
      }
    }
  }

  return $content;
}


How to insert an image into a drupal form

May be this will help..

 function my_module_start_form($form, &$form_state) {
 $image_options = array(
'path' => 'path/to/img.jpg',
'alt' => 'Test alt',
'title' => 'Test title',
'width' => '50%',
'height' => '50%',
'attributes' => array('class' => 'some-img', 'id' => 'my-img'),
);

 /*$image = theme('image', $image_options);
  $form['start']['image'] = array(
    '#markup' => $image,
  );*/
    print theme_image($image_options);//print the image

    $form['start']['next'] = array(
    '#type' => 'submit',
    '#value' => t('Create charts')
  );
  $form['start']['examples'] = array(
    '#type' => 'submit',
    '#value' => t('See charts examples')
  );
    return $form;
}


Overriding Page Title with Contextual Links

It can be done by placing the following code in your theme's template.php file (please note that my fields were named field_last_name and field_first_name, and my view was a page display with the view name 'user_stuff' - so please adjust your accordingly - you can inspect your values by installing devel and uncommenting the dpm statement).

function MYTHEME_views_pre_render(&$view){
  //dpm($view);
  if ($view->name == 'user_stuff' && $view->current_display == "page" && $view->total_rows > 0) {
    $first_name = $view->result[0]->field_field_first_name[0]['rendered']['#markup'];
    $last_name = $view->result[0]->field_field_last_name[0]['rendered']['#markup'];
    $site_name = variable_get('site_name', 'My Site Name');
    $view->build_info['title'] = "$first_name $last_name | $site_name";
  }
}

There is also no need for the pager and you should rather set your view to display 1 item only. Also note that you are outputting the rendered markup (as opposed to the raw value) so there is no need to sanitise the values.


How to Add Existing File to file_managed. File is Blank

Make sure that your $loaded_file is a file object enter link description here not just a file content.


jQuery UI is not included on every request by default. Drupal only adds it when it is requested.  You can ask Drupal to include the libraries you want on some or all pages with a custom module inside a hook_init or hook_preprocess_page.  Something like this would work:

function MYMODULE_init() {
  drupal_add_library('system', 'ui');
  drupal_add_library('system', 'ui.widget');
  ...
}

For a full list of all system libraries see the API documentation here.

Also, new versions of jQuery do not play nice with many system forms (views as you noted but also rules & panels can have issues).  Newer versions of the jquery_update module have the option of setting a different version of jQuery for administration pages. You will probably want to set that to 1.5 (the version D7 ships with), or add the jquery.migrate script to your theme to allow older jQuery to run on newer versions.


You need to look into views https://drupal.org/project/views and you can display your content anyway that you want to display it. There is a small learning curve but displaying content type fields is one of the easiest forms of a view to setup. There are tons of examples setup and disabled by default from many modules so chances are you already have views code somewhere in your site even if you don't have the actual module yet :)
Look at the project page under Resources heading to find documentation and tutorials plus there are millions online with quick Google searches.


How to make method entity_uri work when $entity_type is taxonomy_vocabulary?

I hope it is not the best answer, because it requires customized code. But anyway, it is a possible solution and I'll share it.

/**
 * Implements hook_entity_info().
 */
function mymodule_entity_info_alter(&$info) {
  if (isset($info['taxonomy_vocabulary'])) {
    $info['taxonomy_vocabulary']['uri callback'] = 'my_module_entity_info_uri_callback';
  }
}

/**
 * Return path for taxonomy_vocabulary entities
 */
function my_module_entity_info_uri_callback($taxonomy) {
  return array(
    'path' => 'admin/structure/taxonomy/' . $taxonomy->machine_name,
  );
}


Complex order form presented as series of linked screens

It was a lack of useful earlier search results that led to posting the question. But often the query just needs the right search term. In this case, it's exactly "multistep" or "multi-step." That finds this, which along with the ensuing discussion and comments, answers the question quite well:
https://www.drupal.org/node/324779

So, the capability was already there in Webforms, I just hadn't seen how to use it.


Create a product of type "computer".
Then create a list field in "computer" called "computer type", where you can specify "desktop" or "laptop".

You can have another list field named "brand" on the computer product.


From the question details provided, I'm not sure if the i18nviews module is enabled (make sure it is).

Probably the best option might be to use i18n_taxonomy_term_get_translation as explained also in the questions:

How to get the translated term name by tid?.
how to get the translated taxonomy term programmatically?

Something else you may want to try to get the terms translated, is to use the setting (for Translation mode) Translate. Different terms will be allowed for each language and they can be translated (instead of 'Localize'). This setting can be found within admin/structure/taxonomy/<YourTaxonomy>/edit.


What will be the url to show all content type posts?

You will have to use the Views module to create list filtering for a specific content type.

The Views module provides a flexible method for Drupal site designers to control how lists and tables of content (nodes in Views 1, almost anything in Views 2) are presented. Traditionally, Drupal has hard-coded most of this, particularly in how taxonomy and tracker lists are formatted.

This tool is essentially a smart query builder that, given enough information, can build the proper query, execute it, and display the results. It has four modes, plus a special mode, and provides an impressive amount of functionality from these modes.

Among other things, Views can be used to generate reports, create summaries, and display collections of images and other content.
You need Views if:

You like the default front page view, but you find you want to sort
it differently.
You like the default taxonomy/term view, but you find you want to
sort it differently; for example, alphabetically.
You use /tracker, but you want to restrict it to posts of a certain
type.
You like the idea of the 'article' module, but it doesn't display
articles the way you like.

Views can do a lot more than that, but those are some of the obvious uses of Views.

Here is a series of awesome tutorials on Views  (I am not affiliated with the author(s))


D8 - How to modify url params on form submit?

You might have a logic-error in

$input['end-date'] = $start_date;

should be this:?

$input['end-date'] = $end_date;

How ever you can add a parameter with "query->add":

\Drupal::request()->query->add(['start-date' => $start_date, 'end-date' => $end_date]);

Note that you "mix" POST and GET - variable. So in your "submitForm" - method you need to process the GET - variables by yourself.


First off, I think you misunderstand what form builder is for. As it's project page says ...

  ... [it] does not provide any permanent mechanism for saving data with the created forms. In other words, it does nothing but build the form....

It's a utility for building form data structures, not for creating and capturing data for forms.

The module you're looking for, as you've found, is webform. It provides an interface (albeit not as nice looking) to build web form content and capture data. That's the only module you need. It looks like from your image you've created a webform node. The form components tab link should present a form that allows you to add/edit components. As shown below...

If this interface isn't appearing I would make sure to uninstall both form builder & webform, remove form builder completely, make sure there is no node content type called webform, then try to reinstall webform again. It should work after a fresh install.


Access Denied when Menu CallBack Function is Called

Your AJAX request is calling the path /drupal-7.34/myid_print/callback on the server. The path registered on your Drupal instance (assuming you're running under the drupal-7.34 directory) is /drupal-7.34/print/callback. Hence, the error you're seeing.

If you want to pass an argument to your print callback, you should do this.

$items['print/%/callback'] = array(
    'page callback' => 'print_user_page_callback',
    'page arguments' => array(1),
    'access callback'    => 'print_user_access',
    'file' => 'print.pages.inc',
    'type' => MENU_CALLBACK,
);

function print_user_page_callback($id)
{
    return 'Successful printing '.$id;
}

Read more on hook_menu() if you'd like to understand more how module's can register paths.


usage of theme_more_link in zen template.php

What you have done should work. Have you remembered to clear cache?


How to alter response headers from module hook

in D7 this would happen with drupal_add_http_header()

In other hooks that might have been true, but hook_file_download works the same in Drupal 8 as it did in Drupal 7, without using drupal_add_http_header.

This is the documentation for both versions’ return value from that hook:

  If the user does not have permission to access the file, return -1. If the user has permission, return an array with the appropriate headers. If the file is not controlled by the current module, the return value should be NULL.

Emphasis mine.

You can't get access to the response object in hook_file_download, because it doesn't exist yet. It's not created until after the hook is invoked in FileDownloadController::download(). The headers you return are added to the response, so returning a suitable key-value array from the hook is the way to achieve what you want.


How can I get more than 10 search results on one page in Drupal 7?

I recommend using views for this. Views comes with a search view included (disabled by default). Use an exposed search term filter to provide the search functionality, and customize other aspects of the view as needed.


You can do this by custom module.For this please use below code.First you need to create custom menu using hook_menu.

/**
* Implements hook_menu().
*/
function custom_menu() {
 $items['user/%/edit/about-you'] = array(
  'title' => 'About You',
  'page callback' => 'edit_about_you',
  'page arguments' => array(1),
  'access callback' => TRUE,
 );
return $items;
}

Now You need to write page callback for this menu item.

function edit_about_you($uid){
  $profile = profile2_load_by_user($uid,'profile_type'); // or by default main
  $form_state = form_state_defaults();
  form_load_include($form_state, 'inc', 'profile2_page');
  return entity_ui_get_form('profile2', $profile, 'edit', $form_state);
}

This will return profile edit page for user.Now you need to redirect user when click Edit My Profile tab for this you can user hook_init for that. Check your path argument and redirect user to new created path.

Thanks


Importing non-unique terms with Feeds Importer

Obviously, there is a way to map by term ID on the mapping settings of the Feeds Importer.

Problem solved!


Og Membership entity not created when assigning new node to Group; works when editing node

The issue turned out to be a hook_node_insert using entity_metadata_wrapper.  I refactored that code to use hook_node_presave to set the field value (field unrelated to organic group) instead: $node->field_short_url_code[LANGUAGE_NONE][0]['value'] = $string; and all is well.


Why do you need access to the database for this information?

Have you looked here?
http://drupalcode.org/project/date.git/blob/b7502f3a86628e5c4995c01f20ac64d5cee5888b:/date.install

/**
 * @file
 * Install, update and uninstall functions for the Date module.
 */

/**
 * Implements hook_field_schema().
 */
function date_field_schema($field) {
  $db_columns = array();
  switch ($field['type']) {
    case 'datestamp':
      $db_columns['value'] = array(
        'type' => 'int',
        'not null' => FALSE,
        'sortable' => TRUE,
        'views' => TRUE,
      );
      break;
    case 'datetime':
      $db_columns['value'] = array(
        'type' => 'datetime',
        'mysql_type' => 'datetime',
        'pgsql_type' => 'timestamp without time zone',
        'sqlite_type' => 'varchar',
        'sqlsrv_type' => 'smalldatetime',
        'not null' => FALSE,
        'sortable' => TRUE,
        'views' => TRUE,
      );
      break;
    default:
      $db_columns['value'] = array(
        'type' => 'varchar',
        'length' => 20,
        'not null' => FALSE,
        'sortable' => TRUE,
        'views' => TRUE,
      );
      break;
  }
  // ... more stuff

The answer to your question is that depending on the Drupal "Date" value you're storing it -- for Postgres it is 1 of the following values:

(drupal field of) datestamp = int DBMS field
(drupal field of)datetime = timestamp without time zone DBMS field
(other drupal field of) date = varchar DBMS field analyzed by Date module on save and usage

EDIT

My answer is for Drupal 7. The same module API can be referenced for Drupal version 6 if needed. You didnt specify what version of Drupal you are using and "CCK" can be apart of both.


I ended up doing this with the 'execute custom PHP code' action.  I created a 'Do Foo Once' component with the UI, and then added this to 'Do Foo N Times':

for ($i = $quantity; $i > 0; $i--) {
  rules_invoke_component('rules_do_foo_once', $i, $bar);
}


How to hide Header and footer printed page?

You can use module to print a node
also to remove unwanted region you can change print.tpl.php inside the module

or you can use css

@media print
    {
        #header,.menu_background,.breadcrumb,#comments,#sidebar-first,.footer_bg,.node-links { display: none; }
        .node-view{ display: block;height:800px; }
    }


Whats faster db_query, db_select, or EntityFieldQuery

To answer your question in short, db_query is the fastest! Here are some reasons, facts and figure compiled from different questions, sources:

A simple googling of this question, come up with following results:

For simple queries, db_query() is 22% faster than db_select()
For simple queries, db_query() is 124% faster than EFQ
For queries with two joins, db_query() is 29% faster than db_select()

and this

db_query():

Total Incl. Wall Time (microsec):   796 microsecs
Total Incl. CPU (microsecs):    0 microsecs
Total Incl. MemUse (bytes): 123,352 bytes
Total Incl. PeakMemUse (bytes): 124,248 bytes
Number of Function Calls:   38

db_select()

Total Incl. Wall Time (microsec):   1,118 microsecs
Total Incl. CPU (microsecs):    0 microsecs
Total Incl. MemUse (bytes): 425,216 bytes
Total Incl. PeakMemUse (bytes): 436,392 bytes
Number of Function Calls:   88

If you notice above db_select makes more function calls and utilize more memory than db_query.

See here for reasons on why to use db_select
See here for reasons on why to use EntityFieldQuery over
db_select
See here for performance comparison of db_query and db_select

I guess the choice should be solely based on your requirements. EntityFieldQuery might be slower but, offers many advantages such as simple syntax, field storage is pluggable, loose coupling and many more.


Re-render current form in submit-hook under certain conditions

drupal_rebuild_form() constructs a new $form from the information in $form_state.

I think you can also set $form_state['rebuild'] = TRUE; in a validation or submit hook as well to trigger the form rebuild.


I just tested this out, not sure if it is the best way, but it works.  Create a really simple custom module and implement hook_form_FORM_ID_alter().
YOURMODULE.info
name = YOURMODULE
description = Description of YOURMODULE goes here...
core = 6.x

YOURMODULE.module
<?php
/**
 * Implementation of hook_form_FORM_ID_alter()
 */
function YOURMODULE_form_comment_form_alter(&$form, &$form_state) {
  $form['_author']['#value'] = $form['author']['#value'];
}

Place these files in a directory named YOURMODULE, inside contrib modules directory. Then enable the module.
(Be sure to replace YOURMODULE with the name you choose to give to the module everywhere it occurs.)


Views 3 and HTML5 - how to override output for markup?

You'll notice that in your view under the "Style Settings" block there is a link for Theme: Information. It will expose all the theme files that are called for your view. You can use generic to very detailed theme files that will only be use for your views display.

The first file name in Display output is views-view.tpl.php. That will apply to all views and displays. The next one in the list is views-view--[view name].tpl.php. It will only apply to your view. It keeps drilling down until it gets as specific as possible. views-view--[view name]--default.tpl.php is the last one in the list and only applies to the default display of the view. Clicking the Display output: link will expose the template code that views uses. Simply copy and create a new template file with one of the suggested in the list. It's usually best to be as specific as possible. The template file can go anywhere in your theme and views will pick it up as long as you rescan template files in the theming information and save the view. There are view templates, row templates, field templates and field specific templates.

Once you learn how to manipulate view template files it will really open up your design possibilities.


Is it possible to alter the data passed into a Rule?

I think there are no hooks in rules by which you can achieve it. So you have 2 possible solutions.
1) In rules use the php code for action (Not recommended for security)
2) Use custom module to perform the action rather than using rules.


How to get drush to work with xdebug -- may have recently broken

The former drush script is still available as drush.launcher. I would recommend making this your entrypoint when using Drush with xdebug, and omit the drush "finder" script (called simply "drush") altogether.

If this does not work for you, you should make a report in the Drush issue queue on GitHub.


How to add query parameters in twig using path()?

Twig uses hashes where PHP uses associative arrays. So to fix your code just convert the array syntax to a hash literal:

{{
  path('blue_general.blue',
    {'node': node.id},
    {'query': {
      'destination': path('view.blue_search.page_1'),
      'cookie[blue_referrer]': node.id,
      'cookie[blue_type]':'node'
    }}
  )
}}


In drupal by default anonymous users have UID=0 , and you just need if $user->uid==0 set your variable to what you want , some string like "mehman" ,

because of doing little changes in your code I use inverse checking  of uid value ( the are as the same ,

if ( $user->uid ==0 )  $variables['persianName'] ='mehman';

or

if ( $user->uid !=0 ) ...... else  $variables['persianName'] ='mehman';

)

function apblog_preprocess_comment(&$variables) {
  $user = $variables['user'];
  $user = user_load($user->uid);
  $persianName = field_get_items('user', $user, 'field_user_pname');
  if ($user->uid !=0) {
    $variables['persianName'] = $persianName[0]['safe_value'];
  }
  else {
    $variables['persianName'] ='';
  }

  // …
}

I hope this work to you

be win ;)


I can´t publish the title of my contact form

The page title is in a block, you most likely just need to add that to one of your theme's regions (or create a new region for it).

You can place the block through the settings link visiting Admin -> Structure -> Block Layout.

If you need to add a region, define it in your theme's .info.yml file:

regions:
  ...
  page_title: 'Page title'
  ...

And add it to your theme's page.html.twig template wherever you'd like it to render:

{{ page.page_title }}

Flush the cache, and visit the Block layout page again to place the block in your new region.


You can create a paragraph type (paragraph module replaces field collection in Drupal 8) which contains a reference to your entity type A and a (or more) date and in your entity type B, have a reference to this paragraph.

You can also create a custom field which contains a reference to your entity type A and a date if you want have particular behavior (for example, don't allow users to sort items and sort them automatically by date).


Found a module that just did the job that I wanted.

The module is called FileField Sources


By the definition of that class, anything that is not an object with injected dependencies is legacy code. That's a rather bold statement. ;)

In hooks, it is usually fine to use static methods on the Drupal class. Making that a service like suggested there is only useful if it's non-trivial code that someone might want to implement differently or/and you want to write unit tests for it.

If you're writing a service, plugins, form classes or controller classes, you should inject the dependencies.

So it's not really a question about which methods you should be using or not; it depends on where you would call it.


Alter the wrapper of radios buttons in a custom module

You can do this directly in the form.

Add this to the radios element:

'#attributes' => [
  'attribute_name' = 'attribute_value'
],


Disable a 'enter/return' key function in a form

You need to use evt.preventDefault();

I wrote a blog post on making this work with drupal and ajaxified forms, which may let you see a slightly larger example including Drupal.behaviors.


Add product fields to cart form through line items

To be absolutely clear, you want the "Quantity Per Box" field present on product entities to display on the cart view?  For that you'll need to add I believe the "Commerce Line Item: Referenced Products" relationship in the view.  That should give you access to the product fields, with no need to copy a field from product entities to line item entities.

Since the cart is a Commerce Order view:
Relationships needed to reach products can be visualized as:
commerce_order->commerce_line_items->commerce_product


For internal path you can also specify user/login?destination="page name here"

will redirect to your internal path

For example you have a page called "contact-us" specify user/login?destination="contact-us" will automatically redirect to that page after login

Go through the README.TXT in login_destination module to get more info

hope this helps


IMCE browse server image upload button not displaying on ckeditor toolbar

Make sure you scroll down that same page and look for file browser settings and make sure its set to IMCE. Mine was on none and after switching that, the file browser upload button showed up in the image dialog popup.


What is the relationship between regions and panels?

Panels can be thought of as self contained themes you define within a specific Drupal Theme displaying the page.  Like Drupal themes, panels also contain regions, but you define them, rather than the default theme.

And to expand upon this a bit more:

Panels presents a way to display content similar to a theme, but in a more modular fashion.   This site gives an excellent example of how panels can be used. A mini-panel, for instance, is used similarly to a  block and can, in fact, be placed in a region of a theme just like blocks are.  The advantage is that a panel/mini-panel can contain its own layout regions further breaking down the layout.  For instance, the signature blocks in this Drupal Answers question layout contains the top line with how long ago the question was asked, the avatar, authors site name and reputation.  Using mini-panels this configuration could be defined as a single mini-panel and placed inside a larger panel that holds other mini-blocks laying out the arrows and other graphics at the left side, the actual question, the tags and the action links such as links, edit, etc.

This larger panel construct can also be placed within a theme region such as the 'content' area giving the site display you see for your question page. Other content such as a list of the answers to your question can also be added to the main content area. Other regions such as right sidebar can hold the related questions links.  In this way your panels are placed within the existing theme framework providing additional content layout flexibilities.

Panels can be laid out in prearranged formats or be user designed as custom layouts.  These panel layouts contain their own regions so you are in-essence adding regions within a theme regions.

Panels can also go one step further and totally replace the theme layout using the Panels Everywhere module.  This offers the user the ability to control the layout and styles directly.  While contributed themes can be very flexible and sophisticated, these very capabilities can also make them very complex and difficult to modify to meet individual project demands.  The more experienced you become in using Drupal, the more attractive this ability may become for you.

Panels also offer another advantage.  The panels module works very well with CTools Page Manager, joining graphic control with Page Manager's content control.  In this way you can intercept URL requests before Drupal responds and set rules and layouts to respond to various context conditions using 'Variants'.  IN this way you can vary the content depending upon the permission levels of a user, or the content type being requested.  If specific conditions are not met, then panels/page manager, returns display control back to Drupal.  In addition, panels can display views and even pass its context to the view to determine what the view will show.  All of this gives the designer the control necessary to duplicate the content and layout this site provides.


well bottomline is:

You want to import a spreadsheet (maybe with multiple sheets in it) on a regulary basis.

I'd suggest the module migrate, you find the possiblility to import csv-files (and also an example if i remember right).

Migrate has maybe a little more effort in the start, but it also has many nice features like a hightwatermark, means if there is a counter or a timestamp in your file (for each record), then migrate can skip easily over former imported items.

Also tranformation of data is (if neccessary) with migrate possible.

At least you should have a close look at the module migrate.


Changing the layout of a Taxonomy Term Page

Thanks to @prkos, it turned out that the root of the problem was located inside the Bootstrap Sub-Theme.
Someone created a (hacky) template override for one specific content type in a generic manner. By renaming the file views-view-unformatted.html.twig to views-view-unformatted--SOME-CONTENT.html.twig it kept the override for the mentioned content item, but also made layouts of other, generic content types work as intended.


Drush site install break when a custom commerce feature is enabled, why?

It seems to be a problem with Features and how Drush site-install processes.  Basically, features_include() is called after each feature is enabled during the site install.  Somehow (but most likely due to the ordering of the dependencies), the commerce_features module gets enabled after my custom feature.  As such, features_include(), which has already ran and cached its data, skips calling commerce_features_features_api(), which is crucial for my custom product types, included in yet another custom feature, to be created.

I opened an issue at http://drupal.org/node/1334438, see for more details and follow-ups.


Check the README.txt of the S3 File System module. Contains a couple of instructions that are helpful.

  In the unlikely circumstance that the version of the SDK you
  downloaded causes errors with S3 File System, you can download this
  version instead, which is known to work: https://github.com/aws/aws-sdk-php/releases/download/2.6.3/aws.zip

  IN CASE OF TROUBLE DETECTING THE AWS SDK LIBRARY:
  Ensure that theawssdk2 folder itself, and all the files within it, can be read by your webserver. Usually this means that the user apache (or _www  on OSX) must have read permissions for the files, and read+execute permissions for all the folders in the path leading to the awssdk2 files.

The link to the aws-sdk-php on the AWS installation page will allow you to download the latest version (3.4.1).

On my case, I had to download the 2.6.3 version of the SDK that is mentioned on the README.txt.

You might want to check at admin/reports/dblog if there are any errors related to loading the SDK.

I found that sometimes the libraries info gets hard cached and that is why this module has the _s3fs_load_awssdk2_library(). Take a look of this:

  This function is a replacement for calling libraries_load('awsdsk2'). It's needed because libraries_load() caches failures to load the library, meaning that temporarily having a bad setup (e.g. nonexistent or unreadable files in the awssdk2 folder) can lead to the library being permanently unable to be loaded, even after the bad setup is repaired. This can only be remedied by clearing the full site cache.

TD;LR: sometimes you will need to refresh the libraries cache for the SDK, if that is the case, the _s3fs_load_awssdk2_library() can be invoked by going to admin/config/media/s3fs/actions and use the "Refresh file metadata cache" button option. Or also you can use the Drush command drush s3fs-refresh-cache.


I sort of figured out a way to do this.

Add a variant within the Panels module
Add a visibility rule so that different variants show at different URLs (clean URLs and paths required), for example, example.com/paneltitle/variant1, example.com/paneltitle/variant2.
Create a custom module to hook into the menu. There is a great example of a menu module in the module code samples on drupal.org. A example here for above variants:

`

function custom_module_menu() {
  $items['paneltitle/variant1'] = array(
    'title' => 'variant1',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );

  $items['paneltitle/variant2'] = array(
    'title' => 'variant1',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

This seems to have worked for me.


how to show admin/reports/dblog in terminal ( cli )

You can use drush to do this:

$ drush help | grep watchdog
 watchdog-delete       Delete watchdog messages.
 watchdog-list         Show available message types and severity levels. A
 (wd-list)             prompt will ask for a choice to show watchdog messages.
 watchdog-show         Show watchdog messages.

drush watchdog-show has too many options to fully show here, but these are the examples:

 drush watchdog-show                       Show a listing of most recent 10
                                           messages.
 drush watchdog-show 64                    Show in detail message with id 64.
 drush watchdog-show "cron run succesful"  Show a listing of most recent 10
                                           messages containing the string "cron
                                           run succesful".
 drush watchdog-show --count=46            Show a listing of most recent 46
                                           messages.
 drush watchdog-show --severity=notice     Show a listing of most recent 10
                                           messages with a severity of notice.
 drush watchdog-show --type=php            Show a listing of most recent 10
                                           messages of type php.
 drush watchdog-show --tail --full         Show a listing of most recent 10
                                           messages with extended information
                                           about each one and continue showing
                                           messages as they are registered in
                                           the watchdog.
 drush watchdog-show --tail                Do a tail of the watchdog with a
 --sleep-delay=2                           delay of two seconds between each
                                           poll to the database.


Migrate is putting map tables in legacy database

Read up on the documentation on Map Tables under the heading Map Tables on that page. If you define legacy as the connection to make the map tables on -- then that's where they will go.

  When you construct the MigrateSQLMap object, add a fourth argument to
  tell it explicitly the connection on which to create the mapping
  tables.