Search API Attachments not working I'm running Drupal 7.12. I have a requirement to index files attached to nodes. (DOC, PDF, XLS, etc).

After quite a bit of trail and error, reading and searching I have been unable to get any of the attachment file indexing modules to work.

Search API Attachments  seems the most promising but after configuring it doesn't seem to index any of the documents. It does call Tika to process attachments to new nodes, but doesn't seem to re-index any existing nodes. Searching on any file contents yields no results.

Any thoughts on what I should investigate to track this down would be greatly appreciated. Anyone running this module successfully? If so how did you configure it.

More info:

I followed these instructions: http://permalink.gmane.org/gmane.comp.php.drupal.support/22390

To see if I can track this down:

I configured a fresh installation of Drupal 7.12.
I installed Search API, Search API DB and Search API Attachments

projects/search_api_db-7.x-1.x-dev.tar.gz
projects/search_api_attachments-7.x-1.2.tar.gz
projects/search_api-7.x-1.0.tar.gz

I installed Tika and verified that it is working per instructions.
I created a field called Attachment1 of type File for the "Article" content type: structure -> content types -> article. label: Attachment1 name: field_attachment1, field: File.
I created a search server in Configuration -> Search and metadata -> search api using the database service class.
I then edited the Default Node Index to use the search server I defined and enabled it.
I then went to the Default Node Index fields and using "Add Related Fields" added Attachment1 » The file.
I checked the box next to Attachment1 >> The file and Attachment content: field_attachment1
I created a single Article and attached a word document to it.
I ran the cron service from the admin menu.
In the database I ran select * from search_index and I notice that only the terms from the node content are present, nothing from the document that I uploaded.
I verified that Tika was being called by adding the syslog call prior to shell_exec which yields:

  Mar 17 13:32:06 xeon httpd: Calling Tika: java -Dfile.encoding=UTF8 -cp '/usr/local/tika' -jar '/usr/local/tika/tika-app-1.0.jar' -t 'http:///drupal/sites/default/files/Resume_0.doc'

However, if I select to re-index the site by going to Configuration -> Search and metadata -> search settings -> clear index and re-run cron I notice that Tika is NOT being called.

Also I notice that selecting clear index does not affect the search_index table. (Should it?)

I have separately verified that Tika is properly extracting the text from the document by logging it to a file prior to the call.

My feeling is that I'm missing something obvious.

Ok, this looks like part of this is a case of PEBKAC. Or maybe could be considered an issue of documentation.

It looks like the default search box form does not interface with search API and that in order for the search API indeces to be used you must use the Search API Pages module.

However, re-indexing definitely does NOT re-index attachments on existing nodes. I'm not sure whether it's supposed to or not but that is what threw me to believe it was not working.


Can I display Media Videos in a single "media player" block I have several youtube videos listed on a page. I am currently loading them as Media Fields. What I would like to do is declare a single block (or perhaps a region) where the videos play no matter which video I select. SO rather than displaying the URL to a video, or the video itself, I want to display a play button.

Is there a standard way of doing this with Media, or do I have to create my own Javascript to insert the video into a "video player" block

You could create a View that makes a Block, and set it to display videos that meet whichever criteria. Or, you can just embed videos directly in a block with embed code. You can try the Video module or Video Embed Field to show videos from another source or from your side.


How can I specify where an image is uploaded I have a slideshow block that does a slideshow for a news stories that take two images.  An image for the page and a teaser image for the slideshow.  but the image never shows up in the slideshow.  The image url is sites/default/files/styles/mt_slideshow/public   but the actual location of the image after its uploaded is sites/default/files.   so is there a way to force the image to be uploded where this site is looking, or change where the site looks to where the image  is uploaded?

In your site log in as adminstrator and go to

'/admin/config/media/file-system'

and you can find the place where you can define your path to save any uploaded files.

for Example your siteis example.com you have to access

"**example.com//admin/config/media/file-system**"  as Drupal Administrator and you can change the path there.

image URLs messing up

possibly this will give you a answer


displaying field from node on page in url in block I want to put a link in a block which will pull its url from a url field in the node being displayed on the page on which the block is. Meaning, the block will contain a different url for each different node-info page. How can I reference this node in the block?

I figured out how to do it. Make a template file for that specific node ie: node-job.tpl.php and set the value of that url field (which is available to you while inside of that template file) as a global variable ie: variable_set. Now you can access the url inside of your block using variable_get.


Use a file token for directory path when uploading a file via core file upload field? Is there a way to use a token like [file:fid] when using the file upload field? I either want to use this, or, use the node id it is attached to with [node:nid]. It looks like I can only use global tokens, which are not unique enough to the way I want to store the file on the server.

In core this is not possible, because the file widget sets the #upload_location when it builds the form element.

You need a module, for example File (Field) Paths. This module sets a temp path in #upload_location of the form element and sorts this out later when the file and node entity are available.


What are the pros/cons/alternatives to creating a number of identical content types to allow for divergence? I hope this counts as an answerable question.

A publications database I'm migrating from another content management system to drupal, has different types of publications.  In the current system those publications are kind of the equivalent of a taxonomy.  It is clear from talking to people familiar with the history, and from looking at the state of the database and code, that every couple of years they rearrange things, adding or removing content types and changing the fields available.  They used to try to dynamically change the fields available on the form depending on the content type.  (peer-reviewed journal articles would have volume/Issue, pages, publication name, etc, where books would have different requirements, and online publications would be still different.  This seems to have become very hard to maintain, so the current system now makes all fields available for all content types, and sometimes the same field is used for different types of data (total pages and page range for example).  There are thousands of publications and sorting it all out programmatically seems quite difficult, so the thought is to bring everything over using the same fields (cleaning up the data where it can be done programmatically).  Having differing fields per publication type is desirable, and in the future they would like to have an approvals process built into the system with differing approval paths per publication type.

Initially my approach was going to be much like theirs, to have one publications content type, and a publication type vocabulary to categorize them.  Thinking of the need for future divergence of fields, and the likelihood of a requirement to change the display depending on the publication type, I've modified my approach to start with an identical content type per publication type to allow for things to change over time.

Is this going to cause terrible problems for me down the road if they decide that two types of report are now one publication type?  I'm already seeing a little bit of difficulty in the ability to make dynamic templates that cover the entire set of publication types.  It has been quite painful to move any changes made in one content type over to all the others.

Would it be more sensible to try the approach of having all the fields we need in one content type and trying to dynamically hide or show those fields depending on the publication type selected?

Is there some other more sensible way of going about this that I haven't thought of?  It seems like somewhere along the line I'm going to run into pain either changing the fields or with changing publication types, I'm just not sure which kind of pain is likely to be better.

Initially my approach was going to be much like theirs, to have one publications content type, and a publication type vocabulary to categorize them.

The problem with this approach is that you won't be able to use pathauto to give them different paths per type. Ex: You want the books type to be /books/title-goes-here and the cars type be /cars/title-goes-here

If books and cars are the same content type then node author would have to manually type in the url alias.

Also, how do you plan on theming them? If each type needs to be themed differently, I don't know how you're going to pull that off since they are all the same content type.

I think making 16 different content types is the way to go. You can always re-use existing fields whenever you can.

  I'm already seeing a little bit of difficulty in the ability to make
  dynamic templates that cover the entire set of publication types.

You could use the Panels module which allows you to theme all 16 content types differently or the same. With panels you won't have to deal with tpl (template) files.

Checkout this Panels Video Tutorial series


Passing multiple values in fields as mentioned in another field (as number of values) by user I want a field that upon getting a value in a text field (eg. 1, 2 anything) shows respective fields.
If user inputs 5, then five fields will appear (similar to multiple values of a field, unlimited)

How can I make this possible?
There is a conditional module that provides UI for state API but is that enough for the working?

You can ref Examples for Developers Module. The module comes with various sub-modules for developers to start with.

Similar kind of functionality is already provided as an example in "AJAX Example" module in Examples module. i.e. User has been given a dropdown field with predefined numbers to render those many fields. Check screenshot below:

Hope this helps.


Syntaxhighlighter Insert do not working with CKEditor 4 CKEditor 4 Drupal Module do not depend on Wysiwyg module, so after configuring Syntaxhighlighter Insert module i can not understand how to have the "Insert Code" button in CKEditor, because in CKEditor Plugins section there is no option to enable the button! if you follow this article (http://jordanjr.com/articles/drupal-7-syntax-highlighting-using-wysiwyg-ckeditor-and-syntax-highlighter) then you will see that they need wysiywg module, but now CKEditor do not need wysiywg module!.. any idea to solve this? here is the screenshot:

It's simple - switch to WYSIWYG module and install CKEditor as library. CKEditor module and WYSIWYG module are separated projects that happens to use the same library, so if you want to use modules and articles designed to work with WYSIWYG, you need WYSIWYG.


Is it possible to use a view as a field in another view? I have two views. First one is an unformatted view from a content type, and second one is a table view of most viewed from the same content type. Now I want to show both of these views in a page without using panel module. Is there any way to attach these views?
thanks.

The title of your question and the body of your question seem different to me.

To use the results of a view as a field in another view, you would use Views Field View.

To display two views at the same time, make one a page display and the other an attachment display attached to the page display.


Adding Google Remarketing Script tags to Drupal 7 website I need to find a way to easily add google remarketing script tags to my Drupal 7 website. If there is a module that can do this easier and faster then that's what I need.

I think you are looking for the Google Adwords Remarketing module. Here is a quote about it (from the module's project page):

Adds the Google Adwords Remarketing web statistics tracking system to your website.
NB - Google now has another (easier) method for using Remarketing tags. If your Adwords account is linked to your Google Analytics account you can enable the tag by installing the Google Analytics module and ticking a tick box under the Google Analytics Drupal admin page - see attached image.
This tick box causes a slight alteration in the GA tag which is needed by Google Remarketing.


Unable to get my ContentEntity base field definition to appear as checkboxes I am trying to implement a base field with multiple selections as checkboxes I have had a go at implementing it but it stills appears as a select even after clearing the cache. I'm sure I'm doing this wrong but this is what I have:

$fields['content_display'] = BaseFieldDefinition::create('list_integer')
  ->setDisplayOptions('form', array(
    'type' => 'checkboxes',
    'weight' => -4,
  ))
  ->setSetting('allowed_values', $values)
  ->setDisplayConfigurable('form', TRUE);

Try with options_buttons because this is the ID if the OptionsButtonsWidget widget.

$fields['content_display'] = BaseFieldDefinition::create('list_integer')
  ->setDisplayOptions('form', array(
    'type' => 'options_buttons',
    'weight' => -4,
  ))
  ->setSetting('allowed_values', $values)
  ->setDisplayConfigurable('form', TRUE);


How to remove core taxonomy rss feeds I'm creating my own custom taxonomy rss feeds and have added those sucessfully to the head on term pages. Now, however, I need to remove the core taxonomy feed from those pages (currently it shows 2 feeds: the custom feed and the core feed).

Many people have suggested simply using the taxonomy view which overrides the core term and feed displays, but for complex reasons I can't use this solution.

I need to programmatically remove the feed from the head.

The original feed in the page head looks like this:

<link rel="alternate" type="application/rss+xml" title="RSS - termname" href="/taxonomy/term/2764/0/feed">

My best attempt to remove this is done in template.php and shown below, but it doesn't work:

mytheme_preprocess_page(&$variables) {
  //target taxonomy term pages
  if(arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric($arg2)) {
    $variables['head'] = preg_replace('/<link rel="alternate" type="application\/rss\+xml" title=".*?" href=".*?">/', '', $variables['head']);
  }
}

I probably need to get even more specific on the 'href' portion as well, so it only removes the term feed...but I haven't gotten that far yet.

I also tried adding $variables['head'] = drupal_get_html_head(); at the end just to reload the head, in case it was necessary, and that doesn't help.

How can I programmatically remove this feed?

If you're using D7 hook_html_head_alter is your friend.

something like

function my_html_head_alter(&$head_elements) {
  foreach ($head_elements as $key => $element) {
    if (isset($element['#attributes']['type']) && $element['#attributes']['type'] == 'application/rss+xml') {
      unset($head_elements[$key]);
    }
  }
}

Otherwise your attempt seems to be the best solution. Perhaps try ungreedy regex?

<link rel="alternate" type="application\/rss\+xml" title="[^"]*?" href="[^"]*?">


How can I put the feed import page on a different page and not have it on the node add page? I want the user to be able to either add a new asset by using node/add or import a CSV, but on different pages. Right now both options come out on the add page.

How can I put the feed import page on a different page and not have it on the node add page?

There is an option on the Feeds importer edit page that lets you toggle off the form on the node add page. Just select the Use standalone form option on the Attach to content type setting.


How to store data in database with Form API? I'm new to developing Drupal 7 modules, and I can't figure out why my custom module's form data is not stored in my database's table called 'media_skins'.

I followed the info explained in Creating modules - a tutorial: Drupal 7.x but I can't get it working. What's wrong with my code?

Here's my code:

function media_skins_menu() {
  $items = array();
  $items['admin/config/content/media_skins'] = array(
    'title' => 'Media Skins',
    'description' => 'Configuration for Skins module',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('media_skins_form'),
    'access arguments' => array('access administration pages'),
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

function media_skins_form($form, &$form_state) {

  $form['media_skins_test'] = array(
    '#type' => 'textfield',
    '#title' => t('Test field'),
    '#size' => 20,
    '#maxlength' => 20,
    '#description' => t('Test info for the field.'),
    '#required' => FALSE,
  );
  return system_settings_form($form);
}

function media_skins_form_validate($form, &$form_state) {
    // For now, I will no validate anything
}

function media_skins_form_submit($form, &$form_state) {
  $form = db_insert('media_skins')->fields(
    array(
      'start_date' => $form_state['values']['media_skins_test'],
    )
  )
  ->execute();
  drupal_set_message('Data stored in database successfully');
}

Any help will be very appreciated.

EDITING THE SCENARIO

After reading your comments, I tried the following, but I get "Unexpected error, try it again":

function media_skins_form($form, &$form_state) {
  $form['media_skins_test'] = array(
    '#type' => 'textfield',
    '#title' => t('Test field'),
    '#size' => 20,
    '#maxlength' => 20,
    '#description' => t('Test info for the field.'),
    '#required' => FALSE,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Enviar'),
  );
  return $form;
}

To use your own form submit handler, you should not use system_settings_form in your form, instead just return your form.

If you are just going to save your value in your submit handler, go with system_settings_form.
To get the values, use variable_get('your form field name'). In your case, you can use variable_get('media_skins_test');


How can I show Arabic dates in a block? I have used Drupal7 and I want to add Arabic date in Hijri formate; I have used the Calendar Systems module, but it doesn't add dates as block. How can I implement hook_block() to show dates in Hijri format?

its approved now I just added the new release yesterday

Hijri

  This is a smart module that basically extends Drupal's display date to provide Hijri Date integration with Drupal core date field and with other Drupal contributions.


Want to modify drupal default pager functionality I am creating a page with teaser of articles using views... In the Full pager, the default functionality is....

1 2 3 4 ... next >

when i click next now the next number gets highlightd like...

< prev ... 1 2 3 4 ... next >

and now when i again click next...

< prev ... 2 3 4 5  ... next >

the number set gets altered...

But what i actually need is...

1 2 3 4 next >

< prev  1 2 3 4  next >

< prev  1 2 3 4  next >

< prev  1 2 3 4  next >

and now when i click next...

< prev 5 6 7 8 next >

There are some modules like PAGERER to change the appearance of the core pager... But is there any to make this functionality or should I do some custom work...

I worked on it and found a result... actually Drupal core pager is user friendly enough but in case you need to alter it's functionality you need to edit variables in theme_pager() in your theme's template file.

To obtain the above functionality I altered some variables which are as follows...

$pager_first = (floor($pager_current / $quantity) * $quantity) + 1;

$pager_last = $pager_first + $quantity - 1;

if( $pager_current % $quantity == 0){
  $pager_first = $pager_current - $quantity +1;
  $pager_last = $pager_first + $quantity - 1;
}

I neglected $page_middle variable since I did not needed it...

Warning: Do this when its absolutely necessary...


Get the url for an images in a Field Collection for the Node Template This is a bit messy so bear with me. I've built a node with a field collection 'field_meet_videos'. That field collection contains another field collection 'field_about_video'. The inner field collection has 3 fields (two text fields and an image field 'field_image'). This field collection is also used as multifield so it'll be used more than once (lets say 3 times for this example).

What I'm trying to do is just get a printed output of the image url (with imagecache style) on the node template (to use them as html element backgrounds).

<?php
  $content['field_meet_videos'][0]['entity']['field_collection_item'][34]['field_about_video'][0]['entity']['field_collection_item'][35]['field_image']
?>

This looks to contain enough that I could cobble together a url by sticking these variables into a url string but it feels like there must be a better way to access these variables.

You can find a good example of how to decompose the field_collection with a foreach in drupal.org

https://www.drupal.org/node/1155752#comment-12170687

if (isset($node->field_gallery_images)) {
  $nodeField = field_get_items('node', $node, 'field_gallery_images');
  if (!empty($nodeField)) {
    foreach ($nodeField as $key => $item) {

      $field_collection_item = field_collection_item_load($item['value']);
      $item_wrapper = entity_metadata_wrapper('field_collection_item', $field_collection_item);

      print '
';
      $field_image = $item_wrapper->field_gallery_image->value();

      print theme('image_style', array('style_name' => 'large', 'path' => $field_image['uri']));
      print '
';
  }
}


Display external link using theme settings I'm using theme-settings.php to store links to external pages (like Facebook, Twitter, etc.) and the links aren't storing correctly. In theme-settings.php, I have:

function mytheme_form_system_theme_settings_alter(&$form, $form_state) {
 $form['mytheme_facebook'] = array(
'#type'          => 'textfield',
'#title'         => t('Facebook Link'),
'#default_value' => theme_get_setting('mytheme_facebook'),
'#description'   => t("Appears in sidebar block."),

);

On my Theme Settings page, I enter https://www.facebook.com/ in the "Facebook Link" field. When I hit save, I see that only "www.facebook.com" has been saved in that field.

So, when I call the field on my site, using

print theme_get_setting('mytheme_facebook');

the link that gets outputted is http://www.myurl.org/www.facebook.com/.

How can I get I get rid of the "myurl" stuff, so I get a working link to Facebook? Oh, and I'm using Drupal 7, if that helps.

Thanks in advance for any tips!

Drupal is probably applying your default text format to your field.

Try adding a #format value to the array that matches one of your less strict input formats.


No welcome email sent when users register via profile2 registration path I am using profile2 registration path for two different types of roles. The roles are auto-assigned when users register via one of the paths. I have used mail logger to check and the emails are not sent. Other types of emails are sent. I can block the new users then unblock them and registration emails are sent.

When a user is registered via the regular user registration (/user/register) an email is sent.

I am using Drupal core 7.59, profile2 7.x-1.4, profile2 registration path 7.x-1.13.

Any ideas about how to fix this?

This appears to be an issue with the profile2 module. I've created a patch for another issue and this, in turn, has fixed the no emails sent issue I was experiencing.

For a patch and proposed solution please see: https://www.drupal.org/project/profile2/issues/1993770#comment-12699962


How to automatically upload a file on form submission I have created a form with a file attachment field. I have noticed that users will attach a file but sometimes forget to hit the upload button. I would like the form to automatically upload the file when the form submit button is pressed (if a file has been selected to upload).

I have seen a similar answer answer to this at https://drupal.stackexchange.com/a/31453/4471 but that is a slightly different use case then what I am after. I would have thought that submitting a form would automatically upload attached files as default behaviour.

I am working with Drupal 7 by the way.

Thanks.

If a file has been selected in a file upload field, it will be uploaded on form submit regardless of whether the "Upload" button has been pressed.


How to add special character validation on specific field in form registration process I want to add a special character validation on a specfic field.
Here I have my code but it does not work and there is no error.

function mymodule_form_alter(&$form, &$form_state, &$form_id) {
   if ($form_id == 'registration_node_form') {
        $form['#validate'][] = 'mymodule_form_validate';
   }
}

function mymodule_form_validate($form, $form_state){
    if(isset ($form['field_employer_name']['und'][0]['value']['#default_value'])){
        $special_character_list = '[\'^£$%&*()}{@#~?><>,|=_+¬-]';
        if (preg_match($special_character_list, $form_state['field_employer_name']['und'][0]['value']['#default_value'])== 0) {
            form_set_error('field_employer_name', t('The specified form name contains one or more illegal characters. Spaces or any other special characters except dash (-) and underscore (_) are not allowed.'));
        }
    }
}

Please help. Thank You.

Try using Field Validation  Module it simplifies your work!!

If you want to code it then check this post It solves the same issue

Try changing your code:

 $special_character_list = '\'^£$%&*()}{@#~?><>,|=_+¬\-\[\]';
  if(preg_match('/[' . $special_character_list . ']/',$form_state['field_employer_name']['und'][0]['value']['#default_value']) !== 0)


How do I retain the query string after login? I need the user,opening a certain page of my site (www.foo.com/page_to_visit), to login and then go to the requested page, so I set up an hook_menu for this specific page and a callback. In the callback I added this code which works

drupal_goto('user', array('query'=>drupal_get_destination()))

but if the url contains query strings (www.foo.com/page_to_visit?id=12&od=12) they are removed. I mean that, after login, the user gets redirected to www.foo.com/page_to_visit instead of www.foo.com/page_to_visit?id=12&od=12. How do I avoid this behaviour?

UPDATE: Drupl_goto has something supporting this. Produced this code, following documentation

$args = array();
$params = $_GET;
$args[] = $params['q'];
unset($params['q'], $params['destination']);
if (count($params) > 1) {
  $pippo['query'] = $params;
  $args[] = $pippo;
}
drupal_goto('user', array('query'=>$args));

$args results in --->
Array
( [0] => page_to_visit
  [1] => Array
    ( [query] => Array
            ( [id] => 12
              [od] => 12
            )
    )
)

The result is odd for the redirect looks like
    http://www.foo.com/user?0=page_to_visit&1[query][id]=12&1[query][od]=12

I think, my suggestion is :-

alter login form
add a hidden field for destination URL.
add submit handler  like $form['#submit'][] = 'destination_redirect_handler'
use drupal_goto('destination_redirect_url') in this destination_redirect_handler


Display certain content based on whether a date is in the past or future I have a content type called 'DVD Review' with a field called 'Release Date' which is input using the date module.

On the node page, if the release date is in the future I'd like it to say "Coming Soon", or otherwise, if the release date is in the past say "Out Now".

I'm using Display Suite to arrange the fields, so I'm thinking I could add a code field with a php if statement to handle this.

Please follow below instructions to add new custom code field.

Go to admin/structure/types/manage/your_content_type/display
Click on Add Custom Fields Vertical Tab @ Bottom of Screen.
Click on Add a Code Field.
Use $entity object to get Release Date based on that display the message.
Enable the Code Field in right place.

Post comments if you have any Questions.


Default Field Value based on another referenced field I am now learning drupal 8 and I am struggling about 2 weeks to find an answer to this. I am trying to give to a reference field of the comment a default dynamic value. This value is the same with the referenced field of the article that the comment belongs. There are 2 ways to do this:

1) The easiest and cleaner way is to create a view that will show the specific article's field value that the current comment belongs. Easy but the issue is that although the view has only one result, that result cannot be set as default value. The user has to choose it or type in the autocomplete box in order for the value to appear. Is there any way to make that field been automatically completed and make it hidden? I would like the user not to be aware of that field

2) Here is another solution more difficult to me. https://www.drupal.org/node/1797100#comment-11792569 I should create a text widget for my field. I tried this but it is not working. The field has been created from the dashboard. I would like to keep things as cleaner as possible and not to create the field from the beggining with code. I believe that the text base,text widget and text formatter have already been created by core and that's why my text widget is not working. Should I in this case override (alter) the text widget and not create a new one and if yes how could I do that? https://api.drupal.org/api/drupal/core!modules!field!field.api.php/function/hook_field_widget_form_alter/8.2.x

function hook_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
  // Add a css class to widget form elements for all fields of type mytype.
  $field_definition = $context['items']->getFieldDefinition();
  if ($field_definition->getType() == 'mytype') {
    // Be sure not to overwrite existing attributes.
    $element['#attributes']['class'][] = 'myclass';
  }
}

where should I place the above function?

If you have an answer to 1) or 2) please leave a comment, I am totally desperate as this is very basic for the functionality of my website and I cannot find a solution...

Thank you

You can use a hook_ENTITY_TYPE_create() to prepopulate comment fields with data from the parent entity:

  function mymodule_comment_create(\Drupal\comment\CommentInterface $comment) {
    $node = $comment->getCommentedEntity();
    if ($node && $node instanceof \Drupal\node\NodeInterface) {
      if ($node->hasField('field_example')) {
        $comment->subject->value = $node->field_example->value;
      }
    }
  }


Should I use content-types or database abstraction layer? I am building an admin site for my brother's property management company. The design seems pretty straight forward.

I need a database with tables to store:

Estates. Each estate has a number or properties (flats or houses). Each property has a number of charges (service charge, water bills, maintenance ect.)

Then I have: Owners. Each Owner must have ONE or MORE properties. Owners make payments. Each payment is allocated to ONE or MORE charges.

From there I add CRUD functionality and the ability to produce reports by estate, property and/or owner.

Being new to Drupal I originally thought that the way to do this is create a content-type for each of the tables (e.g Estate, property, charge, owner, payment) and then use the relations module to enforce any foreign keys and automatic additions and update.

However, I have spent this week reading pro drupal development 7 and now I see  I can build the database using the schema module and add functionality through the database abstraction layer with the functions declared in database.inc.

Does anyone have an opinion on which is the best way forward? Or am I missing the point a bit? Do I use them both?

Thanks for any advice and Merry Christmas (or Happy Holidays, whichever you prefer)

Reasons you should go with content type.

Its is what you get out of box from drupal, content type are built on drupal entity concept,lot of api's are exposed to alter the default workflow in case needed,internally it does the same that you can do with custom tables,a lot of contributed modules are there to extend the functionality.
If you are planning to have custom tables then you have to write codes at each point of three layers -tables creation, data insertion/updation, data view,while using content type you can get it done by drupal core and by using some of contributed modules for example to show different data you can use views.

Following modules can be helpfull for the functionalities listed above.

views.
entityreference

Things you need to plan
Try to categorize the listed  (Estate, property, charge, owner, payment) into entities and their properties for example charge might not be a separate entity instead it might be a property(field) of property(content type). So roughly you can have Estate,property as content type. Once you install entityreference module, it will allow you to setup reference from property to estate using reference field(provided by entity reference module).So setting up reference you can establish relationship of what property nodes belong to what estate nodes.Charge can simply a field on property content type, so it will show charge/cost for a property node.Owner can be nodes or if you allow login to owner you can make theme drupal users as well.Again you can setup by relationship between property and owner using reference field in both ways keeping it as users or as node.

I hope this might be helpful in starting,Merry Christmas :)


How do I get my blog on Feed Burner? I'm trying to get my blog onto Google Feed Burner. I've read all about this, but there doesn't seem to be a clear answer. I just get this error.

Received HTTP error code 400 while fetching source feed.

I then validate my blog feed through feedvalidator.org. It says it's validated, but it shows the following message.

This feed is valid, but interoperability with the widest range of feed readers could be improved by implementing the following recommendations.
line 38, column 0: Missing atom:link with rel="self" [help]

The help link seems useless, and I don't think this "recommendation" from the feed validator is my issue. Nonetheless, I've installed
http://drupal.org/project/views_rss  as well as http://drupal.org/project/feedburner.
I've tried burning my feed through the Feed Burner module, but nothing seems to be validated. It looks like there's a lot of Drupal folks having similar problems without a clear answer/tutorial.
Here's what I have:

Drupal6 site. A blog page with numerous blog posts, each with a teaser. URL example.com/blog

What appears like a valid RSS feed when I type in example.com/blog/feed. This spits out some text which looks like.
<?xml version="1.0" encoding="utf-8"?>
<rss version="2.0" xml:base="https://example.com"
xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:media="http://search.yahoo.com/mrss/">
<channel>
<title>Example blogs</title>
<link>https://example.com/blog</link>
<description></description>
<language>en</language>
<item>

I've set up a google Feed Burner account.

I installed the RSS Views and the Feed Burner modules.

I don't know what else to do. I keep getting that awful error.
Hopefully someone out there can help.

This one is ugly on google's part. My site is https, and feedburner doesn't support SSL... I figured that out the hard way.  I didn't want to muck around with my SSL settings given that it's a wildcard cert, so I figured out a painless workaround.
1. Subscribe to your blog feed through Google reader.
2. Create a bundle folder with your blog feed.
3. Grab the bundle URL (not https, which is the workaround)
4. Paste it into feedburner.

Done, google accepts that, and gives you a branded feedburner url.

I'm sure there's a better approach, but this was an easy workaround for those with https sites.


theming form of block subscription newsletter module someone could tell me how to form theming block newsletter subscription module,
I use the bootstrap theme and I want to change the markup and add some classes css

There are many ways. One is this way to theme the blocks.

There is simpler way to add a class to a block then add css in the theme info file.


Commerce Email: HTML Mail not reading template I am attempting to make a custom template for my Commerce Email emails. CE uses Variable Email and HTMLMail. I have put the template (named htmlmail--variable_email--custom_email_order.tpl.php) into the root of my theme folder. Nothing. The test htmlmail template is in the same place and works fine. I have cleared caches on the performance and in PHPMyAdmin, and run cron. Still doesn't work. Is this peculiar to Variable Email or HTMLMail?

It's not enough to leave the theme selection entry as Current theme; you must explicitly state that you want to use the theme you are already using. Now everything works.


Recommended Drush version to use and install for Ubuntu 19 with PHP 7.2 and running Drupal 7 It's been awhile since I've upgraded my server and I'm setting it up from scratch. I'm using Ubuntu 19, apache 2 and PHP 7.2. My site is Drupal 7 which is still running php 5.6 in my old server. I'm in the process of installing drush via the command on the new server:

  composer global require drush/drush:8

I'm not sure which version of drush I should be using or if I should even be installing via that method. What version of Drush should I be using for Drupal 7 and am I using the correct PHP version of 7.2?

Drush 9 does not work with drupal 7, but drush 8 does work with it. I installed it by creating a new ubuntu user and making sure composer is installed globally then install cgr via:

composer global require consolidation/cgr

then add to your ~/.bashrc file

export PATH="$HOME/.config/composer/vendor/bin:$PATH"

then

cgr drush/drush:8.x-dev --prefer-source

link: https://github.com/consolidation/cgr#installation-and-usage

Then I followed the tutorial here: https://docs.drush.org/en/8.x/install-alternative/

  Install a global Drush via Composer

  Follow the instructions below:

  Install Composer globally.

  Install the cgr tool following the instructions in that project.

  Add composer's bin directory to the system path by placing export
  PATH="$HOME/.composer/vendor/bin:$PATH" into your ~/.bash_profile (Mac
  OS users) or into your ~/.bashrc (Linux users).

  Install latest stable Drush: cgr drush/drush.

  Verify that Drush works: drush status

  Please do not install Drush using composer global require. See Fixing
  the Composer Global command for more information.


Using drupal 7 block from another website luckily on same server I have spent several hours searching for my solution. I found some but none of them is working. My problem is I have multi-site setup of drupal. Site A has a drupal views generated block of events calendar with next/back navigation of months (mini calendar). I want to use that block in another website of same drupal installation. Both of website has common user tables, theme and modules. I have tried following options until now

Web Widgets module, web widget block does not have month header and the navigation. I believe I can not use it without IFRAME.
I have also tried setting up REST setup between both domains using clients, OAuth, Services, Remote Views Block modules. Fotunately, connection is set up properly but Remote Views Block module is raising following errors when remote module is added to context.

Notice: Undefined property: stdClass::$weight in context_reaction_block->options_form_submit() (line 104 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/sites/all/modules/context/plugins/context_reaction_block.inc).
Notice: Undefined property: stdClass::$weight in context_reaction_block->options_form_submit() (line 104 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/sites/all/modules/context/plugins/context_reaction_block.inc).

and following errors on other pages when context of remote block is active

Warning: http_build_query(): Parameter 1 expected to be Array or Object. Incorrect value given in clients_connection_drupal_services_rest_7->makeRequest() (line 204 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/sites/all/modules/clients/connections/clients_drupal_rest/clients_drupal_rest.inc).
Notice: Undefined offset: 1 in drupal_http_request() (line 929 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/includes/common.inc).
Notice: Undefined offset: 2 in drupal_http_request() (line 933 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/includes/common.inc).
Notice: Undefined offset: 1 in drupal_http_request() (line 933 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/includes/common.inc).
Notice: Undefined offset: 1 in drupal_http_request() (line 941 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/includes/common.inc).
Notice: Undefined offset: 1 in drupal_http_request() (line 941 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/includes/common.inc).
Notice: Undefined offset: 1 in drupal_http_request() (line 941 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/includes/common.inc).
Notice: Undefined offset: 1 in drupal_http_request() (line 941 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/includes/common.inc).
Notice: Undefined offset: 1 in drupal_http_request() (line 941 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/includes/common.inc).
Notice: Undefined offset: 1 in drupal_http_request() (line 941 of /var/www/vhosts/neumarkets.com/subdomains/southhuron/includes/common.inc).

Am I missing anything here? connection test works properly though and I double checked the module names.

Embed widgets and Remote blocks are not available for Drupal 7.
I read somwhere (I cant find the source right now) that Drupal 7.x.1.1 supports Remote Blocks in the sense that site has other database configured in settings.php. Do we have its documentation anywhere?

Any help would be much appreciated... I am stuck here..

Here's a Shared Blocks module for that purpose written by well known drupal community members.

  Features:

  Allows publishing and subscribing of Drupal blocks
  Changes to published blocks are updated on sites with subscription blocks
  Published blocks provides a JSON endpoint at sharedblocks/{module}/{delta}
  Block subscriptions are updated on cron with an adjustable refresh interval


Commerce programatically Create Order with Customer Profile I am using this method to create order successfully, how do I add a customer profile with all the country/address etc to this order?

There does not seem to be any reference to customer profiles in commerce_order_save. I had a peek into the commerce_order database table and it also must be hidden in data.

function create_order_with_products($product_ids, $uid) {
    $order = commerce_order_new($uid, 'pending');

    // Save the order so its ID is assigned.
    commerce_order_save($order);

    $order_wrapper = entity_metadata_wrapper('commerce_order', $order);

    //add products to order by ids array
    foreach ( $product_ids as $product_id ){
        $product = commerce_product_load($product_id);

        // Create a line item with quantity 1 and this product.
        $line_item = commerce_product_line_item_new($product, 1, $order->order_id);

        // Save the line item to get its ID.
        commerce_line_item_save($line_item);

        // Add the line item to the order using the wrapper.
        $order_wrapper->commerce_line_items[] = $line_item;
    }

  // Save the order.
  commerce_order_save($order);

//somehow attach the profile to the order????
$profile = commerce_customer_profile_load(exampleID);

//How do I use this wrapper maybe?
$wrapper = entity_metadata_wrapper('commerce_order', $order);
$wrapper->{????????} = $profile;

      return $order;
    }

  // Ensure the attached line items are associated with the order if they do not
  // have an order_id set yet.
  foreach (entity_metadata_wrapper('commerce_order', $order)->commerce_line_items as $delta => $line_item_wrapper) {
    if ($line_item_wrapper->order_id->value() == 0) {
      $line_item_wrapper->order_id = $order->order_id;
      $line_item_wrapper->save();
    }
  }

After running a debug on the $order object in the commerce_order.controller.inc save method it was simple to work out the right format for the data. But this is probably not best practice but is useful for generating a bunch of orders.

function create_order_with_products ( $product_ids , $uid, $profile_id ) {
    $order = commerce_order_new ( $uid , 'pending' );

    // Save the order so its ID is assigned.
    commerce_order_save ( $order );

    $order_wrapper = entity_metadata_wrapper ( 'commerce_order' , $order );

    //add products to order by ids array
    foreach ( $product_ids as $product_id ) {
        $product = commerce_product_load ( $product_id );

        // Create a line item with quantity 1 and this product.
        $line_item = commerce_product_line_item_new ( $product , 1 , $order->order_id );

        // Save the line item to get its ID.
        commerce_line_item_save ( $line_item );

        // Add the line item to the order using the wrapper.
        $order_wrapper->commerce_line_items[ ] = $line_item;
    }

    //create the right array for the save controller
    $profile_object = array (
        'und' => array ( array ( 'profile_id' => $profile_id , ) , ) , );

    $order->commerce_customer_billing = $profile_object;

    // Save the order.
    commerce_order_save ( $order );

    return $order;
}


Search API path make SEO friendly I am using Search API. I make a view of all the indexed entities and uses Taxonomy term as Contextual Filter. But the path of view is not SEO friendly. The path is like http://www.example.com/en/Real%20Estate.

I want to make this path SEO friendly and convert this space(%20) to dash.
In views I am getting configuration "Convert dashes into spaces" for contextual filter.

I tried to alter the views  and implement hook_views_pre_render, hook_views_post_render, hook_views_post_build and hook_views_post_execute. This time it is not showing the results.

Can anyone help me regarding this?

I managed to do that with the following code:

/**
  * Implements hook_views_pre_view().
  */
 function hook_views_pre_view(&$view, &$display_id, &$args) {
   /* Search page view */
   if ($display_id == 'search_page' && !empty($args[0])) {
     $args[0] = strtr($args[0], '-', ' ');
   }
}

You should also adjust the search form ofcourse..


If a search yields no results is it possible to show an alternative set of results? I'm using Views to override a search administered through Search API. If a search yields no results is it possible to show an alternative set of results? For example, if I searched for "grettrr" and no results were found I'd get the usual "No results found" message, but underneath this message another message that says "Take a look at these instead" would display along with a set of alternative results. These alternative results could be shown based on specified taxonomy terms.

It is possible: Under the "Advanced" panel of your view (collapsed to the right of the screen), add a new behaviour to the "No results behaviour", then add a "Global: view area" reaction. You can add any view there.


How do I create a custom exposed filter? I try to create a custom exposed filter in views 3 of Drupal 7

Where can I learn about how to create a custom exposed filter for Views 3 and D7?

Someone put some code example in the URL above, but it seems it is in views 2!? Does any one know how to make it in Views 3.

In the module:

/**
 * Implements hook_views_api().
 */
function modulename_views_api() {
  return array(
    'api' => 2,
    'path' => drupal_get_path('module', 'modulename') . '/inc',
  );
}

/**
 * Implementation of hook_views_handlers() to register all of the basic handlers
 * views uses.
 */
function modulename_views_handlers() {
  return array(
    'info' => array(
      // path to handler files
      'path' => drupal_get_path('module', 'modulename') . '/inc',
    ),
    'handlers' => array(
      // register our custom filter, with the class/file name and parent class
      'modulename_handler_filter_filtername' => array(
        'parent' => 'views_handler_filter',
      ),
    ),
  );
}

function modulename_views_data() {
  $data = array();

  $data['node']['filtername'] = array(
    'group' => t('Custom'),
    'real field' => 'my_custom_filter_field',
    'title' => t('My custom filter'),
    'help' => t('Some more detailed description if you need it.'),
    'filter' => array(
      'handler' => 'modulename_handler_filter_filtername',
    ),
  );

  return $data;
}

In modulename_handler_filter_filtername.inc

class modulename_handler_filter_filtername extends views_handler_filter {

  /**
   * Options form subform for setting exposed filter options.
   */
  function value_form(&$form, &$form_state) {
    parent::value_form($form, $form_state);

    // get list of years from database
    $query = db_select('node', 'n');
    $query->addExpression("FROM_UNIXTIME(n.created, '%Y')", 'year');
    if (isset($this->view->filter['type'])) {
      $query->condition('n.type', $this->view->filter['type']->value, 'IN');
    }
    $result = $query->orderBy('year', 'ASC')
      ->execute()
      ->fetchAllAssoc('year');

    $years = array(
      '0' => t('All'),
    );
    foreach ($result as $k => $v) {
      $years[$k] = $k;
    }

    // create form element with options retrieved from database
    $form['value']['year'] = array(
      '#type' => 'radios',
      '#options' => $years,
      '#default_value' => end($years),
    );
  }

  /**
   * Alters Views query when filter is used.
   */
  function query() {
    // make sure base table is included in the query
    $this->ensure_my_table();

    // retrieve real filter name from view options
    // this requires 'real field' filter option to be set (see code above)
    $real_field_name = $this->real_field;
    // get the value of the submitted filter
    $value = $this->view->exposed_data[$real_field_name];

    // finally, alter Views query
    if (is_numeric($value) && $value != 0) {
      /*
        Having several custom exposed filters, make sure subsitution patterns
        (e.g. :filtername_value below) don't match across different filters.
        I spent some time figuring out why all my filters had the same value.
        It looks like the query skeleton is built first and then all replacements
        are made in bulk. Prefixing value with filter name looks good imo.
      */
      $this->query->add_where_expression($this->options['group'],
        "FROM_UNIXTIME(node.created, '%Y') = :filtername_value",
        array(':filtername_value' => $value));
    }
  }
}

There's a module that provides some examples here: https://www.drupal.org/project/views_plugin_examples.  It's limited but has an exposed filter example.

General discussion here:  https://api.drupal.org/api/views/views.api.php/group/views_plugins/7

In broad outline:

Create a custom module, with a subdirectory called "views"
In your .info file, add a line:  files[] = views/MODULE_handler_filter_FILTERNAME.inc Your filter will never show up if you forget this!
In the .module file, add an implementation of hook_views_api():

function MODULE_views_api() {
  return array(
    'api' => 3,
    'path' => drupal_get_path('module', 'MODULE') . '/views',
  );
}

Within the views subdirectory, you will need to create two files, MODULE.views.inc and MODULE_handler_filter_FILTERNAME.inc
In MODULE.views.inc, you will need to implement either:

hook_views_data_alter() - for a new filter on an existing entity type that already has views integration, which is more common OR

hook_views_data() - to provide views integration for your custom entity, including filters.

API documentation is available for both functions.

A quick example:

    function MODULE_views_data_alter(&$data) {
       if ( isset($data['users']) && !isset($data['users']['FILTERNAME']) ) {
        $data['users']['FILTERNAME'] = array(
          'real field' => 'uid', // name of entity field to which filter applies
          'title' => t('HUMAN READABLE NAME OF FILTER'),
          'help' => t('HELP TEXT'),
          'filter' => array(
            'handler' => 'MODULE_handler_filter_FILTERNAME',
          ),
        );
      }
    }

All of the real work happens in MODULE_handler_filter_FILTERNAME.inc. This file defines a new class that implements your filter, class MODULE_handler_filter_FILTERNAME.

You will usually want to extend one of the existing views filter handler classes to get the benefit of existing code.  Many of these can be found in subdirectories of the views module directory.  The basic filters are in the "handlers" subdirectory, but many more complex filters may be found buried in subdirectories of the "modules" subdirectory.  The views filter handlers you find there are the best documentation for how to implement a filter, as well as how to extend an existing filter, and you should read through them.

Normally your custom filter class will a) add fields to the extended filter's settings form, b) in the case of an exposed filter, modify the exposed widget, and then c) implement a query() method that does the real work, based on the saved settings and input from the exposed widget.


Why didn't we got rid of primary entity keys in favour of UUIDs? I just remembered, while working with custom entities, that Drupal 8 was supposed to bring UUID support and replace the old "entity id" keys but then I've also noticed that the old fashioned entity id key is required by tye EntityType annotation and interestingly the UUID key is just optional.

Is this so that urls/entites are easier to remember by their "nid"?

And most importantly: should we use UUIDs or entity ids in logic and/or database operations?

Is this the final approach or we'll see entity id disappear in beta/rc/stable release?

Personally I don't see any good reason to keep using the typical serial keys when we have UUIDs now.

For context and some related discussions, see #1726734 Replace serial entity IDs with UUIDs in URLs, or even globally?. There is also a related issue about using UUID's for references, which I can't find right now.

So one argument is that all URL's would then become very long, there's no user/1 anymore but user/LONG-UUID.

Another is the database performance, the primary key is the main index of every table, and making that bigger makes every change to that table more expensive. Yes, so does having 4 tables, but there's still the hope that to make that optional for non-multilingual sites. I doubt it will be possible, but we will see.

And you have to keep in mind that the storage would not only be increased by the actual field, but also every reference, so every single field table entry would then have to store the full UUID instead of the considerable shorter primary key.

And related to the issue that I can't find right now is that it would also slow down joins that involve entity tables.

That doesn't mean that it will never happen, but it has been pushed back to 9.x to be re-evaluated there.


Can I change the path to Drush? I am trying to use omega-wizard but I think I am using the wrong version of Drush. I want to use the drush the is in Acquia Dev Desktop but when i type which drush I get the one that was last installed with MAMP (running OSX).

When trying to run drush omega-wizard I get this message:

The drush command 'omega-wizard' could not be found.  Run `drush cache-clear drush` to clear the commandfile cache if you   [error]
have installed new extensions.
                                                                                [error]
Drush was not able to start (bootstrap) the Drupal database.
Hint: This may occur when Drush is trying to:
 * bootstrap a site that has not been installed or does not have a configured database. In this case you can select another
site with a working database setup by specifying the URI to use with the --uri parameter on the command line. See `drush
topic docs-aliases` for details.
 * connect the database through a socket. The socket file may be wrong or the php-cli may have no access to it in a jailed
shell. See http://drupal.org/node/1428638 for details.

Drush was attempting to connect to:
 Drupal version         :  7.34
 Site URI               :  `http://default`
 Default theme          :  garland
 Administration theme   :  garland
 PHP executable         :  /Applications/Dev Desktop/php5_5/bin/php
 PHP configuration      :  "/Applications/Dev Desktop/php5_5/bin/php.ini"
 PHP OS                 :  Darwin
 Drush version          :  6.2.0
 Drush configuration    :
 Drush alias files      :
 Drupal root            :  /Users/khrysztov/Sites/devdesktop/acquia-drupal-7.34.40.6204
 Site path              :  sites/default
 File directory path    :  sites/default/files

I cannot see any reference to the database there in the parameters and the default theme is not Garland.

Any ideas?

Answer by Paul worked (thanks):

alias drush='"/Applications/Dev Desktop/drush/drush"'

Needed inner double quotes to allow for space in Dev Desktop.


Can a node be accessible only by ajax? I'm using the ajax_links_api module to "ajaxify" a certain menu. When a menu button is clicked, the corresponding node loads into a specified div via ajax. This works well.

The problem is that the nodes I want to load in this way should not be accessible as pages. I often create Drupal content that is only designed to appear in views, or as related content on other pages and is not supposed to be displayed by itself. My method is to use .htaccess to block these pages. But when I do that, the ajax can't access them either.

Is there a way to block access to pages in a browser but to allow requests coming from Drupal itself? Localhost access is not really an option since the site may well end up spread across different servers and virtual machines.

If not, then can someone recommend an alternative to the ajax links module - perhaps I need to write some custom ajax that triggers Drupal to serve up a node "directly" rather than via a page - but I am confused about this and could use some pointers in the right direction. I must admit I find the "example" modules confusing!

EDIT: I've tried making a custom module as David Thomas suggests below and using hook_node_access. However this stops the ajax call from returning the content.

You can control access to nodes with

hook_node_access

For example, to restrict node viewing on node/[nid] pages:

/**
 * Implements hook_node_access
 */
function MYMODULE_node_access($node, $op, $account) {

  // If viewing node and URL path is node/[nid]
  // where [nid] is current $node->nid
  if($op == 'view' && arg(0) == 'node' && arg(1) == $node->nid){
    // Deny access to view current node page
    return NODE_ACCESS_DENY;
  }

}

You can add your own conditions to get more specific about access control there.

If you want to deny access to all node/%node/view pages, you can do it quite simply with:

hook_menu_alter

For example, set the access callback to FALSE

/**
 * Implements hook_menu_alter
 */
function MYMODULE_menu_alter(&$items) {
  // Disable the node view page at node/%node
  $items['node/%node']['access callback'] = FALSE;
}


Store Drupal 7 webforms in code I am wondering if there is any solution to store webforms in code. So that you can easily duplicate them on other sites and bundle them with your own modules.
I am looking into something similair as the views API.

If it is not available how many people are interested in such functionality? I might develop a module which could handle storing of webforms in Code. And do you have any concerns in creating such a module?

Thanks,
Jaap

Not really, and there is no need for it

If you need form available from code, Form API forms are not that hard to write from scratch. Contrary to Views, you can only theme Webforms bu their node ID, and that would change from site to site, so Webform forms bundled with module will not be convenient.

If you want to bundle forms with your modules, and for any reason you can't use Form API, UUID Features Integration and Webform share provide ways to do it. It will not be a code in pure sense, but it should work.

It's relatively easy to use hook_form_alter to obtain Form API representation of particular webform. Of course, you won't be able to change it easily in future, but again, contrary to views, it is good. Module is not hurt if some data is not displayed. Data not provided, or provided in a way module does not expect, may break things. So if module needs a form, it should not be easy to edit. Edits to form would require edits to module's code anyway, so Form API code makes things easier, not harder in the long run, in such situations.


Node limit - based on cck field of referenced content type I have 2 content types:

Organisation (Name, address, tel, places)
Internship (Reference to Organisation , Student, Mentor, ...)

Now for example I have an organisation with 2 places for students. So when this organisation is selected as a refernce in Internship node creation, it must check for the available places. If the pace is available then it needs to save the node else it should give an error message.

I have tried node limit module but it is not a solution.

Thanks.

My point of view this can be done at node submission time

Alter the access callback for the menu callback:

function custom_module_menu_alter(&$items){
    $items['node/add/internship']['access callback'] = 'my_custom_access_callback'
    // Next line needed for Drupal 7
    unset($items['node/add/review-sites']['access arguments']);
}

Add a function as your custom access callback:

function my_custom_access_callback() {
   global $user;

   /*Now check the selected organization which you are selecting from dropdown of entity reference and call it as $no_of_places. Also check the existing internship with same referenced organization and call it as $occupied_seats*/

   if ($no_of_places > $occupied_seats && user_access("create internship")) {
     return TRUE;
   }
   else{
     drupal_set_message('Print message about exceeded limit and/or user permissions.');
     return FALSE;
   }
}


How to show reset button in a view only when filter is applied? I have created a view with four exposed filters. In exposed form settings, I added a reset link and used auto submit option. Filter and reset works fine without error, but I want to show the reset button only when the filter is applied. If no filter is applied, there should not be reset button.

I have searched, but I didn't find any solution.

How can I achieve this?

hook_form_alter() can also do this

function module_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'Your_form_id") {
    if (!$form_state['view']->exposed_input) {
      unset($form['reset']);
    }
  }
}

You will have some other value for ['view']->exposed_input. Use dpm(0 to get the exposed_input value. ['view']->exposed_input returns nothing if filter is not applied. Hope it works.


Loading mixed content I have a site loading over https. However, two items are being picked up in Chrome as targeting http, and I can't figure out where to look to change them. They are:

GSS search form: we are using Google Site Search module, and it's
posting to http.
Drupal Views are posting to http, rather than https. Not sure how to
    override this.

Any help would be greatly appreciated. Thanks!

If you force https, then these search forms and views should load properly. There are several ways to do this:

1) If you have access to server config, this tutorial covers Apache, Nginex and Ubunto.

2) You can also use .htaccess to force https as described in this codekarate tutorial.

3) Also you can use a module like securelogin to further protect your login forms from mixed http/https cookie hijacking.


in product title on new product type drupal commerce kickstart I created a custom product variation called Switch Plate and on the product displays it is showing Product Name on the title I installed from the 2.0 version of Commerce Kickstart it only shows on my product not on the 2 generated products.

Go to admin/structure/types, and click "Manage display" for your content type, which is a product display for your new product variation.
Choose the "Product list" display, and make sure the title's format is set as Default.


Custom DatabaseConnection driver does not get found by drupal! I need to customize a method on the DatabaseConnection_sqlsrv (MSSQL) driver, so i created a new driver class called DatabaseConnection_sqlsrvseed and extended all depended classes  from the *_sqlsrv classes.

class DatabaseConnection_sqlsrvseed extends DatabaseConnection_sqlsrv {
  public function driver() {
    return 'sqlsrvseed';
  }
  public function databaseType() {
    return 'sqlsrvseed';
  }
}

Basically all other classes in the database/sqlsrvseed folder are empty classes that inherit their functionality from their parents like this one:

class InsertQuery_sqlsrvseed extends InsertQuery_sqlsrv {}

I am doing this because i need a modification on createFieldSql in DatabaseSchema_sqlsrv to create IDENTITY fields with a Seed value.

However, whenever i set

$database['default']['default']['driver'] = 'sqlsrvseed'

i get the error:

  Fatal error: Class 'DatabaseConnection_sqlsrvseed' not found in
  C:[...]\includes\database\database.inc on line 1686

Although i am pretty sure that the class and all dependencies exist.
I did excactly everything like they did it in the sqlsrv driver:

  Drupal and the SQL Server driver Uncompress Drupal in the web root.
  Uncompress this driver as sites/all/modules/sqlsrv, and copy or link
  the sqlsrv directory found inside it in includes/databases.

So I copied the files from database folder as well as the module folder. But there is a strange difference. I can't activate my custom driver module, whereas i can activate sqlsrv one. Any help? How does drupal gets to know this driver, without core modification?

It looks like Drupal's autoload failed. For it to work you should put your classes in .inc file in your module, and then mention it in files line of module's .info file.

If that does not help and your classes are needed even earlier, include them in your settings.php:

require_once('path/to/module/sqlsrvseed.inc');


Broken/missing handler error for my custom views filter? I am trying to write a custom filter for views. The goal is to filter by alias, but that's not important now. It seems like I am missing a step to get view to recognize my filter hander after adding my filter in hook_views_data_alter as in the following:

/**
 * Implements hook_views_data_alter().
 */
function alias_views_filter_views_data_alter(array &$data) {
  $data['node']['alias'] = [
    'title' => t('alias filter'),
    'filter' => [
      'title' => t('alias filter'),
      'help' => t('Provides a custom filter nodes by their alias.'),
      'field' => 'nid',
      'id' => 'entity_alias',
    ],
  ];
}

I am able to get the filter to show in a view filter list.
Now, my filter handler defined in /docroot/modules/custom/alias_views_filter/Plugin/views/filter/Alias.php but it does not seem to be picked up by views and I always get Broken/missing handler whenever I try to add the filter. Here is my handler definition:

<?php

namespace Drupal\alias_views_filter\Plugin\views\filter;

use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\filter\StringFilter;
use Drupal\views\ViewExecutable;
use Drupal\Core\Form\FormStateInterface;

/**
 * Filters by alias.
 *
 * @ingroup views_filter_handlers
 *
 * @ViewsFilter("entity_alias")
 */
class Alias extends StringFilter {

  /**
   * The current display.
   *
   * @var string
   *   The current display of the view.
   */
  protected $currentDisplay;

  /**
   * @var views_plugin_query_default
   */
  public $query;

  /**
   * Constructs a new StringFilter object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param mixed $plugin_definition
   *   The plugin implementation definition.
   * @param \Drupal\Core\Database\Connection $connection
   *   The database connection.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, Connection $connection) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    // this does seem to get evaluated at all ?
    die('Death in handler');
  }

  protected function defineOptions() {
    $options = parent::defineOptions();
    $options['fields'] = ['default' => []];

    return $options;
  }

  /**
   * {@inheritdoc}
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    $this->valueTitle = t('Filter by alias');
  }

  public function buildOptionsForm(&$form, FormStateInterface $form_state) {
    parent::buildOptionsForm($form, $form_state);
    $this->view->initStyle();
  }

  function query() {
    $this->ensureMyTable();
    $field = $this->tableAlias."nid"; //table_alias.".nid";
    $nids = $this->getNidsByAliasString($this->value);
    if (!empty($nids)) {
      $this->query->addWhere('AND', $this->options['group'], $field, $nids, 'IN');
    }
  }

  function getNidsByAliasString($aliasString) {
    $query = db_select('url_alias');
    $query->condition('alias', '%'.$aliasString.'%', 'LIKE');
    $result = $query
      ->fields('url_alias')
      ->execute();

    $nids = array();
    foreach ($result as $data) {
      array_push($nids, end(explode("/",$data->source)));
    }
    return $nids;
  }

}

Am missing a step or naming the filter incorrectly?

Checking the logs,  I am getting these errors:

Notice: Undefined index: field in Drupal\views\Plugin\ViewsHandlerManager->getHandler()
Notice: Undefined index: table in Drupal\views\Plugin\ViewsHandlerManager->getHandler()
Notice: Undefined index: id in Drupal\views\Plugin\ViewsHandlerManager->getHandler()

Specify the data table instead of the base table, just replace node with node_field_data in your hook and run drush cr.

/**
 * Implements hook_views_data_alter().
 */
function alias_views_filter_views_data_alter(array &$data) {
  $data['node_field_data']['alias'] = [
    'title' => t('alias filter'),
    'filter' => [
      'title' => t('alias filter'),
      'help' => t('Provides a custom filter nodes by their alias.'),
      'field' => 'nid',
      'id' => 'entity_alias',
    ],
  ];
}


Content field list(text) : using correctly ? I have a little problem concerning the following :

For a specific content type, I've created a field of type "List(text)", which represents the difficulty of the content ; so in the values I've entered (I want to attach an icon to each value of that list) :

easy| Padawan

middle| Jedi

hard| Jedi Master

I've checked that the image path is correct, but the images don't appear anywhere...!

Thanks for reading ! :)

I tried this too and it didn't work.  https://stackoverflow.com/questions/4248061/what-is-the-easiest-way-to-have-images-next-to-the-text-on-a-html-dropdown-combob you cannot put images in dropdown box in general (unless you use javascript).  I tried it as a 'Check boxes / radio buttons' widget and it did work.  Maybe that will be a good enough solution for you


Drush failing to load drush.php file I have Drupal 8 project on my local machine, which is set up with composer and I got drush included. When I'm in project root I can call drush like:
vendor/bin/drush -v

And that work well (initialized it so I can call it without typing full path):
Drush Commandline Tool 9.7.2

...
But when I moved the same project to staging server, when I try to run the same command I get error message:
PHP Warning:  require(/path_to_project/vendor/bin/drush.php): failed to open stream: No such file or directory in /path_to_project/vendor/bin/drush on line 4
PHP Fatal error:  require(): Failed opening required '/path_to_project/vendor/bin/drush.php' (include_path='.:/usr/local/share/pear') in /path_to_project/vendor/bin/drush on line 4

Inside drush file I'm executing from bin there is only one line (line 4):
require __DIR__ . '/drush.php';

But that require fails and triggers this error. drush.php file is located (in both cases) inside: vendor/drush/drush/drush.php
I have another project with the same setup and drush there works well on local box and on that other staging server, so I know problem is in server setup somewhere, but don't know where exactly? That include path from error message "include_path='.:/usr/local/share/pear'" looks suspicious to me.
Since I'm not server admin do I need his help to solve this?

Yes, what @remy said is true.
Inside /vendor/bin all "files" are actually symlinks. Real files are located elsewhere. However when copying those files (i.e. with Filezilla) instead of copying symlinks original files were copied.
I solved this by zipping whole bin dir, copying archive and unzipping in on remote server.
Zipping it with mac finder keeps sym links well. However, when zipping form command line most likely option --symlinks should be set:
zip --symlinks -r foo.zip foo/

https://serverfault.com/questions/265675/how-can-i-zip-compress-a-symlink


After installing Drush on Mac it only downloads drupal 6x I am having issues installing Drush on Mac OSX 10.9.5. I have tried a variety of methods. The most successful have been;

Using homebrew

Drush 7 using composer

Each method had produced a version of Drush, however each appears old and drush dl drupal downloads the 6.x version, as does drush dl drupal 7.x.

Can you please suggest:

1) How to ensure old versions of drush are removed to ensure that a new installation goes smoothly.

2) The recommended method for installing the latest stable Drush version on Mac OSX 10.9.5

I had tried to delete the old drush version manually by removing folders. Now the composer installation method seems to fail as I get:

Pauls-iMac:~ Trotter$ composer global require drush/drush:dev-master
Changed current directory to /Users/Trotter/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing drush/drush (dev-master 78b1538)
    Cloning 78b15385ba97890dc3431790494f26d6be99ede9
    Failed to download drush/drush from source: The process "git clone --no-checkout 'git://github.com/drush-ops/drush.git' '/Users/Trotter/.composer/vendor/drush/drush' && cd '/Users/Trotter/.composer/vendor/drush/drush' && git remote add composer 'git://github.com/drush-ops/drush.git' && git fetch composer" exceeded the timeout of 300 seconds.
    Now trying to download from dist
  - Installing drush/drush (dev-master 78b1538)
    Loading from cache

    Skipped installation of bin drush for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.php for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.bat for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.complete.sh for package drush/drush: name conflicts with an existing file

I can see that I don't have drush installed as what drush gives No such file or directory and drush info gives -bash: drush: command not found

Drush 7.x doesn't only download Drupal 7 of course. Drush 5 will download Drupal 7 too. Drush 7 is required for Drupal 8 and needs to be selected when installing with composer global require drush/drush:dev-master. Ps the recommended method is the composer method. This what I use on OS X 10.9.

Find old versions of drush with which drush. Check where they live withls -l [path from which drush]. Rinse and repeat until the only one left is in your home folder inside the hidden composer directory.

Check the version of the installed drush with drush --version

Make sure you don't have a .drushrc somewhere with a default core version specified.


Mb Mini Player for drupal7 Is there is any modle avaibale for mini player like

http://pupunzi.open-lab.com/mb-jquery-components/jquery-mb-miniaudioplayer/

I want to implement same player on my website

These are the players :

MP3 Player
AudioField
jPlayer - I think this is a player that you want.


How can I provide anonymous user to access my REST GET API without providing any auth information? The Drupal 8 REST UI configuration page asks me to select Authentication providers for GET method; otherwise, it doesn't allow me to export the REST request.

How can I provide anonymous user to access my REST GET API without providing any auth information?

You could create your own authentication provider; it could then allow anonymous users access to your resource. It is not that difficult, the only thing I found is that you have to be careful to make sure the authentication provider only applies whe you specifically want it to. Look here for a tutorial:

http://enzolutions.com/articles/2014/12/28/how-to-create-an-authentication-provider-in-drupal-8/


Drush 8 throws unknown error on Drupal 8 install UPDATE: I have managed to update Drush using Wim Mostrey's help as seen below. Drush is now at version 8, and continues to work with my Drupal 7 sites, but when I try to use it on my Drupal 8 site, I get this:

Drush command terminated abnormally due to an unrecoverable error.
Error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /home1/[uname]/public_html/_d8/core/lib/Drupal/Component/Serialization/Yaml.php, line 54 Parse error: syntax error, unexpected 'class' (T_CLASS), expecting identifier (T_STRING) or variable (T_VARIABLE) or '{' or '$' in /home1/[uname]/public_html/_d8/core/lib/Drupal/Component/Serialization/Yaml.php

Does anyone know what this issue is?

Original Question: I want to upgrade from Drush 6.5 to 8, even though current Drush is ver 9 because I want to keep backwards compat. I'm not understanding the instructions on github very well, and concerned about it getting gummed up. Is there a clear, simple guide for this?

Looks like the version of PHP you are using does not meet the minimum requirements for Drush and/or Drupal.  Check your PHP version, and compare against the Drush supported versions matrix.


How to create new entity within a hook? I am trying to create a hook that creates a new entity('Notification') when an entity of another type is created (either of type 'Deadline' or 'Message'), but I can't seem to figure out how to add a new entity from a hook, am I completely missing something?
My hook in ost.module looks like this:
function ost_hook_ENTITY_TYPE_create(EntityInterface $entity){
  if ($entity->getEntityType() == ('Deadline' || 'Message')){
    createNotification($entity);
  }
}

The function which is called looks like this:
function createNotification(EntityInterface $notification){
  $newentity = EntityInterface::create([
    'title' => $notification->label() . "notification",
    'field_content' => $notification->toLink()
  ]);
  $newentity->save();
}

That code needs to be changed for the following reasons.
In PHP, $entity->getEntityType() == ('Deadline' || 'Message') doesn't check that $entity->getEntityType() returns either 'Deadline' or 'Message'. Actually, the code you wrote is equivalent to the following one.
if ($entity->getEntityType() == TRUE) {
  createNotification($entity);
}

getEntityType() doesn't return the ID of the type of the entity, but its definition. The method that returns the ID of the type of the entity is getEntityTypeId().
It doesn't make sense to check the value returned from $entity->getEntityTypeId() in hook_ENTITY_TYPE_create() because hook_ENTITY_TYPE_create() is invoked only for the ENTITY_TYPE entities. (You are also supposed to implement hook_ENTITY_TYPE_create() by replacing ENTITY_TYPE with the entity type, for example node for the Node entity, or user for the User entity.)
EntityInterface is an interface, not a class; as such, it's never used to call a method, even if it's statically called as in the code you are using.
The correct code is similar to the following one. I assume that ost_hook is the module machine name, notification is entity type, and Notification is the class implementing the entity you are trying to create.
function ost_hook_entity_create(EntityInterface $entity) {
  if ($entity->getEntityTypeId() == 'Deadline' || $entity->getEntityTypeId() == 'Message') {
    $new_entity = Notification::create([
      'title' => $entity->label() . " notification",
      'field_content' => $entity->toLink()
    ]);
    $new_entity->save();
  }
}

Alternatively, you could use the following code.
function ost_hook_entity_create(EntityInterface $entity) {
  if ($entity->getEntityTypeId() == 'Deadline' || $entity->getEntityTypeId() == 'Message') {
    $new_entity = \Drupal::entityTypeManager()->getStorage('notification')->create([
      'title' => $entity->label() . " notification",
      'field_content' => $entity->toLink()
    ]);
    $new_entity->save();
  }
}

If the file containing the hook is ost.module (as I suspect), the function implementing the hook is ost_entity_create(), not ost_hook_entity_create().
I used hook_entity_create() because the code needs to be executed for two different entity types. Using hook_ENTITY_TYPE_create(), I should  implement two hooks. (I assume that dealine and message are the entity machine names, in the same way the machine name for the Node entity is node.)
function ost_deadline_create(EntityInterface $entity) {
  $new_entity = \Drupal::entityTypeManager()->getStorage('notification')->create([
    'title' => $entity->label() . " notification",
    'field_content' => $entity->toLink()
  ]);
  $new_entity->save();
}

function ost_message_create(EntityInterface $entity) {
  $new_entity = \Drupal::entityTypeManager()->getStorage('notification')->create([
    'title' => $entity->label() . " notification",
    'field_content' => $entity->toLink()
  ]);
  $new_entity->save();
}

As side note, functions implemented from a module should always be prefixed by the module machine name. A module shouldn't have a createNotification() function, which should instead be called ost_create_notification() (assuming that ost is the module machine name).


Selectively clear cache, without AdminMenu I've been using AdminMenu on my site, and have noticed significant performance issues. I'd like to disable it, but I have a number of "Admin Lite" users, who depend on being able to selectively clear parts of the cache - css/js, theme cache, etc. They're not the type of users who are going to install Drush, so I'd really like a simple web based UI that allows selective cache clearing. Rules & Cache Actions feels close, but I don't actually want automated rules for clearing the cache. Is there a module out there? Or do I need to write one?

After going through 19 pages of search results I don't think what you want exists. I'd say you need to write one yourself.

I also checked GitHub Several modules to easily clear everything...


Adding a query string to a link in Views I've added an "Add Comment Link" to a View and I'm wondering how I would go about adding a custom query string to the generated URL?

I'd guess I need to do something under "Rewrite Results", either with "Rewrite the output of this field" or "Output this field as a link" but I only seem to have an option to include the fully rendered link as a replacement token.

Is there a way (without resorting to regex) to get the URL from the link so I can rewrite the output myself? Or is there an easier way to add the query string?

Thanks

If the link is a field of view, it could be possible to get the URL in the template file using the $row variable.


Altering the page title on a /node/add/ page from a custom module I have a new content type I am developing that I am packaging using Features.

What I need to do is alter the page title for the node add page for this content type from the Features' .module file. I cannot see an appropriate module hook to do this.

The node/add/... page is a form, so you could do it with a hook_form_alter().


Tokens not being replaced in D7 I have a default install of Drupal 7 with the Tokens module. I'm using [current-page:title] in a node body, but the content isn't being replaced.

I've looked for settings and at the Token module page, and nothing. What am I missing?

As @kiamlaluno mentioned in the comment, neither the token API in core nor the token.module replaces tokens in node bodies.

For that, you need a module like Token Filter.


Views tabs and argument I have a views with to page displays with following paths:

/question/%/popular (page, title - Popular)
/question/%/new (page_1, title - New)

The views has a contextual filter (argument) tid. I set the first page to be default tab (with parent menu item as Normal menu item in main menu), and the second one - a tab.

I expect at url /question/all to see a views display "page", with argument value "all", active Popular tab (with url /question/all) and also New tab (with url /question/all/new).

But I've got an error

Notice: Undefined index: localized_options in menu_navigation_links() (line 1861 of /var/www/notlookatme/data/www/qa.winfaq.info/includes/menu.inc).

And an item in main menu with url /question/%25

How can I fix it?

This could be caused by a bug in Drupal 7: Inaccessible menu items in navigation links cause "Notice: Undefined index: localized_options". There is a patch available which has worked for some people.


How to add variables to Drupal.settings using form#attached? I found this example: http://deeson-online.co.uk/labs/how-use-formattached-javascript-setting-drupal-7-form-api

I tried:

   $form['#attached']['js'][] = array(
            'data' => array(
                'my_module' => array(
                    'xx_code' => 'dsadsad',
                    'xx_key' => 'sadasd',
                ),
            ),
            'type' => 'setting',
        );

but with no luck, Drupal.settings.my_module is undefined

Documentation is available:

Form API

$settings = array('id' => 'mymodule-element-1');

$form['#attached']['js'][] = array(
  'data' => array('mymodule' => $settings),
  'type' => 'setting',
);

Managing JavaScript in Drupal 7

$element['#attached']['js'][] = array(
  'type' => 'setting',
  'data' => array('myModule' => array('key' => 'value')),
);

Both are roughly the same as what OP (@drupality) said worked for him in a comment on Jun 14 2013.

The code in the original question that the OP said he tried but fails seems roughly the same as the working code, so I can't see what the original error was.


Can I add Vertical Tab on a Node Edit Page in admin I am hoping to add a custom Vertical Tab in node edit page. Is it possible?

As an example, someone did it like this:-

Thanks

You can achieve this with hook_form_alter. Similar example can be found in the Examples for Developers module. Take a look at this after you are done with your form tabs, add a custom submit handler like $form[#submit][] = 'my_custom_submit'; and then save the data in submit handler using variable_set() method like this:

variable_set('MYMODULE_' . $form_state['values']['your_value'] . '_special_option', $values);

Note: put it in template.php or in a custom module.


Individual account access control There might be a thread already with sililar question.- I am very new to drupal and looking for a module which will allow access to a user to their individual account. They should be able to see only their data and nothing else.They should not be able to manipulate site. This shouls be done just by email verification. I noticed that admin can grant access of a user after account creation but I am looking something smooth where anyone who creates account should see only their dat and later admin can change access level.
Can anyone help me here.

Drupal has only a very course access control structure for viewing content.  For the uthenticated use role, you can set permission to 'access content' (Drupal 6) or 'view published content' (Drupal 7), but that's about it.

For more fine-grained access control, you need a node access control module.  There is a page at the Drupal.org wiki giving an overview of node access modules.  You may start by reading that and try to find a suitable module.

One particular module, named Flexi access, allows you to create access control lists consisting of a single user.  This may be what you're looking for.

Disclosure: I am the maintainer of Flexi access.


Menu access callback function called multiple times I have following menu defined with access callback function. As You can see this is a hack so I can use REST via GET ( normally Services do not offer this ).

All my endpoints are defined /rest/api/[endpoint] this is a /config one:

function MYMODULE_menu() {
    $menus['rest/api/config'] = array(
        'title' => 'Configuration',
        'page callback' => 'MYMODULE_config',
        'access callback' => 'MYMODULE_access_callback_basic_auth',
        'type' => MENU_CALLBACK,
    );
    return $menus;
}

The issue is that the MYMODULE_access_callback_basic_auth is called 5-times for every request.

Can You help me why this happens ?

Drupal forms are clever enough to know whether or not they've been submitted in the current page call and can react accordingly. Your best bet would be to move your code logic to inside the form function, where I think you can check for $form_state['#submitted'] to decide whether this code runs or not.

Alternatively you could check for the existence of $_POST variables in the MYMODULE_menu() function.

  Check and read it out $form_state['cache'] = true; from here.

Hope that helps.


Getting configurePhpcs is not callable after update drupal to 8.3.2 I updated drupal with composer composer update

Drupal is updated to 8.3.2 but when I install modules I get anytime this message

Method Drupal\Core\Composer\Composer::configurePhpcs is not callable, can not call post-auto  load-dump script

how to make configurePhpcs callable again?

Website is still working,

I assume, that after the Drupal core update, you've overwritten composer.json with your previous settings.

However, in Drupal 8.3.2, configurePhpcs has been deleted. This part of composer.json (around line 69 has to be changed:

"scripts": {
    "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
    "post-autoload-dump": [
        "Drupal\\Core\\Composer\\Composer::ensureHtaccess",
        "Drupal\\Core\\Composer\\Composer::configurePhpcs"
    ],
    "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
    "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
},

You have to delete configurePhpcs line (and the comma at the end of the line above, so it should look like this:

"scripts": {
    "pre-autoload-dump": "Drupal\\Core\\Composer\\Composer::preAutoloadDump",
    "post-autoload-dump": [
        "Drupal\\Core\\Composer\\Composer::ensureHtaccess"
    ],
    "post-package-install": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup",
    "post-package-update": "Drupal\\Core\\Composer\\Composer::vendorTestCodeCleanup"
},

Then, you won't see the message anymore.


Drupal Pop-Up Image on page load With simple css and javascript code i have created image pop-up which loads automatically after page load, i want to load the pop-up between two specific days (example from date and to date)
please help me with this, is there any module in drupal

You can achieve that using the Popup On Load module.

The module allows to display a popup once after a certain delay on a page load. This fills a gap in popup modules family (Popups, Popup), which are designed to show popups only after a click on an HTML element, or to implement a complex behavior like modal dialog forms.
If you want to just display a popup after a page load, the Popup On Load module possibly fits your needs

The following are one of the module's main features. See project page for more.

Create an action for popup display, which can be easily integrated
into Rules system.

Create a default rules set for popup display.


How to link a Radio Button choice to a taxonomy term or tag Using drupal 7, when my users select a certain choice out of 2 radio buttons, i want whichever one they choose to also have a tag or taxonomy term applied to it. So if they chose "never" then that node will also have the tag "never"

You can achieve that by creating a term reference field for your content type(structure > content types > your content type > manage fields) or users(configuration > people > account settings > manage fields). Just pick radio/checkboxes widget with only 1 value.


Unusual behavior of Shopping Cart (Drupal Commerce) I am using Drupal Commerce for a portal & I am facing a issue which is re-producible on fresh instance as well.

Suppose if I have a account on a website and I am logged in. I add some items to my cart and leave. It will remain in my cart even if I login from another system.

But if I don't login from another system at start & click "Add to Cart", item get added to my cart with help of session. Now if I login into system, only current items are in cart, not which I have added from another system in my account.

I mean, we loose those items which were in cart before.

This behaviour I checked on some other ecommerce website as well, but they add session cart into the account cart once you login.

What can be the solution of this ?

What you describe is the default behavior in Drupal Commerce, as it is supporting the idea of "multiple carts", so when you log in you get the items that you've got in your current cart and the other cart will be kept in the "background".

In fact, if you end the purchase you have once logged in, you'll most probably see that the items you had in the cart in the first place are back in there.

I'm afraid this is something you can't solve without some coding or rules, the theory here is that on the user login event, you get all the past orders from that user and combine them in the current cart of the user. This is not something you normally want as the cart pulled might be old.


ctools module keeps getting unloaded? I keep getting this error while trying to access content using The Course module.

Call to undefined function ctools_get_plugins()

To my understanding this means the ctools module is not loaded, which is why the Course module cannot access this function. When I run drush cc all on the background and refresh, it works, but only once.
I've no idea what to do about it.

ctools_get_plugins() isn't a function defined in a module file, but in the includes/plugin.inc file in the directory containing the Chaos tools module.
It's not the module that isn't loaded. It's the module that is calling the function that should first load the file containing that function, for example adding the following line before the function call.
ctools_include('plugins');

This is the solution used, for example, in ctools_get_plugins() is called without including plugins.inc.
What you can do is checking the issue queue for the module that is causing that error, and see if the issue has been already reported and fixed. If it's so, you should update the module and use that release.
For what I can see, the CourseObject::access() method of the Course module does include the file before the function, and so do other methods in that file, which is the only file using ctools_get_plugins() in the Course module. (I did check with git grep --fixed-strings 'ctools_get_plugins' in the directory containing a copy of the 7.x-2.x branch.)
Probably the module causing the issue is another one.


How to translate menus that are made in views? I'm having hard time translating my menu to other languages, when I try to translate menus that I made with views I confront with "You are not authorized to access this page." Is there any easy way to translate such kind of menus?

I would recommend you to not generate menu items with views. Just give it a path and create menu items manually which point to the appropriate path. If you need to have a speaking URL, create URL-Aliases for it in each language. This does the trick, usually.


How can I get a field value of a node using PHP? I have created a field in a Basic Page with the label of User Name and the field name of field_user_name.

How can I get it's value using PHP?

The easiest non Entity API way of doing it is to use field_get_items():

// Assuming you have the node object and assuming it is a single value
// field or you just want the first value of a multi value field.
$username_value = '';
if ($items = field_get_items('node', $node, 'field_user_name')) {
  $username_value = $items[0]['value'];
}