Drupal Pager Error Causing WSOD When Viewing Term or Edit Term I have recently been through the ordeal of updating D6 to D7. Things went better than I had previously encountered but I have a problem thats really holding me back and I can't work out how to sort it.

When I try to view a taxonomy/term/ page or edit a term I get a WSOD. I managed to show the error which was:

  Fatal error: Call to a member function use_pager() on a non-object in /home/oddeba/public_html/onlinebanter.co.uk/sites/all/modules/views/includes/view.inc on line 690

Line 690:

    function init_pager() {
         if (empty($this->query->pager)) {
           $this->query->pager = $this->display_handler->get_plugin('pager');

        Line 690>>>  if ($this->query->pager->use_pager()) {
            $this->query->pager->set_current_page($this->current_page);
           }

Things are fine with Views disabled. I can for the life of me think how I needed a pager about my taxonomy before.

Could anyone suggest anything that could be causing it?

If you ever run into a WSOD error, follow the directions here and it will generally tell you the file name and the line number that is causing the WSOD. Or, it will tell you that your server resources are too limited (out of memory).

Here are the instructions:

http://drupal.org/node/158043

Or just Google 'Drupal WSOD' and it's the first link on the SERP.


How to redirect based on matching a node field? This question is somewhat similar to How to redirect based on views results? which I think gives me part of the answer I want.  Basically my situation is this:

I am migrating from an old xoops system which had its own set of content ids.  I want to seamlessly make the switch to this new drupal system, meaning the old urls work, but redirect to their new pathauto equivalents.

By way of explanation, say the old url was /view.php?docid=6252 and the new address should be /pubs/capacity_building_climate_change_impact_assessment which has been generated by pathauto.

I can do a redirect at the web server level to get from /view.php?docid=6252' to/pub/6252`.

I have brought over the legacy document id, as a field on the new nodes, and I have a view working where I can visit /pub/6252 and get the right content. Now I want to make sure that the pathauto url is the definitive one url to rule them all for that particular node. How can I redirect to the proper url based on that url segment matching the legacy document id field in a node. It would be nice if it could be done without bringing all of the overhead of a views lookup into it, but if redirecting from that view is the best way, so be it. Hopefully I can aggressively cache that view since that data should almost never change.

I downloaded the Redirect module, hoping that it provided some of that, especially since it claims integration with the views api, but I didn't immediately see anything helpful there, and there doesn't seem to be any documentation for it.

Non-Views Answer

I finally figured out how this can be done without incurring the overhead of views.  I'll leave the views answer below in case it is useful for someone, but this version seems snappier to me.  As always, critique very welcome!

/**
 * Implements hook_menu().
 */
function MYMODULE_menu()
{
    $items = array();
    $items['pub'] = array(
        'title' => 'publications by Docid',
        'access callback' => TRUE,
        'page callback' => '_MYMODULE_pub_to_docid',
    );
    return $items;
}

/**
 * Redirect to a publication page based on its legacy_docid
 */
function _MYMODULE_pub_to_docid() {
    $path = current_path();
    $path = str_ireplace('pub/', '', $path);
    $args = explode('/', $path);
    $query = new EntityFieldQuery();
    if (_MYMODULE_isInteger($args[0])) { // Sanity check, local helper function just to check that the value is an integer.
        $query->entityCondition('entity_type', 'node')
            ->fieldCondition('field_doc_legacy_docid', 'value', $args[0]);
        $result = $query->execute();
        if (isset($result['node']) && count($result['node'] == 1)) {
            $node_holder = array_slice($result['node'],0,1)[0];
            $node = node_load($node_holder->nid);
            $language = language_list()[$node->language];
            drupal_goto(drupal_get_path_alias('node/'.$node_holder->nid, $node->language), array('language' => $language), 301);
        } else {
            return MENU_NOT_FOUND;
        }
    }
    return MENU_NOT_FOUND;

}

Views Answer

Here is a views answer, but I'd still like to know if there is a better or preferred way of doing this.  I added a function in my_module:

function my_module_views_pre_render(&$view) {

  if ($view->name=='staff_views') { // user redirect
    drupal_goto(drupal_get_path_alias('user/'.$view->result[0]->uid));
  }
  if ($view->name=='pub_by_docid') {
      if (count($view->result) == 1) {
          $node = node_load($view->result[0]->nid);
          $language = language_list()[$node->language];
          drupal_goto(drupal_get_path_alias('node/'.$view->result[0]->nid, $node->language), array('language' => $language), 301);
      }

  }
}

Note that this function is actually redirecting for a view that matches users based on their legacy user id first, and then for a view that matches document id as mentioned originally in my question.

Update: I've updated the code here to reflect the suggestion from J. Reynolds that I include a http response code of 301 to avoid drupals default of 302.

I also found that to get things to work for non-English publications, I needed to add a language option to drupal_goto(), which needs to be a language object.  That is the reason for the line creating the $language variable.


When to share fields between content types? I have a content type with a geolocation field on it, and I also want to add this as an extra field to users. Is it okay to share the field between these? Or should I create two different fields?

Generally if you happend to have same Field settings (Cardinality etc) you can re-use the same field. But if you want different Field settings (Not widget settings) you have to use different field.

If you have huge number of users(couple of millions) or contents it'll not be a best solution to re-use same field, because field_date_* and field_revision_* tables will end up having a lot of data and that might give you a bottleneck on performance.


Migrating database content to a new server I am moving a Drupal site onto a new server. I am using putty to scp the database onto this new server; I have not done this before, so there are things I am not sure.

There is a database called 'website' in the mysql on the server already, while my original database name is actually 'mydrupalsite'. If I just import the file mydrupalsite.sql into database 'website', and change the database name in setting.php, will that be ok?

It will be sufficient most of the time, but it is a good idea to open mydrupalsite.sql in text editor and scan it for old configurations. Especially if domain name also changes. Even if not, some modules needs may save things like local network addresses to data import sources et cetera.

And of course don't forget to truncate all cache tables and session table before data export. Best would be to disable cache and css/js aggregation on site before export, truncate tables, and re-enable these performance options on new site.

Alternatively, simply omit data from these tables when exporting with Backup and Migrate module or your favourite SQL client you use for export (for example, phpMyAdmin can do that, too). Of course disabling aggregation to have proper variables exported still needs to be done.

Safety note:

Truncating cache and session tables is only safe if you have put your site in maintenance mode. If you want to avoid it, you can't really truncate them, as they will be instantly re-populated and only effect will be performance hit and users logged out. In that case you need to omit that data, and make sure no one will change anything in the time of server switching, for the sake of consistency. Read only mode can help with that.

When talking about migration security - more modules equals more risk. My experience tells me that if your site is complicated one, you need to assume something will go wrong. So plan for it. Make sure you have time and manpower to fix it, no matter what exactly it is. Make sure you have enough old server paid for at least month after planned migration, so you can postpone and retry it. And make sure hosting company you are migrating away from will keep backups for you for at least 3 months.


Integrate Webform.html.twig into existing template I am attempting to add a webform field into an existing content type which has an associated twig template.  I can add the webform field to a new content type and/or use the default webform content type and the form displays without an issue.  If I add the webform to an existing content type the form does not display.  I tried adding the content from webform.html.twig to the existing content types template but it is still not displaying the form.  I know I am missing something simple here.  I can supply a few screenshots and or the twig files if that would be helpful

thank you for your patience.  I have had the debugging turned on for quite some time now the development version of our site.  The inspect screen appears to suggests the problem with displaying the webform field is in the page.html.twig which I have attached.  Interestingly, I tried adding a few other random fields to the page content type and they do not display either so I am fairly certain now that there is a problem with the twig template.

{#
/**
 * @file
 * Default theme implementation to display a page.
 *
 * @see academyhealth.info.yml
 * @see template_preprocess_page()
 * @see html.html.twig
 *
 * @ingroup themeable
 */
#}

    AcademyHealth
    <button class="header__menu-button"> Menu</button>

       Close

        {{ page.main_navigation }}

        {{ page.utility_navigation }}

          {{ page.search }}

  {#
    A block titled content will be set if pages are extending this template, so
    print that instead of just printing page.content. The templates that extend
    this template, call page.content and place it appropriately.
  #}
  {% set _block_content = block('content') %}

  {% if _block_content is not empty %}
    {{ _block_content|raw }}
  {% else %}
    {{ page.content }}
  {% endif %}

      AcademyHealth

Connect with Us

      {{ page.footer_social_media }}

Navigate AcademyHealth

      {{ page.footer_menu }}

Extras

      {{ page.footer_extras }}

      {{ academyhealth_address_line }} | {{ academyhealth_address_line_2 }} | Tel: {{ academyhealth_phone_number }} | Fax: {{ academyhealth_fax_number }}

Conceptually, you shouldn't be thinking about it as including templates in other templates. Other CMS'es are more "template based" so to speak, but Drupal isn't. Building your content types and pages in Drupal means telling Drupal (through configuration or in code) how to construct its render arrays. From there on, Drupal will figure out which templates to use and how to merge the resulting HTML of one template into another template.

So that's the theory... now what's the problem in your case? The most obvious reason I can think of, is that you added the field, but did not yet configure it to be displayed. To do so, make sure Field UI module is enabled and then go the "Manage Display" page of your content type. The URL will look like /admin/structure/types/manage/[type]/display where "[type]" is the machine name of your content type. If you see your field in the "disabled" part of the form, drag it upwards to make it enabled and save the form. (This is an example of the "through configuration" method I mentioned earlier.)

If the above does not solve your problem, please add more details to your original question.


Disable registration on commerce checkout According to https://docs.drupalcommerce.org/commerce2/user-guide/checkout/allow-register-at-checkout the 'Login or continue as guest' checkout pane should have an option 'Allow registration'. In my environment with the latest commerce 2.12 however I can't find this option. Why is this option not shown?

I don't want to allow registrations on my site and only allow guest checkout. How can I achieve this?

Per Bojan's comments, leave "Allow guest checkout" checked and disable the "Guest registration after checkout" pane. We may need to update the documentation a little, but doing these things and then configuring your general Drupal settings to deny user account registration will leave you with a site that no one can ever register against and anonymous users can still checkout on.

(The fact that you don't see the checkbox to "Allow registration" in the "Login or continue as guest" checkout pane configuration is irrelevant, because it's disabled by default. You don't need access to it in order to disable the ability for guests to register prior to checkout.)

If you don't need this intermediate step at all, you can simply disable the checkout pane and the page will be skipped for all customers.


Difficulty to list taxonomy terms in a block for specific content type (d7) I have made a page using views to list a specific content type.
Then I wanted to make a block to list a taxonomy vocabulary in a sidebar in order to sort the posts according to terms.

The problems I am facing are:

If I select the block to appear for specific content types, the block doesn't show
I am having a multilingual website and the block shows terms in both languages, how do I choose to show the terms in the current users language?
I have also tried the module taxonomy menu but it also lists terms in both languages and doesn't show for specific content types

Any help would be highly appreciated.

To get the block to appear on certain content types you will need to get the common URL for the content types you are looking to put it on.  You may have to use a module like pathauto to set better URLs for your content.  For example if you are on an article content and the URL is www.example.com/article/3 you would go to the block configuration and at the bottom choose to show blocks only on certain pages.  Then in the text box type the urls of the content types you want them to show on.  Again as Article content type as an example you would enter: article/* or just simply article* like so:


Error: Call to undefined function in inc file I searched for an explanation to this issue but didn't find anything. I have other sites where this is working but not in this one.
So, my module info file (draws.module):
name = draws
description = Draws custom module
package = Draws Modules
core = 7.x

files[] = draws.fixturesSavings.inc

In my draws.module I have this function (lines 289 to 231):
function saveToDatabase($response) {
    fixtures_saveToDatabase($response);
}

And then in the same folder of my draws.module I have the inc file (draws.fixturesSaving.inc):
<?php
function fixtures_saveToDatabase($response) {

And when I call function saveToDatabase, I get the following error:
Error: Call to undefined function fixtures_saveToDatabase() in saveToDatabase() (line 290 of /home/.../sites/all/modules/custom/draws/draws.module).

What am I doing wrong here?

files (Optional)
Drupal supports a dynamic-loading code registry. To support it, all
modules must declare any code files containing class or interface
declarations in the .info file, like so:
name = Really Neat Widget
...
files[] = tests/example.test

When a module is enabled, Drupal will rescan all declared files and
index all the classes and interfaces that it finds. Classes will be loaded automatically by PHP when they are first accessed.
Currently this mechanism does not natively support namespaced classes.
Source: Writing module .info files (Drupal 7.x)

This approach only works with Object Oriented PHP. You would have to create a class.
If you want to keep with your current approach, add this to the top of the draws.module file after the <?php open tag.
module_load_include('inc', 'draws', 'draws.fixturesSavings');


Can you query webform settings? I have the task to query data from my phpMyAdmin database and also to query the emails from each webform 'to_email' field. Is there a way to query that data using MySql? I was able to do it using php, but I can't seem to find a way to access the webform email settings by using only MySql.
Edit: I just found out that all the website data is stocated in the database. For example, you can find the data in your 'to_email' field inside your node.type. row, in a blob.

Yes, it is possible. you can try the following query to find all entries in 'cache_config' that contain 'to_email':
SELECT cid, data
FROM cache_config
WHERE data LIKE '%to_mail%'

This will get you all the blobs that contain the given field.
Even more than that, you can look for what follows 'to_mail' to get the actual mail by using the LOCATE and SUBSTRING functions.


Related Content By Taxonomy Term and fields I have a content type which has taxonomy term field (Department). There is another field of the same taxonomy term (Priority Department)

I want to create a list of related content where the block shows only priority department related content and not the department field.

I tried views and contextual filter and relationship with no luck

You don't need to duplicate Taxonomy Vocabulary, one is enough.

You do need to have two Fields referencing the same Taxonomy Vocabulary, one for Department categorizing it, and the other for Select through which you're controlling what the related content is.

This is still a case of showing sibling nodes but through criteria of matching one field to a different field that just happens to references the same taxonomy.

Create Views listing your Organization nodes in a Block Display
Add Filter Select, set it to your vocabulary and then choose Is not empty (NOT NULL)
Add a Contextual filter for the Field Department and configure it:
 When the filter value is NOT available
Provide default value
Taxonomy term ID from URL
Load default filter from node page, that's good for related taxonomy blocks
Filter to items that share any term
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term ID
[your vocabulary]
One or more IDs separated by , or +
Place your block in a region shown only on Organizations, you will see nodes listed that are tagged with the term that is in the current node Select field.

This solution relies on the concept that you won't have the same terms in Select Field that you have in the Department field.


How to make sure no emails go out after importing users? I'm creating a new Drupal site and importing users from our existing website. I want to make sure users don't receive any email notifications of any kind from our new website during this process. What things should I check to ensure this?

I am using Drupal 7.54.

You can use the Development Environment module for this. Some more details about it (from the project page):

When developing Drupal sites, we are often working in a development environment in which we want behaviors different than we would like on a production environment. An example of this is sending emails - it's often preferable to not send emails from a development environment, as they can end up in our client's email boxes. This is particularly true when there is a production (live) version of the site on the web, as users may receive emails from your development environment, which will be both confusing, and any links to the site within the emails will be unusable by anyone without access to that development environment.
This module aims to provide various settings which are specific to development environments only.

Disclosure: I developed this module.


query string of tid not working on page I need my view to default the exposed filter depending on the ?tid= variable that i put in the url .  It was working before, but now it no longer does.  Is there a setting in the view that makes that tid variable work?

In the view you need an exposed filter on the term field. In the settings for this field, expand on the "More" section near the bottom and you'll see a field called "filter identifier" - enter tid in this field (in this screenshot, you can see I used "category" it can be whatever label you want to give it). Click Apply this display. Save the view.


Linking slideshow thumbnail to slideshow views content I have a view containing pictures from a content type "Slideshow". When I click the Slideshow title in a view containing the slideshows, it takes me to the slides from that slideshow. However, I want to get rid of the title and be able to click the picture instead of the title so I can do the same thing. Could you please tell me how I could do that?

You will earn time by coding a small hook_block() that calls your JavaScript plugin for your slideshows. Then, you will be able to configure easily your module and your link.
Views can be really harmful when you try to do things like slideshows.

Just pick a jQuery plugin from the ones listed on 13 Super Useful jQuery Content Slider Scripts and Tutorials and the rest of the job will be easy.


Slideshow business theme on every page I have the business drupal theme aplied on a test site, in this theme u have a slideshow on the front page. I wanted to display it on every page so I copied following code to page-tl.php

    <?php if (theme_get_setting('slideshow_display','business')): ?>
    <?php
    $url1 = check_plain(theme_get_setting('slide1_url','business'));
    $url2 = check_plain(theme_get_setting('slide2_url','business'));
    $url3 = check_plain(theme_get_setting('slide3_url','business'));
    ?>

                    <a href="<?php print url($url1); ?>"><img src="<?php print

base_path() . drupal_get_path('theme', 'business') . '/images/slide-image-4.jpg'; ?

>">
                    <a href="<?php print url($url2); ?>"><img src="<?php print

base_path() . drupal_get_path('theme', 'business') . '/images/slide-image-5.jpg'; ?

>">
                    <a href="<?php print url($url3); ?>"><img src="<?php print

base_path() . drupal_get_path('theme', 'business') . '/images/slide-image-6.jpg'; ?

>">

<?php print check_markup

(theme_get_setting('slide1_desc','business')); ?>

<?php print check_markup

(theme_get_setting('slide2_desc','business')); ?>

<?php print check_markup

(theme_get_setting('slide3_desc','business')); ?>

                1
                2
                3

    <?php endif; ?>

  <?php print $messages; ?>

  <?php if ($page['homequotes']): ?>

 <?php print render($page['homequotes']); ?>

  <?php endif; ?>

  <?php if ($page['home_high1'] || $page['home_high2'] || $page['home_high3']): ?>

     <?php if ($page['home_high1']): ?>

<?php print render($page['home_high1']); ?>

     <?php endif; ?>
     <?php if ($page['home_high2']): ?>

<?php print render($page['home_high2']); ?>

     <?php endif; ?>
     <?php if ($page['home_high3']): ?>

<?php print render($page

['home_high3']); ?>

     <?php endif; ?>

  <?php endif; ?>

Now the sliding effect is gone (except on the front page), so I thought that there was missing javascript. However I can't find a solution...

U can see the problem on Click for problem here

You may have to review your code, your sliding effects javascript file is missing from your other pages except for the front page.

<script type="text/javascript" src="http://karelmaes.stijnaerts.be/sites/all/themes/business/js/sliding_effect.js?n8jrx6"></script>

Above missing.

You can check this out for more information Adding Javascript to themes


Confidential webform submissions I'm using Webform to set up a number of enquiry forms on a company's extranet and they require submissions to be confidential. Since access to anything on the extranet requires user login, the forms can't be submitted anonymously and some user info is associated with each submission.

I can get around this issue in outgoing emails by removing the user-specific info from the email template, but submissions stored in the database still retain user info.

I suppose my question is this: how can I disable Webform submissions from being recorded in the backend, OR, how can I modify recorded submissions to remove user info (basically to store nothing but the date/timestamp and message)?

Well you can always use form altering to provide you own submit function


What's the proper use of EntityFieldQuery? In Drupal 7, the API documentation for node_load_multiple() specifies using the $conditions parameter has been deprecated in favor of using EntityFieldQuery. How does one use the class to generate a list of node IDs for use with node_load_multiple()? Are there any other use cases for it?

EntityFieldQuery uses a set of hooks to interface with field storage modules, such as Field SQL Storage, in order to work for fields as well as other node properties. Long term, EntityFieldQuery is a much more reliable way to query any type of entity, and in some situations it can perform cross entity queries (see field_has_data or _list_values_in_use() for an example.

Here's a simple example of using EntityFieldQuery to get a list of all nodes published before a specific timestamp:

$query = new EntityFieldQuery();

$query
  ->entityCondition('entity_type', 'node', '=')
  ->propertyCondition('status', 1, '=')
  ->propertyCondition('created', '1294694496', '<');

$result = $query->execute();

$results from that query would look something like this:

Array
(
    [node] => Array
        (
            [1] => stdClass Object
                (
                    [nid] => 1
                    [vid] => 49
                    [type] => article
                )

            [2] => stdClass Object
                (
                    [nid] => 2
                    [vid] => 2
                    [type] => page
                )

        )

)

You could then use that array as input to node_load_multiple:

$nodes = node_load_multiple(array_keys($result['node']));


How to populate a dropdown list from array in FORM API Hopefully this is clearer, and my last question in a long time!

Using PDO I have connected to an external DB, I can query this and return an array of values, Using html/php I can populate a standard select box. However I am unsure how to do this in the Form API, taking the array from the second paragraph, or do I query within the form item that produces the drop down? I want to take the name and the id, display the name. So that I can store the ID later.

      $stmt = $conn->prepare("SELECT admin_name, adminuser_id FROM adminuser_tbl");
if ($stmt->execute()) {
$stmt->setFetchMode(PDO::FETCH_OBJ);
$user_list = array();
foreach ($stmt as $row) {
    $user_list[$row->adminuser_id] = $row->admin_name;
}
}

$form['user_list']=array(
    '#type'=>'select',
    '#title' => t('Users'),
    '#options' => $user_list,
    '#multiple' => false,
    '#attributes'=>array('size'=>4),
    '#weight'=>8,
);

In a while looping over your result, populate array.

$user_list = array();
while ($row = $stmt->fetch()) { // See this line in your original code
   $user_list[$row->user_id] = $row->name;
   // Apply transformations and conditions here, if needed
}

Or, as Clive suggested:

$user_list = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);

Then simply use this array

'#options' => $user_list,

By the way, if you really want to make assignment in condition, proper way to write it is:

while ( ($row = $stmt->fetch()) )

As you can see, assignment is wrapped in double parentheses. It is the way to say future developers and code review tools "yes, it is not a typo, I really wanted it this way, I did not forgot about second =".


User registration page edit I want to add some div's and hrefs to user registration form. any ideas? I'm using ajax login/register module to get user login/register form in ajax windows. and i have no idea how to add some divs and hrefs to register form.

Assuming you're using Drupal 7.

Using hook_form_FORM_ID_alter and a custom module you can achieve it. Like below,

function mymodule_form_user_register_form_alter(&$form, &$form_state, $form_id) {
  $form['links'] = array(
    '#type' => 'item',
    '#markup' => l('some links','http://www.example.com'),
  );
  $form['additional_markup'] = array(
    '#type' => 'item',
    '#markup' => '

',
  );
}


Adding html/css to a module form How would I go about adding html/css into this module e.g. to place the different form items into a table, so i could have a column with one field entry the next column with another entry, and then rows below with other entry fields. I noticed when i put an image into the module it appears on every page on the website too?

 function form_example_menu(){
   $items = array();
   $items['form_example'] = array(
   'title' => 'My example form',
   'type' => MENU_NORMAL_ITEM,
   'access arguments' => array('access form_example'),
   'page callback' => 'drupal_get_form',
   'page arguments' => array ('form_example_form'),
     );
 return $items;
  }

function form_example_form($form, &$form_state){

    $form['mytextfield'] = array (
    '#type' => 'textfield',
    '#title' => t('My text field'),
    '#size' => 60,
    '#maxlength' =>128,
    '#required' => TRUE,
     );

 $form['mytext'] = array (
   '#type' => 'textarea',
   '#title' => t('My text area'),
   '#description' => t('enter some text.'),
   '#defauly value' => '',
   '#required' => TRUE,
  );

 $form['submit'] = array(
   '#type' => 'submit',
   '#value' => t('Add an item'),
 );
return $form;
}

You can use #prefix and #suffix to add any amount of html markup to your form and/or any of its fields.  Tons of information can be found in the Drupal Form API Reference.  I would tend to suggest you stay away from tables and instead investigate css floats and divs, most probably doable without any additional markup, but that's just personal preference.


Callback to Drupal site after curl call to 3rd party site doesn't resume authenticated session if more than 120 seconds elapsed since authentication UPDATED SITUATION:

A user authenticates on my site.
The user selects items to purchase and is sent via curl call (see below) to a payment site.
The payment site does its thing and returns to my site via a callback URL I posted to it. I assume it is also a curl call, since data is posted back.
Upon return, if less than 120 seconds has elapsed since the user originally authenticated on my site, the user's authenticated session is resumed (good).
Upon return, if more than 120 seconds has elapsed since the user originally authenticated on my site, a new session is started (bad). The user is effectively signed out.

This behavior is 100% consistent. I can call the 3rd party site and return any number of times within the 120 second window after authentication and the authenticated session is always resumed. But as soon as I return after 120 seconds, a new session is started.
It doesn't matter whether I authenticate, immediately go to the 3rd party site, and then wait there 120 seconds, or if I authenticate, wait at my site 120 seconds, and then go to the 3rd party site, if the return to my site happens more than 120 seconds after original authentication on my site, a new session is started instead of resuming the authenticated session.
What could cause this? Some kind of timer setting, cache setting, etc.? Maybe a module? I'm asking before I begin the process of disabling modules one by one.
My curl call:
$ch = curl_init('https://commerce.cashnet.com/404Handler/pageredirpost.aspx');
curl_setopt($ch, CURLOPT_POSTFIELDS, $data); // $data includes the callback URL
curl_exec($ch);
curl_close($ch);
exit;

AN EARLIER VERSION OF THE PROBLEM DESCRIPTION talked about session ids changing, information passed, etc. I removed all that to simplify, as it got too long to leave it in. The original set of comments below are based on that earlier description, which is why they don't seem to make sense now. But they were helpful in guiding me to further testing that revealed the 120-second issue.

A callback from a credit card processing site to your Drupal server should never have the same session as the paying customer. If it does, then you have a problem.
But I'm not sure that's what you're saying - you are vague when you talk about session ID. If you mean that the paying customer's session ID shouldn't change when your server sends the payment information to the credit card processing site then receives the response, then you are correct. But why even mention credit card processing and posting back in this case, as it's not very relevant? If the paying customer's session ID changes, then you need to investigate how the session ID is invalidated and what your session timeout is. Perhaps your callback is invalidating a cache tag that forces a new session to be generated for that user.


Synchronize teaser config file Issue After creating a new content type in DEV and then in STAGE importing the exported DEV; After successful import I find below file in in CHANGED stage(1 Changed).

core.entity_view_display.node.my_node_type.teaser

Is anyone having any idea why it is happening?

.

I cannot say what exactly is the problem (it is a bug for sure), but here's how you solve it: Go to the "Manage Display" tab for the content types for which the teaser display setting is not imported.
On your DEV instance go to the teaser display and save it without changing anything (or changing something if you want to).
Now export the config and push it via Git.
Re-import on Stage and it should import cleanly now.


How can I clone and use the default taxonomy view to learn its behavior? Views comes with a default taxonomy view packaged with it.

I can see it over here and modify it:

admin/structure/views/view/taxonomy_term/edit

Taxonomy term
A view to emulate Drupal core's handling of taxonomy/term
default/taxonomy/term/%,/taxonomy/term/%/%/feed

Now how do I actually "view" this view!

I want to clone it, modify it and experiment, but can't access it from front end...

The % symbol in the URL works a placeholder for a parameter. So if you access taxonomy/term/1 or taxonomy/term/2 note that the number is actually the term id, so that is the way you "view" (access) the view. You can see, edit, add, delete or modify those parameters if you click the advanced option in the view and you will see the option "Contextual filters".

Now, to clone it, you can access the up right button and then click the "duplicate" option, wich for this case will have a URL /admin/structure/views/view/taxonomy_term/duplicate. Note that this will clone all the view and its styles, in this case, will duplicate a view with two styles: the page view and the RSS view.


How do I remove the language_content_entity query from the canonical URL? Following the Translating content documentation we have setup our site to have Spanish, English, and Japanese. When we are adding, editing, deleting, and publishing pages in different languages we have no issues. However, when we view the canonical url, we find that the language_content_entity=en is added for English pages, for example. We are already adding the hreflang to each page so don't need this extra parameter in the canonical.

For all English pages:

<link rel="canonical" href="https://www.somedomain.net/some/path?language_content_entity=en">

For all Spanish pages:

<link rel="canonical" href="https://www.somedomain.net/some/path?language_content_entity=es">

How can we remove the language_content_entity=en from the canonical url?

Just to illustrate once again what you are supposed to do with the first duplicate question's answer:

/**
 * Implements hook_page_attachments_alter().
 */
function MYTHEME/MYMODULE_page_attachments_alter(array &$attachments) {

  foreach ($attachments['#attached']['html_head'] as $key => $head) {

    if ((isset($head[1]) ? $head[1] : FALSE) == 'canonical_url') {

      $href = isset($head[0]['#attributes']['href']) ? $head[0]['#attributes']['href'] : FALSE;

      if ($href) {
        // Strip ?language_content_entity=en from the end of the URL if exists.
        $href = rtrim($href, '?language_content_entity=en');
        // Strip ?language_content_entity=es from the end of the URL if exists.
        $href = rtrim($href, '?language_content_entity=es');
        // Then set the new value.
        $attachments['#attached']['html_head'][$key][0]['#attributes']['href'] = $href;
      }
    }
  }
}


How to get Drupal 7 to search attached PDF and Word documents From what I have read it seems like you have to use Solr to have PDF and Word attachments indexed and returned in a search.  I have Solr working with Drupal but I think I need Tika working on Solr in order to do the document indexing.  There is very little documentation I can find for Tika.  Does anybody know where a good source for this is?  Is there a better/easier way to have search in Drupal index attached documents?

To help you, you've this nice module Apache Solr Attachments. If you download the module you'll have a README.txt that give you some clues how to help you install and configure Tika.


Multiple aliased pages for same taxonomy term (e.g. blog/term1 and images/term1) I have some taxonomy vocabularies that are used on different content types (blog posts, images, businesses etc.).

I want to create a main page for each content type listing, and filter those listings by taxonomy terms, creating multiple aliased pages.

For example:

BLOG:

main blog page listing all blog posts and some related blocks @ /blog
blog sub-pages for each vocabulary/term listing blog posts with that term @ /blog/vocabulary/term

ACTIVITIES:

main page listing all businesses @ /activities
activities sub-pages for each vocabulary/term applied to the businesses @activies/vocabulary/term

The problem I am having is to have aliases and metatags set automatically using the taxonomy data.

I would like "content-type/vocabulary/term" (not "vocabulary/term/content-type"), and to still be able to use "vocabulary/term" (default Views or Panels taxonomy term templates) as general pages listing all content types.

Is this possibile?

The problem with dynamically creating every page is with the "content type", Drupal does not support dynamic arguments (wildcards) as the first part of a path, so there really isn't much you can do about that.

But let's approach it a little different, actually you should be able to use the taxonomy view that comes disabled with views by default to achieve what you are looking for, I would create a new page and:

enable it
create a contextual filter "Content: Type"
add relationship "Content: Taxonomy terms on node" and require it
add contextual filter "Taxonomy vocabulary: Machine name" using the relationship
rearrange the contextual filters: "content type", "vocabulary", "term id(with depth)", term id("depth modifier")
edit "Content: Has taxonomy term ID (with depth)", in the section for "WHEN THE FILTER VALUE IS IN THE URL OR A DEFAULT IS PROVIDED" change "Filter Value Type" to "term name"
edit the path for the page (browse/%/%/%)

save your view and that should do it.

Again, remember that we can't use a dynamic path argument as the first part of a path in drupal which is why I added "browse".


How to set parent on taxonomy term I have done:

$term = Term::create([
  'name' => 'title',
  'vid' => 'myvocab',
])->save();

It works.

But I don't seem to be able to set the parent term.

I have tried:

$term->parent = array($parent_tid);
$term->save();

It gives an error:

  InvalidArgumentException: Value is not a valid entity. in Drupal\Core\Entity\Plugin\DataType\EntityReference->setValue() (line 106 of /core/lib/Drupal/Core/Entity/Plugin/DataType/EntityReference.php).

I have also tried:

$term->parents = array($parent_tid);
$term->save();

It gives no error, but also does nothing.

In my code $term could be a new term or an existing term I've loaded, which is why I set the parent and then save it. But I can't get it to work.

Documentation for D8 is sparse. I've dug around the code in the taxonomy module, and it looks like parent is an entity reference field that accepts multiple values, but I can't work out how to set it. It looks like setting parent to array($id) should work, but I think the magic setter is breaking. Any help?

The correct way for a reference field is to set the property target_id:

$term->parent = ['target_id' => '2'];

All this shorter versions work too:

$term->parent = ['2'];
$term->parent = '2';
$term->parent = 2;

Also works like this:

$term->set('parent', ['target_id' => 2]);
$term->set('parent', 2);


Conditional field on checkbox is not woking If the checkbox is checked then it will show the textbox else not, for this purpose i've written this code. But it is not working, even the textfield is not showing.what do i need to change in this code ?

      $form['details'] = array(
       '#type' => 'fieldset',
       '#title' => $this->t('Details'),
      );

      $form['details']['field_type'] = array(
       '#type'    => 'checkbox',
       '#default_value' => 0,
       '#title'   => t('Choose entry type.')
      );

     $form['details']['text'] = array(
      '#type'          => 'textfield',
      '#title'         => t('Enter the text'),
      '#states'        => array(
         'visible'      => array(
           ':input[name="field_type"]' => array('checked' => TRUE),
         ),
       ),
    );

Please try this code ... It works !!

$form['field_type'] = array(
  '#type'    => 'checkbox',
  '#default_value' => 0,
  '#title'   => t('Choose entry type.')
);

$form['text'] = array(
  '#type'          => 'textfield',
  '#title'         => t('Enter the text'),
  '#states'        => array(
     'visible'      => array(
       ':input[name="field_type"]' => array('checked' => TRUE),
     ),
   ),
);


A button to delete multi images on one click from imagefield In a content type I have an image field. For the upload I use Multiupload Imagefield Widget. So now it is easy to upload 10 images into one field of the content type.

If I want to remove this 10 images, I have to click remove button 10 times. Is there a module which provides a single remove button to remove all images in this field on one click?

Refer to the question about "Delete multiple images at once from one node in Drupal 7", which appears to be similar to yours.

You may also want to look at the article about Drupal 7 Unlimited Fields Remove Button, from where you can also download the Unlimited Fields Remove module.


Create a View which shows Nodes AND Taxonomy Terms I am working with Search Autocomplete to create a suggestion list which includes nodes and taxonomy terms. Is there a way to include both entity types within a single view?  Thanks for your time.

Create a view and select show content of type All
Under format in show fields select fields.
3.Create a relationship Content: Taxonomy terms on node
Select Content: Title and  Taxonomy term: Name fields under Fields
Under filter criteria select two fields first one Content: Title  and second one  Taxonomy term: Name and dont forget to check the Expose this filter to visitors, to allow them to change it


Display field inputs side-by-side in node edit form I have quite a few Field Collections on my node edit form that each have three text input boxes. By default drupal displays them one on top of the other which makes for a very long page:

Ideally I'd like to display the three fields in a single row. Do I have to override this with CSS or is there a setting I'm missing? It's a pai to Google a solution because I keep getting article about in-place editing or theming webforms.

If you are using Field Collections you can have them displayed in a few different ways, one of which is a table, which is more relevant for some situations than others. Have a look at Field Collection Table and see if it suits your needs.
It will, in your example, put the three fields side by side - but in table cells.


How do I add a custom block to a view? In preset views like the Taxonomy Term one (/taxonomy/term/%), it can be done by adding a custom block to the footer, but it is not controllable as block layout on /admin/structure/block.

Is it possible to add a region to a custom view template?

Simply go to /admin/structure/block and add the block to a region.

In configure block, under Visibility, click on pages tab and type path with wildcard /taxonomy/term/*.

Therefore, this block will only be visible in your taxonomy page view.


Send push notifications by limit per user I have configured multiple rules to send push notifications to multiple users with no limit (because push notifications does not provide any limit how much notifications system send to user). I would like send push notification to particular user with limit of 4 notification for some extent of time. If user get lot more notification he remove app from mobile or frustrate. Anybody have any idea how this can be achieved.

A simple way to do this is to add a user field. This field will keep track of the number of push notifications sent and will increment every time you send a new push notification to the user.

In your rule, add a condition that checks the value of the field and execute the actions if value <= 4.
Then, in the action part of the rule, increment the value of the field by one.


After webform submission restrict/greyout certain fields when user goes back in to edit On my Drupal 7 instance I am letting anonymous users "edit own webform content" or "access own webform results." The thing is, I want one or two of the fields to become un-editable after the initial submission. Once they click through the link in their confirmation email to edit their submission, I want the email and company name fields to be greyed out but all other fields to be editable. What is my path of least resistance?

From Programmatically modifying a webform with hook_form_alter():
function mymodule_form_alter( &$form, &$form_state,$form_id ){
  global $user;
  if (!$user->uid && $form_id == 'MY_WEBFORM_ID') {
    $form['submitted']['MY_FORM_COMPONENT']['#disabled'] = TRUE;
  }
}


How to display all values of List (text) instead of just the selected ones? When viewing a node, how can I display all values of a List (text) instead of just the selected ones.

So, instead of displaying:

B (good)

I want to display all values, with some markup telling selected and unselected apart:

[_] A (superior)
[_] A-
[_] B+
[X] B (good)
[_] B-
[_] C+
[_] C (average)
[_] C-
[_] D+
[_] D (poor)
[_] F (failure)
[_] I (incomplete)
[_] PR (course in progress)
[_] W (withdrew from course)
[_] FF (failing in a pass/fail course)
[_] PP (passing in a pass/fail course)
[_] N/C (not for credit)

Now, I have actually solved this already for myself and for some others (who had desperately been searching for this functionality) in my sandbox module https://drupal.org/sandbox/kari.kaariainen/1349570, but I just wanted to ask if anyone else has a) needed this, b) solved it and how?

Edit: my solution is to rebuild the $items at hook_field_formatter_prepare_view so that it doesn't have just the selected items, but all items, including data about whether an item has been selected or not. $items will then be handled by hook_field_formatter_view actually outputting items with added markup and translated.

It's kind of frustrating to bring back data at prepare_view, so I'm wondering if data for all items could be retrieved from database initially.

Another thing is i18n support, which I'm now copying from i18n module. Code for each field type (there will be more than just text lists) will need to be duplicated and modified separately. I'm wondering if field translation could be left for i18n and not duplicating code.

Even if no one here says they have needed to do that you can pretty much bet others out there have, so it's good that you have your code on drupal.org where other can use it if they need it.

I had a quick look over your code and your solution is the way I would do it: create a new field formatter for text list fields using hook_field_formatter_info() and hook_field_formatter_view().

A couple of things I notice though are:

The name of the module is very long. If you can make it shorter while still being somewhat descriptive I think that would be good (also better for you as the coder).
The markup you are outputting is not themeable, so if other people start to use the module and want to override the markup in any way it is harder for them. See image_field_formatter_view() as an example of creating a render array with a specific theme function. Also see hook_theme() for defining your own theme functions.
Text that gets displayed to the user that is hard coded into the module should be run through the t() function so that others can write translations for your module. See the drupal 6 version of that t() api docs page for better and more thorough information. t() is not currently used is for $form['instructions'].
This one is a bit more of a personal choice but I would probably make the  markup options a lot less than 500 characters. I would also quite possibly not allow HTML markup and just allow them to enter characters that would then display in a span. If the user wants something fancy they can override the theme function (as per point 2). Also, the instructions encourage users to use inline styles, which are not recommended. Users should use the classes you provide to add any css in their theme's css files.


Undefined error: 0 OR Unable to load autoload.php. Drush now requires Composer I've installed drush in /usr/local/lib/drush/drush and composer in /usr/local/bin/composer.

When I try to run drush /usr/local/lib/drush/drush I get the following:

  /usr/local/lib/drush/drush: line 129: /Applications/MAMP/bin/php/php5.2.17/bin: is a directory /usr/local/lib/drush/drush: line 129: exec: /Applications/MAMP/bin/php/php5.2.17/bin: cannot execute: Undefined error: 0 –

OR the following:

  Unable to load autoload.php. Drush now requires Composer in order to install its depedencies and autoload classes. Please see README.md

What am I doing wrong? I'd like to install drush to use with MAMP if anyone has any suggestions. I've done through the readme and nothing seems to be working.

Drush switched to requiring composer. The documentation provides details on how to install both composer and drush, but it boils down to:

Install composer globally:

curl -sS https://getcomposer.org/installer | php
mv composer.phar /usr/local/bin/composer

Install drush globally (for your user), you can specify the version:

composer global require drush/drush:6.*

Add the composer path to your path (in your .bashrc or .zshrc or other):

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


How to unblock IPs in bulk? I use the Drupal Core IP blocking feature (/admin/config/people/ip-blocking) to block IP addresses during spam attacks. However, as most of these will be dynamic ones owned by legitimate users a day later, I want to remove these blocks.

I could delete them one by one in the IP blocking interface, but with dozens of addresses, that is not a comfortable way. Any alternative?

There are several options, choose depending on your requirements:

You can use module Blocked IPs Expire to add an expiration date to IP blocks when adding them. The Drupal cron job will remove the blockings after expiry.
You can remove all of the IP blockings at once with this drush command:

drush sql-query "TRUNCATE TABLE blocked_ips"

You can remove just some IP blockings (e.g. an IP range) with similar drush commands. For example to delete all IPv4 blocks:

drush sql-query "DELETE FROM blocked_ips WHERE ip LIKE '%.%.%.%'"

Note that auto-banning users and IP addresses after a number of unsuccessful login attempts is a different Drupal Core mechanism, resulting in entries in table flood – more details. To remove these bans, the Flood Unblock module can help you. (But that mechanism is out of the scope of this question anyway.)


Link field title from entity/route I have a Drupal link field configured to allow both internal and external links and have the title field enabled, but optional.

I want users to be able to reference internal entities without having to specify anything in separate title field, and have the Link field's title pulled from the entity label.  However it appears that when the field's internal title value is left null, Drupal ends up using the field's uri value as the link title. This behavior seems odd to me.

My question is this: given an internal uri value that looks like: entity:node/3500 how can I preprocess or alter the functionality of the Link field to load in the entity's title/label as the  title when it is left empty by the content editors.

I've searched for issues on drupal.org but didn't turn up much of anything useful. I found Get title from Route, which seems to recommend using the TitleResolver, but that depends on putting together a $request object, which seems extremely impractical.

Suggestions?

So, I've written a preprocess function to do this:

/**
 * Prepares variables for link fields.
 */
function mymoduleortheme_preprocess_field__link(&$variables) {

  // If the link is a reference to an internal entity and there was no
  // link title provided by the content editor, then use the entity
  // label as the link text.
  $i = 0;
  foreach ($variables['element']['#items'] as &$item) {
    if (empty($item->get('title')->getValue()) && $item->getUrl()->isRouted()) {
      $parameters = $item->getUrl()->getRouteParameters();
      if (!empty($parameters)) {
        foreach($parameters as $entity_type => $id) {
          if ($entity = \Drupal::entityTypeManager()->getStorage($entity_type)->load($id)) {
            $variables['items'][$i]['content']['#title'] = $entity->label();
            break;
          }
        }
      }
    }
    $i++;
  }
}

This is working with both the standard Link field formatter as well as the "Separate link text and URL" formatter provided by Drupal 8 core.

My only doubt here is that I'm not sure how safe it is to assume getRouteParameters() will always be keyed with an entity type name and a value of the entity id.

Would appreciate your help to review and vet this. Thanks!


How to disable text format options in CKEditor I wish users don't have the option which text format they want to use as shown here:

I have been playing around with the better formats module, Currently only works on Field API fields on fieldable entities implementing core style text processing. So this module only makes sure with which text format they will start off editing with, so this dCurrently only works on Field API fields on fieldable entities implementing core style text processing.oesn't do anything at all, as the users still have the option to choose which text format they would like to choose.

Besides hiding this option with CSS, is there another way to disable this option for specific users?

The simplify module will allow you to hide text format selection, and a lot of other bling too: https://drupal.org/project/simplify

The simplify module allows you to hide the text format selection globally on all content types, as in the attached screen. Alternately, you can disable text format selection for each content type individually.

I've really only used it one one site so far, but haven't had any trouble.


How to display the replies count of the each user comments with show/hide option in node view page in Drupal 7? Now, I am having comments section like this in node view page.

  Comment 1
    comment 11
    comment 12
  Comment 2
  Comment 3
    comment 31
    comment 32
    comment 33

But, I would to show this with show/hide option for replied comments with replies count. like below

  Comment 1
    show/hide 2 replies
    ------------------
    | comment 11     |
    | comment 12     |
    ------------------
  Comment 2
  Comment 3
    show/hide  3 replies
    ---------------
    |  comment 31 |
    |  comment 32 |
    |  comment 33 |
    ---------------

I tried to solve your problem . The best way to solve this is to create a new CUSTOM MODULE.
 - Create a new folder in Your sites/all/modules folder custom_module name could be anything.

In folder create two files custom_module.info and custom_module.module and  a folder js . In that folder create a .js file custom_module.js .
So now you .js file will be located at sites/all/modules/custom/js/custom_module.js . Now Go to custom_module folder and in custom_module.info file add the lines of code..

name = Custom_module
description = Displays total count of replies to a comment and add display toggler to the replies of the comment.
core = '7.x'
version = '7.x-1.x'
dependencies[] = comment

Now in your  custom_module.module file

<?php
drupal_add_js(drupal_get_path('module','custom_module') '/js/custom.js');
function custom_module_preprocess_comment(&$variables) {
  $query = db_query('SELECT COUNT(*) FROM comment WHERE pid = :cid', array(':cid' => $variables['id'])) ;
  $result = $query->fetchField();
  $variables['content']['links']['comment']['#links']['comment-reply']['title'] = 'reply  ('.$result.') Show';
}

So what the module did is fetched the total no of replies of a comment from the database and appended them to reply link.
A Simple jQuery file will get you what you wanted. Edit your js/custom_module.js file custom_module.js file

(jQuery)(document).ready( function() {
  jQuery('div.indented').css('display', 'none');
  (jQuery)('div.comment .comment-text ul li.comment-reply span').click( function() {
    if(jQuery('show-hide').html()=='Show') {
      jQuery('show-hide').html()='Hide';
      (jQuery)(this).parents("div.comment").next().slideToggle();
    }
    else {
      jQuery('show-hide').html()='Show';
      (jQuery)(this).parents("div.comment").next().slideToggle();
    }
  });
})(jQuery);

Click On Show in Comments and it will toggle . I have also added a screenshot..

SHOW
.

HIDE


How to use multiple reverse relationships from different content types in a single View Drupal 7? i have three content types

1- News

2- Articles

3- Press Releases

On every content type we have a custom field called 'industry'.

so when we create a news (or article or press release) we fill the industry field 'construction medical energy etc etc' (Means on which page[of content type industry] it should be display)

i want to create a view where i want to show all three content types "news ,articles, press releases" which have the field 'construction' in it.

Step by step Snap shots are attached for my views and content types.

adding news: http://prntscr.com/b940qh
my view screen shot: http://prntscr.com/b943oi
Want Result like : http://prntscr.com/b948qv

Going of memory here, so things may not be exact.

One possible solution:

For Contextual Filter add Industry

When Filter is not in the URL select fixed value

Type select fixed

In the text box put construction

Another possible solution, if your Industry field is tax term reference field then add Terms of the node as a relationship. Then in Filter Criteria (below Fields), add tax terms and type your term name construction


Change Form submit button's title I have a content type called "project" . I want to change the title of the submit button of the edit form.
I wrote a module with the following:

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'project-node-form') {
     $form['actions']['submit']['#value'] = t('Publish');
  }
}

I enabled this module but no change of the button title.

please help...thanks.

The form ID of the form alter function is wrong. It should have _ instead of -.

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'project_node_form') {
     $form['actions']['submit']['#value'] = t('Publish');
  }
}


Access content at alias without redirecting to original content location Is there a way to generate an alias for content WITHOUT having it redirect to the original content location and therefore preserve menu location?

For example - I have one node which is located at http://mysite.com/oranges but I'd also like to access it at http://mysite.com/apples WITHOUT being forwarded on to the original URL.

Is this possible? I know, from an SEO standpoint this is not ideal, but we are creating several groups of pages (sub-sites) and several of the sub-pages need to have the same content and it will be tedious to edit them one-by-one.

Is the only option here to create and embed blocks on the pages so that the content is unified?

With the core module path you can do this:

  Tips about URL aliases

  Although it is possible to assign the same internal URL to multiple
  aliases, this is generally not a good idea for search engine rankings;
  Google, for example, penalises your site by dropping its rank if
  Google thinks that you are publishing duplicate content under multiple
  URLs (a form of web spamming).

I just tried to add 3 aliases on the same node/123 and it works without any problem. Go to Administer > Configuration > Search and metadata > URL aliases or directly to admin/config/search/path to add a new alias and see the existing ones.


How to make Adaptivetheme dropdown menu show on start page? I'm using Drupal 8 with an Adaptivetheme subtheme. The horizontal navigation menu resides in the leader board region. Some menu entries have submenus, but they do not show on the start page. One has to click on the respective menu (e.g. "Football"), which loads the single page "Football", and it is only here that submenus will be shown.

Is there a way to make submenus work on the start page with Adaptivetheme?

Try editing the relevant menu at /admin/structure/menu/

Edit each (first level) items that is not showing it's submenu items and tick off "show as expanded".

This is a general tip. I don't know exactly how your theme works.


Enabling text editor on statuses form I was looking to use a text editor with statuses. Statuses is neither a Node nor an Entity. I searched a lot and found a simple solution. I just has to replace '#type' => 'textarea', with '#type' => 'text_format', in statuses/includes/utitlity/statuses.form.inc file. It converted it to a text format enabled textarea, but there are few problems.

Ckeditor is not respecting the character limit set by the module, so I found maxlength module and added '#maxlength_js' => TRUE, but it does not make the default work. Instead it adds a separate character counter. The markitup library is respecting this, but I want to use ckeditor as I think it is the best editor. How to overcome it?
The form is now scrollable after enabling ckeditor. I want to disable scrolling. The resizeable was already set to FALSE in the module, but ckeditor is not respecting it. How to solve it?
How to hide paragraph counter and word counter? I have not enabled it from settings. I was there by default.

Here is the SnapShot of the statuses form.

Code was added like this: Only 2 modifications were made to the code, the rest is the original code of the module.

$form['fbss-status'] = array(
    '#type' => 'text_format',
    '#rows' => variable_get('statuses_box_rows', 2),
    '#maxlength_js' => TRUE,
    '#maxlength' => 140,
    // 508 compliance: add a label, but visually hide it
    '#title' => t('Status'),
    '#title_display' => 'invisible',
    '#default_value' => $default,
    '#attributes' => array('class' => array('statuses-text', 'statuses-text-main')),
    '#resizable' => FALSE,
    '#prefix' => '
',
    '#suffix' => '
',
    '#weight' => -40,
  );

Regarding your 2nd and 3rd questions, you could try this answer here: https://drupal.stackexchange.com/a/62407/12701

Instead of hacking the statuses module, you should create your own module and use hook_form_alter() like this:

/**
 * Implements hook_form_alter().
 * Adding WYSIWYG editor to statuses
 */
function MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  switch ($form_id) {
    case 'statuses_box':
      $form['fbss-status']['#type'] = 'text_format';
      $form['fbss-status']['#format'] = 'filtered_html';
      break;
    case 'fbss_comments_edit':
      $form['status-comment-edit']['#type'] = 'text_format';
      $form['status-comment-edit']['#format'] = 'filtered_html';
      break;
  }
  if (substr($form_id, 0, strlen('fbss_comments_box')) === 'fbss_comments_box') {
    $form['status-comment']['#type'] = 'text_format';
    $form['status-comment']['#format'] = 'filtered_html';
  }
}


How to get the list of fields which are referenced to particular vocabulary As the title say I want to get the list of fields which are referenced to particular vocabulary.

For example field1 and field2 are taxonomy reference fields and the vocabulary associated to them is vocab1, now if I pass vocab1 I should get field1 and field2 as the results.

The vocabulary that a term reference field is associated with is held in the data column in the field_config table. Unfortunately that's a serialised PHP array so there's no clean way to query it directly.

The Field Info API doesn't seem to have a function to query fields by type so you'll need to implement your own. The basic logic would be to grab a list of fields that have the taxonomy_term_reference type, along with their data, then loop through each to determine if it has the correct vocab assigned.

Something like...

function MYMODULE_term_reference_fields_by_vocab($vocab) {
  $args = array(':type' => 'taxonomy_term_reference');
  $data = db_query('SELECT field_name, data FROM {field_config} WHERE type = :type', $args)->fetchAllKeyed();

  $field_names = array();
  foreach ($data as $field_name => $info) {
    $info = unserialize($info);

    if ($info['settings']['allowed_values'][0]['vocabulary'] == $vocab->machine_name) {
      $field_names[] = $field_name;
    }
  }

  return $field_names;
}

You'll probably want to add a static caching mechanism to that for performance, but it'll work as-is if that's not important.


Drupal generating broken URLs containing "http" twice My drupal site website started recently generating broken links/URLs within markup. It might have happened after I updated to version 7.41 or due to recent module update. I'm not sure.

Example:

<link rel="canonical" href="http://www.mydomain.nethttp:/" />
<link type="text/css" rel="stylesheet" href="http://www.mydomain.nethttp:/sites/default/files/css/css_xE-rWrJf-fncB6ztZfd2huxqgxu4WO-qwma6Xer30m4.css" media="all" />

Any idea what is going on? My drupal is hosted at the top of domain and not in a subdirectory. I was fine for years and didn't have to set $base_url in settings.php or anything.

My site uses clean urls and I double checked that rewrite apache module is on and working correctly.

I did try setting the $base_url in settings.php, this made the front page load correctly, however when I visit any node the apache returns 404, e.g. in access.log I see:
"GET /content/some-nice-article-i-had HTTP/1.1" 404

I'm using Apache/2.4.17 and PHP 5.6.14 on Archinux.

Any ideas?

It appears that Apache 2.4.17 break rewrite functionality when fastcgi PHP is used. With mod_php everything is working fome but I'm looking forward to Apache 2.4.18 or 2.5.


How can I display the value of an addressfield in a single line? I modified the "Address form (country-specific)" bundled with the Addressfield module to take only a country, administrative area, and city; this works fine on the node edit form, but when the field is displayed upon viewing the node, it looks like this:

What I want to do is display it on a single line with commas like this:

  Indianapolis, Indiana, United States

I am using the Views module to display the field.  How can I rewrite (using Views or custom code) the addressfield output to be a single line?

I had to do the same thing a couple of days ago, this is what I came up with using hook_field_formatter_info() and hook_field_formatter_view():

function MYMODULE_field_formatter_info() {
  return array(
    'inline_address_field' => array(
      'label' => t('Inline Address Field'),
      'field types' => array('addressfield'),
    )
  );
}

function MYMODULE_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $build = array();

  $count = 1;
  foreach ($items as $item) {
    $inline_address = "
Address $count
";

    $address_parts = array();
    if (!empty($item['first_name'])) {
      $address_parts[] = $item['first_name'];
    }
    if (!empty($item['last_name'])) {
      $address_parts[] = $item['last_name'];
    }
    if (!empty($item['premise'])) {
      $address_parts[] = $item['premise'];
    }
    if (!empty($item['thoroughfare'])) {
      $address_parts[] = $item['thoroughfare'];
    }
    // And so on for all of the columns that you're interested in, in the order
    // that you want them to be displayed.

    $inline_address .= '
' . implode(', ', $address_parts) . '
';

    $build[] = array('#markup' => $inline_address);
    $count++;
  }

  return $build;
}

It provides a field formatter you can pick for the address field on the node's "Manage Display" form.


How can I load entity form for comment? I want to load entity form for comment entity type.

I can load entity form for node (entity type = node and bundle = article).

But the entity type = comment and bundle = comment.

Here is the code of loading entity:

  $values = [];
    $definition = \Drupal::entityManager()->getDefinition("node");
    $bundle_key = $definition->get('entity_keys')['bundle'];
    $values['entity_type'] = "node";
    $values[$bundle_key] = "article";
    $entity = \Drupal::entityManager()->getStorage($definition->get('id'))
      ->create($values);
   return \Drupal::service('entity.form_builder')->getForm($entity);

=> This example works well.

But if i replace entity type with comment and bundle with comment, not work :(.

        $values = [];
        $definition = \Drupal::entityManager()->getDefinition("comment");
        $bundle_key = $definition->get('entity_keys')['bundle'];
        $values['entity_type'] = "comment";
        $values[$bundle_key] = "comment";
        $entity = \Drupal::entityManager()->getStorage($definition->get('id'))
          ->create($values);
       return \Drupal::service('entity.form_builder')->getForm($entity);

it also needs the field name I think, check CommentDefaultFormatter::viewElements

https://api.drupal.org/api/drupal/core%21modules%21comment%21src%21Plugin%21Field%21FieldFormatter%21CommentDefaultFormatter.php/class/CommentDefaultFormatter/8

It uses a lazy builder so it can be built after render caching

$output['comment_form'] = [ '#lazy_builder' => ['comment.lazy_builders:renderForm', [ $entity->getEntityTypeId(), $entity->id(), $field_name, $this->getFieldSetting('comment_type'), ]], '#create_placeholder' => TRUE, ];


Filter taxonomy terms in common to nodes related to the viewed node I want to filter taxonomy terms in common to nodes related to the viewed node, but I cannot figure out how. What I am getting are all the terms that the related nodes have (with repeated terms too). Please take a look at this recipe page, side block STAG RICETTA

I am filtering seasonality terms (months) in common to ingredients nodes (the ones related to the node being viewed) used in a recipe node (the viewed one).

How can I achieve this?

To show a list of season terms on the ingredient nodes related to the recipe node:

Create a view of taxonomy terms of type season.
Add a relationship: Taxonomy term: Content with term
Add a relationship: Entity Reference: Referencing entity (A bridge to the entity that is referencing Content via field_recipe_uses_ingredient) via the relationship created in step 2.
Check "require this relationship".
Save.


Simplenews does not apply templates and does not resend I have a strange issue. Simplenews sends ok html formatted emails but it does not read the extra info I write in template. It actually doesn read them at all.

The second issue it doesn't resend no matter how much I try.

About You Second Issue - Here is a "dirty" solution.

Go to phpMyAdmin and find simplenews_newsletters table
Edit that table and change s_status on the newsletter you want from 2 to 0.

s_status - 2 Newsletter has been sent

s_status - 0 Newsletter has not been sent

s_status - 1 Sending Newsletter


How to determine block module given block delta Is there a way to determine a block's module given only the block's delta? I'm hoping for a solution that does not require a custom query.

Use case:
We are enabling our client to decide which blocks are displayed on a given content type. Those options include blocks created through the block admin interface and blocks created through the views admin. From what I can tell, a regular block and a view's block are rendered differently so psuedo code would be something like.

// In preprocessing
if($block_module === 'views') {
    // do view rendering
} else {
    // do normal block rendering
}

Any ideas?

No, it's not possible without having the module name.

Block deltas only need to be unique per module, so any two modules could implement a block with exactly the same delta, and you'd have no way to determine which was which without the module name.

The simplest proof of this in the code is the block_load() function, which has this signature:

function block_load($module, $delta) {

As you can see, even Drupal can't load the details of a block without knowing the module name unfortunately.


Error: Syntax error, unrecognized expression: I want to display a form in CTool modal dialog, but failing badly.

When I click link to show modal form, ajax request is started:

POST http://drupal.dev/my_mod/arg1/ajax/arg3

and returns:

Error: Syntax error, unrecognized expression:

          <button type="button"
class="close" data-dismiss="modal" aria-hidden="true">&times;</button>

&nbsp;

I tried to click different link, but gets an error:

  TypeError: Drupal.CTools.Modal.modal is undefined

Code:

function my_mod_menu() {
  return array(
    'my_mod/%/%ctools_js/%' => array(
      'title' => 'Entity Modal Edit',
      'page arguments' => array(1,3),
      'page callback' => 'my_mod_modal_page_callback',
      'access callback' => 'my_mod_modal_access_callback',
      'access arguments' => array(1,2,3),
      'type' => MENU_CALLBACK,
    ),
  );
}

function my_mod_modal_page_callback($entity_type, $id) {
  ctools_include('modal');
  ctools_include('ajax');
  ctools_modal_add_js();

  $form_state['user'] = user_load($id);
  $output = ctools_modal_form_wrapper('my_mod_form', $form_state);
  ctools_modal_render('Edit', $output);
  exit;
}

I'm creating my edit link in custom views_field_handler:

class my_mod_handler_field_links extends views_handler_field {

  function init(&$view, &$options) {
    parent::init($view, $options);

    if (! isset(self::$some_property)) {
      ctools_include('modal');
      ctools_include('ajax');
      ctools_modal_add_js
    }
  }

  function render($values) {

    $edit_link = array(
      'href' => 'my_mod_ctools/some_value1/nojs/some_other_value',
      'title' => t('edit'),
      'attributes' => array('class' => array('mymod-ctools-links', 'ctools-use-modal', 'use-ajax')),
    );

    $links[] = $edit_link;

    $build = array(
      '#prefix' => '
',
      '#suffix' => '
',
      '#theme' => 'links',
      '#links' => $links,
    return drupal_render($build);
  }

  function query() {}

}

I had using jQuery 1.9. I changed it to 2.1 and the problem is solved (jquery_update module)


How to go about creating location selector: a languages like "countries" global variable? I'm interested how should I approach creating a language switcher like countries switcher?

The idea is that I wish to have country specific content and restrictions (just like with languages) but I want to allow all languages for every country.

Ideally I'd need to have the country value as a global variable and even in the cookies. A great bonus would be if I could assign it to the url like languages (../en/.. -> --/us/en/..) without ruining routing for core or path auto/url aliases etc..

But I don't know how and where to start and can't even find materials on people having done anything similar before.

My train of thought here would be the following:

Create custom module

Create a countries database/list
Set the country as a global variable somehow
Set the country as a cookie and fetch on every page load (or if possible to and from url)
Create the selector widget

Any ideas how to better understand what I'm facing and recommendations for tackling this? Also a lot of big corporations have location selectors with that locations languages which restrict content, how is this not possible with Drupal? (Couldn't even find anything for D7)

This is a typical use case for domain access:

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

This module includes a domain switcher, which would be the selector widget you asked for. There is only a dev version for D8. This is a heavy weight module and until now I did avoid using it in D8 and did some custom coding for the functionality I need. To get some ideas I would investigate this module.


Views PHP: Comparing two Field and display Answer I tried to build a soccer magazine website. I want to display Match Win/Loss/Draw in the Match Result Page with the score result. I want to display it like:

if [field_score1] > [field_score2] display 'Win'
if [field_score1] < [field_score2] display 'Loss'
if [field_score1] = [field_score2] display 'Draw'

Im stuck please Help.

First,  In your Match Results view, add a Global: Custom text field and just leave it blank/empty. (we will use this field to print the outcome)

You can override the view's display through your themes template file.

Go to sites/all/themes/YOURTHEME/  look for template.php and open it. You probably have other code inside there, so make extra space by hitting enter at the bottom and add the following code.

function YOURTHEME_preprocess_views_view_fields($vars){

      if ($vars['view']->name == "VIEWNAME" && $vars['view']->current_display == "DISPLAY" && $vars['fields']['field_score1']->raw > $vars['fields']['field_score2']->raw){
        $vars['fields']['nothing']->content = print 'Win';
      }

      else if ($vars['view']->name == "VIEWNAME" && $vars['view']->current_display == "DISPLAY" && $vars['fields']['field_score1']->raw < $vars['fields']['field_score2']->raw){
        $vars['fields']['nothing']->content = print 'Loss';
      }

      else if ($vars['view']->name == "VIEWNAME" && $vars['view']->current_display == "DISPLAY" && $vars['fields']['field_score1']->raw == $vars['fields']['field_score2']->raw){
        $vars['fields']['nothing']->content = print 'Draw';
      }

}

Replace YOURTHEME with your actual theme name

Replace VIEWNAME with your view machine name. (example: match_results)

Replace DISPLAY with your display machine name. (example: block, block_1 ) You can find the name by looking at your view. (see picture below). If you're using the Master view, then the machine name is "default"

.jpg


How can I do the dynamic select in Drupal 7 forms? I work with drupal 7. In the following code I call the function players() which returns array of values for option. This values were defined beforehand by hand. How can I load it dynamically from the database?

 $form['officers']['officer'] = array(
'#title' => t('Select the officer'),
'#type' => 'select',
'#description' => t('Please, select the officer'),
'#options' => players(),
'#multiple' => FALSE,
'#empty_value' => ' ',
'#empty_option' => '- None -',

);

For example in the "Text Field" there is property #autocomplete which defines a path where Drupal’s automatically included JavaScript will send HTTP requests using jQuery.

 $form['team_name'] = array(
'#title' => t('Name'),
'#type' => 'textfield',
'#description' => t('Please, insert your name'),
'#autocomplete_path' => 'autofillform/teamname' ,

);

And i created the module which handles it.

<?php
function autofillform_menu() {
$items['autofillform/teamname'] = array(
'title' => 'Example autocomplete',
'page callback' => 'autofillform_teamname',
'access callback' => TRUE,
'type' => MENU_CALLBACK,
 );
 return $items;
 }
 function autofillform_teamname($string){
 $matches = array();
 $result = db_query("SELECT name FROM users where lower(name) like '".$string."%'  LIMIT 10");
 foreach ($result as $user) {
 $matches[$user->name] = check_plain($user->name);
  }
 print drupal_json_encode($matches);
 return;
 }

Are there any possibility to do the same with "Select" ?

You need to focus on #ajax option. That will look like

$form['officers']['officer'] = array(
  '#title' => t('Select the officer'),
  '#type' => 'select',
  '#description' => t('Please, select the officer'),
  '#options' => array(),
  '#multiple' => FALSE,
  '#empty_value' => ' ',
  '#prefix' => '
',
  '#suffix' => '
'
  '#empty_option' => '- None -',
  '#ajax' => array(
     'callback' => 'path/to/callback/handler',
     'wrapper' => 'officer-wrapper',
     'method' => 'replace',
     'effect' => 'fade',
  ),
);

In the submit handler you will have change the form element for #options and render to post back using drupal_json_output.


How can I display site logo, name and slogan? how can i show site logo, name and slogan Separately in custom area in my site theme, I now use this code to display theme, buts this code don't allow me to edit each of them Separately.

{{ page.header }}

function mytheme_preprocess_page(&$variables) {
  $site_config = \Drupal::config('system.site');
  $variables['site_name'] = $site_config->get('name');
  $variables['site_slogan'] = $site_config->get('slogan');

  // logo needs to be placed within specified folder
  $variables['logopath'] = file_url_transform_relative(file_create_url(theme_get_setting('logo.url')));

}

Then in page.html.twig you can use variables site_name and site_slogan as follows:

{{ site_name }}
{{ site_slogan }}

and for the logo:

<img src="{{ logopath }}" />

note: logo image file will need to be available in your current theme's root folder (or subfolder of your choice).


Is there a way to use File Field but have it’s directory path be different for different instances of content, instead of the same? I’m selling mp3’s via Commerce File/File Field modules and i need these files to reside in different directories based on artist name and album name, etc. For example:

mp3s/some_artist/album_name/some_song.mp3.

so typically a catalog would have numerous dirs.

but by default a Drupal content type only allows a single directory to be specified.

so far the only way to achieve this is to have to continually make changes to the product variation content type.
i have to keep changing the file directory setting

this is not a good solution and limits the amount of bulk uploading i can do at one time.

is there a way to get Drupal to just accept these file references as i input it? to accept any number of different file paths, in the context of bulk import?

(i hope i’ve asked this question clearly…

You can define your file paths with node tokens. File (Field) Paths module provides the functionality that you are looking for.

  The File (Field) Paths module extends the default functionality of
  Drupal's core File module, Image module and many other File upload
  modules, by adding the ability to use entity based tokens in
  destination paths and file names.


Drupal assuming admin created user, when user registered normally This is something that I'm pretty sure worked when in beta, but doesn't work now anymore.

I have setup the user registration to be allowed by visitors, but a confirmation by the admin is required. Email verification isn't required. I have composed all the necessary emails.

Now, when a user registers, two things go wrong:

no mail is sent to the admin
the wrong mail is sent to the new user

The new user receives a mail stating that the admin created his account and that he can use the one-time login link to change his password. When he clicks on this link, he doesn't have access to the page, because the account isn't active yet.

The user should receive the mail telling him he registered succesfully and his registration is waiting for approval. The admin should receive the mail that a new user was created.

Sometime, the admin will create the users, so both mechanisms will be used. But I get the impression Drupal thinks it was always the admin that created the user, even if it was a normal user registration.

I have a rule setup (from the Rules module) for when a new user registers, to add him to certain roles. But this worked in beta, now it doesn't anymore. Also, disabling this rule, or disabling the rules module entirely didn't help.

Any ideas where I can start looking?

As it turns out, a custom-made module conflicted with the normal behavior in a sneaky way.

In D7, when you create a user as an admin, the checkbox to send an email with a one-time login link is not selected by default. As the person creating users is not a technical person, I thought it might be user friendly if this was checked by default.

After a bit of searching, I found a small module that could help. What this piece of code did was:

if ($form_id == 'user_register_form') {
    $form['account']['notify']['#default_value'] = TRUE;
}

However, as you can see there is no check if the current user is the admin. So Drupal assumes the admin is creating the user, even for a normal registration by a visitor. Subsequently, the visitor gets a mail that the admin created his/her account.

I explained this for the author also, and hope someone fixes it (or I'll try myself when I find the time).


How to direct authenticated and anonymous users to different ( custom ) front pages? I want anonymous users to always see /node/1 but authenticated users to see /myview/uid where uid is the current user's id.

I don't want to use Rules, but would prefer a code solution.

You can use hook_user_login function to achieve this.

function custom_module_user_login(&$edit, $account){
  if($acount->uid > 0) {
          $redirection = 'myview/'.$acount->uid;
  } else{
      $redirection = 'node/1';
  }

  // Unless there is already a redirection going, or the user is trying to reset his password, we redirect to $redirection.

  if (!is_null($redirection) && (!isset($_POST['form_id']) || $_POST['form_id'] != 'user_pass_reset')){
    $_GET['destination'] = $redirection; // Should we use $edit['redirect'] instead..?
    $GLOBALS['destination'] = $redirection; // Should we use $edit['redirect'] instead..?
  }

}

For more info check here


Drupal, Displaying a Content list of a User from their Profile, accessible by anyone via Views I am running Drupal 7 and I would like to know how to create a View that displays as a tab on a users profile that displays all of his or her created content. This is what I have so far, but it only shows the tab for the logged in user, no one else can access it.

I got most of the code from here.

It seems like you were very close.  I would add on to the contextual filter.  You need to provide a default value for the filter.  Either of the following will work:

Using PHP Code.  Enter the following into the box "return arg(1);" without the quotes.
Raw value from URL.  Change Path component to 2.


Calculate distance using Geolocation module I'm using the drupal/Geolocation module to assign a location field to a specific content-type.

I have created a View (REST Export display) to return all the content-type entries with all the fields and it's working fine.

I'd like to calculate the distance between a sent lat/lng point and the location of each entry and sort them by distance (and also include it in the resulting JSON).

I'm already applying some changes to the JSON output using the views_post_render hook (and changing the $output variable), but I don't think in that hook I can access a query string (sent via Ajax request).

What would be the best way to pass the user's location from the website frontend to the view? Right now my bet would be sending the query parameter via an Ajax request, adding something like ?location=-17.000,19.000 to the URL.

And where could I access that data (the user's lat/lng location) and calculate the distance to pass it again to the frontend?

I've found a solution.

Getting the user location

I'm using the Browser API to get the user location in the frontend and then pass those parameters as query strings to my view, like ?latitude=xxxx&longitude=xxxx.

if (navigator.geolocation) {
    var options = {
        enableHighAccuracy: true,
        maximumAge: 0
    };

    function success(pos) {
        var crd = pos.coords;
        // Send ajax request with crd.latitude and crd.longitude in query strings
    };

    function error(err) {
        console.warn(`ERROR(${err.code}): ${err.message}`);
    };

    navigator.geolocation.getCurrentPosition(success, error, options);
} else {
    console.warn('Geolocation not available.')
}

Using the location to calculate distances with Drupal hook

Then, using the THEME_views_post_render(\Drupal\views\ViewExecutable $view, &$output) hook I check that $view->id() is the view in which I want to make the calculations and I get the data from the URL using the Drupal function \Drupal::request()->query->get('latitude'); (and longitude).

From that point, I decode the JSON variable $output['#markup'] and change the JSON objects the way I need to fulfill my requirements.

if ($view->id() == 'farmacias_perto') {
        $user_latitude = \Drupal::request()->query->get('latitude');
        $user_longitude = \Drupal::request()->query->get('longitude');
        $json_result = json_decode($output['#markup']->jsonSerialize());

        foreach ($json_result as $pharmacy) {
            $latlong = explode(',', $pharmacy->field_geolocation);
            $pharmacy_latitude = $latlong[0];
            $pharmacy_longitude = $latlong[1];
            $distance = distance($pharmacy_latitude, $pharmacy_longitude, $user_latitude, $user_longitude);
            $pharmacy->distance = round($distance);
        }

        $output['#markup'] = json_encode($json_result);
}

I used the distance function explained here.


How to add newsletter functionality (just stable modules if possible)? I've searched a little and I needed to add newsletter functionality to a Drupal 7 installation. I've found Simplenews, which is in Beta version for Drupal 7 nothing more. I don't need anything really complicated, just these functionalities:

Guest user can subscribe to newsletter by leaving their email address in a field
Registered users can tick a checkbox in their profile to choose whether to receive newsletters
Users can unsubscribe from newsletter by clicking a link in the newsletter
A WYSIWYG editor for sending newsletters (but, I think this can be accomplished with the WYSIWYG module)

nothing more. If any of you tried the development version of Simplenews, please provide your experience.

Simplenews is really your only way of going. I have personally been holding off on it's implementation in 7 because of its state as well. More specifically, emails were not being sent (test ones were) and it's lack of mimemail support.


Entity API fieldable entity path issue So, after studying several examples, I started writing my own module to implement a notification-like entity.

I wanted it to allow separate bundles and be fieldable. This example was a great guide to me.

I've spend several hours and almost brought the wall down with my head due to the following issue though.

My implementation of hook_entity_info_alter:

function mymodule_entity_info_alter(&$entity_info) {
  foreach (notification_types() as $type => $info) {
    $entity_info['notification']['bundles'][$type] = array(
      'label' => $info->label,
      'admin' => array(
        'path' => 'admin/structure/notification-types/manage/%notification_type',
        'real path' => 'admin/structure/notification-types/manage/' . $type,
        'bundle argument' => 4,
      ),
    );
  }
}

to provide admin UI for my bundles, wouldn't work. It would provide "Manage Fields" and "Manage Display" tabs in my /admin/structure/notification-types list page with "broken" links such as /admin/structure/notification-types/manage/%25notification_type/fields.

Furthermore when I tried to manage fields of my bundles, I got a "page not found" error.

When I changed the 'path' array element to this:

'path' => 'admin/structure/notification-types/manage/%',

all of a sudden it worked, the wrong tabs went away and the bundles were manageable. My question: Why?!

GOT IT! After googling for a while I came accross this: http://drupal.org/node/224170

This clarifies that

"When a % symbol is used in a menu element (see example), the text that follows will be used to build the name of wildcard loader function.

In the example above, "%node" tells drupal to pass the value of the second element to the function node_load(). _load is always added by Drupal to construct the wildcard loader."

So as long as the notification_type_load() function wasn't implemented it lead to a bug :)


How to rename or choose twigs file name suggestions? When I create a custom block called Lorem ipsum Dolor, I have not the possibility to choose the machine name. So when I have to make a twig template, the file suggestion is :

  block—loremipsumdolor.html.twig

I mean it is without undescore. I found it hard to handle all these twig file when I work on a custom template. It is not human friendly readable.

Is there a way to choose the name of the file name or the block machine name ?

Other example :

  Block name : Custom Search form

<!-- FILE NAME SUGGESTIONS:
   * block--customsearchform.html.twig
-->

I have not this problem with node :

  node--13--teaser.html.twig

Given a block name of 'Custom Search form', you can add to the file name suggestions using a preprocess hook in your theme.

An example of code to add to the .theme file:

/**
 * Add an alternative to file name suggestions the Custom Search form block.
 *
 * Implements hook__suggestions_HOOK_alter().
 * @return array Suggestions.
*/
function mytheme_theme_suggestions_block_alter(array &$suggestions, array $variables) {
    if($variables['elements']['#id'] == 'customsearchform'){
        $suggestions[] = 'block__custom_search_form';
    }
}

This will result in an additional file name suggestion:

<!-- FILE NAME SUGGESTIONS:
   * block--custom-search-form.html.twig * block--customsearchform.html.twig
-->


Glossary input filter saving to node_revisions I have been using the Glossary module and it has been working great. I add  "ADSL" into a node and if a glossary definition exists, on render it converts it to "<acronym title="Asymmetric Digital Subscriber Line">ADSL</acronym>".

However, today I noticed it has started putting the glossary term markup into the node content (saving in the database table node_revisions). When I edit the node again, it no longer contains "ADSL"; it contains the full markup generated by the Glossary input filter (<acronym title="Asymmetric Digital Subscriber Line">ADSL</acronym>).

As far as I am aware, the data is saved straight to the database before any input filter should touch it, as per Drupal Input Formats and Filters.

I am completely confused to how this is possible. Does anyone know what might cause an input filter to act so?

Resolved, somehow the Glossary filter got enabled in the CKeditor's security settings "Please choose carefully all filters that protect your content (probably not all filters listed below are security filters)."

Disabled this and now the Glossary works as it should.


How to create a Drupal database on the server if you only have access via an FTP client I am a bit confused about how to set up server database,because my host provider(is a university site),only provided me with a ftp client username and password. I don't have access to phpmyadmin.:/

You need to ask your server admin to create a database and a user for that database to be able to install drupal. You don't need phpmyadmin but you do need a database/user.