Local Dev .theme file not loading I'm working on a local development environment (via Acquia Dev Desktop).  Our theme is a subtheme of the Stack theme.

In this situation, I'm making changes to my .theme file, but they don't seem to be loading at all.  If I make the same changes to the stack.theme, they load and work as expected.

I've ensured I'm using function <subtheme>_theme_suggestions_page_alter but still no luck.  There is nothing in the error.log either.

Got it fixed on my local environment by putting the base theme name in quotes and then clearing the cache.
Changed base theme: classy to base theme: "classy".
Also, check for a single quote on your theme's description. If you find it, make sure you put the whole description in quotes.


page not rendered from module i would show a page not themed by drupal from a specific path from my custom module.

I'm using drupal7.

Here is the example module:

file: custom_example.module

<?php
/*
 * Implementation of hook_menu()
 */
function custom_example_menu(){
  $items['foo/bar'] = array(
    'title' => 'Page Title',
    'description' => 'Simple custom hook_menu() implementation.',
    'page callback' => 'my_page_function',
    'access arguments' => array('access content'),
  );
  return $items;
}

/*
 * Returns custom content to Drupal
 */
function my_page_function(){
   return theme('my_custom_template');
}

/*
 * Implementation of hook_theme().
 */
function custom_example_theme(){
  return array(
    'my_custom_template' => array(
      'template' => 'custom-page',
    ),
  );
}

file:custom-page.tpl.php

hello

This works fine to show the page at mysite.com/foo/bar link but the page is themed with all drupal stuffs (header footer sidebar) that i don't want.

Thanks all

You would need to do something like this in your my_page_function

$output = '

hello

';

print $output;
die;

So don't return anything. It's not great and avoids everything drupal related really but it sounds like what you want to do. As using anything to do with drupal's theme functions will always be wrapped in the site of the site content


Draggable views weights not applied? I have hard time setting up a DraggableViews (DV) view to re-order content. The DV actually does save the weights - they appear correct in the draggable table, but on the user side (when viewed on the site page) the weights are all zero (not retrieved?).

The site is bi-lingual and the content is tagged with a vocabulary. The purpose of the DV is to set the order within a term. In the header there's an exposed filter to allow the admin set the correct sequence within a term.

To my eyes, the query run to generate visitor's view is correct, but I'm not an expert.

Please refer to the attached mockup image to get an idea what's going on.

I have the latest version of DV + Views 3.5.

Has anyone been through this? Does this have a known workaround? Is this module limitation or is it the view set up incorrectly?

Edit:

User-facing View:

SELECT draggableviews_structure.parent AS draggableviews_structure_parent, node.title AS node_title, node.nid AS nid, node.language AS node_language, draggableviews_structure.weight AS draggableviews_structure_weight
FROM
{node} node
LEFT JOIN {draggableviews_structure} draggableviews_structure ON node.nid = draggableviews_structure.entity_id AND draggableviews_structure.view_name = 'project_reorder' AND draggableviews_structure.view_display = 'page' AND draggableviews_structure.args = '[]'
WHERE (( (node.status = '1') AND (node.type IN  ('project')) AND (node.language IN  ('en')) ))
ORDER BY draggableviews_structure_weight ASC

Sorting UI View

SELECT draggableviews_structure.parent AS draggableviews_structure_parent, node.title AS node_title, node.nid AS nid, node.language AS node_language, draggableviews_structure.weight AS draggableviews_structure_weight
FROM
{node} node
INNER JOIN {field_data_field_genre} field_data_field_genre ON node.nid = field_data_field_genre.entity_id AND (field_data_field_genre.entity_type = 'node' AND field_data_field_genre.deleted = '0')
LEFT JOIN {draggableviews_structure} draggableviews_structure ON node.nid = draggableviews_structure.entity_id AND draggableviews_structure.view_name = 'project_reorder' AND draggableviews_structure.view_display = 'page' AND draggableviews_structure.args = '{\"field_genre_tid_i18n\":\"1\",\"language\":\"en\"}'
WHERE (( (node.status = '1') AND (node.type IN  ('project')) AND (node.language IN  ('en')) AND (field_data_field_genre.field_genre_tid = '1') ))
ORDER BY draggableviews_structure_weight ASC

Note that the sorting view makes use of arguments (derived from exposed filter), while the user-facing one does not. I would think this might case the problem.

Solution from Chris (original post):

It worked to me.

"
Only solution that worked for me was the following:

go to your content type/vocabulary
add a weight field (label: weight | machine name: weight | field type: integer
edit your sorting view and add sort criteria for your newly added weight field
edit your draggable views field and change "Handler" from Native to FieldAPI
under Field select your weight field
-go to your content view and add the new weight field as you sort criteria

This is the only thing that worked for me. If it doesn't work immediately, just reorder a few items on your draggable view so that the ordering values are reset.

Hope this works for you too.
"


Uploaded images in theme settings is going to be lost I have a flexslider and I make its images customizable through the theme settings. I added a caption property for the the slide to meet multiple languages websites as follows in theme-settings.php:

// setting property to determine the rendered images fields
$form['best_responsive_settings']['imagesCount'] = array(
      '#markup' => t('Enter the total number of images in the slideshow'),
      '#type' => 'select',
      '#options' => associate_array_vals(explode(',',  theme_get_setting('imagesCountOptions'))),
      '#selected' => theme_get_setting('imagesCount'),
      '#default_value' => theme_get_setting('imagesCount'),

  );

  $lang_list = language_list();
// rendering upload image form with caption textfield for every language supported by the website

  for ($i = 0; $i < theme_get_setting('imagesCount'); $i++){
      $form['best_responsive_settings']['slideshowImages'.$i] = array(
        '#type' => 'managed_file',
        '#title' => t('Image').' #'.($i+1),
         '#required' => false,
        '#upload_location' => file_default_scheme() . '://slides',
    '#default_value' => theme_get_setting('slideshowImages'.$i,'best_responsive'),
    '#upload_validators' => array(
      'file_validate_extensions' => array('gif png jpg jpeg'),
      'file_validate_image_resolution' => array('960x400','430x400')        ),

      );
      foreach ($lang_list as $lang){
      $form['best_responsive_settings']['slideshowCaption'.$lang->language.$i] = array(
    '#type' => 'textfield',
    '#title' => t('Caption').' #'.($i+1).' -- '.$lang->name,
    '#required' => false,
    '#default_value' => theme_get_setting('slideshowCaption'.$lang->language.$i, 'best_responsive'),
  );
      }
  }

In page.tpl.php I use the following to render the images:

<?php if (theme_get_setting('slideshow_display','best_responsive')): ?>

            <?php for ($i = 0; $i < theme_get_setting('imagesCount'); $i++): ?>
              <?php  if (theme_get_setting('slideshowImages'.$i) != ''): ?>
 //the following line causes a problem after some time

<img src="<?php echo file_create_url(file_load(theme_get_setting('slideshowImages'.$i))->uri);?>" alt="Slide"/><?php if (theme_get_setting('slideshowCaption'.$language->language.$i)): ?><?php echo theme_get_setting('slideshowCaption'.$language->language.$i) ;?><?php endif;?>

              <?php endif; ?>
            <?php endfor; ?>

    <?php endif; ?>
    <?php endif; ?>

Everything, initially, works fine, the images are uploaded to the theme settings and images are rendered well in the slideshow. However, after some time! I noticed that the images are disappeared from the template settings page and only the caption if supplied is remained. In addition I got the following notice:

Notice: Trying to get property of non-object in include() (line 159 of C:\xampp-2\htdocs\4test\drupal-7.28\sites\all\themes\best_responsive\templates\page.tpl.php).

Where the line 159 is the line regarded in the comment of the second code snippet above. This notice is repeated twice. What is the problem here? What is making this code initially works then after sometime it fails? What is making the uploaded files disappeared from the settings. In addition, the destination in-which images should be uploaded /sites/default/files/slides becomes empty. i.e the uploaded images files are deleted!

My solution is to ensure to make permanent the image when drupal load page theme settings. You don't need to create a custom submit handler because after the new settings are saved the settings page is reloaded, and the fix executed.

Plus, you cannot use "active theme" because sometimes the current active theme is the admin theme, and not the default or maybe the user is changing the settings theme in a theme that it's not set as default.

function YOUR_THEME_form_system_theme_settings_alter(&$form, &$form_state)  {

  $default_file_dir = 'public://template/logos';
  $folder = file_prepare_directory($default_file_dir, FILE_CREATE_DIRECTORY);
  $settings_theme = $form_state['build_info']['args'][0];

  if ($folder) {
    $my_logo = theme_get_setting('my_logo');
    // BUG: Force file to be permanent.
    if (!empty($my_logo)) {
      _fix_permanent_image('my_logo', $settings_theme);
    }
    $form['my_logo'] = array(
      '#type'               => 'managed_file',
      '#title'              => l('My logo'),
      '#default_value'      => $my_logo,
      '#progress_message'   => t('Please wait...'),
      '#progress_indicator' => 'bar',
      '#upload_location'    => $default_file_dir,
      '#upload_validators'  => array(
        'file_validate_extensions' => array('gif png jpg jpeg'),
        'file_validate_image_resolution' => array('375x50', '30x50'),
      ),
    );
  }

}

function _fix_permanent_image($image, $theme) {
  $fid = theme_get_setting($image, $theme);
  if ($fid > 0) {
    $file = file_load($fid);
    if (is_object($file) && $file->status == 0) {
      $file->status = FILE_STATUS_PERMANENT;
      file_save($file);
      file_usage_add($file, $theme, 'theme', 1);
      drupal_set_message($image . ' saved permanently.', 'status');
    }
  }
}


How to make a view specific to only 1 node, not all nodes I am building a register event calendar so people can sign up for future events. I have the calendar and the registration for events already completed. Now all I want to do is create a view that will display all the current registered users for the event, but here is the problem i'm running into.

In drupal views it is listing ALL the register users for ALL events. So instead of viewing only a group for one specific event, its adding every single person that has ever clicked the register button.

What steps do I have to go through to say "no, only list register users for THIS event"?

My content type is "Date" for setting a event and my registration is set to "Meetings". I'm not quite sure how to tell views to organize each event separately, rather than together.

At Taxonomy add one vocabulary and name as "Event". At content type add fields for particular info and "Event". User will fill up the particular as well as event type. At views filter by Event category. This is an example and I not really what is your structure. Hope it help


How can I get a block to display only on node view in Drupal 6 I have a block that I need displayed only on the main page of a node.

I can get it to display on node/1/view by putting node/*/view in the conditions, but that only works if view is in the URL. I want it to show whether I go to node/1/view or node/1, but NOTHING else. If I try node/* it shows it for every node page, not just node/1. I also tried node/*/ but that didn't work at all as it appears the ending slash is being removed.

In the visibility textarea of your block, select PHP code and put the following:

<?php
if (arg(0) == 'node' && is_numeric(arg(1)) && (arg(2) == '' || arg(2) == 'view')) {
  return TRUE;
} else {
  return FALSE;
}
?>


How to make menu items of restricted pages visible to all user roles? On a website I'm working on, logged in users can post their feedback about some functionalities which the website provides. While only logged in users should have access to fill the form, invisibility of the menu item "Share your experience" caused to not many users navigate to this page and fill the form.

So what I need is to have the menu item being visible and when anonymous user navigated to this link Drupal will show them the login form automatically (which would be a different issue).

There was an Always Visible module for Drupal 7. Now I want to know what technique should I use to make the menu item always visible in Drupal 8?

Ah look, Always Visible already had an issue regarding D8: Drupal 8 port of Always Visible. Some nice person created a Gist you can easily build a custom module from to always display all menu items.

I've done that for you and put it on GitLab: Always Visible (D8). Simply download the Zip file, unpack it, rename the folder to always_visible and put it into your /modules/custom folder, enable the module, done.


Permisssions based on file folders & content collection Can user permissions be customised based on file folders and content collections?

If so, what are the modules for this?

The FileDepot module should do what you want.


How to disallow certain strings in signatures? As I mentioned here, spam filters do not apply to forum signatures. This opens the door to human spammers to put their spam content in their signature. I am wondering what is the easiest way to tackle this problem? One obvious solution is to extend the signature or spam modules to fix this loophole. But that is beyond my coding capacities as I know very little of drupal API.

So I am wondering whether this can be done using some sort of preprocessing or defining some rules to check the signature for certain regexps and disallow registration/saving profile when the string is flagged as potential spam? I really appreciate your hints as I'm badly suffering from this problem.

In drupal, whichever field you are taking input as, you need to make sure that only plain text is inserted by the user. This way, drupal will run check_plain function to the text added, and no links, xss attacks can be made.


Why are field widgets not form elements? Form elements are often separate from field widgets, yet they implement very similar functionality.

Sometimes, their functionality also creep across the two apis, such as in this question: Is displaying a working Field Widget Form on its own possible?

It seems logical to me that a field widget could be a form element, that also happens to map directly to some underlying storage, especially since form api was already in place when field api came about.

I'm wondering why this is not the case.

Edit:
As pointed out by kiamlaluno below, according to the official docs, widgets are Form API elements, which means I need to edit my question a little.

I came about wondering about this, because I wanted to use the Core tagging widget as a form element. To the best of my knowledge however, there is no easy way of doing that. Despite the docs claiming widgets are elements, that does not seem to necessarily be true.

If a widget was declared as

function hook_widget_info() {
  return array('my_widget' => array(
    'base element' => 'some_form_element_machine_name',
  ))
}

then the element definition would be separate from the widget, so that it could be used on both ways, but currently this is not the case.

Edit 2:
Feature request opened.

It seems logical to me that a field widget could be a form element, that also happens to map directly to some underlying storage

Widgets are form elements; they just have additional capabilities a form element doesn't have. The documentation about the field widget API describe the widgets using the following words:

  Widgets are Form API elements with additional processing capabilities. Widget hooks are typically called by the Field Attach API during the creation of the field form structure with field_attach_form().

Every widget is implemented using at least one form element, but a module implementing a widgets needs to implement some hooks that are not required from a form element:

hook_field_widget_info()
hook_field_widget_form()
hook_field_widget_error()

While the first can be considered the equivalent of hook_element_info(), the other two are additional hooks necessary for the widgets to work. It's thanks to the information passed to hook_field_widget_form() that a widget is rendered.

Drupal could have implemented widgets expanding the properties returned from hook_element_info(), but the truth is that a widget and a form element are two different things that are used in different cases; consider a widget a more specialized type of form element.
If hook_element_info() were used also to return information about widgets, the code looking for widgets would need to filter out the form elements to keep the widget information; vice versa, the code looking for form elements should filter out the widget information. Considering how ofter that information is required, that is the reason why two different hooks are necessary.

Drupal could have used a "base element" property returned from hook_field_widget_info(). If such property has not been implemented, it means nobody proposed it, or it has been proposed, but it has been though to be useful on few limited cases.

As for Drupal 8, things changed a little, and form elements are objects of classes implementing FormElementInterface, while field widgets are objects of classes implementing WidgetInterface. The interface that is common between those interfaces is PluginInspectionInterface, which doesn't define any method for rendering a form element, which are instead defined from RenderElement, an abstract class.
Since now widgets are implemented with classes, the base widget is essentially the base class from which a widget class is derived; there isn't the need of a property to define the base widget of a widget.


Copy nodes of content type into Commerce Products I currently have a Drupal website for an art gallery with a content type of Listing (A piece of Art work). Each Listing has a price in a decimal field type.

We are now looking to convert the website to ecommerce using Drupal Commerce, but there is about 500 Listings.

Is there a way to bulk copy/create all the Listings into Products and auto create the product reference and copy the price over as well?

There is no direct option or module which can convert a content type nodes to commerce products. But there are few ways you can do it.
You can export your nodes to CSV via node export or views bulk operations and then import those products using commerce feeds module.
Another way is to create a custom module and do db_select of all nodes of your particular content type and then create commerce products programmatically. You can use batch process to do this so that php execution time don't break your script.


Checking if a field is empty fails, on a node template file Trying to use empty() on a "longtext" field in a custom node template, the field is always reported not to be empty (whatever the field is empty or not).

<?php if (!empty($content['field_myfield'])): ?>

additional content

  <?php print render($content['field_landing_petition']);?>
<?php endif; ?>

Why doesn't it work?  How else could I test for empty fields in the template file for a node?

$content['field_myfield'] is an array containing some keys; if you pass that array to empty(), you would not get back TRUE as result.
For example, I added a three fields to a content type (their types are "taxonomy term reference," "decimal," and "list of float values"); what you see in content['field_name'] is the following:

$content['field_name']['#items'] contains the content of the field; it's an array, as in Drupal 7 fields can contain multiple values.

The generic code that allows to check if the field is empty, which works for any field, without to know details about how the field values are stored, is similar to the following one:

// $field_name contains the name of the field.

$field = file_info_field($field_name);
$function = $field['module'] . '_field_is_empty';

foreach ((array) $content[$field_name]['#items'] as $item) {
  if (!$function($item, $field)) {
    $result = TRUE;
  }
}

$is_empty = empty($result);

$is_empty is equal to TRUE when all the items of the field are empty, giving to empty the meaning given to the word from the module implementing the field. For example, the module could consider the field empty when its value is "none" or any similar value (e.g. "empty" or "<none>").


Node export module imported node as another node numbers I used Node Export module to export my nodes.

I exported 3 articles that are node/1, node/2 and node3.

While I imported it into another site, the node became node/4, node/5 and node6.

How do I make it imported as the same node number.

If there is already have that node, it will override it.

Drupal 6

Settings:

Node export

When importing a node that already exists: Create a new revision of the existing node

UUID

Automatic UUID generation for taxonomy:

You can't, and you shouldn't.

Node Export requires UUID for a reason, and that reason is decoupling database identifier of a node (nid) from it's logical identifier and address. These are supposed to be defined by UUID now, so if you are using UUID module and still have addresses like http://example.com/node/1 then your site is not using modules in a way they are designed to work.

Also, as Node Export project page says, if you need anything fancy on import, you should export in Feeds format, and use Feeds for import. I believe that updating existing nodes is a case where it would be recommended approach.


Metatag and page title modules conflict I am using Drupal 7 with the Metatag module along with the Page title module.

I have a requirement to build the title of a custom content type using some node fields and additional conditions that I can't reproduce using the tokens provided, so I have hooked to the page title API ( hook_page_title_alter(&$title)) to build my custom title only for one node type.

The function works and the page title is set. But the meta tags are wrong, they are not using the page title found in <TITLE> (under <HEAD>) but the node's title which I don't want to use.

How do I feed metatags module with my custom title ? I am out of ideas, so anything is appreciated.

As commented by someone you don't need the page_title module if you use metatags, but page_title provides an API with hooks to alter the page title, and that's what I am using and what I need to use, so maybe the question could be reformulated to "How do I alter the page title generated by metatags?"

It is indeed a bad idea to have both modules altering the page title. A better approach I have found is to create a custom token, (which is really trivial with the provided example) and use it inside a metatag configuration for the desired node type. This way page_title could be uninstalled since it's no longer needed.


create directory with node I am interested in making a 'physical' folder structure to match a hierarchy I create through content types.

My hierarchy currently exists in the format

-Container
--folder
---presentation

and I want to create a folder structure when each level is created that mimics this, so that would be

[container_name]
[container_name]/[folder_name]
[container_name]/[folder_name]/[presentation_name]

I've been trying to use the drupal_mkdir() function within a module of my own creation which uses hook_node_insert, but I am a little too 'green' to know exactly what to do.

The method I used to solve this was that in my Drupal site I had entity references at each level that connected me all the way down to my root. It was a simple process of using the functions such as node_load() to return information about the entity and its title, which I was then able to concatenate into a string of text like is in the example above: container_name]/[folder_name]/[presentation_name]
After that I was able to simply use this code to build the folder after each node was submitted:

//$path contained the remaining file path to be built
$dirpath=variable_get('file_public_path', conf_path() . '/files');
drupal_mkdir("$dirpath/$path");


How to classify a view by letter? I have tags (taxonomy terms) and created a tags pageview.
I want to sort my tags alphabetically and group them by letter of the alphabet.
How can I do this? Thank you
I want a single page. I don't want to filter the results.
A :
ring
accessory
B :
bracelet
cap
candle
...

UPDATE
I have found a possible solution but I need help. In my view I created a "Global: Custom text" field and I grouped this field in the format of the view.
It sounds really good. Now what TWIG code to put in the "Global: Custom text" field to extract the first letter of {{ name }} (which corresponds to the field "Taxonomy term: Name").
I tested the following code, but it doesn't work :
{{ '{{ name }}'|first }}

I expect you could arrive at this by having a hyerachrical vocabulary. Use the drag handles indent terms as below.
A
- term 1
- term 2

B
- term 3
- term 4

If you needed to list terms in a view, you could use the 'terms with depth' option.
No idea why someone has downvoted your question. It seems perfectly reasonable.


Latest added data in a particular contenty-type on custom page I am a newbie in Drupal,I have content-type "News" where the user adds news related to product. I want to show the latest 3 added news on content-type "Home-Page" (Home-Page is not front page).

What would be the standard way to get the desired output?

**I am using Drupal7

There are many, many ways to accomplish this but here is one of the simplest ways I can think of.

I'm going to use the Drupal Views module to do this.  The intent of this is not to cover all things Drupal, rather it's to give you a crash course in creating a block using Views to accomplish what you're looking to do.

First, install and enable Views.  There are several tutorials out there that show you how to do this.  Nodeone has an awesome video introduction to Drupal Views.  (Personally this is one of my favorite Drupal resources. :)

Now that Views is installed and enabled, go to Structure, then 'Views' (In D7 this will be at http://www.example.com/admin/structure/views.)

Next create a new view (Add New View.)

Next, configure your View settings.  The example settings below will create a new block that contains the three most recent News items that link to the full version of each article article.  Views is capable of far more, but for the sake of simplicity I'll stick to creating a simple block.

Now go back to "Structure" and this time go to "Blocks."

My theme will be different from yours, but what you need to do is find the view you created, choose a location on your theme where you would like it to be displayed and then click save.  In this example I'm moving the block to the top of the navigation bar on the right hand side of my theme.

Once saved you should see similar output on your site as in the image below.  Note that this has my theme applied and your block will look different.

Lastly, to control which pages this block will be displayed on you can use the Blocks visibility settings.  How do I show blocks only on certain pages? is a great resource.

There are likely a million other ways to accomplish this, but this was the quickest I could think of using my nifty Greenshot app.


Omega 3.x base theme missing after Drupal upgrade After upgrading Drupal to 7.4.3, i am missing my Omega 3.x base theme in the ui. My subtheme is still present, but the layout is all messed up. Any idea's?

Where did you put your base theme?

It should be in the same folder as your theme "sites/all/themes". If you put it in the top themes folder, beside Bartik, Seven, etc, it was in the wrong place and this folder is overwritten when you update.

If his is the case you can probably just download it again and put it in the correct folder "sites/all/themes".


Image upload permissions problem I have my local site running on my Win 7 machine using Acquia Dev Desktop.

I also have a "live" version of the site.

In both environments I cannot upload an image for an article. I must have messed something up because it was working several days ago.

This link https://www.drupal.org/documentation/modules/image was useful, but the suggestions on Troubleshooting/The image doesn't show up didn't fix the problem. I'm sure it's because I don't really understand what I'm doing.

I'm wondering if a disable of the image module then a re-enable would solve the problem?

Have you checked Home » Administration » Configuration » Media
IN this Public file system path should be "sites/default/files" and Temporary directory should be "/tmp".
And check whether you files folder has read/write permissions and its subfolder's where you are saving image.


/admin/* pages "The website encountered an unexpected error" After two clean installs of Drupal 8.0.2 without issues on my server (Debian 7.1 / PHP 5.6.17 / MySQL 5.5.31) I can log in and out fine and view my user profile page, but that's it.

Any /admin/* pages returns the following error:

  The website encountered an unexpected error. Please try again later.

I'm a little stuck as effectively I can't do anything and this wasn't an issue locally on WAMP. Can someone offer me guidance please? I've had a look for error logs on the server but unless I'm looking in the wrong places I'm not seeing anything.

Database watchdog shows the following error. (The serialized array has been edited to show the relevant parts.)

  GuzzleHttp requires cURL, the allow_url_fopen ini setting, or a custom HTTP handler.
  GuzzleHttp\choose_handler()
  /var/www/virtual/mysite.info/drupaltest/htdocs/vendor/guzzlehttp/guzzle/src/functions.php";
  line 116

As suggested in other similar posts I have tried increasing max_allowed_packet.

Just to get this marked off as answered (with thanks to Clive).

First of all was understanding how to make use of the database watchdog table to find the errors. You have to download and view the variables column... the error's in there. In my case it was that cURL was not installed.

It was as simple as installing cURL and restarting the Apache service.

apt-get install php5-curl

Thanks again to Clive!


link each active block to it's page url I want to link availaible block bids with active url. Then i want to clear page cache by block. How to do that best way? I wanted to use

block_list($region)

But it's overhead.

Knowing where any block is displayed can be tricky; you would need to keep a nontrivial database table in order to do that (Boost 6.x does this with nodes that are in panels and views). A better option would be to output the block via AJAX or ESI.

http://drupal.org/project/esi/ (has ajax output option)
http://drupal.org/project/ajaxblocks/
http://drupal.org/project/ajaxify_regions/


Create a view of nodes based on user record In Drupal 7, I have a Content Type, let's call it fruit. I have added an entity reference field to fruit to the user record. I want to create a view that lists all the fruit, but puts a mark next to those that have been ticked on their user record.

I am unable to work out how to do this, principally because I can't see how to add a Relationship to the user record.

Any help would be appreciated.

For entity reference fields there are 2 types of relationships added to views: a Referenced entity and a Referencing entity.

Referenced entity is used for a reference from the base table (e.g. A user view that references a fruit node).
Referencing entity is used for a reference to the base table (e.g. a fruit node view that references a user)

In your case, it's Referencing entity that you want.

Create a node view and a Entity Reference: Referencing entity relationship (the description should read A bridge to the User entity that is referencing Content via field_FRUIT_NODE_REF) that refers to your fruit node reference.

That should handle the data/reference part. What remains is aggregation/filtering (e.g. there will duplicates if fruit node references aren't distinct for each user) and display (e.g. how to display marking a fruit node referencing a current user).

Depending on your needs, you might need a custom field/template since there is a limit of what you can do with field basic rewriting and default user contextual filters.


How do I customize a table display with views I want to setup a View that will display all Title's within the company in a certain way.

History (not sure if necessary, but I imagine it can't hurt): I had a lot of duplicate Title's, because I grab the title from the user node, no distinct features seemed to help. I found a way of using hook__query_alter(QueryAlterableInterface $query) to make sure the titles were in order and they were not duplicated. If I display the View, as is, as a table, it looks like a normal list:

But I want the table to look like the following:

Can I do this without code? No idea how, If I can't, which is fine, my real question is below:

I can grab the view in template_views_pre_render(&$view), I noticed I can also snag some of it in the hook_preprocess_views_view(&$vars), and I can grab pieces in the template (...tpl.php) files like views-view-field-w/e.tpl.php and views-view--w/e.tpl.php. But as it stands I really don't know where to begin my algorithm and sifting through. In order to do this I imagine I build 3 arrays, array A, B, and C (eventually also D, E, F, etc.) and just spit them out in one of the template files to build rows for each alphabetical column in a table structure, but where do I build these arrays up, I hear preprocess hook is where it might be done? If so, how do I hand them over to the template files (stuff them back into the views array?). If I shouldn't be doing it that way, should I just build up my arrays and spit them out in the table format all in the template files?

In order to do this I handled everything on the views-view-unformatted-{view_name}.tpl.php level.

I am not sure if it is the most efficient way of doing all of the work, but it works like a charm. If anyone has any suggestions on how to optimize the code, or if I should be putting this work in the template.php file please let me know, but as it stands this answered and solved my problem.

/* Issue:         In order to accomodate the appropriate style requirements of
 *               this view we need to override with this file and handle the $rows
 *               in the following format. The standard Table Format for Views
 *               does not provide what we want (refer to Description to understand
 *               what we wanted).
* Description:   Overriding the views-view-unformatted...tpl.php file so we can
 *               better control view page. This View displays
 *               all the Employee Titles. Which is fine, but we want it in a
 *               particular format:
 *  (headers)                  A                 B                 C
 *  (titles)              App Specialist   Batch Processor   C.........
 *                        App Developer    B..........       C.........
 *
 *
 * ==========================================================================
*/
?>
<?php
    /*
     Lets grab and collate all of the Employee Titles and the the headers for
     each set of Employee Titles (Example of a set = all titles that start
     with 'A', or 'B', etc.
    */

    // Employee Titles.
    $titles = array();
    // Employee Title Headers.
    $title_headers = array();
    // Keep track of the character we are on.
    $first_character = '';
    // Keep track of the last character we were on.
    $last_character = '';
    // Header count for the iteration process.
    $head_count = 0;
    // Title count for the iteration process.
    $title_count = 0;

    foreach ($rows as $row) {
      $employee_title = strip_tags($row); //strip
      $employee_title_trimmed = trim($employee_title); //trim
      $first_character = $employee_title_trimmed[0];

      // We don't have the character saved.
      if ($last_character != $first_character) {
        // Increase count.
        $head_count++;
        $title_count++;
        // Fill the headers array.
        $title_headers[$head_count] = $first_character; // add the letter
        $last_character = $first_character; // update the last character
      }
      // Fill the employee title's array
      $titles[$title_count][] = array($employee_title_trimmed => $row);
    }

    /* Time to display the header and title arrays. */
    // We only want 3 columns, so that's what this variable ensures. if we
    // wanted 4 or 2 columns we just change this variable and it will take effect
    // throughout.
    $columns_limit = 3;
    // counter for the employee title headers.
    $count_header = 1;
    // Max counter for the headers.
    $max_count_header = $count_header + $columns_limit;
    // Counter for the employee titles.
    $count_list = 1;
    // Max counter for titles.
    $max_count_list = $count_list + $columns_limit;

    print("
");
    while($count_header < sizeOf($titles)){ //never exceed size of titles
      print"
"; // Header row starts.
      // Display 3 or less headers, depending on where we are in the array.
      for ($count_header; $count_header < $max_count_header; $count_header++){
        print "";
        print $title_headers[$count_header]; // Display header.
        print "	";
      }
      print"
"; // Header row stops
      print"
"; // Employee title row starts
      for ($count_list; $count_list < $max_count_list; $count_list++) {
        print'';
        print"
";
        foreach ($titles[$count_list] as $titles) {
          $title_value = array_values($titles);
          $title_entry = $title_value[0];
          print"
";
          print $title_entry; // Display the employee title.
          print"
";
        }
        print"
";
        print"	";
      }
      print"
"; // Employee title row stops.
      $max_count_header = $count_header + $columns_limit; // Update Header's Max
      $max_count_list = $count_list + $columns_limit;     // Update Employee's Max
    }
    print("
");


Filter referenced item without losing other content I have 2 entity types Content type A and B.
Content type B has a date field and an entity reference to A.

I need a view that shows all the nodes of content type A
But also shows all the referenced content, until this point I have no problem.

The only problem is that the content type B needs a filter to only show the content from this year. But when I add a filter to the date field all the nodes that don't have an entity reference also get filtered out.

Content type A are assets

Fields:

Title
Address
lat/long

Content type B is the maintenance of these assets

Fields:

Title
Entity reference to A
date field

Now I want to show all the assets in a view.( also the ones that don't have maintenance done)
In the same view there should be a column with all the maintenance within a certain timespan.

When I have this view i can put these on a google map and show which assets need maintenance and which are already done

As what I understand your needs its very simple.

You have to set the filter criteria in the views:

Add Content Type A
Add Content Type B
Add Published field twice
Add Date Field and set its criteria as you already set
The field (Entity Reference field in Type B) that reference to Type A and set its operator as Is not empty (NOT NULL)
Now, Open re-arrange the filter criteria fields

 7. You need to Create new filter group under the filter criteria and drag drop your fields in required group like below

I hope this will at least give you an idea how to filter different content types with different field(s).

Thanks


What is the difference between \Drupal::request()->getSession() and \Drupal::service('user.private_tempstore')? As the title suggests, I'm a bit confused about those two methods of creating and accessing a session on Drupal 8. I'm not quite sure when to use the one over the other, could someone point me to the right direction?

My issue started after a Drupal update, where originally I was using this way to start a session for anonymous users on my module:

$request       = \Drupal::request();
$this->session = $request->getSession();

$session       = $this->session->get('mymodule');

After the update, the above code won't create a session for anonymous user and the only way to make it work was this piece of code:

$tempstore = \Drupal::service('user.private_tempstore')->get('mymodule_name');
$tempstore->set('my_variable_name', ['test var' => 'this is my value']);

echo '<pre>';
print_r($tempstore->get('my_variable_name'));
echo '</pre>';

So, even though I've managed to make it work, I'm not quite sure why it did work that way.

The main difference is that session data is stored in the database table sessions and PrivateTempStore in key_value_expire. Session data is preloaded in memory, private tempstore data only when requested. Session data is for small amount of data not exceeding a few megabytes, private tempstore for bigger chunks of data you don't want to have in memory when not needed.

What you've posted is not starting a session, it gets a value. You would need to set a value first to start a session.


Display only banners for a specific month I need to create a View that will display a banner for a specific month (regardless of the year).

I create a field for that called, DisplayMonth, which holds an integer (so September is 9).

I would like for that banner image to change automatically for 2014. Any september month, no matter what year, it will display the record with DisplayMonth = 9.

Create a contextual filter against the field that holds the month number. Provide a default value of PHP code:

return date('n');

Now only those nodes will display in September that have 9 as the month number.


Cannot clone an aegir site I am getting this error while cloning the site on aegir

  Unknown option: --profile.  See drush help provision-backup for available >options. To suppress this error, add the option --strict=0. [2.39 sec, 21.19 MB]

I am using aegir3 on ubuntu 14.04.4.
Can anyone please help me solve this.
I have searched on web but there is no solution regarding this issue.
This issue also occurs while migrating.

As I mentioned in IRC, the following work-around should resolve that particular issue:

Login to the server via ssh.
Become the 'aegir' user (sudo -u aegir -s -H)
Create a file call /var/aegir/.drushrc.php with the following contents:

 <?php
 $options['strict'] = 0;

That said, this appears to be a bug, though not one that has been reported previously. If anyone else stumbles across this issue, please file a bug report at https://www.drupal.org/node/add/project-issue/provision.


Aegir installation issue While installing Aegir in a VM, during the hostmaster installation, I got the following error:

Do you really want to proceed with the install (y/n): y
PROVISION_SITE_INSTALLED                                             [error]
The external command could not be executed due to an application     [error]
error.
Drush command terminated abnormally due to an unrecoverable error.   [error]
Error: Unsupported operand types in
/var/aegir/drush/includes/environment.inc, line 916

Drush version 4.5

Here is an issue on Drupal Groups: http://groups.drupal.org/node/96639.

Possible solutions:

Check if your system is Ubuntu (the installation script assumes that
it is)
Remove everything in /var/aegir and run the installation script again.
Run 'mysql_secure_installation' command and finish it successfully. Aegir
checks for security flaws during installation and block it if, for
example, you have anonymous users enabled in mysql.


Preprocess execution is not where my view is I'm trying to create a preprocess function to my custom view. Template is called as expected but my preprocess is called at beginning of html and left my entire page blank.

If I change to default template (views_view_unformatted.html.twig) the execution of theme_preprocess_views_view_unformatted() works as expected, right on my view is. But if change to views_view__custom.html.twig the execution of theme_preprocess_views_view__custom() occur at beginning of html!

This is the normal behavior? Or something is wrong? I just want to create my custom view template and create a preprocess function for it.

In Drupal 8 it is possible to have preprocess functions for the theme suggestions.

So let's say if your template for the View is views-view--test-view--block-1.html.twig, you would have following preprocess functions:

THEMENAME_preprocess_views_view__test_view__block_1
THEMENAME_preprocess_views_view__test_view
THEMENAME_preprocess_views_view


Adding META tag to nodes with a specific topic If a node has a term reference to a specific term (say termid 123) I want to add this META tag to prevent search engine spiders from indexing the page:

<meta name="robots" content="noindex">

Is hook_page_build() the right hook for this?

I think you definitely could use hook_page_build() (it would work), but since that hook is really intended for use with page.tpl.php, and meta tags are outputted in html.tpl.php, I think it might not be the 'Drupal' way.

Another option might be to use hook_html_head_alter(), which allows you to alter the <head> tags before they're rendered:

function MYMODULE_html_head_alter(&$head_elements) {
  if ($node = menu_get_object()) {
    $tid = function_to_get_term_id();
    $related_tids = field_get_items('node', $node, 'field_FIELD_NAME');

    if (!empty($related_tids) && $related_tids[0]['tid'] == $tid) {
      $head_elements['MYMODULE_meta_robots'] = array(
        '#tag' => 'meta',
        '#type' => 'html_tag',
        '#attributes' => array(
          'name' => 'robots',
          'content' => 'noindex'
        )
      );
    }
  }
}

You might also want to look at adding rel="nofollow" attributes on the links to those node in teaser displays, it might help speed up the process a bit.


How do I configure the REST API? A couple months back I successfully setup a development site to learn about the Drupal 8 REST API with version 8.0.x using the REST UI module for configuration. When I heard about the improvements to the REST Services in Drupal 8.2 I was pretty excited (from my understanding it is now possible to access configuration data such as content types and taxonomy terms) so I setup a new install using version 8.2.1. However, understanding the configuration for 8.2 is pretty daunting, and since it's so new there are very little resources around the setup and configuration.

I was able to locate this resource and I imported the example configuration provided, but was still unsure on how to configure other REST Endpoints.

I used the default configuration provided in the above resource. It looks like this:

langcode: en
status: true
dependencies:
 module:
   - basic_auth
   - hal
   - node
id: entity.node
plugin_id: 'entity:node'
granularity: resource
configuration:
 methods:
   - GET
   - POST
   - PATCH
   - DELETE
 formats:
   - hal_json
 authentication:
   - basic_auth

How do I edit the configuration once it's imported via the configuration manager?
Where can I find the available plugin_id's so that I can configure other resources? Where can I learn more about plugins?
How would I begin to implement my own REST endpoint?

I know this is a lot to ask, but at the time of writing there is little to no information covering these topics so I figure other people might be confused as well. I would like to create a guide on this, but that would first require that I understand it first.

I search a lot too after 8.2x and this is how i got it working :

Example for a custom user ressource :

  myModule/config/install

  rest.resource.user.rest_ressource.yml

langcode: en
status: true
dependencies:
  module:
    - basic_auth
id: user.rest_ressource
plugin_id: 'user_rest_ressource'
granularity: resource
configuration:
  methods:
    - GET
  formats:
    - json
  authentication:
    - basic_auth

  In myModule/src/Plugin/rest/resource

  UserRestRessource.php

<?php

namespace Drupal\myModule\Plugin\rest\resource;

use Drupal\Core\Session\AccountProxyInterface;
use Drupal\rest\Plugin\ResourceBase;
use Drupal\rest\ResourceResponse;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Psr\Log\LoggerInterface;

/**
 * Provides a resource to get view modes by entity and bundle.
 *
 * @RestResource(
 *   id = "user_rest_ressource",
 *   label = @Translation("User Rest"),
 *   uri_paths = {
 *     "canonical" = "/api/user/getInfo"
 *   }
 * )
 */
class UserRestRessource extends ResourceBase {

  /**
   * A current user instance.
   *
   * @var \Drupal\Core\Session\AccountProxyInterface
   */
  protected $currentUser;

  /**
   * Constructs a Drupal\rest\Plugin\ResourceBase object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param array $serializer_formats
   *   The available serialization formats.
   * @param \Psr\Log\LoggerInterface $logger
   *   A logger instance.
   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
   *   A current user instance.
   */
  public function __construct(
    array $configuration,
    $plugin_id,
    $plugin_definition,
    array $serializer_formats,
    LoggerInterface $logger,
    AccountProxyInterface $current_user) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);

    $this->currentUser = $current_user;

  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->getParameter('serializer.formats'),
      $container->get('logger.factory')->get('restimadiff'),
      $container->get('current_user')
    );
  }

  /**
   * Responds to GET requests.
   *
   *
   *
   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
   *   Throws exception expected.
   */
  public function get() {

      $responseResource=new ResourceResponse(
          array()

      );
    return $responseResource;
  }

}


Mimemail + SMTP + Mail System: inline images make body empty I'm trying to send HTML mails on a Drupal 7 install.
For this, I use Mail System, SMTP authentication and Mime mail modules.
I used settings as Alternative approach on this page http://drupal.org/node/1200142

The mail content is built within custom modules I'm writing (not by rules or simplenews, I mean).
I tweaked default Mail mime template to my needs, within a separate, light drupal theme.

My mails are sent (and received) without error when they contain only HTML and styles.
There are no error also when I had images with absolute url: Mime mail is leaving them as such.

I need to embed a few small images within my mails and when I try to do so, accordingly to what's written in Mime Mail README, I get a "Message body empty" at the top of my page when my code tried to send the mail.

I placed dpm($message) along the Mime mail code to locate where the body content is left empty.
I finally reached the
class MimeMailSystem implements MailSystemInterface
located in mimemail/includes/mimemail.mail.inc

Body content was still there.

Then the class MimeMailSystem__SmtpMailSystem implements MailSystemInterface
in default/files/mailsystem/MimeMailSystem__SmtpMailSystem.mail.inc

Again, my content was still there, along with inline BASE64 encoded images.
So the content disappears somewhere after that (in Mail System ?)

As I pointed it out here, switching Site-wide default MailSystemInterface class in Mail System settings from
MimeMailSystem__SmtpMailSystem
to
MimeMailSystem
allows the mail to be sent with its images, but the mail is no more sent through SMTP.

I'm pretty sure this is not due to a bug within one of the 3 modules, but I can't figure what I'm doing wrong.

The only thing I doubt from here is how I build the mail content :

I build some variable HTML content
I store it in $message['body'][] in my module's hook_mail implementation
then I print $body in my mimemail-message.tpl.php within static HTML part of the mail

The images I try to embed are in public files. I tried to link them :

with relative paths like sites/default/files/<filename>
with relative paths like public://<filename>

with no success.

Does anyone has a magical one character solution for something I missed ? ;)

Regards,

Further investigations lost me into the SMTP Authentication Support module
It's complicated enough and I couldn't locate something to help me find what was the problem coming form my configuration.

After a quick search within issues of Mime mail, someone was linking to another module to handle SMTP connection: enter link description here

Basically it works the same way than SMTP Authentication support but its benefit is you don't have to create a bridge mail system class between it and Mime mail, it's natively integrating with Mime mail.

To make it work properly, I had to configure Mail system as such :

Site-wide default MailSystemInterface class: MimeMailSystem
Mime Mail module class: MimeMailSystem
PHPMailer module class: DrupalPHPMailer

and in Mime mail settings :
 - set Mail engine to PHPmailer


Views - Filters - weird scenario Ok, I'll try to describe the scenario I am facing since I can't narrow it down to sub-questions to see what feedback I can get.

Say I am constructing an e-commerce site that sells cakes (I love that example as it seems).

I have already created a view that shows all my cakes sorted alphabetically as thumbnails and also one view that shows all my cakes at a themed alphabetical 'catalogue' style (as this question shows) and both views link to eachother.

All nice and nifty.

Now what's come up is that the cakes are tagged with taxonomy terms that mark their... ehh.. flavor, their size, and say their... use (party - wedding - just a normal cake). I know the example is stupid but you get the idea.

The tricky part comes when I need a global (global as in available in all pages throughout the site) dropdown list menu that lists those taxonomy terms and upon selection takes the user to the first view (the thumbnail one) which is filtered only with the cakes that match the selected taxonomy.

I hear you mumbling that that's easy and that contextual filters is all I need. And I agree, and I've done that.

The tricky part comes now: If the user was lead to the view by this route and he clicks to go to the 'catalogue' view, the cakes that match, should be higlighted and if the user is in the 'catalogue' view and selects another taxonomy term from the menu he should remain in the current view and the appropriate cakes should be highlighted. Also if he should go back to the 'thumbnail' view, it should be also be filtered accordingly.

So, recap:

1) clicking a taxonomy term leads to a filtered 'thumbnail' view.
2) clicking the 'catalogue' view link while on the filtered 'thumbnail' view leads to a highlighted 'catalogue' view and vice versa.
3) clicking on taxonomy while on either 'thumbnail' or 'catalogue' view should perform the aforementioned mentioned actions.
4) if the user navigates away from either of the pages the whole process resets until a taxonomy is selected again.

P.S. on the 'catalogue' view the cakes' divs have their taxonomy tags as classes to make highlighting easier.

Thanks for your time in advance.

EDIT: I managed using arg(x) to make the links from one view to another dynamic, i.e:

if the user is in www.cakes.com/Cakes/AllCakes/[tid] and clicks the link to the 'catalogue' view, the link instead leads to www.cakes.com/Cakes/AllCakesList/[tid] which is filtered, which leads to the following question too:

5) is there a way to use contextual filters NOT for filtering but for other functions like adding a CSS class for instance?

EDIT #2: Marking with strikethrough the tasks already completed.

EDIT #3: First EDIT marked since filtering is (obviously) not the way to go. But since I have the [tid] on the URL and thus on arg(x) I could somehow use it to highlight the appropriate divs.

EDIT #4: Managed via inline javascript and using the arg(x) argument to highlight the cakes in the 'catalogue' view!

It's funny how some times after you ask someone or a community for some solution you actually see the problem more clearly.

I was able to complete all of the mentioned tasks and I will summarize here just in case someone bizarrely stumbles upon a similar scenario in the future - although I really doubt it.

So, the views linking to each other dynamically was accomplished using the [tid] argument from the URL and passing it accordingly:

<a href="/Cakes/AllCakes/<?php echo arg(2);?>">
<a href="/Cakes/AllCakesList/<?php echo arg(2);?>">

The jump menu itself is set to Link to the thumbnail view by default unless the url is that of the 'catalogue' view. If so, via theming:

<?php if (arg(1) == 'AllCakesList'){
  $output=  str_replace("/AllCakes/" , "/AllCakesList/",$output);
}?>
<?php print $output; ?>

It leads to the 'catalogue' view.

And if the user is on none of those pages, the jump menu will lead him to the thumbnail view thus also fulfilling the 4th task in my question. That's all folks, sorry for the monstrous post!


Using Fivestar to list items that are 'trending' (highly rated in the last week) I would like to create a list of items that are 'trending'. By 'trending' I mean nodes (in my case, Watches) that have been highly rated within the last several days. Right now I have a block that displays the 4 highest rated Watches, and would like to create a similar block that displays the 4 highest rated Watches, but only using votes that have been cast within the last 3 days.

For the trending block, I have the following filter criteria (the content type for a watch is Watch Detail):

Content: Published (Yes)
Content: Type (= Watch Detail)
(Vote results) Vote results: Timestamp (>= -3 days)

The watches are sorted by highest rated using the following sort critera:

(Vote results) Vote results: Value (desc)

It's a fairly standard view, and I used the Relationship Content: Vote results to access the voting results for sorting and filtering.

The problem with what I've done is that while it is filtering by watches that have received votes within the last 3 days, it is not calculating the average value of the rating on votes that have been cast in the last 3 days. It is using the rating of the watch since the watch node was created. Hence, the Trending block and the Top Rated block essentially are identical, since the rating isn't limited to the last 3 days.

If anyone has done something like this I would very much appreciate some tips for how to limit the calculation the the average vote value to only votes cast within the last 3 days.

See http://ratemytimepiece.com/ for the exact website I'm working on if that helps you visualize this a little better.

Fivestar uses voting API. Voting API stores the individual votes and the total aggregates. You'll either have to create your own aggregates or calculate it "on the fly".

If you have lots of ratings in a week you'll be better off calculating your own aggregates. I would take a look how voting API does the calculation and copy that to your own module. Then modify it to only aggregate votes in the last week.

If you don't have a lot of ratings you can do it in views. Create a view of your type "watch detail". Add relationship "content: votes", require relationship, value type "percent", vote tag (whatever vote tag you are using for those fivestar ratings).
Then add filter "votes: value" >= 80 (gives you all 4 + 5 star ratings), "votes: timestamp" > "-1 week". Check to make sure you'll see the correct ratings show up.

Now turn on aggregation, add "nid" and use "count distinct" to show the number of ratings for each node. Then sort by that value.

Turn on query caching to make sure the view renders quickly for future requests.


exposed filter default values from user fields How can i set the default value of exposed filter for a view with the current logged in user profile checkboxes?

There can be multiple choices.

Thank you

Try like this.

function custommodule_form_views_exposed_form_alter(&$form, &$form_state){
  if($form['#theme'][0] == 'views_exposed_form__article__page_1'){
      $form['ct']['#options']['All'] = 'All Article';
  }
}


Drupal update domain whitelist I'm working on a Drupal project that will live on a locked-down webserver. The internet access on that box is constrained by a domain whitelist so I need to be able to provide a complete list of the domains that are needed for Drupal to update itself and its modules.

We're using Acquia-Drupal so we'll certainly the following to be able to update Drupal itself:

git.acquia.com

I ran a drush update while listening with netstat -t -u -c to try and get a feel for which domains are needed. This raised the following:

*.drupal.org  (obviously)
ec2-174-129-202-133

The latter seems to be an AWS domain.

I realise it may depend on the modules to some extent, but is there a definitive (and unchanging) list of domains that are required to update Drupal's modules?

I'm particularly concerned that if I start getting into AWS domains, they will change down the line, breaking our update path!

The whitelist that we used (which seems to work fine) is as follows:

master.drupal.org
master2.drupal.org
ftp.drupal.org
ftp-osl.osuosl.org
git.acquia.com  <-- we are using this repo for Drupal core, you may not need it

They may not all be needed, ftp-osl.osuosl.org in particular may be required by another part of our stack, but this represents a working list of required domains.


Update script fails due to Service capacity I am trying to update the core of my Drupal site. I neglected updates for some time and the update script had 19 updates pending. Apperently the update script tries to do all of this in one go, and fails miserably. I get an error message like this:

StatusText: Service Unavailable ResponseText: 503 Service Unavailable Service
Unavailable The server is temporarily unable to service your request due to maintenance
downtime or capacity problems. Please try again later.

and this one:

  An AJAX HTTP error occurred. HTTP Result Code: 503 Debugging
  information follows. Path: h t t p
  ://mysite.com/update.php?op=selection&token=7R0M7yvUZR09UsRDFf9FUAYhV9Ui82efUzsZPh61JZU&id=152&op=do
  StatusText: Service Unavailable ResponseText: 503 Service Unavailable
  Service Unavailable The server is temporarily unable to service your
  request due to maintenance downtime or capacity problems. Please try
  again later.

I have the following questions:

Has anyone seen this one before? If so how do I solve it?
If not, can I run the other 18 pending updates somehow?
If not, how harmfull is it if I don't run update.php?

Attempt to answer your questions ...

  Has anyone seen this one before? If so how do I solve it?

I've never seen this error before. But what I don't see anywhere in your question is that you FIRST disabled all modules, prior to upgrading Drupal core. And that is problably where your error originates from.

So if you have not done that, try doing so now as a first step. Note each of the modules you're disabling, so that afterwards you know which one to re-enable again. Note "all" is more then just the 18 modules you mentioned that needed updating (so also those modules which do not require any update).

After all these modules are disabled, try to upgrade Drupal Core. I'd expect that upgrading core then should work just fine.

  If not, can I run the other 18 pending updates somehow?

I would NOT try to do that. Instead first make sure core is upgraded, as explained in my prior item.

After core upgrade completed fine, re-enable all modules again that you disabled to complete the core upgrade. From then on the 18 pending updates should appear also again (of course). Then perform the update of each of those 18 modules, one by one.

  If not, how harmfull is it if I don't run update.php?

NOT running update.php is not something I would consider. In other words: if your Drupal installation shows messages that updates are pending, you better apply them ASAP.

Does this help somehow?

PS: worst case (if everything else goes wrong): restore from your last backup (you have that, right???). Then apply the steps I described above. I'd assume you would not run into similar errors anymore.


How to print id of user whose profile I visit rather than id of  logged in user? I would like to print the id of the user on his profile page? How can I do it in Drupal 7. So far I could only print logged in user id..Any advice appreciated.

The function menu_get_object() allows you to get a user/node/.. object based of the current request URL.

To get the account object, you can do this:

if ($account = menu_get_object('user')) {
  print $account->uid;
}


How to get nid of all nodes that are displayed inside a view? I have view named 'xyz' set on example.com/xyz. I want to access nid of nodes that are shown by 'xyz' and show them on example.com/abc. I want to do it in a custom module. What hook i can use?

I tried to look into views API but no ups there.

You can use views_get_view_result($name, $display_id = NULL)

API Docs: views_get_views_result();


How can I verify users the first time they log in? I was reading this article. I would like to know how logging in with the REST API in Drupal 8 works. By default, when users log in, Drupal will verify username and password. After the login, the browser has a cookie for the created session.

With the REST API, how can Drupal 8 verify users the first time they log in? After the login, how does it check the current login?

Log in to Drupal by POSTing the user credentials. Make sure you set the "Content-Type" header. This starts the user's session.

POST URL:

/user/login?_format=json

Header:

Content-Type: application/json

POST data:

{
  "name": "username",
  "pass": "password"
}

Successful response:

{
  "current_user":{
    "uid": "1",
    "roles":[
      "authenticated",
      "administrator"
    ],
    "name": "username"
  },
  "csrf_token":   "asda09820380_2238019280dk09n908asjdlkajdaoa",
  "logout_token": "asdasd09a8sdaslkdasl-asdasdklsajdlkasdjlksj"
}

Use the CSRF token in subsequent GET, POST, PATCH, DELETE etc. requests by setting the header:

X-CSRF-Token: asda09820380_2238019280dk09n908asjdlkajdaoa

To log out, use the logout token in a POST request. This ends the user's session.

/user/logout?_format=json&token=asdasd09a8sdaslkdasl-asdasdklsajdlkasdjlksj

GET login status:

/user/login_status?_format=json

GET token:

/rest/session/token

References:

JavaScript and Drupal 8 RESTful Web Services
Change record: Additional RPC endpoints: user/login user/login/status user/logout user/password/reset


Internal links aren't getting aliased When saving an internal link to content (within the wysiwyg editor), the paths don't get aliased like they do with D7.

If I have a node (at path /node/10), with an alias of /some/other/path, when that page gets saved, then cached/viewed, the link that gets generated for the user is /node/10.

This has several drawbacks, not the least of which is that we have our breadcrumbs reliant on the URL path.

I've looked at all the input filters on the appropriate text format, but there's nothing there for it. This seems like kind of a huge issue for Drupal, I'm hoping that the fact that I can't seem to find anything on the issue means I just have a config wrong somewhere.

Drupal 7 doesn't do anything like that in core. You likely used another module. Pathologic provides this, also exists as a D8 version, only as a dev version, though.


country based product price should be changed in commerce kickstart? I have installed commerce kickstart. I have to add the two prices for single product.

  If Indian subscribers view the site means product price should display as
  2000 INR.

  If other users visit the site means product price should display as $ 50.

How to identify the user whether view the site in India and other country and how to change the price also ? Anyone guide to me? Based on country how can i change the price also?

You can use IP based Determination of country module for identify the user ip address and the country.

You can use Commerce Multicurrency module for INR price field in the products content types.

By using Rules module to change the price for indian users


Share content with All Groups Is there a way around to get Share with All Groups option in the group audience field for a specfic group content type.With share with All Group I mean to say share content to all groups we are not even if are not member of.
I am using og module on drupal 7 installation.

I managed to it with some custom coding basically i alter the form add a one more option to group audience field and then on form validation I am checking if user has input that field then I am making a db query to grab all og groups on site and then assign the group ids to the group audience field,looks kinda hackish but did'n get any better solutions.


Right way to include nusoap in D7 I should include nusoap library in my module, there is two way:

1- Download and extract it in my module directory and simply include it.

2- Writing another module to provide nusoap wrapper for other modules need it including mine.

I searched for existing module but I didn't find any. so which way is better?

It depends what you need really.

If you only need nusoap once, for a single project, then just download the library and include it using include (or even better, module_load_include(), that way it's still a 'Drupal' method!) There's no point writing a whole new module just to include a few files.

If you think you can provide useful wrappers for nusoap functionality though (as in ones not intrinsically provided by the library itself), or if you're likely to want to use nusoap again in a future project, it will probably save you some time later on to write a new module.

If you did this then you also have the added benefit of being able to contribute the module back to the community; a lightweight Drupal-capable soap library would probably be useful to a lot of people.

If I could offer any advice it would be to plan out what functionality you'd want your new module to have (what entities it could interface with, view/rules integration etc) before you dive in and write it. It's a lot more difficult to make a module generic halfway through writing it than it is at the beginning :)


How to alter and rewritte current path programmatically in Drupal 8? Here is what I'm trying to achieve :

I have a multilingual site with 2 languages (en, fr) but I I also have 4 iso_codes (us, gb, fr, be).

I want Drupal to understand that /us and /gb for example is an alias of /en (they share the exact same content).

Do you know if there is a way to  achieve that programmatically or with a module ?

I'm currently looking into two event subscriber to setPath on the go : RouteCollection and KernelEvents::Request, but no result for now.

Any help would be greatly appreciated.

I was able to achieve what I wanted to do by using PathProcessor service.

Here is my services.yml
  mymodule.path_processor:
    class: Drupal\mymodule\PathProcessor\PathProcessor
    arguments: ['@language_manager', '@config.factory', '@path.alias_manager']
    tags:
      - { name: path_processor_inbound, priority: 200 }

And my code in my PathProcessor.php class :

/**
 * Processes the inbound path using path alias lookups.
 */
class PathProcessorCustom implements InboundPathProcessorInterface, OutboundPathProcessorInterface {

    protected $language_manager;
    protected $configFactory;
    protected $aliasManager;

    public function __construct(LanguageManagerInterface $language_manager, ConfigFactoryInterface $config_factory, AliasManagerInterface $alias_manager) {
        $this->languageManager = $language_manager;
        $this->configFactory = $config_factory;
        $this->aliasManager = $alias_manager;
    }

    public function processInbound($path, Request $request) {
        if (!strpos($path, '/admin/')) {
            $path = $this->removeISOCode($path);
        }

        return $path;
    }

    public function processOutbound($path, &$options = array(), Request $request = NULL, BubbleableMetadata $bubbleable_metadata = NULL) {
        if (!strpos($path, '/admin/')) {
            $path = $this->insertISOCode($path);
        }

        return $path;
    }

    protected function removeISOCode($path) {
        $langcode = $this->languageManager->getDefaultLanguage()->getId();
        $isocodes = $this->getISOCodeMapping();
        $path_items = explode('/', $path);
        if (isset($path_items[1]) && strlen($path_items[1]) == 2 && in_array($path_items[1], $isocodes[$langcode])) {
            $config_negotiation_url = $this->configFactory->get('language.negotiation')->get('url');
            if (!in_array($path_items[1], $config_negotiation_url['prefixes'])) {
                array_splice($path_items, 1, 1);
                if (count($path_items) == 1) {
                    $config_system_site = $this->configFactory->get('system.site')->get('page');
                    $path = $config_system_site['front'];
                }
                else {
                    $path = implode('/', $path_items);
                    $path = $this->aliasManager->getPathByAlias($path, 'en');
                }
            }
        }

        return $path;
    }

    protected function insertISOCode($path) {
        $path_items = explode('/', $path);
        if (isset($path_items[1]) && strlen($path_items[1]) == 2 && $path_items[1] == 'gb') {
            $config_negotiation_url = $this->configFactory->get('language.negotiation')->get('url');
            if(!in_array($path_items[1], $config_negotiation_url['prefixes'])) {
                $path_items[1] = $language;
            }
        }

        $path = implode('/', $path_items);

        return $path;
    }

    protected function getISOCodeMapping() {
        return [
            'en' => ['gb', 'us'],
            'fr' => ['fr', 'be']
        ];
    }

}

What I do is I decompose URL and remove what I know I don't need and map the URL to an actual content URL. Otherwise, redirect to the default 404.


cannot login after theme change or backup/restore I am using Drupal 7, with VMware 5.0.1 build-894247 with Ubuntu 12.10. 2GB ram, 20GB disk, 32 bit VM, hosted by Windows 7 Enterprise.

I am developing on a team with SVN (subversion) as the source control. All of this works fine on everyone else's (on my team) local dev environment and on our staging/prod servers.

I set up a shared folder from my C: drive on Windows called Sites (C:\Sites), and it appeared as /mnt/hgfs/Sites on Linux.

My dev folder is under that, so /mnt/hgfs/Sites/test.dev

I configured Apache sites-available to point to this new path, and enabled it. I setup the mysql database fresh, and ran through the default install of Drupal. No problems so far. At this point I can log in and out without issue.

When I make a change like importing a theme and setting the theme, then log out, I can no longer log in. The login screen will not even tell me why I am not being logged in (normally there is an error message... it is as if someone disabled java-script or something). If I blow away the database and recreate it, start over with the default install, it works again. My real goal is to enable a backup and restore that to the new site, but that changes the theme and more, and has the same problem (although the theme does change and content is there when I do this... just can't log in)

another kicker, if I move the files back to /var/www/ and re-point apache, it works again.
UPDATE: It turns out this problem does not have to do with VMware, as it is now failing in the exact same manner while in /var/www.

I have checked permissions and even set everything to completely unrestricted access (chmod 777 -R).

Any ideas why?
This seems very reminiscent of this other post too...

UPDATE: after hours of diagnosis, discovering drush, and playing with variables, my buddy  noticed this: If we switch the theme back to Bartik, and login from  login, it will fail without even showing an error message. BUT, if we just go to the home page, there is a login block on the left, and if we login there, it works! The top nav bar comes back and everything. Log out and try again from http://sitename/users, and it fails again. He thinks it may be a modules or theme-based permissions issue.

Try the following:

check the existence of .htaccess file in Drupal root
truncate the cache tables in the database
check and eventually increase the PHP memory limit in /etc/php5/cli/php.ini
Read and check some other trouble shooting ideas at
http://drupal.org/node/158043


Path aliases more than one I could explain everything, but that will take me a while, so, long story short.

I need one node to have 2 path alises (Not re-direction) 2 path aliases, and this is what I need to do, to show some fields in my view or hide them.

The idea is if I access from one view I need to show some fields, or If I join from another one I should hide it

Its not good idea to have one page or node with 2 different url, what i suggest to you is to override node view page with panel and create 2 variants.

Create the 2 different views panes and drop them each one in variant.

In the link to that node add GET variabile and switch the right variant based on that

Example
/my-url will show the first variat
/my-ulr?show=1
Will show the second variant

You control that with panel visibility rule and use php code to check the $_GET array


Limit items in shopping cart Is there a way to limit users on my site to buy only 2 items from a list of products?
Am using Drupal 7 with Commerce module and Rules.
I added a new rule to when adding or removing and item from the shopping cart, it would check if the total quantity is bigger than 2, then it would remove the last element like this.

  Event
  Before adding a product to the cart

  After adding a product to the cart

  Conditions

  Total product quantity comparison
  Parameter: Order: [commerce_order], Operator: >, Quantity: 2

  Actions

  Remove an item from a list

  Selected list: commerce-order:commerce-line-items

and the item to remove is

  commerce-order:commerce-line-items:2

Sadly its not working, and I really need your help.
thanks

I had a similar problem:
I had to check for certain conditions before adding an item to the cart (not after adding). And if the condition is not met the item should not be added.

The only way i could resolve this is by adding a "Execute custom PHP code" action with the code:

drupal_goto('any_path');

This doesn't look very correct but its the only thing that worked for me.


Form with managed_file value as link in email Like the title says I want to make managed_file value to be a link on form submissions in the email.

Webform has this option. When a user uploads file, on the email form submission there's a link with the path of the uploaded file. I want to achieve this with custom module.
This is my code:

<?php

function mymodule_page($form, &$form_state) {
    $form['description'] = array(
        '#type' => 'markup',
        '#markup' => t('Add description'),
    );
    $form['file'] = array(
        '#type' => 'managed_file',
        '#title' => t('Upload image'),
        '#upload_location' => 'public://files',

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

    return $form;
}

function mymodule_page_submit($form, &$form_state) {
    $file = file_load($form_state['values']['file']);
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);

    //dpm($file);

    $description = $form_state['values']['description'];

    $params = array('file' => $file->uri, 'description' => $description );
    drupal_mail('mymodule', 'mymodule_news_mail', 'myemail', language_default(), $params);
    drupal_set_message(t('Message sent!'));
}

/*
** Implements hook_mail().
*/
function mymodule_mail($key, &$message, $params) {
    switch($key) {
        case 'mymodule_news_mail':
            $message['subject'] = t('Hello');
            $message['body'][] = t('This is a test');
            $message['body'][] = t('Image upload: @file', array('@file' => $params['file']));
            $message['body'][] = t('Description: @description', array('@description' => $params['description']));
        break;
    }
}

As you can see it from my code I'm saving the file properly into the server. After that with dpm($file->uri) I can see the string public://files/file_name.

How can I display the link from the path of the uploaded file on the email, so will be able to click on the absolute path?

Thanks to Jaypan from drupal.org, I've got the answer:

<?php
file_create_url($file->uri);
?>

Simply with adding this code and make another variable that will use the code, I've got the right result.


Is there a "description" field for Rules actions? I have several rules that are very complicated and have many steps.  Even though I am the only web developer, I often have to study rules I have written a bit to remember how they work.

Does the Rules module have "description" fields somewhere like Views so developers can make notes to other developers/themselves?  Surely other people must have this same problem...

This is so needed.  I agree.  Luckily, it's in the works: http://drupal.org/node/1244738

I'd add your vote to that Drupal module issue!  :-)


hook_update a rule configuration? I would like to update a payment method settings. As I understand, the settings are inside a RulesReactionRule.

Is it possible to modify the configuration of a RulesReactionRule using a hook_update ?

Thanks.

I've finally found how to export the Drupal commerce payment method settings using commerce_features and the patch: https://www.drupal.org/node/1973098#comment-10559856


How do I programatically add a Node to an Organic Group in Drupal 7? This question and the documentation would suggest that the og_group function is the way to achieve this; however, calling og_group thus:

$values = array('entity_type' => 'node', 'entity' => $node);
og_group($gid, $values);
node_save($node);

Does not update the group_audience field on the node.

I'm referring to 7.x-1.3 of the og module; currently the only stable release on D7.

How can I go about programmatically adding a node to a group?

Thanks in advance.

Try og_set_association() its listed under their API section of og.module

I have done this in the past with D7, but I believe the API I used has changed since then.


How can I replace the "Add to cart" button with an "Ask about product" button, based on product property? Let's say client wants button "Ask about" for chosen product instead of "Add to cart" (he requires personal contact for some products). It should be based on data from a specific product field, so he could choose for what products he requires personal contact. It would be also nice if that optional button would redirect user to webform, that would automatically contain name and attributes of chosen product. How can I approach this?

Added:
I can disable "add to cart" form, from hook_preprocess_node, or hook_node_view_alter, but I wonder if it can be ajaxified, so only if user will choose specific product, from configuration of attributes, the "add to cart" button, would disappear and "Ask about product" would appear. I also need to turn off possibility of adding that product to cart by forged POST requests. Anyone know how to do it?

I figured out answer, and it's not that bad as I though. I decided to write a tutorial for it as it looks like very useful feature. So here it is:

Tutorial

Install everything, I mean, Commerce and Webforms,
Create example webform - let's name it "Contact",
Create Product Display, create some product with few attributes, and one boolean field (not attribute) "Contact required",
Configure webform, specifically, create there a field that will have default value, fetched from GET query string (how to do this: http://drupal.org/node/296453#webform-url-default ), we will pass to our Contact form a SKU of our product by using GET method.

Now create your own module, I will not elaborate on that, as there is a lot of info out there. The hooks that we will need are:

  HOOK_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state)

  HOOK_commerce_cart_attributes_refresh_alter(&$commands, $form, $form_state)

The first one will allow us to manipulate our form initially (if default product will have "Contact required = true"), the latter will allow us to adjust our form to AJAX calls.

Yes, that means that, our "Add to cart" button will be dynamically changing based on current product "Contact required" field. Looks promising doesn't it? :)

We will also use two helper functions that are not hooks:

  MODULE_ask_for_product($product)

  MODULE_contact_required_validate($form, &$form_state)

The first one will return HTML of our new button "Ask for product" (I encapsulated it in function, because we will need that data in both above hooks),
and the second one will validate our form, so if "Contact require" field on product, will be set to 1, the form will not validate, and product will not be added to cart. The submit button for regular user will be removed, but this is only against smart guys that would like to annoy you by sending this form even if you hide submit button.

Those are the functions:

    function HOOK_form_commerce_cart_add_to_cart_form_alter(&$form, &$form_state) {
    // Adding new class to our button, that will allow us, to target it by jQuery
    $form['submit']['#attributes']['class'][] = 'add-to-cart-button';
    // Adding new validator, that will make sure that our products with required contact, will not be added to cart
    $form['#validate'][] = 'MODULE_is_contact_required_validate';

    // Getting value of field_is_contact_required of default product
    $product = $form_state['default_product'];
    $field = field_get_items('commerce_product', $product, 'field_is_contact_required');

    // If value is 1, then replace our button with markup.
    if($field[0]['value'] == 1) {
        unset($form['submit']);
        $form['ask_for_product'] = array(
            '#markup' => MODULE_ask_for_product($product),
            '#weight' => 50,
        );
    }
    }

Now we need to do something with AJAX:

    function HOOK_commerce_cart_attributes_refresh_alter(&$commands, $form, $form_state) {

    if (!empty($form_state['context'])) {
        // Getting value of field_is_contact_required of new chosen product
        $product = $form_state['default_product'];
        $field = field_get_items('commerce_product', $product, 'field_is_contact_required');

        // If field_is_contact_required is set to 1, then replace a container that have class ".add-to-cart-button" (we just added that class), with our markup
        if($field[0]['value'] == 1) {
            $replacement = '.add-to-cart-button';
            $commands[] = ajax_command_replace($replacement, MODULE_ask_for_product($product));
        }

    }

    }

And our helpers:

// Return markup of our new button. 'node/7' is node of our contact form, 'subject' is a key of our query string
function MODULE_ask_for_product($product) {
    return '
' . l(t('Ask about product.'), drupal_get_path_alias('node/7'), array('query' => array('subject' => 'Ask about product with SKU: ' . $product->sku))) . '
';
}

// Prevent some products from be added to cart.
function MODULE_contact_required_validate($form, &$form_state) {

    $product = $form_state['default_product'];
    $field = field_get_items('commerce_product', $product, 'field_is_contact_required');

    if($field[0]['value'] == 1) {
        form_set_error('', t('Don\'t try to be annoying! :P'));
    }

}

That's all, you can customize it, or by extending the idea, do much more with it (maybe by using webform api).


How to embed a view or a rendered node into a field group I'm afraid my question is a bit to general because I don't quite know where to start.  I still really don't have my head wrapped around the drupal 7 theming system.

Scenario

I have two content types:

Type main
Type secondary (this type has a required entity reference field, referencing Type main

The display on Type main has a set of 2 horizontal tabs htabs group named group_expandables.

Desired Outcome

What I would like to happen is, if an entity of Type secondary has been added referencing this node; add a third horizontal tab containing the Type secondary node and make it the default.

Initial Approach

These are the steps I thought through that should probably happen on page load for a node of type Main:

Look for a Type secondary node referencing this node, return if not found
If found, build up a new render array for the Type secondary node htab.  I was thinking it would be easiest to build this display in views, and load in the view, but doing it in a template file would probably work too.
Once the variable has been for the new htab, insert it in the htabs  render array and modify the render array to remove the open by default indicator on the old default tab.

So far I have used hook_preprocess_page to grab the $variables['page']['content']['system_main']['nodes'][nid]['#fieldgroups']['group_expandables'] and add a new group name to its children, clone one of the htab field groups and append it to the ['#fieldgroups'] array, and modify the elements that referenced the old htab and replace them with the name for the new tab.  Once I figured out that I needed an entry in #group_children too, I actually got the tab to appear in the group, but I haven't had any luck getting content to show up in it yet.

Question

Here are the places I'm really hung up:

Is hook_preprocess_page the best place to start this?
Is my general strategy for how to go about this sound?
How would I build my desired content into the new htab?

I'm sorry for the broad nature of the question, any pointers would be greatly appreciated.

I'm not sure your general strategy is the absolute best way to go, but I don't see any major problems, I think hook_preprocess_page is too broad as it runs everywhere and would suggest template_preprocess_node instead (even though this is a template preprocess it can be run like a normal hook preprocess in a module)

In regards to getting the content you will need to do a EntityFieldQuery using the nid of the page being viewed as a fieldCondition, the only problem I can see is when there is more than one secondary type assigned to the same main type.

An alternative approach would be to see whether it's possible to write a View which takes the nid as a Contextual Filter and then builds all the content, I think you'd need to add a Relatonship to the secondary type, etc. and if it's possible this would cut down on the amount of custom coding needed.


Menu items shown in Navigation menu? I made a module for displaying nodes(links) from database. And I have simple question, why are the links displayed in the navigation menu? I want to be displayed in a separate menu (like navigation menu with my custom title etc etc...), but whatever I do they show up in the navigation menu.

function test_menu(){

$items = array();

  $items['test1'] = array(
    'title callback'   => 'test_callback1',
    'page callback'    => 'test_output1',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,
  );

      $items['test2'] = array(
    'title callback'   => 'test_callback2',
    'page callback'    => 'test_output2',
    'access arguments' => array('access content'),
    'type' => MENU_NORMAL_ITEM,

  );
       ..... etc etc
      return $items;
}

This is page-test.tpl.php

<?php
 print $content;
 ?>

It's because you're using the MENU_NORMAL_ITEM type, which will add the item to a menu, and haven't set a menu_name. From the docs:

  "menu_name": Optional. Set this to a custom menu if you don't want your item to be placed in Navigation.

If you want to add the link to a different menu try something like this:

$items['test1'] = array(
  'title callback'   => 'test_callback1',
  'page callback'    => 'test_output1',
  'access arguments' => array('access content'),
  'type' => MENU_NORMAL_ITEM,
  'menu_name' => 'main-menu'
);

If you don't want the link to be added to a menu automatically at all, change MENU_NORMAL_ITEM to MENU_CALLBACK.

Remember to clear the caches when you make any change to hook_menu(), otherwise the changes won't be picked up.


How to add custom text settings to a custom theme? I'm working on a custom theme called "YingYang". I didn't make the theme, but I have to do some stuff with it. The theme has custom text settings which is bassically some pre-set content.
It looks like this

Now my question is: How can I create a new text setting for this theme?
I've been searching for a while in the drupal UI and in the code, but I can't find anything about it.
Thanks!

Right now this option in your theme is in configuration setting. I think they done it using some custom module. Edit the module file, add a new text area using following code..

 $form['name']= array(
'#type' => 'textarea',
'#title' => t('Main Address'),

);

Save the

$form_state['values']['name']

using variable_set('name' , value) in form submit. Then retrieve variable in template using variable_get('name').

Another easy method is just edit your theme-settings.php. Add a new textarea field. you will get the field in your Home » Administration » Appearance » Settings.
 You can access that value using

theme_get_setting('field name');

Hope this will helps you...


Move from Wp to Drupal without downtime If I have wordpress right now with a bit of content (on a linux VPS with apache) and I want to switch over to drupal with the least possible downtime what do you recommend? Is it possible to install drupal separately and then put the content in it and then make it active over the wordpress somehow? Sorry if this was a silly thought as I don't have experience with any of this.

Based on what you've mentioned, you will want to install drupal 7 separately and try Wordpress Migrate.

https://www.drupal.org/project/wordpress_migrate

It only needs the export of Wordpress which can be done in the Wordpress admin.

You will want to try this out first on your own machine, Acquia Dev Desktop will work for you. Read through some of the docs and walkthroughs on the migration. I've done it a few times, it's very quick and typically works fine.

https://www.acquia.com/products-services/dev-desktop

Once you are setup and established, you can migrate to Drupal 8.2.x-8.3.x without much trouble.


Add class and extra HTML to specific menu items with hook In page.tpl.php I have the following to echo out the main menu:

<?php if ($main_menu): ?>
        <?php print theme('links__system_main_menu', array('links' => $main_menu, 'attributes' => array('id' => 'top', 'class' => array('links')))); ?>
<?php endif; ?>

The site is responsive so on desktop monitors it displays like this:

But as you reduce the screen to mobile size it turns into a navigation list that can be opened and closed with a button. See here:

However the desired effect is to have small descriptions for each of the menu items in the mobile version simply by using
little description
 wrapped within the menu li and a tags. See here:

I also want to add CSS class 'nobile' to tthe list item 'Home' in the menu so that it doesn't display on the mobile version.

So how can I add this CSS class to the 'Home'
? And how do I go about adding the link descriptions to each
? Can I use a hook in template.php? If so how do I go about this?

Thanks for your help!

You can add a custom class to menu items by using the Menu Attributes module. You can also use hook_menu_link for the same. For displaying the menu description, here is a sample code. Paste it in your template.php file

/**
* Implements theme_menu_link().
* Adds menu description under main menu
*/
function themename_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';
  $element['#localized_options']['html'] = TRUE;

  if ($element['#below']) {
    $sub_menu = drupal_render($element['#below']);
  }

  if ($element['#original_link']['menu_name'] == "main-menu" && isset($element['#localized_options']['attributes']['title'])){
    $element['#title'] .= '' . $element['#localized_options']['attributes']['title'] . '';
  }

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

Note : You've to use css/js to show/hide the menu description based on the screen size.


Webforms - Is it safe to allow users to upload attachments? Is it safe to include a 'File' type field into a webform that allows users (anonymous or authenticated) to upload their files? After reading few articles on the web , it seems it makes a website vulnerable to hacking and malware.

I would like to know better about this so that I can make a decision on this and provide an answer for and against using it.

Here is a security advisory from drupal.org that explains some of the dangers of letting anonymous users upload files: https://www.drupal.org/psa-2016-003

tl;dr

Configure upload fields that non-trusted visitors, including
anonymous visitors, can upload files with, to utilize use the private
file system.
Consider forcing users to create accounts before
submitting content.
Audit your public file space to make sure that
files that are uploaded there are valid.