Selective CSS Aggregation for fast D7 development performance On D6, we had the this module. Depite the module's name, it has an hidden extra feature to optimizes all CSS files except for the module or theme being actively developed. This has the benefit of performance (since all files except the actively developed file are compressed) yet allows for quick development.

Which alternative exists for Drupal 7?

At this time, it appears this module is not needed for Drupal 7
this has been committed and fixed in D7 core.

refer to this:

IE: Stylesheets ignored after 31 link/style tags

==========
css aggregation of all stylesheets EXCEPT certain one. just add this to your theme's template file

drupal_add_css(drupal_get_path('theme', 'mytheme') . '/css/custom.css', array(
'group' => CSS_DEFAULT,
'preprocess' => FALSE,
'every_page' => TRUE
));


Administrator users can add records, end users can view them How can the administrator users add few records into the database (through a form), and how can the end users view them in the front end?

Administrator users will be adding records of training classes, through a form in an administration panel.
The end user will be viewing the list of training classes in the front end, in a block.

How to achieve these tasks?

here in short all the steps for the simplest solution I can think of:

depending on your content (needed fields...) you may need to create a new contentype (YOURCONTENTTYPE)(maybe using the CCK module (drupal6))
make sure the roles are set correctly (e.g. admin can create and view this content, authenticated only view...) via admin/user/permissions
create a block (node-)view with the views module where you filter by YOURCONTENTTYPE and sort by date
modify the visibility setings of this block via admin/build/block or in the view itself
admin can create content via node/add/YOURCONTENTTYPE

But it really depends on what exactly you want to do.


Rendering field with the help of functions I have a field and I can render its value in a such way:

<?php print $entity1->field_list_of_options['und'][0]['safe_value'];?>

But I have many different entities at the page so I want to hide the following tail in a function in order to get something like this:

<?php print $entity1->Get_list(); ?>

How can I do it? I tried to get predefined functions in a custom module but couldn't find a proper hook. How can I handle this problem?

I wrote the following in order to collect my "tails":

function mymodulename_getText($entityId,$field){
    return $entityId->$field."['und'][0]['safe_value']";
}

And so, I use it in such way:

<?php
$enityId = 2;
$entity2 = entity_load_single('entitytype', $entityId); ?>

<?php print getText($entity2, field_list_of_options); ?>

But I don't know how to implement my function to my custom module in order to get it in node's body where I want to print it using PHP Filter.

The correct syntax for your approach would be:

function mymodulename_getText($entityId,$field){
    return $entityId->$field['und'][0]['safe_value'];
}

I suggest to sanitize that with a isset().


Do Drupal 8 / backbone.js have conflict when using AngularJS on top? I've just pulled D8 HEAD for my website and I want to use AngularJS instead of backbone.js to create a web app but realized D8 have already embedded backbone.js on every page.

I can disable modules that depends on it like edit or ckeditor if needed.

Even if I could disable it on a specific custom path I create with my module is still a good alternative for now.

There is also a conflict with Twig and AngularJS double curly braces in Drupal 8.

Seems like Backbone.js and AngularJS don't have conflict if used in the same page.

So one can ignore Backbone.js existence and do stuff with AngularJS.

Still there might be better ways doing this in future since D8 is still in development as I post this.

And for curly braces conflict with Twig in AngularJS we can config interpolateProvider service explained here


How to use Google and Ubuntu fonts on Zen theme How can I use Ubuntu font and Google fonts on Zen theme?

You can also try Google Fonts.

  This module enables you to add Google Fonts to your site using the Google Font API.

  Benefits of the Google Font API

  A choice of high quality open source fonts.
  No Javascript needed, pure CSS!
  Works in most browsers.
  Extremely easy to use.


date_default_timezone_get() returns the wrong timezone I have several Drupal 7 sites using the same installation in the same server. Two of those sites are returning "Europe/London" when running date_default_timezone_get(). This timezone is different from the one returned by drupal_get_user_timezone() or variable_get('date_default_timezone'), which (correctly) return "America/Denver". For the rest of the sites the returned timezone is the same for all three functions.

The fact that I get a different timezone with the php function is creating issues for those two sites; for example, token replacements of date field are returning London time, not the site timezone's time.

What may be causing this discrepancy? Is there any way to correct that? I tried including the line date.timezone = "America/Denver" in php.ini without success.

I'm running php5.6 on Apache 2.4.36

I figured out what was going on. I am using the module print with the external   library mPDF (version 6.0). mPDF.php was changing my default timezone to "Europe/London" in line 80 (this bug has been reported in this version of mPDF). Apparently this line was running after drupal_session_initialize() in session.inc, which sets the default timezone for the session to match the site's selected timezone.

What's strange is that mPDF was only affecting 2 of my sites. Apparently the session initialization in the other sites was running after the mPDF command? I commented out those lines and all the timezones now match.


Can a drupal admin user get FTP rights to a godaddy server I have a Drupal 7.28 site running on a godaddy server.  I just recently copied it from my local box to godaddy's.  I can't use the function "add module by using URL" method now.  I see the message that I must have FTP rights.  I do have FTP rights when logged in to godaddy through their interface, but wondering if a drupal admin user can be given FTP rights and then be able to add modules, etc through URL's at the "Add module" page?  How does everyone deal with this?  Do you just manually FTP modules to the server and then go back to drupal's interface and enable?  Or do you use Drush to install modules remotely?  Just wondering how everyone deals with this...  Is it best practice to not make a site live until all modules are installed locally and then move the site to a remote server?

Thanks for the help.

Dave N

I don't use Drush. But using the install module function at admin/modules/install I have installed modules before when live on a GoDaddy server.

I don't know what is causing the problem, I would maybe contact their support. But certainly it's doable, and I've done it in the past.

However depending on the module I would stay clear of installing on a live server, particularly if you are on shared hosting environment with GoDaddy (contrary to a lot of people I actually find them okay and the best solution at that price for hosting a site).

However whilst you'll find installing modules okay you may find you run into problems enabling them with PHP memory limits, or other server issues. Generally doing dev on a local machine if you have hosting like GoDaddy is going to be faster, more flexible, and generally easier.


How to show a view each 5 rows in another view I'd like to create a complex view which combines several views.
I'm using Views Infinite Scroll

The view logic:

view A row-1
view A row-2
view A row-3
view A row-4
view B Block 1
view A row-5
view A row-6
view A row-7
view A row-8
view B Block 2

The difference between view B Block 1 and view B Block 2 is that Block 2 has offset from view B Block 1

Ok the adequate minimum is to insert view B Block 1 to each n row of the view A.

I tried to insert block in the view template but vainly.

Please help!

this can be done by overriding your View's template for the Style Output plugin (e.g. views-view-unformatted--yourview_machine_name.tpl.php). Then in that template outputting something like this:

<?php if (!empty($title)): ?>

<?php print $title; ?>

<?php endif; ?>
<?php foreach ($rows as $id => $row): ?>
  <div<?php if ($classes_array[$id]) { print ' class="' . $classes_array[$id] .'"';  } ?>>
    <?php print $row; ?>
    <?php
      // this tells the view to do something after every 4 rows
      if (($id % 4) == 0):
      print views_embed_view('view_machine_name', 'block_1');
      } ?>

<?php endforeach; ?>

If you wanted to alternate your secondary View's blocks - you could add some logic for that too.


How can I commit changes to a theme? I worked on Omega-7.x-3.0-alpha1 and added some fixes to fluid style sheets in rtl mode.

How can I commit them to the drupal.org repository?

Unless you are one of the maintainers or have been explicitly granted write access to the repository, you will not be able to push your commits to the "official" branches.

The recommended route to contribute is the following:

Checkout the git repository for the correct branch (instructions here)
Create  patch with your changes (instructions in the above link)
Search for a relevent issue or create a new one in the project's issue tracker on Drupal.org
Submit the patch in the issue


Print a view inside a block In Drupal 7, I use the following code to print more than one view inside a block.

<?php print views_embed_view('view_name', 'display_name'); ?>

In Drupal 8, it doesn't work and it returns Array. Although the documentation for views_embed_view() says it's the same as in Drupal 7, it doesn't work in blocks using the PHP filter module.

I can't help with the PHP filter and I don't think it is safe to use it in D8 by looking at the project's page.

There are better solutions. You could for example add a Views Reference Field to the block type or use Twig Tweak in a template. You can also try to embed the View in the WYSIWYG text area, which is a bit more work to set up, but then should give you all options you have now in D7. See Views entity embed.


How to call watchdog() outside Drupal I'm getting used to use the Drupal watchdog() function. It provides me a very simple and accessible way to log events in my code.

However, I would like to use the same (or very similar) function in some other PHP projects outside Drupal. Accessing the results via the Drupal reports interface would be nice.

Does anyone know any proper way to include the relevant files of a Drupal instance to provide this functionality in custom PHP code? I know that there are already other PHP logging solutions which may be better, but I'm looking for something similar to watchdog().

Requiring the existence of a Drupal installation for all of your other non-Drupal PHP projects isn't something I've come across before...but you can bootstrap Drupal to make the watchdog() function available like so:

define('DRUPAL_ROOT', '/path/to/drupal/installation');
include_once(DRUPAL_ROOT . '/includes/bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

watchdog('my_module', 'A message');


How do I test if a field has a value in twig? I am writing a template and if 2 fields, one of which is required the other is not.  I would like to display the one thats not required if has been filled out by the user.

I have tried numerous things

{% if content.not_required %}
 {{ content.not_required }}
{%else%}
  {{ content.required }}

{% if content.not_required  is null %}
 {{ content.required }}
{%else%}
  {{ content.required }}

{% if content.not_required  == false %}
 {{ content.required }}
{%else%}
  {{ content.required }}

{% if content.not_required  == null %}
 {{ content.required }}
{%else%}
  {{ content.required }}

{% if not  content.not_required %}
 {{ content.required }}
{%else%}
  {{ content.required }}

all of these display all stories the same whether or not content.not_required was filled in.

Is there a way to do this in twig or do I need to set up some variable in a preprocess function?

There is an issue about this on Drupal.org: Checking for empty fields in Twig templates is complicated.

Use the following syntax and keep an eye on updates:

{% if content.not_required|render %}
    {{ content.not_required }}
{% else %}
    {{ content.required }}
{% endif %}


Will deleting the Body Field from one Content Type also delete this field from other Content Types? When creating a new Content Type that does not need the body field, is it safe to just delete the body field from that new Content Type without affecting other Content Types?

Yeah is safe, but directly you can't delete the body field, in the page where you admin the fields there is no link for delete it.

The way to delete it is when you create a new content type in the field where you put a label for "body" just let it in blank.


How to change property 'string' in object with class Drupal\Core\StringTranslation\TranslatableMarkup in my hook? The property 'string' is protected as I can see here https://api.drupal.org/api/drupal/core!lib!Drupal!Core!StringTranslation!TranslatableMarkup.php/class/TranslatableMarkup/8.2.x

but I need to change word "- Any -" in my exposed filter form to my string "All terms"?

I cannot do this cause I do not know how to use this class and how to change output.

This hook says: cannot get value of protected property.

function MYtheme_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ( ( $form['#attributes']['class'][0] == 'views-exposed-form' ) &&
       ( $form['#info']['filter-field_color_target_id']['operator'] == 'field_color_target_id_op' ) )
  {
      dpm($form['color']['#options']['All']->string);
      //$form['color']['#options']['All']->string = t('All terms');
  }
}

The object TranslatableMarkup is the result of t(). It's not possible to modify the content of this object. You overwrite the object with a new instance:

form['color']['#options']['All'] = t('All terms');


Drupal 7 Node Revisions per Role I have created a new role 'news contributor'.
I have created a new content type 'news'.

The 'news contributor' role has permissions enabled to view, revert, delete revisions.
However, this setting also gives them access to view, revert, delete revisions on ALL nodes.

How can i restrict node revisions on specific content types based on user role and content type?

The 'news contributor' should only be able to tinker with revisions for the 'news' content type and nothing else.

At the moment they have access to revision any node which is undesirable.

Has anyone had this issue before and, how did you resolve it?

Thanks.

I haven't tested it, but there is a relatively new module with a stable 7.x release that looks like it was built only for this purpose: Node revision Permissions Per Role

  Node revision Permissions Per Role allows to give roles administer per content type node revision permissions without giving them full administer nodes permission.

  For instance, you may let certain users(eg: roles:External-blogger ) manage node revision of a specific content type(eg: blog) but restrict to manage node revision of all other content type that this module is perfectly works for you.


Scan Remote FTP server (Akamai) for files, use filename to create content I'm wondering if there is an existing workflow to achieve what I'm looking for before I'm forced to go and build my own.  This is, preferably, in drupal 7.

I have media files stored on an akamai server that need to be scanned either via a cron or manual start and after they're scanned, their filenames need to be put into separate content.  I do not need the files individually parsed, I just need the filenames added to title and add the filename to a textbox within the created content.

I have found a few methods that sound similar to what I'm looking for such as:
- Storage API: Does connect, but cannot find files that were not uploaded via their service.
- File Field Sources: No remote FTP, but does scan local and such.
- Bulk Media Upload: Does scan and create a new node for each, does not do remote.

Any ideas?

How about feeds?

(Sorry this would/should be a comment but I don't have enough rep yet)


How to get date values from field collection to a node? I am trying to print the values from a field collection using following code in Drupal 7 node.But the date values are not getting.

$wrapper = entity_metadata_wrapper('node', $node);
 $formtype = field_get_items('node', $node, 'field_latest_schedules');
 foreach($formtype as $itemid) {

 $item = field_collection_field_get_entity($itemid);

 print $item->field_course_starts_on['und'][0]['safe_value'];
 print $item->field_course_ends_on['und'][0]['safe_value'];

 }

How can i print the date from a filed collection?

I suppose that field_course_starts_on and field_course_starts_on are fields that represent date and you want to print it as date. Correct me if I'm wrong.

So you can print those fields as date like:

print date('d F, Y', $item->field_course_starts_on['und'][0]['safe_value']);
print date('d F, Y', $item->field_course_ends_on['und'][0]['safe_value']);

The part 'd F, Y' is a date format. Take a look at PHP Documentation to see all options for format parameter.

Update

First you have to load the ids of the field collection fields of the node:

$formtype = field_get_items('node', $node, 'field_latest_schedules');

// Extract the field collection item ids
$ids = array_column($formtype, 'value');
foreach ($formtype as $ft_field) {
    $ids[] = $ft_field['value'];
}

To iterate over all fields you can use the following code:

//Get the entities
$collections = field_collection_item_load_multiple($ids);

//Loop over the array - if you have more than one entity
for ($i = 1; $i <= sizeof($collections); $i++) {
    $collection = $collections [$i];

    //Iterate over all member vars of the FieldCollectionItemEntity object
    foreach($collection as $key => $value) {
        //Look for fields - there are some other class vars, too.
        if (strpos ($key, 'field') !== false) {
            //Search for textfields
            if (isset($value['und']) && is_array($value ['und']) && isset($value['und'][0]['value'])) {
                print "Field ".$key." ".$value['und'][0]['value'];
            }
        }
    }
}

And than debug, target wanted fields and print those fields' values.


Change title of a node programmatically before displaying it I am a newbie at Drupal tweaking. I have copied Bartik theme into sites/all/themes and am modifying it as per our requirement.

One such requirement now is to programmatically modify the node title by appending value of some other field in the node to it before displaying the node. I have identified that the right way to achieve it is by updating the variables in hook_process_page() or hook_preprocess_node() function in template.php file of the theme.

For testing purpose I have done the following change:

/**
 * Override or insert variables into the page template.
 */
function MyThemeName_process_page(&$variables) {
    // Raj: Experimenting
    $vars['site_name'] = 'New title';
    drupal_set_title('Test changed title');
    echo "<script type=\"text/javascript\">alert('MyThemeName_process_page');</script>";
.
.
.
}

I could see that none of the changes are affected. Since I am just beginning to tweak, I have no idea how to debug a php function as it is a server side script. For the same reason I have tried to display alert which fails to display too!

I thought that the function is not being triggered at all, so I intentionally induced error in the 'echo' line by removing a character:

ech "<script type=\"text/javascript\">alert('MyThemeName_process_page');</script>";

The interpreter complains with this error:

  Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING in /Applications/XAMPP/xamppfiles/htdocs/MyWebsite/cms/sites/all/themes/MyThemeName/template.php on line 48

This means that the interpreter is triggering the function, but why does not it echo and put out the alert?

Also, what is the approach to update the node title? I am assuming that there is some variable which I should be interested in the array "&$variables" and conditionally update it, am I right?

Awaiting help!

To modify the node title while displaying, I had to do changes in the theme.

Implement the hook (don't remember if it was already there) in template.php file:

function themeName_process_page(&$variables)

And then had to add this part of custom code at the end of the function:

// Raj: To Append the scientific name and it's desciber to the title
$nodesArray = $variables['page']['content']['system_main']['nodes'];
if (!empty($nodesArray))
{
    foreach ($nodesArray as $speciesNode)
    {
        if (!empty($speciesNode['field_common_names']))
        {
            $scientificNameArray = $speciesNode['field_scientific_name_1'];
            if (!empty($scientificNameArray))
            {
                $theScientificName = '' . $scientificNameArray[0]['#item']['first'] . '';
                $theDesciber = '' . $scientificNameArray[0]['#item']['second'] . '';
                $prominentName = $variables['title'];
                $sciFiNameAndDescriber = $theScientificName . ' ' . $theDesciber;
                $variables['title'] = $prominentName. ' ' . ' ( ' . $sciFiNameAndDescriber . ' ) ';
                $variables['title'] = '
'.$variables['title'].'
';
                break;
            }
        }
    }
    unset ($speciesNode);
}

Please see that in the above code, most of it belongs to the context of my website where I had to append the scientific name of the species to the title of the species inside brackets. The point here is, you need to modify the $variables['title'] inside process_page() hook.

Also most important, to see the changes in affect, clear the cache. I had a rough time thinking that the changes are not working, only very late did I realize that I was doing everything right but did not clear cache. It's a learning experience for me.


How do I make the bootstrap dropdown menu work? I like to install in a bootstrap subtheme dropdown menu. But it does not work in my subtheme. Using the bootstrap theme it works.

my jolly.info.yml looks like this
    core: 8.x
    type: theme
    base theme: bootstrap

name: 'Jolly'
description: 'Theme for ...'
package: 'Bootstrap'

regions:
  navigation_collapsible: 'Navigation (Collapsible)'
  header: 'Top Bar'
  highlighted: 'Highlighted'
  search: 'Suchleiste'
  help: 'Help'
  content: 'Content'
  sidebar_first: 'Primary'

libraries:
  - 'jolly/global-styling'
  - 'jolly/bootstrap-scripts'

my jolly.libraries.yml looks like this

global-styling:
  css:
   theme:
     css/style.css: {}

bootstrap-scripts:
  js:
    bootstrap/js/affix.js: {}
    bootstrap/js/alert.js: {}
    bootstrap/js/button.js: {}
    bootstrap/js/carousel.js: {}
    bootstrap/js/collapse.js: {}
    bootstrap/js/dropdown.js: {}
    bootstrap/js/modal.js: {}
    bootstrap/js/tooltip.js: {}
    bootstrap/js/popover.js: {}
    bootstrap/js/scrollspy.js: {}
    bootstrap/js/tab.js: {}
    bootstrap/js/transition.js: {}

   dropdown:
    css:
      css/styles.css: {}
    js:
      js/dropdown.js: {}

and I use the same

  menu--main.html.twig

like the bootstrap theme.

I try so many things but do not find what's wrong or what kind of dependency is necessary.

Can anybody help?

Add dependency in libraries.yml file just below the bootstrap js file:

dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once


Devel's dsm & dpm not working I am trying to print out the $view object using devel and dsm.

My function in function.php is

function my_theme_views_pre_render(&$view) {

  if ($view->name == 'my-view') {
     dsm('$view');
  }
}

But I just get this message below, there is nothing inside the message, the html is

  ×

Status message

$view

You are dsm'ing a string, try dsm($view);


Fivestar - filter by number of votes I want to filter a view that shows nodes sorted by rating. I would like to filter it to only show nodes with at least 5 votes.
I added the relationship for "vote results - number of votes".
When I add the filter it doesn't give me an option for "greater than":

Any ideas how to fix that?
Thanks

When i added the Vote results: Value type field for output. It shown like percent or points so how can we filter the varchar field type with number behavior.
I think  you should filter by Vote results: Value not Vote results: Value type


What is the basic concept behind hooks? I am intermediate in PHP. To polish my skills I start learning Drupal 7. While learning Drupal architecture concepts, the terms hooks and bootstrapping puzzled me a lot. I read the "Pro Drupal development" book, and some documentation on drupal.org, but it is so advanced for me to learn how hooks work in Drupal to display the web page.

Can anyone tell me what hooks are in simple words?

The other answers are great, accurate, detailed, but I'm not sure they're the "simple words" explaining the bare bones of the concept that the asker was looking for.

I think of hooks as a point where the code pauses and shouts "Anyone else got anything to add here?". Any module can have a function that replies to this, and gets triggered with appropriate data passed to it at that point in the code.

A nice straightforward example is hook_node_delete(). Any module can use it to make things happen every time a node is deleted. The docs tell you this hook passes the module the object of that deleted node to work with, and outlines other useful information such as about the exact timing of when it's called (e.g. that it is before the node data is actually deleted from the database), and where in Drupal's code the hook is called (which can be more than one place).

You can explore what hooks exist and find out what data is passed to them by exploring things starting with "hook_" in the Drupal api.

Hooks work by a name conventions: using hook_node_delete as our example, when the node deletion process reaches the point where the hook is called, for every module with a function like this [modulename]_node_delete() where the word hook in the hook's name is replaced with the module's name (e.g. my_amazing_module_node_delete() ), those functions get called.

Why? So any module can do anything at these key points: for example you could look at the deleted node and do things if it meets a certain condition (say, email an administrator, or launch some long process).

Some hooks let you alter things that have been generated just before they're processed. For example, hook_menu_alter() passes you the current menu items that the system has generated. Any module can define a function some_modulename_menu_alter() and look at them, optionally change them (delete some, add some, sort them...), and pass the newly altered menu back in.

It's simple, really powerful and is at the heart of how Drupal works as a modular system. Implementations of hooks are at the heart of most Drupal modules.

When looking through the code of a Drupal module, you can spot which functions come from hooks (as opposed to functions that are simply called from within the module code itself), as the Drupal community enforce a convention whereby each implementation of a hook has a comment in front of it like this (note the "Implements hook_..." bit):

/**
 * Implements hook_some_hook().
 *
 * Some descriptive summary of what this does
 */
function my_amazing_module_some_hook() {

Some modules that act as APIs define their own hooks. For example, Views defines many hooks that allow you to add to, read and edit data at various points in the process of creating or displaying a view. You can find information about hooks created in custom modules from two places (assuming the module follows conventions etc):

The code and comments in the modulename.api.php file in the module folder
drupalcontrib.org - for example, here's their list of D7 modules they have info on, and here's their page of Views hooks

Bootstrapping is, as others explained, basically booting up - I won't duplicate the other good clear explanations.


how to load RTL style in RTL language I have a multi language website, one of languages is a RTL language, in Drupal 7 I put my CSS in style.css and RTL CSS to style-rtl.css and by default drupal also load style-rtl.css file, Now in Drupal 8 ,I have a multi language theme, how can I tell Drupal to load my RTL style in RTL language?

update
I found this link but I am not sure about that because  I have a CSS file with almost 1400 lines, I should put [dir="rtl"] before all of any selector ? !!!

Drupal 8 uses libraries, and you can load these in templates. One way of achieving language direction dependant libraries would be to use the html_attributes['dir'] variable in html.html.twig and load different libraries depending on the value:

{% if html_attributes['dir'] == 'ltr' %}
  {{ attach_library('your_theme_name/styles') }}
{% elseif html_attributes['dir'] == 'rtl' %}
  {{ attach_library('your_theme_name/styles_rtl') }}
{%- endif -%}

Set up a couple of libraries:

styles:
  version: 8.x-1.0
  css:
    theme:
      css/styles.css: {}

styles_rtl:
  version: 8.x-1.0
  css:
    theme:
      css/styles-rtl.css: {}


Not able to import images using feed image grabber module in content image field I am using Feed and Feed Image grabber module for importing data form non Drupal site to my Drupal Site. All fields are successfully imported except image field, I have checked all the steps to FIG module configuration but with no success.

I have also tried for new content type but again no success.
My CSV file have following data
Title,Description,image
Test1, testdescription,https://s3.amazonaws.com/brewerydbapi/brewery/snQlvg/upload_qMSc0A-medium.png

When file imports, only first two columns data saved not image and also no error shows in logs also.

Please confirm whether we can use external links or not?

Any suggestions?

Finally with a struggle for more than a day, I finally get succeeded in importing images in Drupal Content type.

I used Feed Image Grabber Module with feed but not works for me might be my image path is from external server.

Then I used Media, File Entity and Media Feeds module which gives me ability to import images from external URL too.

After all the above modules get enabled.
I have added one more mapping "source->target" in my Feeds Importer under Mappings and Select "Target Field" appended with "(media_internet)(field_image)" and then save.
Then upload CSV file and finally my images start getting saved in
image field.

Hope this will help someone.


How do I use another field inside view as the base table? I would like to know how I may use a database field from a custom module to build queries on.

By default, using content view starts off querying from the "node" table. I would love to have the Views module to query from my own custom table.

I have tried using hook_views_data() and set a base table, but it all came to nought so far.

Give this module a shot - Views Expose Tables

  Exposes Drupal DB tables to Views

  This is a simple module which does one thing: provides an admin page
  for site-builders to choose which tables in a site's Drupal DB to
  expose to Views.

  The module then loads all the fields for each chosen table and detects
  the data type of the field and sets appropriate views field, sort,
  filter, and argument filters (for example numeric, string, date, or
  "default").

  It also looks for a primary key of the table and if one is found it
  sets it as the base field for a views base table and makes the table
  accessible to views.


what is the difference between using drupal_add_js and ['#attached'] What is the difference between drupal_add_js() and $form['#attached']['js'][] ?
When is the purpose of using each of the above functions?

(I mean I know that it is used to attached js to say form if used inside form but when is drupal_add_js used and when is $form['#attached']['js'][] used ?)

If you are using drupal_add_js() in your form building function, you are attaching JavaScript to a page, and that's it.

If you are using $form['#attached']['js'], other modules may interact, test and change it as they need, using hook_form_alter(). That's the way you should choose every time your JavaScript is functionally related to particular form.

Other than that, they are functionally the same.

Note that it is usually better to use JavaScript libraries than plain JavaScript files, as they allows you to declare versions, keep relations between JS and CSS, manage dependencies, well, they are generally way more powerful.

Of course then you should use $form['#attached']['library'] when your JavaScript Library is functionally related to particular form, and only use drupal_add_library() when no form is in any way related to library's function.


Rule to update referenced node after customer completes checkout I've got a rule which fires on "Customer completes checkout".

When it fires I would like to update a field in a node which is related to the one which was "checked out".

The node which is "checked out" has an entity reference field which relates it to another node, of a different content type.

So I have my Rule Event: "Customer completes checkout"
And the condition: "Entity has field" which checks for the entity reference field

Under Actions, I have: "Fetch entity by ID" to fetch the referenced node.
And I have provided a "Variable name" for the Fetched Entity.

I know this much works because I can print the Title of the referenced node as a status message on the site at this point. I can even print the contents of the field that I want to update using the token [the-fetched-node:field-name]

But when I add an Action: "Set Data value" and look for the field to update, the-fecthed-node:field-name is not available.

I can see things like the-fetched-node:body and the-fetched-node:title, but none of the fields of the node seem to be available to Set Data values on...

How can I get access to set the data in my required field?

I'm using the Rules (7.x-2.9) and Ubercart (7.x-3.9) modules.

This question seemms to be a variation of Populate an entity reference field, which suggests a solution like so:

Add Condition: “Entity has field”, checking for your reference field
Add Action: “Fetch entity by id”, supplying your node/user id from another field in the dataset and providing a meaningful name
(Note: This solution implies you get the id by a simple field value in your dataset; you might want to add another condition to register the id first)
Add Action: “Set data value”, which you now can supply your entity object from the step before (hence a name you'll identifiy in the dataset)

Apart from some Rules "Event" you probably need to add to it (related to your "After customer completes checkout"), this should be pretty close to what you're looking for.


How do I programmatically update the allowed values of a list field? I have created a field_time_zone field for the Article content type.
I want to set the allowed values for that field to the values returned from system_time_zones().
For this, I implemented hook_form_alter() using the following code.
$zones = system_time_zones();
$entityManager = \Drupal::service('entity_field.manager');
$fields = $entityManager->getFieldStorageDefinitions('node', 'local_market');
$options = options_allowed_values($fields['field_time_zone']);

if(empty($options)) {
$options =  $zones;
$form['field_time_zone']['widget']['#options'] = $options;
}

The code adds the desired values, but the node cannot be saved, as it throws the following error.

The value you selected is not a valid choice.

How can I set the allowed values for a text (list) field?

You can't do this in a form alter hook, because the entity field validation will fail.

You have to add a function to the field settings. This is not in the field UI, so you have to export the configuration and change the field in field.storage.node.field_time_zone.yml:

type: list_string
settings:
  allowed_values: {  }
  allowed_values_function: 'mymodule_allowed_values_function'

Reimport the configuration. Then you can implement this function in mymodule.module to set the options dynamically:

use Drupal\Core\Entity\ContentEntityInterface;
use Drupal\field\Entity\FieldStorageConfig;

  function mymodule_allowed_values_function(FieldStorageConfig $definition, ContentEntityInterface $entity = NULL, $cacheable) {
    $options = [
      ...
    ];
    return $options;
  }

See https://chromatichq.com/blog/dynamic-default-and-allowed-values-list-fields-drupal-8

For the question added later:

How can I set allowed value options to a field of type text(list) and save it accordingly?

The question originally was what to do with the code which doesn't work in form alter, where you can place it instead.

If you mean with this question you have a static allowed value list, then you can copy and paste the list in the field settings UI and save it:

And now it is stored in the mentioned yaml file of the exported configuration here:

  allowed_values: {  }


How do I reset the number of failed login attempts? I am trying to unlock the admin user of a drupal install using these instructions

http://www.aslingandastone.com/2011/how-to-reset-root-password-in-drupal-7-with-ftp-and-phpmyadmin/

But the user is blocked and email reset is not working:

  Sorry, there have been more than 5 failed login attempts for this account. It is temporarily blocked. Try again later or request a new password.

Where in the database can I reset this blocked status? The admin user's status is set to '1' in the user's table.

Drupal 7 prevents brute force attacks on accounts. It does so by refusing login attempts when more than 5 attempts failed. The amount of failed logins is recorded in the table 'flood'.

You can either wait before trying to login again, or clean the flood table following one of the procedures below:

Manually delete all of (or the last applicable) rows in 'flood' table.
Execute the following query on the Drupal database. To execute this query it will be necessary to login to the database. This is typically done through the command line or through a GUI interface such as phpMyAdmin.

DELETE FROM `flood`;

From the command line, with drush installed, execute the following command:

drush php-eval 'db_query("DELETE FROM `flood`");'


Only display content that belongs to User in admin/content I have a role called Content Editor and 2 users Chang and Liang with that same role.

They can both add/edit their own content. The role permission is set in such a way that they can only edit own content.

However, when Chang navigates to /admin/content, this user can see all the contents written by all the users.

How to restrict Chang so that he can see only the contents he has written when visiting the /admin/content link?

I created a sandbox-module for that called Content Admin Access
Maybe this is what you are looking for.

With Content Admin Access you can set permissions to show or hide others content in the admin/content overview.
Enabling this module will by default show only your own content in the admin/content overview.


feeds module cannot handle csv files exceeding 8gig? I am trying to import a very big CSV file into my Drupal 7 site using the Feeds module, but I get the following error:

  Warming: POST Content-Length of 40245470 bytes exceeds the limit of 8388608 bytes in Unknown on line 0

How can I fix this?

8388608 bytes is 8MB, not 8GB. 40245470 bytes is < 40MB.

Your PHP settings are limiting the maximum POST content length to 8MB, which is why you're getting the error.

To fix, edit your php.ini file and add/update these lines:

post_max_size=50M
upload_max_filesize=50M


Entity reference widget I know that in Drupal 8 the taxonomy term reference is deprecated and it's implemented by an entity reference in Drupal 8 Core.

Is there any widget to select items by checkbox list instead of the default autocomplete entity reference widget?

Yes!!

Go to Manage form display of the content type
Go to the entity reference field and there you can find a list of options including checkbox .


Inside drop-down menu child menus are not working I am using bootstrap sub-theme and created a drop-down menu and set it's menu levels they are working correctly but when i extend to child menus it's  not working.
I have searched Expand menu links down in a tree and Child navigation sidebar or drop-down navigation displaying child items but not found any solution.

Any Help?

Bootstrap 3 and 4 have dropped support for nested (multilevel) menus

One has to include the relevant code (that was excluded) in their own custom theme to make it work.

Check this stackoverflow answer for relevant code to add to your theme

NOTE: the reason the support was dropped is that multilevel nesting is problematic in mobile or smaller screens so you have to implement solutions for small screens on your own.


Creating node when cron runs I'm a bit new to drupal and I have a task, where I have to create a node when cron runs. I set up the node like this in my custom module's cron hook:

$node = new stdClass();
$node->type = 'reports';
$node->language = LANGUAGE_NONE;
$node->uid = 1;
$node->status = 1;
$node->promote = 0;
$node->comment = 0;
$node->sticky = 0;
$node->moderate = 0;
$node->title = 'Daily Report for ' . date('d.m.Y');
$node->field_reporting_cycle[LANGUAGE_NONE][0]['value'] = 1;
$fid = generate_periodic_report(1);
$node->field_period_of_reporting[LANGUAGE_NONE][0]['value'] = date('Y-m-d', strtotime('-1 days'));
$node->field_period_of_reporting[LANGUAGE_NONE][0]['value2'] = date('Y-m-d');
$node->field_reciver[LANGUAGE_NONE][0]['value'] = 2;
$file = file_load($fid);
$file = (array)$file;
$file['display'] = 1;
$node->field_report_file[LANGUAGE_NONE][] = $file;
node_object_prepare($node);
$node = node_submit($node);
node_save($node);

The node doesn't get created. I don't get any error messages in the log. I don't know what I'm doing wrong.

So I got my answer by myself: I ran clear cache and it performs everything perfectly. @Andrew Morris: I haven't used Rules before but I think it can't be performed by that. The generate function creates 2 xls files via PHPExcel and gets all files uploaded by user in a period of time. Then it compresses all the files into a zip archive via ZipArchive and saves the data for the zip file. Then it returns the fid of the saved file.


How to access boolean field in content node template? I've created a content type (event) that has a boolean field (status). I've created a template in my theme called node--event.tpl.php and I've got just about everything working as intended, but I want part of the template to be conditional based on that boolean.

How can I access that boolean in the template so I can use it in an if/else statement?

Probably the same way as other fields: http://api.drupal.org/api/drupal/modules!node!node.tpl.php/7


Multiple payment targets I have a scenario where payments should be made to different targets based on some conditions. I was considering multi-store approach but I felt it might be a overkill considering that we only need payment targets and not complete store management.

Is there any simpler way of achieving this?

Which payment gateway are you planning to use? If it is Paypal, then there is this system called Adaptive payment which helps you split payments.


What is the minimum I need to get a test for a module on D7? I have a custom module that's fairly mature and I'm just now getting around to writing tests for it. However, I'm having difficulty getting the it to show up in the tests menu. What is the bare minimum that I need to get automated testing going for my module?

I have:

module.info:

files[] = tests/module.test

tests/module.test:

<?php
class ModuleTestCase extends DrupalWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Module Test',
      'description' => 'Automated testing of Module.',
      'group' => 'Module',
    );
    function testModule() {
      $this->assertTrue(TRUE, 'Tests are working');
    }
  }
}

I've even set up a bogus test module that's basically what's outlined above, and it works. But my module with all my functionality it in won't show its tests on the test menu. So I'm trying to see if there's anything simple I'm overlooking.

Does the test file have to be called module.test or can it be called anything.test? Does the name of the class have to be ModuleTestCase or can it be arbitrary? I do have my files called module.test and the class called ModuleTestCase. I've also run the module.test on the command line php to test for syntax errors and I get none. What could I be overlooking?

What you got there will suffice. I copied the code to a project I was working on and it showed up fine.

You problem is either:

Cache (You need to clear cache after updating the .info file)
Overlooked, The test could be there, but you didn't see it. It will show up under the group with the name written in name.


Add link to view data if no matching record I have a view that shows taxonomy terms with a relationship to show nodes that have a term reference to that term (relationship not required, aka LEFT JOIN).

For terms that don't have a matching node I would like to show an "add content" link.

The usual "no results" behavior doesn't seem work in this situation. What's the trick?

Views PHP to the rescue:

<?php
if (is_null($row->nid)){
    print 'tid.'>add node for this term';
}
?>

I can even pass the tid through the URL and have it prepopulated on the form (using prepopulate).


How to change the look and feel of exposed filters in a block I have view which has exposed filters. I have configured those filters to block.
But now I want to change the look and feel of the exposed filters .

How to do this.

If you want more control over your exposed form template, you an write a template file for it. This article will help you to define template file.

Otherwise you can change the appearance with css, And you can use form alter in case of alter any elements.


Private website with Rules - Inherit custom fields I want to create a website where all the content is only visible to logged in users.

(I don't want to solve it by using other access modules or by configuring the permissions of the roles, for specific other reasons.)

What I basically try to do with Rules is the following:

Given the value of "custom field X" (boolean) of "content type A" is true,
When a user  views a node of "content type B"
Then I want to redirect the user to [site:login-url]

But it seems that there is not a straightforward way to do this. Couple of methods that could be possible are:

Using entity reference: inheriting the value and firing the condition on the node view
Views looping: creating a view and firing the condition on all node views
Checking the value somehow when Drupal is initializing

I could do this also within a template tpl preprocess, by simply adding the logic. But it feels not right to solve it that way. Possibly because then there are other security issues that I'm afraid of neglecting.

Is there a better / easier way to do this? What would you recommend?

This is very straight forward in Rules without the need for extra modules:

Event: Content is viewed of type [content-type]

You can add one event for each content type, or as the description in the Rule itself states: If you need to filter for multiple values, either add multiple events or use the "Entity is of bundle" condition instead.

set a boolean field in the content type to determine if it should be public or not
Condition: Data Comparison: Parameter: Data to compare: [node:field-to-determine-if-viewable], Data value
Action: Page Redirect: Parameter: URL: user/login

This will check every page load of a content type (or all if you so desire) and redirect if the boolean is set (or not set) depending on how you want it set up


What are the implications of changing the default language? On the official docs about Install a language there is a warning:

  Never change the default language, otherwise things will break!

I wonder what exactly this means because there is no explanation about it.
I have searched and only found this.

I changed the default language and updated the translations about two weeks ago and haven't seen any warning or error yet but I'm still looking for some documentation since the site is going on production.

The main problem used to be i18n and all the things that it translates.

Most of those (like taxonomy terms, fields, node types, menus), do not have an explicitly language assignment like nodes do. So the original strings are assumed to be in the default language (unlike interface strings, where the original is always en).

If the old default language was english and you change it to german, then i18n will no longer translate them to german on the german site but will try to translate them from english to english.

i18n added a workaround for this problem, on one of the many settings pages can be controlled if a different language than the default should be used as that original language. That's not a perfect solution, because it means that the site admins must create the original fields, node types, menu links and terms (assuming that i18n_string is used to translate them) in english and then translate them to german.


Define a resource of Service module, But 'access callback' cannot work This following is my resource:

For clearly read, I delete some line.

/**
 * Implementation of hook_services_resources().
 */

function baidu_push_services_services_resources() {
  $resources = array();

  $resources['message']['actions']['send'] = [
    'file' => array(
      'type' => 'inc',
      'module' => 'baidu_push_services',
      'name' => 'baidu_push_services',
    ),
    'access callback' => '_message_access',
    'callback' => 'baidu_push_services_send',
    'args' => array(
      array(
        'name' => 'uid',
        'type' => 'string',
        'source' => 'data',
        'optional' => FALSE,
      ),
  ];

  return $resources;
}

In order to test my 'access callback' function will be invoked, I always return FALSE in my 'access callback' function:

function _message_access($op = 'view', $args = array()) {
  return FALSE;
}

But when I try to use curl command line to test with no SESSION and no Token, but It work!(return the right result to me), Did that mean 'access callback' not be invoked?

So I try to use drush cc all to clear cache, But still above problem.

Is your access callback in the same file? If not, you'd have to add: "access callback file" to your definition, and point to it.

I'd also clear cache within Drupal, as I've seen drush cc all not always clear all caches.

Also, I'd name-space your access callback function, as it could be conflicting with something else in the system. _message_access is a pretty generic name. You should rename it to: _baidu_push_services_message_access().

Otherwise, your syntax looks correct.

Or, if you solved your issue, perhaps post it in here, to help others.


D8 services errors - No route found for the specified formats : */* I'm trying to get data from a Drupal 8 website to Go application.I created a view that it would display title and body on json format. Here is an example
  Th when the Go application try to get the request I got this error.

Symfony\Component\HttpKernel\Exception\NotAcceptableHttpException: No route found for
the specified formats : */*. in Drupal\Core\Routing\AcceptHeaderMatcher->filter() (line
64 of core/lib/Drupal/Core/Routing/AcceptHeaderMatcher.php).

What I'm doing wrong ? As far I know, the Go application is asking the request properly.

Just in case you are wondering about the Go app here is the code.

If you update to the next beta, You will have to use: "http://dev-d8go.pantheon.io/d8go/node/1?_format=json"


How to Disable some Page for View I have a website. In which I need to disable some pages for full view. Because I am using them in view. I don't need full view.

Is there is anything in D7 so we can stop full view of Page

Go to your nodes which you want to disable from viewing.

Go to node edit and find 'Published options' and uncheck published option.

So now you want to display them at view's page. So go to your View Filter criteria and select Published 'No'

That's it. Now you can see the unpublished nodes at view's output but not at node output.

There is another way you can do it.

If those nodes (which you want to disable at node output) are all belongs to same content type, you can manage them under content type display settings. You can manage view modes there.


Remove links from the menu tabs How can I remove the some links from the Tab, when we are login as a particular user. Please see the below picture. I want to remove the tab Items maked in red rectangle (deny access to this link).

I tried with hook_menu_alter, but it do not worked and also understood, hook_menu_alter only hide the item in the tab.  Please give me a solution. I am using drupal 7 version

Please note:
I am using node gallery module to this content type to attach gallery with a node. I have added roles & assigned role to a particular user. Also give permission form that this content type in permission tab. The problem is that, when we logged as user, only the edit link is disappearing, not the gallery attached  with it. I want to set this in page wise. The same user want to edit the gallery in some page & also want to edit the node. I used simple access module, but no use. it only remove the edit of that page, not the gallery attached with it. I also tried hook_node_access(). For that also the same result.  Please give any solution.

Please see: node gallery permission is separate, which is not connected with a content type. I need to deny below url based on the roles.
1) node/#/items,
2) node/#/upload
3) node/#/sort

You can give permissions to menu links according to role.give permission to the above links then they will appear as per according to roles.
use the below given module for permissions as per role

Menu per Role

May this will help you.


remove cache in hook_preprocess_node I'm using hook_preprocess_node to get node field and make some processes, then pass a variable to the node to use it in the node twig template. The problem with me that when I edit this node, it doesn't affect on the view, I have to clear cache to see this change on the node view.

function THEME_preprocess_node(&$variables) {

    if (isset($variables['elements']['#node'])) {
        $node = $variables['elements']['#node'];
        $bundle = $node->bundle();
    }
    if (isset($bundle) && $bundle == 'crse') {
        $course_schedules = array();
        foreach ($node->get('crse_sched') as $schedule_item) {
            $schedule_entity = \Drupal\node\Entity\Node::load($schedule_item->target_id);
            $schedule = new stdClass();
            $schedule->title = $schedule_entity->get('title')->getValue()[0]['value'];
            $schedule->seats = $schedule_entity->get('seats')->getValue()[0]['value'];
            $schedule->state = $schedule_entity->get('moderation_state')->getValue()[0]['value'];
            $course_schedules[] = $schedule;
        }
        $variables['schedules'] = $course_schedules;
    }
}

You have to add cache tags of all entities you get data from. Add this line to the foreach loop:

$variables['#cache']['tags'][] = 'node:' . $schedule_entity->id();

The parent node is already tagged, which would also happen for the schedule entities if rendered normally.

This is all you need to do, adding the tags of the entities you use to build the rendered output. The entity system invalidates cache items, which are tagged correctly, automatically on all CRUD operations.


How can I set the view mode of a node through rules I'd like to change the view mode of a node based on the role of a user and another flag in the node, and by using the Rules module.

Since a call to display the node by default is full content, I wrote a rule that on Content is Viewed for that node type, it then checks the conditions and sets data value view-mode to teaser.

However, even when the conditions are met properly the node still displays full text.

From this I am assuming that Content is Viewed is being executed after rendering or am I missing something in my approach?

What "Content is viewed" actually means, seems to be like so:

The event Content is viewed is what it is: the user has (already) started viewing the content.
The (system) event Drupal is initializing is what you should use instead (possible combined with other Events and/or Actions), if you want to trigger some Rules "Action(s)" BEFORE the user can start viewing (= looking at) the content.

For more details, and a working sample (in Rules 'export format'), refer to
How to specify a Rules event like "Content is 'going to be' viewed"?

Be aware: this applies to D7 ... and D6 is another story (from the question context I'm not sure if this is fopr D6 or D7 ...).


What are Hooks in Drupal and can I learn and use them if I've yet to learn PHP? Whenever I try to read about what are Hooks in Drupal, and how to manipulate forms or content with them, the text seem not to deal with the UI at all, but mostly with coding... Maybe I did not encounter the right reading material about UI-Hook relationship?

Can someone please detail in simple words and  a simple example?

What are Hooks?
Do you use them via UI or only through Coding?
Do I need to know PHP to use a module such as Hook form-alter?

Hooks can be thought of as internal Drupal events. They are also called callbacks, but because they are
  constructed by function-naming conventions and not by registering with a listener, they are not truly
  being called back. Hooks allow modules to “hook into” what is happening in the rest of Drupal.

Suppose a user logs into your Drupal web site. At the time the user logs in, Drupal fires hook_user_login.

That means that any function named according to the convention module name plus hook name will be called. For example, comment_user_login() in the comment module,
locale_user_login() in the locale module, node_user_login() in the node module, and any other
similarly named functions will be called.

If you were to write a custom module called spammy.module and
include a function called spammy_user_login() that sent an e-mail to the user, your function would be
called too, and the hapless user would receive an unsolicited e-mail at every login.

  The most common way to tap into Drupal’s core functionality is through the implementation of
  hooks in modules.

You have to use coding to implement hooks and you need to know PHP.

  For more details about the hooks Drupal supports, see the online documentation at
  http://api.drupal.org/api/7, and look under Components of Drupal, then “Module system (Drupal hooks).”


How to upload a csv file with an admin form? In a custom module, I created an admin form but I need an input to upload a csv file. When the file is uploaded I need to parse in and then I add data to db.

I already made "add to db" and "parsing" functions because when I installed the module, a default file is parsing and added to the db.

Thanks.

EDIT :

I'm using Drupal 7...

The data is stocked in a custom table that is create when the admin user will install the module. There is no node or content type. I just need to save all data of the CSV file (5 columns) in the table by an admin user form. 1 time par month the admin user need to update the table with a new .CSV.

In frontend I have a form and when the user will submit it I check that the code is in the table.

My issue is that I didn't know how to upload the file into a Drupal directory and then access to it after the form submit.

As I said above I already created a parsing function and I tested with a CSV file directly in the module directory, it's working. Data is insert into the table that I have created.

In your custom form create input button like

$form['upload_csv'] = array(
        '#name' => 'files[mycsv_data]',
        '#type' => 'file',
        '#title' => 'Upload csv'
    );

Next in form submit you can use

file_save_upload($source,
                array('file_validate_extensions' => array('csv')),
                $destination_dir,
                FILE_EXISTS_REPLACE)

Here for getting uploaded file details like file name and file path you can use $_FILES global variable.

and then,

if ($file) {
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
}


Webform is not submitting after 1st submit? I am not able to submit a webform which is configured with honeypot.
I have tried following steps for anonymous user:

Place the webform using the webform block in a page.
Submit the webform. It got worked for 1st time.
When trying to submit from 2nd time onwards it is showing a message "There was a problem with your form submission. Please refresh the page and try again.".
After clearing cache only one submission is happening. From second submission onwards iit is not working.

Following are the module details:
Drupal: 9.1.x
Webform module:6.0.3
Honeypot: 2.0.1
There is no time restriction given in Honeypot module.

This piece of code helped to solve the issue.
Clearing the cache for every submission of a webform which is protected by honeypot.
    function MODULE_NAME_form_alter(&$form, FormStateInterface $form_state, $form_id) {
      $advanced_validation = \Drupal::config('honeypot.settings')->get('advanced_validation');
      if ($advanced_validation) {
        $form['#cache'] = ['max-age' => 0];
      }
    }


How to manage user permissions? I would like to manage user permissions with Drush, but I don't find any command on the official documentation website.

How to achieve this?

I am using Drupal 6, and Drush 6.0-dev.

Try this command:

drush role-add-perm 'user-role' 'permission'


Filter child field options by a parent field There are many scenes, each assigned by an entity reference field to exactly one show. Same for set pieces.

Show
—Scene
—Set piece

I am using entity references rather than taxonomy so that non-technical users can add shows, scenes and set pieces easily.  And when users add content, they select a reference to show it belongs to, and optionally a particular scene and optionally a particular set piece.

When they select the show on the first field, how can I have scene and set piece fields under it only show the scene and set piece options for that show?

I have done this type of thing before. I did it by creating a map (array) of what 'scenes' belong to which 'shows' and sent the javascript array to the page with a hook_form_alter. I then used javascript/jquery to listen for the change event on the 'show' dropdown which then hid or displayed the the corresponding 'scenes' using the array as reference. It could also be done via ajax if you preferred.


How to disable and grey out a form button if the textfield is empty? I have a custom module built, and I would like to grey out and disable the submit form button if the textfield is empty.  Can anyone help?

Here is the code for the textfield and the form button:

$form['ro-user-details']['nickname'] = array(
    '#type' => 'textfield', '#width' => 50,
    '#title' => t('Nickname'),
    '#default_value' => $ro_user->nickname,
    '#size' => 50,
    '#maxlength' => 200,
    '#required' => TRUE,
    );

    $form['ro-user-details']['change_nickname'] = array('#type' => 'submit', '#value' => t('Change Nickname'));

Obviously you will want to do this with some jQuery...And of course there is more than one way to do this, but:

$(function(){
      //Set button disabled
      $("input[type='submit']").attr("disabled", "disabled");

      //Append a change event listener to your input
      $("input[name='nickname']").change(function(){

            if($(this).val().length > 0) {
              $("input[type='submit']").removeAttr("disabled");
            }
      });

      // You could then trigger the a change event on load just to check
      $("input[name='nickname'").trigger('change');
});

That should be the gist of it.  Of course you would want to change your "name" value to whatever your input name is.


How to render entity reference data in field template? I have a field collection with adding multiple items. In each item there is an entity reference field with multi-selection of contents. I can render entity reference content by target_id using node_load in an entity_reference field template. But it is getting only first value of each item.

How can I render all contents of each item from field collection? Is  there another way to fetch?

Paste the below code template.php;

function mytheme_preprocess_node(&$variables) {
  if(isset($variables['node']))   {
    switch ($variables['node']->type) {
      case "value":
        $var_abc = $variables['node']->field_abc;

        foreach ($var_abc['und'] as $key => $value) {
          $variables['abc_fields'][] = $value;
        }
      break;
    }
  }
}

Paste the below code to create separate node tpl for that specific content type;

<?php
foreach($variables['abc_fields'] as $key => $value) {

  $var_authorvalue = $value['node']->field_author;
  //echo "
";
  //print_r($var_authorvalue['und'][0]['value']);
  $var_fields = $value['node'];
  print render($var_fields->title)."
";
  print render($var_authorvalue['und'][0]['value'])."
";

}
?>

OR

Check How can I print a field from a referenced entity in my theme?


Remove tagging on node view I am building a social network with Drupal. I have the following requirement:

A person who adds a post can tag his friends when adding his posts.
His tagged friends can untag themself when viewing the post.

Requirement #1 was met by the amazingly efficient entity reference view widget (see my recent answer).

But how to achieve requirement #2 ?

What is the best way to implement such a feature?

Is there any inline editing tool (such as the edit module) for entity reference fields?
Does editablefields really works for Drupal 7?
Should I just implement it using the Rules Link module?
Any other approach?

Please advise.

I tried to define a custom field formatter but it didn't find the hook.

In the end it was much easier to use the Entity Reference Views Formatter module, then theme the view field to add the desired behavior to the relevant link. I used the rules_link module to define the untag link, then added the untag link into the field's theme. Next time I should probably use a tpl.php file as well.

File: views-view-field--with--block--field-with.tpl.php

<?php
  global $user;
  $my_uid = $user->uid;
  $node = node_load ($row->nid);
  $results = db_query(      // Load the field without loading the entire node.
    "SELECT field_with_target_id
       FROM field_data_field_with
      WHERE entity_id = :entity_id",
    array(':entity_id' =>$row->nid));

  $lines = "";
  foreach($results as $result) {
    $uid = $result->field_with_target_id;
    $account = user_load((int)$uid);
    $rendered = l(mymodule_get_realname($account), "user/$uid");
    $untag = "";
    if ($uid == $my_uid) {
      $rules_link = rules_link_load('un_tag_me');
      $untag = render(rules_link_render_link($rules_link,$row->nid));
      $untag = str_replace (
        array("<div ", 'title="x"'),
        array("


Change form input attribute I have form with an alt attribute like the following.

<input type="text" alt="abc">

I want to replace that attribute with data-alt.

I tried the following code, but it doesn't seem to work.

function theme_form_alter(&$form, &$form_state, $form_id) {
    foreach($form["submitted"] as $newForm)
    {
        foreach($newForm as $keyid=>$frmArr)
        {
            if(isset($frmArr[]["#attributes"]["alt"]))
            {
                    $alt = $frmArr["#attributes"]["alt"];
                    unset($newForm[$keyid]["#attributes"]["alt"]);
                    $newForm[$keyid]["#attributes"]["data-alt"] = $alt;
            }
        }
    }
}

The following code is not working either.

foreach($form["submitted"] as $newForm)
    {

        foreach($newForm as $keyid=>$frmArr)
        {
            if($keyid=='#attributes'){
                $newForm[$keyid]['data-alt']=$newForm[$keyid]['alt'] ;
                 unset($newForm[$keyid]['alt'] );
                $form["submitted"]['#attributes']['alt'] = array("sss");
                form_set_value($form["submitted"]['#attributes']['alt'], array("aaa"), $form_state);
            }
        }

    }

What code should I use to achieve what I want?

function act_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'the_id_of_your_form') {
    unset($form['submitted']['#attributes']['alt']);
    $form['submitted']['#attributes']['data-alt'] = 'abc';
  }
}

Won't this work?


Create OS user specific Drush commands I know how to create drush commands in a project, but there are a number of commands which I would like to add to my local system simply because they affect my particular workflow a lot.

In Clisp, I can define this in .clisprc.lisp. In git I can add commands to the ~/.gitconfig command, I'm looking for similar for Drush.

So, for example, I might like to have a locally defined Drush command, add-squeeky-table:

drush add-squeeky-table

And I would be able to call that on all Drupal 7 projects installed on my system.

Put your extensions in ~/.drush.

If add-squeeky-table is a drush command, put it in ~/.drush/squeekytable.drush.inc.  See drushify.

If you want to define add-squeeky-table as a shell alias, put it in ~/.drush/drushrc.php.  See the example Drush configuration file.


How to make a relationship to two views I am creating a website in which i am already created two view (1. Category 2. Location) , now i am created the taxonomy for Location and in Category view  I am exposed the Location Taxonomy,,, and in Location View here also i am exposed the view-block,,, so the Taxonomy is same in both views,, Now I want to know that if I will select the Category view Location  then automatically Location will be select in @nd view (Location view),,,

Plz provide any suggestion ..?

Here is the image of Location View (1st pic):

Checkbox (2nd pic):

So if i will select the Bangalore in Search Menu in 1st pic,  then the Bangalore will automatically selected in 2nd pic (View) (i.e. in checkbox).

Assuming both views are showing the same page, it could be accomplished using something like this:

Using Views Field Views, create the second view as a child field of the first

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.

pass the arguments (instructions included in module) to the second view to ensure it is getting the correctly information
use Views Auto Refresh, Views Flag Refresh or Block Refresh - depending the exact set up you have and want to refresh the second view


Apache SOLR show only nodes with images How can I filter SOLR results to show only nodes with images? There seems to be no support for image fields. I don't mind writing custom field mapping or something like that but some guidelines would be really appreciated.

You can override the template file that outputs your SOLR items with a check for a set image field.

This type of check is generally ok to use in a template file:

<?php if(isset($item['image'])): ?>
  <?php print render($item); ?>
<?php endif; ?>


404 Not Shown For Custom Module - Drupal 7 In a hook_menu() implementation, I am defining a route for login.

function my_account_menu() {
  $items['login'] = array(
    'title' => 'Customer Login',
    'page callback'    => 'drupal_get_form',
    'page arguments'   => array('my_account_login_form'),
    'access callback' => 'user_is_anonymous',
    'type' => MENU_CALLBACK
  );

  return $items;
}

However, if I try accessing login/asdfdsa, it still loads the login page, instead of showing a 404 error.

Is there an error on the code I wrote, or in the module?

It's the expected behavior, and it's described in the documentation for hook_menu(), even it  could not be clear, at a quick read.

  Callback Functions

  The definition for each path may include a page callback function,
  which is invoked when the registered path is requested. If there is no
  other registered path that fits the requested path better, any further
  path components are passed to the callback function. For example, your
  module could register path 'abc/def':

function mymodule_menu() {
  $items['abc/def'] = array(
    'page callback' => 'mymodule_abc_view',
  );
  return $items;
}

function mymodule_abc_view($ghi = 0, $jkl = '') {
  // ...
}

  When path 'abc/def' is requested, no further path components are in
  the request, and no additional arguments are passed to the callback
  function (so $ghi and $jkl would take the default values as
  defined in the function signature). When 'abc/def/123/foo' is
  requested, $ghi will be '123' and $jkl will be 'foo'. Note that
  this automatic passing of optional path arguments applies only to page
  and theme callback functions.

This means that, for example with login/asdfdsa, Drupal will first check if there are modules that handle that path. If there aren't modules handling that path, Drupal will check if there are modules handling every path matching login/*; if there aren't modules for those paths, Drupal will check if there are modules that handle login. In your case, that is your module. (I left out how Drupal handles the path aliases, as in this case isn't relevant.)

That happens also for other paths, for example node/1. If you have a node whose ID is 1, /node/1 shows it. If you try to access a path like, for example, /node/1/sdfgrgjpqwd432az, you will still see that node. (sdfgrgjpqwd432az is just a random string, to be sure I am not using a path for which a module defines a page callback.)


How to translate metatag token into text? I'm trying to get the data from meta tag using node_load and for some reason when is using the default field, which is Token it gives me this ugly array.

Instead of title and description that contain the strings.

Do you know how I can translate the Token into the actual text?

I was running a very out-dated Metatag version. Once I update to the latest version I was able to run metatags_get_entity_metatags and get all the meta tag the way it supposes too.


Permissions / Roles / Taxonomy / Workbench -- combination? Hello dear Drupal enthusiasts,

I'd like to hear your opinion - how to organize mentioned modules/functionality to achieve nice permission granularity.

After user is logged in we have a list of his e-groups (outside structure, we have its names).
I want to build drupal inner hierarchy where I organize user e-groups to tree structure.
I would like to divide nodes to groups, to allow people who are members of some e-groups to edit some nodes (gathered in group).

What comes to my mind it's to organize page structure in one vocabulary, and allow admin to add a e-group name to some taxonomy.

Example:

Main Site admin [taxonomy: egroup-main]

Department A admin [taxonomy: egroup-department-a]
Group 1 [taxonomy: egroup-group-one]
Group 2 [taxonomy: egroup-group-two]

Subgroup 1 [taxonomy: egroup-students]

Group 3 [taxonomy: egroup-group-three]

And now, after somebody logs in first time, and we know he is part of egroup-main, we give this user taxonomy egroup-main, which is the same we set to Main Site Admin term in vocabulary shown in example.

Is there any better way to organize this? I need fine, good grained control over users by egroups, to access, create and delete nodes.
What about workflow management? I mean - module like Workbench is nice to control workflow, let beginner users to edit, and let admins to publish stuff after review.

I know there's a module called Taxonomy Access but it seems it bases on Drupal Roles which means apart from taxonomy we would have to create dynamically user roles (depending on e-groups), attach permissions to them and assing users to these roles...

Waiting for your hints people!

Confused Drupal developer

http://tutr.tv/t4991?list=4948 is a video from Drupal Con London where they talk about the Workbench Modules and will answer most of your questions/concerns.

If you have Workbench Moderation you can have users submit content for review.  Then a content moderator will publish the content or return it as a draft for changes.

Workbench Access will limit users to what content a user can create/edit.  You just need to create a role, assign the role to a Workbench Access Section of the site, and then when they create a new account you can assign them to the correct role.

I have this on my site and have created a rule to email me whenever someone logs in for the first time so I can assign them a role.


How do Image Optimize pipelines coexist with core's Image toolkit optimization? I have the Image Optimize module installed. I've also installed and configured Image Optimize Binaries and Image Optimize reSmush.it.
I've created a simple pipeline that processes an image through reSmush.it's magic, setting the desired quality to 80%. This basic setup allows me to apply an optimization process to images after they have an image style applied. (The Image Optimize module adds an option to the image style creation form to choose your optimization pipeline.)
From my understanding, for any particular image, core's process might look like:

Original image uploaded via image field (1200x800px, unoptimized).
In my display, I apply the image style to scale and crop this image to 300x200px.
When this image is accessed, the image is scaled and cropped to 300x200px, and then core's JPEG quality would take effect and optimize this cropped image.

With the Image Optimize pipelines, I'm not sure if core's JPEG quality settings are still used: does the image get core's optimization plus the Image Optimize pipeline? or does the Image Optimize pipeline override core's optimization? I can't seem to find an answer to this anywhere. How do these options coexist?

With the Image Optimize pipelines, I'm not sure if core's JPEG quality
settings are still used: does the image get core's optimization plus
the Image Optimize pipeline?

Yes

does the Image Optimize pipeline override core's optimization?

No
According to the module's creator you should set your core's image toolkit to 100%; otherwise, you will endup with double compression and lower image quality.


Show image filenames on Drupal 7 node I upload multiple images to a node using one content type image field. I need to render the file name for each image under the image when viewing the node, all I get at the moment is just a page of images. Tried a view but that REALLY screws everything up. Any ideas how this can be done on the node?

Thanks.

You can do this using hook_preprocess_node() either in your theme's template.php file, or a custom module file. You'll want to use API functions to get the data from the node rather than accessing the arrays directly, so you don't need to worry about language codes etc.

function MYTHEME_preprocess_node(&$vars) {
  $node = $vars['node'];

  if ($node->type == 'the_type' && $vars['view_mode'] == 'full') {
    $field_items = field_get_items('node', $node, 'field_name');

    if (!empty($field_items)) {
      $filenames = array();
      foreach ($field_items as $item) {
        $filenames[] = $item['filename'];
      }

      $vars['filenames'] = theme('item_list', array('items' => $filenames));
    }
  }
}

You can obviously change the output to whatever HTML you need, but the above will produce an unordered list of image filenames, available in the $filenames variable in your node.tpl.php file.


Remove an item from list of taxonomy terms prior to rendering What is the correct way to remove an item from a list within hook_entity_view or hook_preprocess_node?

I am trying to remove a taxonomy term from a list of terms EntityReferenceFieldItemList. I calculate two boolean values, if both are true then the item should be removed from the list.

I've tried removing the second item in the list. That works, but removing the first item results in all the items being removed. Is this because the list keys are no longer sequential?

function mymodule_node_view(&$variables) {
  # calculate $field_hide_term and $node_in_past

  foreach($build['field_terms']['#items'] as $key => $term) {
    if ($field_hide_term && $node_in_past) {
      unset($build['field_terms'][$key]); # This also removes other items in the list if key is 0.
    }
  }
}

Instead of using unset(), you can use #access = FALSE, like this:

$build['field_terms'][0]['#access'] = FALSE;


Save xml file produced by views data export module to a different location I am using "views data export" module. And I am able to download the xml file.

I want to place a button "save to D:\" such that when I click on button it directly get saved to "D:\" drive .

I want to do something like this: if XML path is given

http://localhost/drupal/exhibti-dataexport.xml

I want to download the file.

If XML path is given

http://localhost/drupal/exhibti-dataexport.xml/savetoD

I want to directly save to D drive.

What I observed is when I am giving the path like this also

http://localhost/drupal/exhibti-dataexport.xml/savetoD

the file is getting downloaded.

Not able to understand the views data export module code.

Where should I modify the code in views data export module such that if xml path has arguments It should save the file to D drive.

Any help is appreciated.

You will not be able to save anything automatically expecially to a particular path

Some browsers allow you to remember the action (Save/ Open) for each file type. If the user had chosen to "Remember my Answer", then the browser saves the file automatically. You can not force a similar it on all users using your site.

Regarding the path, it again depends on the browser config. If the user had configured a download directory, some browsers save the file in the download folder by default. Else will ask the user to select the path showing the last saved path.

If browsers allowed websites to save files directly to d:\ on your machine without your consent at the click of a button, your machine would have been full of stuff that you never intended to download!!!!


Rules content unpublish in 30 days I've followed this thread https://groups.drupal.org/node/240678#comment-782543, but that's based on a date field and it has a different scenario.

My idea is: When a new content is created, after 30 days will be automatically unpublished.

How can I achieve this without using additional date fields?

Instead use Auto Expire module, Using this module you can set the node to unpublish after 30 days.

For your case set zero in purge field, otherwise it will automatically delete from database.

  This module allows site administrators to set expiration times for
  content types.

  End users creating content that has auto expiry set cannot control the
  expiry time. They could be allowed to renew the content for one or
  more cycles.


How to change fields to not be required before they are validated In Drupal 7, How can I change certain fields to not be required using the form api, depending on which button they click to submit?
It seems the validation is occuring before the validate function.  Where can I change this before it gets there?

I believe the form validate hook triggers after the default validation which would include checking required fields. It might be easier to not mark the fields required by default and check in your validate hook if they need to be required and then throw a form error if necessary.


Can I turn a regular content type into a Commerce product display? I have an existing working site with lots of content. I've come to the realisation that I could actually sell this content. So is there a way to turn my existing content type into a product display for Drupal 7 Commerce or would you recommend to export all these nodes and create a new product display type and add them back in?

All you need is a product reference on a node for that node to be a "Display Node." A simple solution would be to just add that and any other fields you think necessary to the "selling" part of the node's function. You might need an alternative View Mode for the content type if there are items you need displayed or not dependent on circumstances.


Hook for the "Welcome (awaiting approval)" email I need to modify the email for "Welcome (Awaiting Approval)."

I know I can use hook_mail_alter(), but I don't know what the ID is for "Welcome (Awaiting Approval)," nor do I know how I can directly access a user's profile2 fields.

I assume I have to do something like:

function module_mail_alter(&$message) {
  if ($message['id'] == 'welcome_waiting_approval') {
    global $user;
    $fid = $user['firm']['firm_id'];
    $message['body'][] = "Your Firm's ID is: $fid";
  }
}

I have used the Maillog / Mail Developer module to debug things such as your question.

To find the message ID, simply use code similar to the following one:

function YOURMODULE_mail_alter(&$message) {
  dpm($message['id']); // Assuming Devel module is installed.
  // Or just ...
  print $message['id']; exit;
}

Hooks are run for every module they are declared in; if you don't know the message id, simply create the hook and output the message id it finds. (Exiting might actually be a bad idea if your sending many types of messages—you didn't state that—because then the code might stop short of the exact message ID you're searching for.) Since the hook is declared, it will run for each outgoing message.

To access the user's 2 profile fields, they are just fields as long as you have a user object you can access them:

function MYMODULE_mail_alter(&$message) {
  global $user; // Get's a reference to the logged in user.
  if ($message['id'] == 'welcome_message_approval') {
    $message['body'][] = t("Your Firm's ID is: @firm", array('@firm' => $user->firm);
  }
}

To easily access fields I recommend the Field data extraction module.

I believe the Profile2 module should "eagerly" load the profile fields. If they are not in the global user object because of lazy loading, then you should be able to get at them by calling field_attach_load().


How do I customise individual menu links? I have a menu created through admin/structure/menu.

On some of the menus, I would like to place a var after the title.

I have tried placing the following in my theme template, but nothing happens.

 function mytheme_menu_link(array $variables) {
   print_r($variables['element']);
 }

How could I just place the content of a PHP variable after the menu link title?

If you just need to add a string after the menu title, you can use the following code.

function mytheme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

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

  $output = l($element['#title'] . ' ' . t('the string you need to add'), $element['#href'], $element['#localized_options']);

  return '
' . $output . $sub_menu . "
\n";
}

The alternative would be using the following code, which would give to who translate the string more context to translate it.

function mytheme_menu_link(array $variables) {
  $element = $variables['element'];
  $sub_menu = '';

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

  $output = l(t('!title the string you need to add', array('!title' => $element['#title'])), $element['#href'], $element['#localized_options']);

  return '
' . $output . $sub_menu . "
\n";
}

You could also implement a preprocess function to alter the title.

function mytheme_preprocess_menu_link(array $variables) {
  $variables['element']['#title'] = t('!title the string you need to add', array('!title' => $variables['element']['#title']));
}


Flowplayer controlbar D7 I've been trying to hide the controlbar when the canvas is being shown (the video has't been started up) and show a controlbar once the video has been started up. (see below) Thanks in advance :)

here is how its now by default

here how I want it to looks like...

As the Flowplayer API states the basic configuration is like this

$f("player1", "flowplayer.swf", {
    clip: {
        url: 'KimAronson-TwentySeconds59483.flv',
        autoPlay: true,
        autoBuffering: true
    },
    plugins: {
        controls: null
    },
    onLoad: function(){
        alert("player loaded");
    }
});

Note the  controls: null section this will allow you to render the player without controls.

Read Flash plugins section for more detailed information.


Categorize the contents of content type without creating a different template file for each I want to apply similar style to the nodes of same content type (style may vary or may be same between content types,  but will definitely be same for the nodes of same content types) without creating a template file for each of the content type.

I know one way is to create a template file as node-TYPE.tpl.php but I am looking if there is some other way.

You can use

Panels Module

It gives you UI to override node templates,providing appropriate selection criteria you can have different layout as per content types.

Display Suite

Display Suite allows you to take full control over how your content is displayed using a drag and drop interface. Arrange your nodes, views, comments, user data etc. the way you want without having to work your way through dozens of template files. A predefined list of layouts (D7 only) is available for even more drag and drop fun!


Restrict admin to search specific content types 1.Using search configuration module I have restricted the user role to search particular content type, this worked for me. But when I tried to apply the same approach to administrator this did work. I have unchecked the Admin bypass (primary user with id 1) the option too.

Is there a way to restrict the admin too to search specific content ?

2.And my second issue is about pagination, using the same module pagination is successfully applied, but for admin it is default set to 10 items per page, can I alter this?

I don't think so; you would have to either:

Create a new role and then limit search configuration for that node.
Use Views to simply create another page for administrators where they can search the title/body, limited to a certain type.
Install Views Bulk Operations and Admin Views which will then allow you to change the default administration pages, and limit the displayed content types if you want.
If you need more complex search, look into Search API with Search API Database Search. These modules integrate with Views and you will be able to cover more complex scenarios.

Solutions 2, 3 and 4 use Views, so you will be able to change the number of items displayed per page.

Hope this helps.


Alert after form radio has been selected I am trying to use drupal ajax to test if an email address from the form it is in my database. For that i have altered the form and added the following line to the element:

   $form['field_radio']['#ajax'] = array
    (
       'callback' => '_get_member',
       'progress' => array('type' => 'throbber', 'message' => '')
    );

and the callback function:

function _get_member($form, $form_state){

     $sid = $form_state['values']['details']['sid'];
    $commands[] = ajax_command_alert("Hello World");

    return array(
    'type' => 'ajax',
    'commands' => $commands
  );
}

As you can see from the callback i just want to return an alert message but it does not work. The callback is called because i have tested using watchdog but the alert popup never fires. Why ?

'wrapper' is a required key for #ajax on form elements, you're probably just missing that. From the docs

  This property is required for using AJAX requests in on a form element

If you add the wrapper it should work:

$form['field_radio']['#ajax'] = array (
   'callback' => '_get_member',
   'progress' => array('type' => 'throbber', 'message' => ''),
   'wrapper' => 'some-element-id'
);


how to get the region (the menu is rendered in) or block name/ID in hook_preprocess_menu I have a menu that want to behave differently based on the region its displayed in.

By default there is no file suggestion that differentiates which twig file to be used for a menu based on the region.  Even if there was I think for the purpose of adding/removing a class it is more convinient to modify a variable in a preprocess function than keeping to versions of a twig template.

here is what I have

function THEMENAME_preprocess_menu(&$vars) {
    $test = "";
    if ($vars['menu_name'] == 'main') {
        if (!isset($vars['attributes']['class'])) {
            $vars['attributes']['class'] = [];
        }
        //test region or block name before merging
        $vars['attributes']['class'] = array_merge($vars['attributes']['class'], ['main-menu-regionA']);
    }
}

I need a way to test the region or the block name to add a specific class to the parent UL element

my 2nd choice would be to explore the hook_theme_suggestions_alter

hook_preprocess_menu is missing a lot of variables that other preprocessors have so I finally solved my problem using hook_preprocess_block (which I think would not have been possible in earlier versions of drupal)

New solution since people have been reporting that $vars['configuration']['region'] is empty

function THEMENAME_preprocess_block(&$vars){
    if($vars['base_plugin_id'] == "system_menu_block"){
        if($vars['derivative_plugin_id'] == "main"){
            $block = \Drupal\block\Entity\Block::load($vars["elements"]["#id"]);
            if( $block->getRegion() == "navbar")
                $vars['content']['#attributes']['class'][] = 'in-navbar';
                $vars['content']['#attributes']['class'][] = 'nav';
            }
            elseif($vars['configuration']['region'] == "footer"){
                $vars['content']['#attributes']['class'][] = 'in-footer';
            }
        }
    }
}

NOTE if using in a recursive function/twig MACRO (which probably you are) you should  removeClass all the classes you don't want in inner UL tags in a way similar to this

{{ menus.menu_links(item.below, attributes.removeClass('nav','in-navbar'), menu_level + 1) }}

old solution

function THEMENAME_preprocess_block(&$vars){
    if($vars['base_plugin_id'] == "system_menu_block"){
        if($vars['derivative_plugin_id'] == "main"){
            if($vars['configuration']['region'] == "navbar"){
                $vars['content']['#attributes']['class'][] = 'in-navbar';
                $vars['content']['#attributes']['class'][] = 'nav';
            }
            elseif($vars['configuration']['region'] == "footer"){
                $vars['content']['#attributes']['class'][] = 'in-footer';
            }
        }
    }
}


Editing the Book Template I'd like to edit the way the Book navigation is structured.
I'd like to be able to edit the html output of the book.

I was looking for a way to do this with the book template but had no luck. Looking at book-navigation.tpl.php I did see that $tree contained the children of the current node. However it used like this

<?print $tree; ?>

I don't see a way to alter the html of how the tree is output.

The theme hook you'll want is menu_link__book_toc_123, where 123is the node ID of your book's outline node.
For the wrapping markup, use menu_tree__book_toc_123.

You can also find the ID by inspecting the navigation list:


Displaying hook_form I have implemented a hook_form in my custom module and I can't figure out how I can get the form to display.

Here is my hook form:

   function data_retrieval_form($node, &$form_state)
    {
        $type = node_type_get_type($node);

        $form ['title'] = array(
            '#type' => 'textfield',
            '#title' => check_plain($type->title_label),
            '#default_value' => !empty($node->title) ? $node->title : '',
            '#required' => TRUE, '#weight' => -5
        );

        $form ['field1'] = array(
            '#type' => 'textfield',
            '#title' => t('Custom field'),
            '#default_value' => $node->field1,
            '#maxlength' => 127,
        );
        $form ['selectbox'] = array(
            '#type' => 'select',
            '#title' => t('Select box'),
            '#default_value' => $node->selectbox,
            '#options' => array(
                1 => 'Option A',
                2 => 'Option B',
                3 => 'Option C',
            ),
            '#description' => t('Choose an option.'),
        );

        return $form;
    }

I have also implemented hook_menu which registers a url with a callback to the form:

function data_retrieval_menu()
{
    $items = array();

    $items ['examples/form_example'] = array(
        'title' => 'Example Page',
        'page callback' => 'drupal_get_form',
        'access arguments' => array('access content'),
        'type' => MENU_SUGGESTED_ITEM,
    );

    return $items;
}

The problem I am having is that I cant understand how to get the form to display, the url does not work, how exactly do I display the form?

Please check hook_menu() documentation.

You need to specify page callback arguments like:

'title' => 'Example Page',
'page callback' => 'drupal_get_form',
'page arguments' => array('my_form_id'),
'access arguments' => array('access content'),
'type' => MENU_SUGGESTED_ITEM,