Running a site on a non-standard port I have a server which I want to run drupal site on it.

The default http port 80 was block and it does not have a static IP address.
I have to run Drupal on non 80 port, let's say 8765.

Since I do not have a static IP, I apply a sub-domain name from noip which is
drupal8.myftp.org.
So finally my domain name should be
drupal8.myftp.org:8765

First, I read the tutorial here

From line 46

  Note that if you are installing on a non-standard port number, prefix the
  hostname with that number. For example,
  www.drupal.org:8080/mysite/test/ could be loaded from
  sites/8080.www.drupal.org.mysite.test/.**

So In my scenario, I should create a directory like
sites/8765.drupal8.myftp.org/
and put the settings.php here.
Then I also need to create a 8765.drupal8.myftp.org.php file under “sites” directory to tell Drupal to looking for the settings.php within sites/8765.drupal8.myftp.org directory.

I did create the directory and the file.

But Drupal still looking for the settings.php under default directory, why?

Questoin1: what content should be in the 8765.drupal8.myftp.org.php file?
Since I can not find any tutorial about this, I just leave it blank, I assume it's just a symbol to let Drupal know it should look for the settings.php in the  8765.drupal8.myftp.org category.

Question2: Why Drupal doesn't look for the settings.php under 8765.drupal8.myftp.org directory? Do I did sth wrong?

Since I need to add

$base_url=”http://drupal8.myftp.org:8765”

in the settings.php and the file under sites/8765.drupal8.myftp.org directory doesn't work.
So I have to add it to the settings file under default directory.
But still, If I open the site drupal8.myftp.org:8765
and view the source code

<link rel="shortcut icon" href="http://drupal8.myftp.org/core/misc/favicon.ico" type="image/vnd.microsoft.icon" />
<link rel="alternate" hreflang="en" href="http://drupal8.myftp.org/node/3" />
<link rel="alternate" hreflang="zh-hans" href="http://drupal8.myftp.org/zh-hans/node/3" />

We can see all the link are still point to drupal8.myftp.org,
therefore, all image and css info are gone.

So could anybody give me some instructions, I have be stuck in this for three days, any help is highly appreciated.

Thanks in advance.

@Pathak,

Thank you for your kind reply.

Yes, I create a folder called 8765.drupal8.myftp.org and place settings.php within it. So the path is

sites/8765.drupal8.myftp.org/settings.php

I also create a file call 8765.drupal8.myftp.org.php reference to example.sites.php.

The path is

sites/8765.drupal8.myftp.org.php

According to example.sites.php

  The array is written in the format: '..' =>
  'directory'. As an example, to map
  www.drupal.org:8080/mysite/test to the configuration directory
  sites/example.com, the array should be defined as:

  $sites = array(
      '8080.www.drupal.org.mysite.test' => 'example.com',   );

Then in the 8765.drupal8.myftp.org.php, I write the $sites array as follow;

$sites = array(
    '8765.drupal8.myftp.org' => '8765.drupal8.myftp.org',
  );

But still, if open the site drupal8.myftp.org:8765, the settings.php under the default directory was read. All links are point to drupal8.myftp.org without the port number.
Could you please point out on which step I was wrong?

All of those instructions only apply if you actually want to have a multi-site installation and e.g. different installations on different ports. Something that most people recommend to not do as it results in maintenance issues sooner or later.

If you just want to have one installation, use sites/default/settings.php and you're good to go.


Issue with Disqus comments I seem to be having a difficult time getting the Disqus module to work on my Drupal website. Installation is normal, I just can't get to Disqus configuration page. The configuration page is blank.

I want to know: Does Disqus have any tables? If it does: Can someone give me the table structure, to see if I can use it?

Yes, the Disqus module has it own table (named disqus).

To see this table, look up the file disqus.install and examine the array called $schema.

You'll find this file inside the project directory (normally sites/all/modules/disqus/) where you installed Disqus, or in the project's git repo at drupalcode.org.

The Disqus schema is reproduced below for easy reference:

$schema['disqus'] = array(
  'fields' => array(
    'did' => array(
      'type' => 'serial',
      'not null' => TRUE,
     ),
     'nid' => array(
       'type' => 'int',
       'not null' => TRUE,
       'default' => 0,
     ),
     'status' => array(
       'type' => 'int',
       'unsigned' => TRUE,
       'size' => 'tiny',
       'not null' => TRUE,
       'default' => 0,
     ),
  ),
  'primary key' => array('did'),
  'indexes' => array(
    'nid' => array('nid'),
    'status' => array('status'),
  ),
);


Displaying all sub-menu items even when not "expanded" I'd like a menu structure that is something like the following to be placed into a page's sidebar.

Insects
Animals
----Mammals
--------Bears
--------Whales
----Reptiles
--------Snakes

I'd like it to be set up so that if a user is on the bears page, the animals and mammals menus will be expanded...but the user COULD click an arrow next to reptiles to have that menu expand, and see the snakes option. When I checked the $page['sidebar'] render array, however, child menu items that are not expanded are not even included in the array. So, if I am on bears, there is nothing below $page['sidebar'][whatever number reptiles is]

I thought about writing a module that builds this through the DB, but at that point I'd be pretty much re-writing and implementing the menu modulem since I'd need to also include the html output of this new data on the page. What's the best way to approach this?

The jQuery Menu module gives you that functionality.


.inc files in Features - how are they being included? Regarding the features module: I am working with a module which was created by features. I see a lot of .inc files in the module, but see very few actually included. Does this make any sense? I know that they are all being used and are creating fields etc.

Most include files exported by features are included on-demand by the modules that define that type of component.  For instance, example.views_default.inc is included by the views module when loading default views.  This is a common pattern in Drupal, not something that is specific to Features.


Programatically change the base theme of the current theme I have a theme that is a child theme of 'stable'.

Currently the base theme is defined in the info.yml file, however i don't want its parent theme to be so permanent.

I am looking for a way to be able to programatically change the base theme in code so that the theme could switch its parent on demand.

So as it turns out an info.yml file can be altered inside HOOK_system_info_alter

To change the base theme definition of an existing theme you can use the following

function HOOK_system_info_alter(&$info, $file, $type) {
  if ($type == 'theme') {
    if ($info['name'] == 'YOUR THEME NAME') {
      $info['base theme'] = 'NEW_BASE_THEME_NAME';
    }
  }
}

As this hook is only fired when caches are flushed there is no need for a separate cache flush after the change is made.


How to remove Taxonomy term Title Can anyone please guide me how to remove the title of the Taxonomy terms.

I would like to give the title along with the description so i want to remove the default title.

Thanks for your help

If I understand your question correctly, I think you need the Auto Entity Label module. Using this module, you can automatically generate labels by a given pattern for the taxonomy term names.


Modules update failed I just tried to update some Modules on drupal 7 and got this:

  Update failed! See the log below for more information. Your site is still in maintenance mode.

  ckeditor

Error installing / updating
File Transfer failed, reason: Cannot remove file /home/myinvoice/public_html/sites/all/modules/ckeditor/ckeditor/plugins/dialog/dialogDefinition.js.

  imce

Error installing / updating
File Transfer failed, reason: Cannot remove file /home/myinvoice/public_html/sites/all/modules/imce/tpl/imce-file-list.tpl.php.

  menu_token

Error installing / updating
File Transfer failed, reason: Cannot remove file /home/myinvoice/public_html/sites/all/modules/menu_token/menu_token.module.

  recaptcha

Error installing / updating
File Transfer failed, reason: Cannot remove file /home/myinvoice/public_html/sites/all/modules/recaptcha/recaptcha.install.

  Next steps

Your modules have been downloaded and updated. - DOES THIS MEAN THAT IT DID IN FACT WORK???
Run database updates

Your site will most likely work, but with some bad luck the files could cause errors. The reason is either a file permission issue or, less likely, that you had the files open and that they were locked for that reason.

To be on the safe side you should manually update the affected modules, i.e. delete the directory and replace it with a downloaded copy. Then run the update script.

Do this for the affected ones:

http://drupal.org/project/ckeditor
http://drupal.org/project/imce
http://drupal.org/project/menu_token
http://drupal.org/project/recaptcha


Corporate website, each page different style I need to create a corporate business website under Drupal 7, and on each page (home, about, sevices, contact, etc.) the design is really different.

What would be the best way to structure/build this in Drupal? I'm used to Wordpress theme per page, but this does not look like it's built in Drupal.

Like thi theme: http://demo.drupalizing.com/?theme=corporateclean
http://drupal.org/project/corporateclean

The design change quite a bit for each page. But when I download the theme, I don't see how they did that, since there's only that general page...

You can create a new theme using one of the many starter themes, and then override templates to get as specific as you please.

For example, to override a particular content type's look, you'd edit node--contenttype.tpl.php where contenttype is your custome content type.

The template guide contains further info, including naming conventions to get your templates applied in the right place.


views exposed filter to have dropdown of entity reference in cutstom entity I generated with drupal console utility my own module and content entity code. After I added a user entity reference field and a taxonomy term entity reference field.

Now I'm listing my content with views, I don't do nothing with the code generated the integration is done.

But, when I expose a filter by taxonomy field and user field it doesn't give me the option to show as a dropdown, it directly appears as a textfield.

In others views, listing nodes with entity reference fields, if I add exposed filter of entity reference  offers to me a dropdown or autocomplete widget.

What I have to change to my entity to have dropdown select for my entity reference field as exposed filter in a view?

Here is the field definition in the Entity class

    $fields['term_id'] = BaseFieldDefinition::create('entity_reference')
  ->setLabel(t('Log type'))
  ->setDescription(t('The term ID of the Log entry type.'))
  ->setRevisionable(FALSE)
  ->setSetting('target_type', 'taxonomy_term')
  ->setSetting('handler', 'default:taxonomy_term')
  ->setSetting('handler_settings',
    array(
      'target_bundles' => array(
        'logs_type' => 'logs_type'
    )))
  ->setTranslatable(FALSE)
  ->setDisplayOptions('view', array(
    'label' => 'inline',
    'type' => 'taxonomy_term',
    'weight' => -2,
  ))
  ->setDisplayOptions('form', array(
    'type' => 'entity_reference_autocomplete',
    'weight' => -2,
    'settings' => array(
      'match_operator' => 'CONTAINS',
      'size' => '60',
      'autocomplete_type' => 'tags',
      'placeholder' => '',
    ),
  ))
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

Update:

I achieve to have a dropdown in the exposed filter in my view creating the file mymodule.views.inc and puting this code:

function log_activity_views_data_alter(&$data) {
  $data['log']['term_log_tid_depth'] = array(
    'help' => t('Display content if it has the selected taxonomy terms, or children of the selected terms. Due to additional complexity, this has fewer options than the versions without depth.'),
    'real field' => 'term_id',
    'argument' => array(
      'title' => t('Log type (with depth)'),
      'id' => 'taxonomy_index_tid_depth',
      'accept depth modifier' => TRUE,
    ),
    'filter' => array(
      'title' => t('Has taxonomy terms (with depth)'),
      'id' => 'taxonomy_index_tid_depth',
    ),
  );
}

But when I choose a term to filter the view, it does not return any item and it should do so.

As Berdir said, as long as https://www.drupal.org/node/2429699 is not ready, you need to provide your own Views Filter plugin.

I created this plugin, based on TaxonomyIndexTid, for Nodes, see https://gist.github.com/StryKaizer/ae1cb9abc4844a9e7ac12317a9d84a78

You need to place this file in a custom module at yourmodule/src/Plugin/views/filter/NodeIndexNid.php, and also implement hook_views_data_alter in your yourmodule.module file, like this:

/**
 * Implements hook_field_views_data_alter().
 *
 * Views integration for entity reference fields which reference nodes.
 * Adds a term relationship to the default field data.
 *
 * @see views_field_default_views_data()
 */
function yourmodule_field_views_data_alter(array &$data, FieldStorageConfigInterface $field_storage) {
  if ($field_storage->getType() == 'entity_reference' && $field_storage->getSetting('target_type') == 'node') {
    foreach ($data as $table_name => $table_data) {
      foreach ($table_data as $field_name => $field_data) {
        if (isset($field_data['filter']) && $field_name != 'delta') {
          $data[$table_name][$field_name]['filter']['id'] = 'node_index_nid';
        }
      }
    }
  }
}


How can I see what visitors are searching for? Are visitor search terms stored somewhere in Drupal 6? I see a search_total table that might hold that info but the data in there looks kinda weird.

I'm using search module in core.

Unfortunately it's pretty limited.

View top search phrases (in Drupal 6.x):
yoursite.com/admin/reports/search

The data originates from the watchdog table, which means that how much data is provided depends on how far back your watchdog data goes (usually not far).

The Search Log module will provide more robust results. Or use Google Analytics, as the commenter above suggested.


Send email when a user has finished watching something A user watched a video (added listening event to id of video via jwplayer), and a person is notified of said user finishing the video.

jwplayer('some-id-of-video').onComplete( function() {
  //$.ajax or .post whatever to send email to a person to let them know without refreshing page
});

I want to just add this script to this page (this functionality is only needed for this ONE VIDEO). How do I link the PHP code to send the email? Not a form everything will be a standard response.

This  does not work.

$message = array(
  'to' => 'email address',
  'subject' => 'subject text',
  'body' => 'body text',
  'headers' => 'header text'
);

drupal_mail_send($message);

Where do I put this? Is this wrong? And if it is wrong, what do I need to fix it? How can I call this code from AJAX?

Create an end point for your ajax request to call using hook_menu(). In this example I'm passing the UID of the user as an argument.

E.g:

/**
* Implementation of hook_menu().
*/
function myModule_menu() {
  $items['mymodule/send-email/%user'] = array(
    'page callback' => 'myModule_ajax_send_email',
    'page arguments' => array(2),
    'type' => MENU_CALLBACK,
    'access arguments' => array('access content'),
  );
  return $items;
}

The callback for your menu item will be responsible for actually sending the email. See this question: How to send email in drupal

E.g.:

function myModule_ajax_send_email($user) {

  // Here you put the code to actually send the email
  $status = some_logic_to_check_email_sent();

  drupal_json(array('status' => $status));
}

So then once your video has finished playing you just need to make an ajax request to your new end point, passing any information required as parameters.
E.g:

(function($) {
    Drupal.behaviors.myModule = {
        'attach': function(context) {

            jwplayer('some-id-of-video').onComplete(function(){
              //$.ajax or .post whatever to send email to a person to let them know without refreshing page
              var UID = 1; // actually set UID here
              var url = 'mymodule/send-email/' + UID;
              $.get(url, null, emailCallback);
            });

        }
    }
    var emailCallback = function(response) {
        var result = Drupal.parseJson(response);
        if(result.status !== 1) {
          // Some code to let user know there was an error
        }
    }
})(jQuery);


Problem with drupal 7 multisite installation OS: UBUNTU 11.10

What I want to achieve:

www.example.local     Main Installation

www.example1.local    Installation inside sites folder

I took the following steps:

Installed drupal 7 as normal installation in the folder /var/www/example.

in /etc/hosts added the following:

127.0.0.1   www.example.local

127.0.0.1   www.example1.local

Then in /etc/apache2/sites-available ::

ServerName www.example.local

DocumentRoot /var/www/example

in example file.

and

ServerName www.example1.local

DocumentRoot /var/www/example/sites/www.example1.local

in www.example1.local file.

I created folder

  /var/www/example/sites/www.example1.local

and copied default.settings.php and made a settings.php from it.

Now , when I go to www.example.local I get the normal(main) installation it works fine.

But when I go to www.example1.local I see the list of files in the www.example1.local folder

What is the step I am missing?
Or did I do something wrong ? Thank you in advance.

PS: I have not made any change in settings.php of the subsite.

Documentroot is not proper for the second case.
It should be like this

ServerName www.example1.local
DocumentRoot /var/www/example


How can I do math on fields? I am trying to learn the principals required to make a Drupal 7 math/calculator module that simply takes user's inputs and does some math on them and then displays the results on the same page without a page refresh.

Drupal modules are basically PHP code, and because PHP is on the server side, you cannot do mathematical actions upon user's input without submitting your data to the server(Which will refresh your page).

The only solution to do what you want is to add some Javasciprt to do it for you.

Here is a tutorial explaining how to add JS to Drupal

https://www.drupal.org/node/756722


Unable to retrieve checkbox values from a template file I have created a checkbox option for a field.

Category

One
Two
Three
Four

This is the code I am using.

    {% for key, item in content.field_room_category if key|first != '#' %}
         <li>{{ item }}</li>
    {% endfor %}

In the <li> tag, I get all the checked values, but I also need to check which values have been selected.

For this, I tried {{ item.value }}, {{ item.content }}, and {{ item['#title'] }}. None of them worked.

Is there any way to get all the checkbox items with their values?

I want to achieve something similar to the image above. If the item is checked, I show an icon; if the item is unchecked, another icon will be shown.

Checkbox values are preprocessed so only checked ones you can get in your twig:
I think you need to preprocess your field by implementing hook_preprocess_HOOK to add unchecked ones to your variables something like:

/**
 * Implements hook_preprocess_HOOK().
 */
function MY_MODULE_preprocess_field(&$variables) {
  $element = $variables['element'];
  if ($element['#field_name'] == "field_room_category") {
    // Node object.
    $node = $element['#object'];
    // All allowed values in the field.
    $allowed_values = $node->field_room_category->getFieldDefinition()
      ->getSetting('allowed_values');

    // Checked values.
    $checked_values = array_filter($element, function ($key) {
      return is_int($key);
    }, ARRAY_FILTER_USE_KEY);

    for ($i = 0; $i < count($allowed_values); $i++) {
      // If the checkbox already checked add is_selected as true.
      if (isset($checked_values[$i])) {
        $variables['element'][$i]['is_selected'] = TRUE;
      }
      else {
        // If the checkbox not checked add the item with is_selected as false.
        $variables['element'][$i] = [
          '#markup'       => current(array_slice($allowed_values, $i-1, 1, FALSE)),
          '#allowed_tags' => [],
          'is_selected'   => FALSE,
        ];
      }
    }
  }
}

now in your twig you can do something like:

  {% for key, item in element if key|first != '#' %}

       {% if item.is_selected %}
           {{ item }}
       {% else %}
           {{ item }}
       {% endif %}

   {% endfor %}


step by step filtering drupal view hi i have a site in which i want to show items, now i want to be able to filter the items based on several paramaters (*note the parameters aren't related to one another which is why dependency filter module isnt the solution.)

what i want to do is the user can choose a value and filter the results by it, then the remaining filters and filter values would only be ones that have items remaining that fit the criteria.

an example if the items are computer screens and i have 3 attributes - color, width, company
then if a user chooses hp for company and they only have white screens then i will only see white as an option in the color filter.
if i choose dell and they have black and white then both colors will show on the filter.

is there a module that achives this affect, if not is there a way for me to do it myself (im pretty new to drupal i understand what hooks are but not to familiar with them and never developed a module).

You can use Search API with Facet API to create search pages with dynamic filters like here but you can use another modules like Ajax facets if you need checkboxes or select lists as filter widgets.

Search API needs also a database backend (Search API Database Search).


How to call external api to pull data into json format? There is an api that is used to expose data from an external website. How can I use the drupal API to call the external api and pull the data into json format?

the external api would be, for example, "api.website.com/api/get_data".

return results would be in json format "{"data":[....]}

How would I use a module to call the external api and return the data in json?

It depends on what you wish to do with said data.

If you are looking for a purely code approach, you could do something like:

$response = drupal_http_request($url);
$result = json_decode($response->data);

If you want a Rules based approach, you could could use the Rules HTTP Client module, which allows you to do essentially the same as the above code but via the Rules UI.


Build custom module with similar maintenance mode behaviour I'm building a custom module that denies access to the site based on some custom rule.

I;ve already build the module form, variables get stored, in hook_init I do my check against the variables I set on my custom module.

What I would like to do now is to have a template behaviour like the maintenance mode one.

By default it should be a blank page with Site name and message like maintenance mode(maybe overriding html.tpl.php). The default mymodule-page.tpl.php should leave in mymodule/templates/

This page can be overridden in theme folder so the user can apply its own style, logo, region etc...

function my_custom_module_menu{
  $items['my-custom-module-page'] = array(
    'title' => t('My custom module  title'),
    'page callback' => 'my_custom_module_page_callback',
    'type' => MENU_CALLBACK,
  );
}

function my_custom_module_theme($existing, $type, $theme, $path) {
  return array(
    'my_custom_module_template' => array(
      'template' => 'my-custom-module-template',
      'variables' => array('variable' => NULL),
    ),
  );
}

function my_custom_module_page_callback() {
  return theme('my_custom_module_template');
}

The code above keeps the layout of the page but I would like to override the entire page.

Which hooks should I use to achieve this?
How can I call this template from my hook_init?

Thanks in advance.

You are getting the regions being printed because your page callback is returning a string. If you want your page callback to just print your output, you need to change your code to the following one.

function my_custom_module_page_callback() {
  print theme('my_custom_module_template');
}

The reason is visible in drupal_deliver_html_page(), which uses the following code.

// Menu status constants are integers; page content is a string or array.
  if (is_int($page_callback_result)) {
    // Omissis
  }
  elseif (isset($page_callback_result)) {
    // Print anything besides a menu constant, assuming it's not NULL or
    // undefined.
    print drupal_render_page($page_callback_result);
  }

If your page callback returns NULL (which also happens when it doesn't have an explicit return statement), then drupal_render_page() will not be called. As result, just the output from your page callback will be returned to the browser.

This is what node_feed() does: It prints an RSS feed without letting Drupal output anything else. Contrary, the output would not be handled as a RSS feed from the client side.


How to add product display nid to user order view? On a typical Drupal Commerce website a user can see the following tabs on his user-page:

View
Edit
Orders
Address Book

I am trying to figure out how to get Products tab added to this list, which would list all the Products (actually Product Displays to be exact in Drupal Commerce terms) purchased by the user. It would be very much like Orders page, but instead of Order numbers this page would be outputting Product Display nids, titles, etc.

Alternatively, getting Product Display nids listed on the Orders page would suffice to my purposes, if this is easier. The order page is represented by the 'commerce_user_orders' view, but I can't figure out how to get product display nid there as there is no any product-related options. There is a "Line items" option which lists Title of the product, but doesn't link to actual Product Display page. Basically I need users to be able to go to the specific Product pages from their orders pages directly associated with the product displays.

You can use the module commerce_product_attributes to show more product details on the line item.

  Attribute field for line item: This field allows the presentation of
  the product in the shopping cart by a separated view mode. A new
  product display is added. There you can define the fields which should
  be displayed for this product type in the shopping cart.

While it can be used on the shopping cart, it can also be used on the Orders view.


When viewing a user, display their content profile When I go to /user/uid I want it to go to /content/content-profileID by default. This is a node typer that is used by content profile.

How can I go about doing this?

function MYMODULE_user($op, &$edit, &$account, $category = NULL) {
  switch ($op) {
    case 'view':
      profile_load_profile($account);
      // Now $account will contains all profile data;
      // some code
      break;
    }
  }
}


Commerce 2.0: How can multiple email addresses receive copies of orders? If I understand the configuration correctly, only one email address can be specified when defining a Store (the text under the field says "Store email notifications are sent from this address".

When a person places an order, they will receive an email confirmation showing as being sent from that Store owner's email address. No one else - not even the store owner - gets an email copy of the order.

I am converting a client's website from Wordpress to Drupal 8. Their current configuration is that four different people in the office all receive email copies whenever an order is placed. How can the same be implemented in Commerce 2.0? (They don't want to log into the site and check the database for new orders - they want the email notifications sent to them if and when orders are actually placed.)

Has anyone already implemented something similar?

Their current configuration is that four different people in the office all receive email copies whenever an order is placed.

See our documentation for order receipt emails: https://docs.drupalcommerce.org/commerce2/user-guide/orders/customer-emails

I think you'll be fine adding those four emails separated by commas.

EDIT: Also see our docs for setting up HTML emails https://docs.drupalcommerce.org/commerce2/developer-guide/core/html-emails


#states and #ajax are not working on pop up I need to get form only with HTML. To do this, I've used delivery callback in hook_menu(). This is my sample code:

function test_menu() {
  $items['htmlform'] = array(
   'access callback'  => TRUE,
   'page callback'    => 'test_htmlform'
   'delivery callback' => 'delivery_text_plain',
   'type'             => MENU_CALLBACK,
 );
  return $items;
}

In this form, I've used #states and #ajax.

I've another form which is in the normal callback. I need to show htmlform into this Drupal form. So I've written a ajax callback to 'htmlform', get html, paste it into the drupal form & show this in pop up.

This is my ajax callback:

$.ajax({
    url: '/htmlform',
    success: function(data) {
      $('#formpopup').empty();
      $('#formpopup').html(data);
      $("#form_demo_pup").modal({backdrop: 'static',keyboard: false});
      Drupal.attachBehaviors($('#form_demo_pup'));
    }
  });

Now the drupal form page have all the CSS and JavaScript but the pop up (htmlform) have only the HTML.

On this pop-up, #states and #ajax are not working since it has no Drupal form JavaScript.

How do I fix this? Even I tried "Drupal.attachBehaviors" in my custom ajax.

You need to load the required JS on page load, not on Ajax load. You will need to load the Drupal.ajax library as well.


PHPUnit calling external function as object I'm doing a unit testing with my CVRClient file using the code below.

//CvrapiTest.php

<?php

namespace Drupal\cvr\test\Cvrapi;

use PHPUnit_Framework_TestCase;
use cvr\src\Cvrapi\CVRClient;

class CvrapiTest extends PHPUnit_Framework_TestCase {

public function testSearchOnlyVAT()
    {
        $result = \Cvrapi\CVRClient::request('29910251', 'dk', 'vat', 'Unit Testing');

        $this->assertTrue(property_exists($result, 'vat'));
        $this->assertTrue((int)$result->vat === 29910251);
    }

I have a CVRClient class under cvr/src/Cvrapi folder that queries data from an api.

I know that phpunit command is working fine but I'm getting the error below.

  Fatal error: Class 'cvr\src\Cvrapi\CVRClient' not found in
  /Applications/MAMP/htdocs/query/modules/custom/cvr/test/Cvrapi/CvrapiTest.php
  on line 17

NOTE: It's the \Cvrapi\CVRClient:: that causes the error. If I remove this line, I need to have a code to assign values to $result.

The problem is that your use declaration is incorrect, and is causing your call to the client to look in the wrong namespace. You probably need to change this:

use cvr\src\Cvrapi\CVRClient;

To this:

use Cvrapi\CVRClient;

And change this:

$result = \Cvrapi\CVRClient::request('29910251', 'dk', 'vat', 'Unit Testing');

To this:

$result = CVRClient::request('29910251', 'dk', 'vat', 'Unit Testing');


Node Update Problem on hook Cron I am trying to update a node in a hook_cron() function. I am using Drupal 6.
Here is my code:
function offers_cron() {
  $query= db_query("SELECT * FROM {node} WHERE type = 'product'");
  while($allnodes = db_fetch_object($query)){
    $node_id=$allnodes->nid;
    $node=node_load($node_id);

    $node = new stdClass();
    $node->nid = $node_id;

    $node->type = 'product';
    $node->language = 'en';
    $node->uid=1;
    $node->status = 1;
    $node->created = time();
    $node->changed = $node->created;
    $node->comment=0;
    $node->promote = 0;
    $node->sticky = 0;
    $node->format = 2;
    $node->title='test';
    $node->field_price[0]['value']='120';

    if ($node = node_submit($node)) {
      node_save($node);
      drupal_set_message(t("Node ".$node->title." added correctly"));
    } else {
      drupal_set_message(t("Node ".$node->title." added incorrectly"), "error");
    }
  }
}

Now it shows it has updated all nodes. Here is screen shot for this :

Now when I click any node the update does not show.
Please take a look:

Does anybody have any ideas about this?
I have even tried clearing the cache.
Thanks

I got the solution: If the node doesn't change, don't create a new revision.


Webform - Multilingual Support I have a webform which is built in English. I need to add two more languages. Is that possible to display many languages in webform?

Take a look at Webform Localization module

  The Webform Localization module provides multilingual features to the Webform Module. Special options in the webform and component configuration let you enable different ways to manage translation of forms and questionnaires.


Get data from a field using query in Computed field and use it as an array I have a content type wherein the user will add holidays.

It has Holiday Date field(field_holiday_date).

How can I get the dates in that column using query and use it as an array in Computed field?

Thanks for you help!

You can pass any value of node or something else in jquery like

$node_id = 5;
$node = node_load($node_id);
$settings = array(
    'title' => $node->title,
    'custom-data' => 'ABC',
);
drupal_add_js(array('mymodule' => $settings), 'setting');
drupal_add_js(drupal_get_path('module', 'mymodule') . '/js/mymodule.js', 'file');

And get that value in jquery like (you have to put this code in mymodule.js)

(function($) {
        Drupal.behaviors.mymodule = {
            attach: function(context, settings) {
                var title = Drupal.settings.mymodule.title;
                console.log(title); // or perform some operation as you prefer
                var custom_data = Drupal.settings.mymodule.custom-data;
                console.log(custom_data );
            }
        };
    }(jQuery));


Display form errors on each field instead of at the top of the page using form_set_error I use form_set_error to set the error text after validation fields (email, phone, etc.). The validation error messages are show at the top of the page. This also happens with errors for required fields that are not explicitly set with form_set_error.

How can I make them appear under their relevant fields.

Note: I'm not using the Webforms module, but rather the Forms API. I'm on Drupal 7.

You can use the Inline Form Errors module for that

  IFE or Inline Form Errors allows you to place form submission error inline with the form elements. Three options are provided for setting your inline error behaviour. You can configure the default behaviour or override the behaviour on a per form basis. You can add as many forms as you like.

Or alternatively the Inline Messages module:

  The Inline Messages module allows you to move form messages (error/status/warning) from the top of the page to just above where your form appears.

The former would appear to be the more actively maintained of the two.


How do I debug a CKEditor installation on Drupal 7? I installed the the CKEditor module in Drupal 7.  I've also installed the CKEditor JavaScript library from the website CKEditor. However, no matter what I do, the editor don't show up as it is supposed to.

Here are, roughly in the order you should try them, some tips that may help you debugging a CKEditor configuration.

1. Clear the cache

Remember to clear the cache after you've changed any setting that has something to do with wysiwyg.  Not clearing the cache is probably the most common source for CKEditor not showing up as you would expect.

2. Check out that roles are configured correctly

Navigate to your text formats: Administration » Configuration » Content authoring  » Text formats and ensure the roles are configured correctly.

Add the roles you want to use wysiwyg to Filtered HTML and Full HTML.

3. Check out that profiles are set up right

Navigate to your ckeditor profiles: Home » Administration » Configuration » Content authoring » CKeditor

Go to the profiles, and verify that the text formats for the profile are set, and the editor appearance is set properly.

Under Basic Setup, check the text formats that apply
Under Editor Appearance, set default state to enabled, and show the toggle.

4. Check the paths

Navigate to Administration » Configuration » Content authoring  » CKeditor » Global settings. press Edit, and check that all the paths listed there actually exists.

5. Check the default text processing option

Make sure that you've selected "Filtered text" as your default text processing option.  To change this, navigate to Administration » Structure » Content types, select the content you experience problems with and click manage fields and edit  on the body field (and other text fields you want to use the wysywyg editor). Make sure that the preset text format for that text field is set to to one of the formats configured for wysywyg (e.g. Filtered HTML).

To make sure that Filtered HTML is selectable, you need to make sure that the setting for "Text processing" is set to Filtered text (not Plain text):

Press Save settings after changing this.

Make sure that when you create content, a text format that is set up to use use WYSYWYG (e.g. Filtered HTML) is selected.  The screen dump below shows how the pull-down menu immediately below the text field for content should look like:


Add css to theme function I'm declaring, on my module, a custom theme function:

<?php
function monitor_chart_theme() {
  return array(
    'chart_monitor' => array(
      'template' => 'monitor_chart',
      'variables' => array(
        'container' => null,
        'theme' => null,
        'classes' => null,
        'chart' => null,
      ),
    ),
  );
}
?>

On my tpl I would like to add additional classes that I want to pass when I call the function.
Now I've declared a preprocess functions like this:

<?php
function monitor_chart_preprocess_chart_monitor(&$vars) {
  if ($vars['classes']) {
    foreach ($vars['classes'] as $class) {
      $vars['classes_array'][] = $class;
    }
  }
}
?>

My tpl is this:

<div id="<?php print $container; ?>" class="<?php print $classes; ?>">

If I don't use the preprocess function, "class" attribute of the div has value "chart-monitor", the name of the theme function.

Is there a more elegant way to pass extra variables to my tpl?

Thanks a lot.

Yes, arguments can be passed when calling the theme function:

$tpl_data = array(
    'data1' => $data1,
    'data2' => $data2,
);

return theme('my_theme', $tpl_data);

Then in the template $data1 and $data2 will be available.

To add a variable passed here to the default drupal class variable in the template we could add the line:

$class .= " $data1";

before the $class variable is printed.

However I think it's questionable  whether or not this method is preferable to your original.


How can I save and exit from the middle of editing an already completed multipage webform submission? I've got a multipage webform I'm letting users edit after they submit. There are many pages, and I don't want to force the user to go all the way to the last page to save. Is there a way to submit/save the form either with a Save Draft button, or when they use the prev/next buttons? Or is there a way to programmatically save the edited form ? That would also work.
This question is about editing a completed submission, not creating a new submission.
I've tried adding the submit button to every page, but it seems to function like a next button. If I set rebuild to false, the I can exit the edit process where I want, but the changes are not saved.
I've also tried manually adding a save draft button copied from the webform submission form, but that also did not work, failing the way the submit button did.

I was able to get this to work like so:
In a form alter, make the Submit button visible, and change the name.
   if (stristr($form_id, 'edit_form') !== FALSE) {
    $form["actions"]["submit"]['#value'] = t('Save & Exit');
    $form["actions"]["submit"]["#access"] = TRUE;
    $form["actions"]["submit"]["#_webform_access"] = TRUE;
    // Add a custom submit function so we can redirect the edit form.
    $form['actions']['submit']['#submit'][] = 'mymodule_webform_submission_form_submit';
    $form['actions']['submit']['#validate'][] = 'mymodule_webform_submission_form_validate';

  }

Next, in the custom validation function:
  // If this is the edit form, and the submit button is the trigger, always
  // do the final submit by setting the current wizard page to the confirmation
  // page.
  $trigger = $form_state->getTriggeringElement();
  if ($trigger["#id"] == 'edit-actions-submit' &&
    stristr($form['form_id']['#value'], 'edit_form') !== FALSE) {
    $form_state->set('current_page', 'webform_confirmation');
  };

Finally, in the custom submit function:
$build = $form_state->getBuildInfo();
$callback_object = $build['callback_object'];
$entity = $callback_object->getEntity();
$source = $entity->getSourceEntity();
if (!is_null($source)) {
  $nid = $entity->getSourceEntity()->id();
  $form_state->setRedirect('entity.node.canonical', ['node' => $nid]);
  $form_state->setRebuild(FALSE);
  \Drupal::messenger()->addStatus("Your work has been saved.");
}

While this answers my question, it leaves me having to deal with potential errors from conditionally required fields affected by whatever changes the user is trying to save.


How to customize download filename? Drupal version: 7.14

Currently drupal save the downloaded filename as the last part of the URL, just like a file link "http://example.com/system/files/abc.txt", the default saved filename is "abc.txt".

I want to ask is how to change "abc.txt" to other filename such as "xyz.txt" while downloading.

For this issue there's a prerequisite,that is, your download method must be 'private', otherwise there's no chance for drupal to call your 'hook_file_download', it's important!

Here's an example from drupal's file module, change $file->filename to what you want, then return to HTTP headers.

/**
 * Implements hook_file_download().
 *
 * This function takes an extra parameter $field_type so that it may
 * be re-used by other File-like modules, such as Image.
 */

  function file_file_download($uri, $field_type = 'file') {
     global $user;
     // Get the file record based on the URI. If not in the database just return.
     $files = file_load_multiple(array(), array('uri' => $uri));
     if (count($files)) {
         foreach ($files as $item) {
         // Since some database servers sometimes use a case-insensitive comparison
         // by default, double check that the filename is an exact match.
         if ($item->uri === $uri) {
             $file = $item;
             break;
         }
      }
   }
   if (!isset($file)) {
     return;
   }

  //...........................other codes.........................

  // Access specifically denied.
   if ($denied) {
     return -1;
   }

  // Access is granted.
   $headers = file_get_content_headers($file);
   return $headers;
  }


Does the Search API module integrate with the standard search? I have Profile2 installed and want to be able to search on Profile2 fields that I have created. Does the Search API module integrate into the default Drupal search, which would therefore when configured, find Profile2 field values and the associated user?

If not, is there another approach I can use to include the Profile2 fields into Drupal standard search?

Search API and core search do not integrate. Just use Search API and scrap core search (Core Search does not work on Profiles as entities See http://drupal.org/node/1369544). The Search API can search on an entity known to Drupal. Profile2 creates profiles as entities. Therefore Search API can search Profiles. When adding a new index to Search API, just choose "Profile" or "Profile Types" under "Item Type".


How can my module add xml sitemap entries? I have a module with a page callback handler for the path "products". So if the user navigates to products/apples then the module presents a page about our apples, and if they go to products/oranges then etc. These pages include detail about the various products.

I would like XML Sitemap to be populated from my module. After all, it's my module that knows what products exist, their descriptions etc.

Any hook or anything I can use for that?

The base function you call is xmlsitemap_link_save.

I am unaware of any docs on how to use this, but nodes get added to the sitemap via xmlsitemap_node_nodeapi which in turn calls xmlsitemap_node_create_link.  The code for that should provide some guidance on how to build $link.


How do I add tabledrag with 'weight' to admin form I have built a fairly basic module but i'm struggling with the UX of the admin form. Essentially I need a list of items that have several values; a textfield, checkbox, select list and a button to delete them.

I've built all of the functionality (including the "add one more" using the example in the drupal ajax examples module) and its working great, except now I need to be able to reorder the items and the webmin style up/down buttons are not good UX. I've been hacking to no avail at numerous examples like:
http://www.urbaninsight.com/2012/09/11/creating-table-with-draggable-weights-in-drupal-7

It doesn't appear that theme_hook_form is being called so I can't inject the weight javascript, styles or markup.

I added this to the .module file:

function module_cache_theme() {
  dpm("themehook");
  return array(
    'theme_module_settings_form' => array(
      'file' => 'module_form.inc',
      'arguments' => array('form' => NULL),
    ),
  );
}

The menu item is in the hook_menu:

  $items['admin/config/development/module'] = array(
    'title' => 'module',
    'description' =>'',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('module_settings_form'),
    'access arguments' => array('administer site configuration'),
    'file' => 'module_form.inc',
  );

When the cache is regenerated I get a dpm message but the method theme_module_settings_form is never being triggered.

Ideas?

At the risk of oversimplifying, have you tried using or integrating Draggable Views?

If the items you are sorting are nodes (I'm not clear on this) it is a great option for achieving drag-and-drop sorting as you can assign as many fields to an entity as you'd like and set different sort priorities depending on the circumstances.  That as apposed to 'weight' which is a one size fits all number.


What might be causing my problem to access user variables in Rules? I use the module Rules link event to trigger a rule based on visited path. The problem I have that in condition I need to use user variables but get an error - variable user is not defined. If I try php condition and use global $user, I get Notice: Trying to get property of non-object in eval() and Warning: in_array() expects parameter 2 to be array, null given in eval()

What could be the problem here?

Not sure what the reason might be that is causing your problem. But something that you could do to make this work, for sure, is like so:

Add a Rules Action "Fetch entity by id", whereas you want to fetch the user entity, and where you use the uid of the "current-user". For any subsequent Rules Action, you then have all fields of that user available as tokens.
Enable the Conditional Rules module, which allows you to specify Rules Conditions as part of Rules Actions. Using that technique, you can then like "move" any of your existing Rules Conditions (ie the ones where you need those user variables, as per your question). In doing so, you can then use any of the tokens that you made avaiable via the preceeding Rules Action "Entity has field".

BTW, no dangerous PHP code (stored in your database) needed to get this to work ...

Easy, no?


Custom template file field output I have a Netrunner Card content type. (It's a card game I play.) I have a "field_card" field that holds the card image.
In the node--netrunner-card--Runner_Identity_Card--full.tpl.php file, I am trying to control the output of each field. Instead, I seem to just be dumping the same fields on the screen.

I tried using the following code.

<img src="<?php print render($content['field_card'])?>" />

It scattered the HTML, because the output of render() is the HTML.
What is the standard practice for doing what I am trying to do?

I'm trying to theme the output of each card to make it look like I want it to be, and to learn the theming engine for Drupal.

Typically, to control the output of your field you'd just print out all your fields in your template files by doing precisely what you have up there:

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

You can have as much html in your template file in addition to these rendered fields and then style them with css!  So you can have

  <?php print render($content['field_1']); ?>
  <?php print render($content['field_2']); ?>

And then theme this with css using any of the ids and classes you get and whatever the fields themselves render.

If you really need to modify the field's output more precisely and the standard output from print render doesn't work for you, you could certainly look into the field structure itself and grab the individual field parts you need.  I'd only do this if you absolutely need to...

To start peering into the exact structure of the fields, I'd

Install and enable the devel module... You can just enable the 'Devel' module that comes with it for this purpose
In your template file, put a

<?php dsm($content['your_field']); ?>

statement somewhere.  That function is only available if you have the devel module enabled, and it will print out the field array for you to inspect in detail.  Here is an example of the dsm output:

Once you can look into the structure of that array, you can take any pieces of the field you need, if you don't want to render it in the default way.

So, you can do something like getting only the uri of your image...

<img src="<?php print $content['field_image'][0]['#item']['uri']; ?>" >

Anyway, hope this helps!


How to slow down migrate? Cloud Files can't keep up I'm using migrate to import 2800 blog posts. Each have a header image which is getting imported. I'm using Rackspace Cloud Files as my CDN so the system is copying the image files up to Rackspace Cloud Files, but after it's been running for awhile I start getting this error:

  (/home/drupal/html/sites/all/libraries/rackspace/php-cloudfiles/cloudfiles.php:608)
  Invalid response: (curl error: 35) error:02001018:system
  library:fopen:Too many open files: Failed  [error] to obtain valid
  HTTP response.

My -guess- is that the migrate is working too quickly and the file transfers are happening in parallel or something and I'm hitting a limit on the number of open files for Rackspace. I'm not exactly sure.

I'd like to try adding a delay in between each node. There are only 2800 and I can let it run for a little while, so I don't mind the delay as long as it'll let me complete the migrate.

In your migration scripts you can use either prepare() or complete() (http://drupal.org/node/1132582) and add in sleep(). It's a hacky solution but it should give you enough time between processing each row for Rackspace to catch up.

public function prepare($node, stdClass $row) {
  sleep(30); //wait for 30 seconds
}


Filter view list items by user property and item property I have a view where I want to output a list of content node teasers. At the moment all content nodes are used, but I want to filter the output to only contain nodes that have a certain value in a taxonomy field property they have, check if the current user has a certain role that is similar to the property and only then show them in the output.

So far I've tried to programmatically filter the output in the hook mytheme_preprocess_views_view_unformatted of my theme with the following code

function mytheme_preprocess_views_view_unformatted(&$variables) {
    $result = $variables['view']->result;
    $entity = $result->entity;
}

but that crashes the site and doesn't give me the results to filter.

Is there a way to filter the content nodes programmatically or view the view settings and if so how?

I think I understand what you're describing, and it is theoretically possible to handle in the hook as you've started, with something like this:

/**
 * Implements hook_preprocess_views_view_unformatted().
 */
function mymodule_preprocess_views_view_unformatted(&$variables) {
  if (isset($variables['view'])) {
    $view = $variables['view'];
    // You'll want to check the ID && possibly the current_display so as not to fire on every View!
    // In this example, my View is called "test", and I have a page display called "page_1".
    if ($view->id() == "test" && $view->current_display == "page_1") {
      $result = $view->result;
      // You mentioned doing something regarding the user, so you could grab that here.
      $current_user = $variables['user']->account;
      // The $result will be an array of ResultRow entities.
      foreach ($result as $key => $resultRowEntity) {
        // Do some customized logic on each row.
        // You can access the entire entity here if needed like this:
        $row_entity = $resultRowEntity->_entity;
        // In my case this is a Node, so can do something to get a term field from it.
        // In this example, getting the "some_field" and the first delta of it as a string value.
        $some_field_on_the_node = $row_entity->get('field_some_field')->getValue();
        // You could do some sort of logic here to determine whether or not to unset this row.
        // In this example, I'll say if the field doesn't equal 2, OR the user ID is not equal to 1, unset the row.
        // This would remove it from the result.
        if ($some_field_on_the_node != "2" || $current_user->uid != 1) {
          // You'll want to unset it from 'rows' to not display it.
          unset($variables['rows'][$key]);
        }
      }
    }
  }
}

I think the takeaway is to use "isset" to avoid those nasty PHP errors, and I highly recommend using XDebug, or at the least the devel && kint modules, so that in your code, you can put things like ksm($variables['view']) to get some insight into what variables you have available to use. PHP can be very finicky when you try and reference things that don't exist!

Even though this might technically work, it's worth noting that a better approach would be to implement a relationship in Views to bring in the taxonomy term entity being referenced on your node, and that would allow you to add View filters in the UI to massage out the data that way. You could also add a role that could be associated with viewing your particular content type, and this would automatically exclude it from Views results regarding the user if they didn't have this role.

Of course, I may me misunderstanding the complexity of your use case. Another "better practice" approach would be to implement a custom Views filter, which could then be added via the Views UI and maintained separately in a custom module, and would possibly allow for a cleaner implementation - It's somewhat of a broad topic, but I think this is a great intro to the topic: https://www.webomelette.com/creating-custom-views-filter-drupal-8.

I hope this helps point you in the right direction!


Want to display the validation error message above the webform I have a webform created in Drupal 8 using the webform module I have to submit the data to 2 different 3rd party API.

The scenario is I have to submit the data to the 1st API if there is no error response found then submit the data to 2nd API so now I have created a submit handler and attached the handler to the webform. Now the issue is when I got an error response message while submitting the data to 1st API and showing the  message using drupal_set_message() function everything is working fine but the form validation js not loading at this point.

The used code is like the below:

drupal_set_message(t($msg), 'error');
$form_state->setRebuild(true);

can anybody help me with this?

you can put the validation messages above the webform by -

1.put the generic element above the form

messages:
  '#type': status_messages

2.make sure the webform's status messages purge all messages using the below hook in a CUSTOM_MODULE

function CUSTOM_MODULE_webform_element_alter(array &$element, \Drupal\Core\Form\FormStateInterface $form_state, array $context) {
  if (isset($element['#type']) && $element['#type'] === 'status_messages') {
    $element['#pre_render'][] = 'CUSTOM_MODULE_webform_element_status_messages_pre_render';
  }
}

/**
 * Pre render callback to display status messages element.
 */
function CUSTOM_MODULE_webform_element_status_messages_pre_render($element) {
  // Replace the status messages placeholder with the rendered messages.
  // Calling drupal_get_messages(NULL, TRUE) will purge all messages, which
  // prevent the messages block from being displayed.
  // @see \Drupal\Core\Render\Element\StatusMessages
  // @see drupal_get_messages()
  $element = [
    '#theme' => 'status_messages',
    '#message_list' => drupal_get_messages(NULL, TRUE),
    '#status_headings' => [
      'status' => t('Status message'),
      'error' => t('Error message'),
      'warning' => t('Warning message'),
    ],
  ];
  return $element;
}


How to move drupal into a subdirectory so non-drupal content works in the original folder? I have a D7 site and then a lot of other non-drupal stuff I would like to keep in my joe/ folder on our server as joe/thing1/ joe/thing2/ etc. Right now, my folder joe/ just has the drupal installation and my other stuff is not deployed. I would like to move drupal into a subdirectory, but still have http://website/joe/ work as my original drupal site with clean urls, etc. Then I would like to be able to deploy my other stuff into http://website/joe/thing1, http://website/joe/thing2 etc.

How can I build an .htaccess file to serve drupal from a subdirectory unless a url points to an existing file? Or is that the correct way to go about this?

If your non-drupal files are just a few and are static content (just plain HTML files or similar) you can create symbolic links in the root Drupal foolder that point to your non-drupal files.

Webserver (Apache at least) will serve those files if the URL points to them, instead of call index.php with the URL rewriten into params.

This way if you accidentally delete root Drupal directory (for example, using an automatic core update) you only have to put the simbolic links again, not all your non-drupal files.


Force the usage of path aliases The title is explaining what I'm trying, my question is: Am I doing it right?

function hook_entity_view($entity, $type) {
    if (arg(0)=='node') {
        drupal_goto($entity->type.'/'.$entity->nid);
    }
}

My aliases look like this: article/123

article is the entity type.
123 is the node ID.

When I go to ../node/123 than I get a 503.

Looks like you are creating loop redirection. But that you can test by examining logs. I believe there is an easier way: already implemented Global Redirect module:

  This module uses hook_init to interrupt the page load and action the alias lookups. If any of the above rules apply then the appropriate action is taken. If no rules apply then the page load continues uninterrupted. An example of this in use is on the site it was developed for. http://www.sportbusiness.com/node/160559 will redirect to http://www.sportbusiness.com/news/160559/lagardere-sets-up-sports-division due to the alias setup on this site.


Print a list of checked form options in TWIG I need to print out a list of checked form options in a TWIG template in Drupal 8.

I'm using Better Exposed Filters, and editing the views-exposed-form.html.twig template.

Iterate over the form options, returning the # value of each item:

{% for choice in form.filter['#value'] %}

Then Print out the title value of each one of those options:

{{ form.filter[choice]['#title'] }}

All together it looks like this:

{% for choice in form.filter['#value'] %} {# Find each checked option #}
  {{ form.filter[choice]['#title'] }} {# Print the Title #}
{% endfor %}


Free Shipping for selected products in Drupal Commerce I'm trying to set up a rule to allow free shipping for selected products. I'd like to use a boolean field with a checkbox for free shipping. If the box is ticked the product should be excluded from any postage calculations during the checkout.

I'm using the commerce and commerce shipping module.

Any help would be greatly appreciated!

I definitely think you should give Commerce Discount a try for this, it provides a Free Shipping offer type when commerce shipping is present and thanks to Inline Conditions, you can filter for the products you might want.


Error messages aren't displayed when submitting the form I want to display an error message when I submit a form. I added an AJAX callback to the form, and the error message appears after I refreshed the page.

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

$response = new \Drupal\Core\Ajax\AjaxResponse();
$message = drupal_get_messages();
$output = $response->addCommand(new \Drupal\Core\Ajax\PrependCommand(".region-highlighted",$message));
return $output;

I also tried the following code.

$status_messages = array('#type' => 'status_messages');
$text = \Drupal::service('renderer')->render($status_messages);
return $text;

this works for form messages (in a regular ajax form callback):

    $form['status_messages'] = [
      '#type' => 'status_messages',
      '#weight' => -10,
    ];
    $response->addCommand(new ReplaceCommand('#yourFormWrapperElement', $form));

but using drupal_get_messages() screw's things somehow up .... sometimes. plus you need enable showing messages here: /admin/config/development/logging

So - your second try should also work !

$status_messages = array('#type' => 'status_messages');
$text = \Drupal::service('renderer')->render($status_messages);
return $text;

Maybe the mentioned settings are needed ..


Is it Inethical/Bad Practise to create a custom table and save content instead of using drupal fields? I was going through the Drupal 8 and find that it offers a lot in terms of structural data. There are many modules that use this structure data to execute very important web tasks.
Like
Search engine optimization,
Feeds,
API etc.

As a developer for a quick fix, we often create some content and save it on a custom table using a custom module, instead of putting content into Drupal structure as node field. Though this will solve our problem for short span of time quickly.

So is it something we should never do in case of Drupal?

Not at all. It's up to the developer and the needs of the site. Setting up a field to tie in  with the Field UI has a lot of benefits - it makes the field reusable on different entities, and allows it to be altered and manipulated as necessary. But it also adds a lot of overhead, and if you have to code your own fields, it adds time. If you know your data is to only be used for a single-case situation, then often it can be better to set up your own table and APIs in order to make the code more lightweight, and quicker to develop.

It's a case-by-case situation really.


How can I change the css classes on a menu's ul when it is placed in a particular region? Drupal 7: I am struggling to figure out a way to change the menu structure that is printed when I place a menu block in a particular region.

What I want to do is change the classes on the ul when the menu is printed to a sidebar.

Everything I can find, and attempt will change the structure for all menus, but I need to print them differently depending where I put the menu.

Also, I need it to work for any menu I place in the region if possible. I will be creating menus for different areas of the site, and I hope I can get this to work based on the region that the menu is placed in.

Thank you

You don't need to change or add new classes because each region has already a class. You need to specifically reference each menu class () in your stylesheet by adding first your region class name:

#region-menu ul.menu li {display: inline...}

#region-sidebar-first ul.menu li {display: block...}

etc...

so check you won't interfere.

Make sure the main menu has a unique reference as #region-menu to avoid inheritance.


Drush command from contrib module not recognized I have installed a new module called S3fs using Composer. When I try to execute /root/.composer/vendor/bin/drush drush_s3fs_copy_local, it shows the following error.

  Command "drush_s3fs_copy_local" is not defined

I found out that I could not run any command from third-party modules I installed and enabled.

Please help me.

drush_s3fs_copy_local is the name of the PHP callback function for the command; the command itself is named s3fs-copy-local, with an alias of s3fs-cl.

So:

drush s3fs-cl

Is what you're looking for.


Manually sort Views output Is it possible to manually sort items from Views? I want to be able to define which content goes first and which one's last.

DraggableViews was designed for just this purpose.


Change markup of single form field I have constructed a form manually using the Form API. I have one field in particular that needs to have it's markup changed a tad.

The #prefix/#suffix output should come immediately before/after the input control. I think the output currently looks like:

Can I override the themeing for a single field using something like:

$form['control'] = array(
  '#theme' => 'control_field',
  '#title' => 'Some title',
  '#type' => 'textfield'
);

Do I then implement MYTHEME_custom_theme in the templates.php???

Do you know of any exmaples I might use?

I tried adding:

function theme_control_field($variables) {

}

This did not seem to work...also I need control over all the markup for this field not just the field control but I need to relocate the prefix/suffix output as well!?!

Regards,
Alex

You can have a complete custom HTML for a particular field by defining a #theme and setting #theme_wrappers with an empty value.

$form['control'] = array(
  '#title' => 'Some title',
  '#type' => 'textfield'
  '#theme' => 'YOURMODULE_control_field',
  '#theme_wrappers => array(),
);

Then Drupal needs to know about this new theme by implementing the HOOK_theme. You can either work with a template file or generate the HTML within the theme callback function

function YOURMODULE_theme()
{
    return array(
        'YOURMODULE_control_field' => array(
            'template' => 'templates/control-field', // if you want to have a tpl file, templates/control-field.tpl.php using the $element variable for your textfield element
            'render element' => 'element',
        ),
    );
}

// If you dont want to use the template file
function theme_YOURMODULE_control_field($variables)
{
    $element = $variables['element'];
    // $element is here your form textfield element, this function return HTML to generate
}


What is the encoding for JSON:API operators? I'm trying to filter JSON:API results based on the "greater than" operator (>).
The filtering documentation lists the operators:
\Drupal\jsonapi\Query\EntityCondition::$allowedOperators = [
  '=', '<>',
  '>', '>=', '<', '<=',
  'STARTS_WITH', 'CONTAINS', 'ENDS_WITH',
  'IN', 'NOT IN',
  'BETWEEN', 'NOT BETWEEN',
  'IS NULL', 'IS NOT NULL',
];

But it also notes that the symbol operators need to be encoded:
&filter[a-label][condition][operator]=%3D  <- encoded "=" symbol

Which "encoding" is this referring to? What is the encoding for the other operators (>, >=, etc.)?  How do I look them up?

Thanks to Hudri, here's the list:

= %3D
<> %3C%3E
> %3E
>= %3E%3D
< %3C
<= %3C%3D


Command to install Drupal 9 with Composer The latest version of Drupal 8 can be installed via Composer with the following command:

composer create-project drupal/recommended-project mynewproject

What is the equivalent command to install the latest version of Drupal 9 (beta1)?

create-project can take a version number, and recommended-project has some tags in for 9.x, so for example:

composer create-project drupal/recommended-project mynewproject "9.0-beta1"

Or if you just want the bleeding edge to play with:

composer create-project drupal/recommended-project mynewproject "^9.0" --stability=dev --prefer-dist


How to set an exposed filter to enable current user to view nodes that he has not commented On my D7 site I am trying to create an exposed filter where current users would choose whether he wants to see all nodes, or only those that current users have not commented. Tried adding 'Comment: Comments of the node' and 'Comment: Author' relationships, 'Comment: Author uid' contextual filter. I didn't want to set a  default value because I want users to switch between all nodes and ones commented by current user. Then I added a filter criteria 'Comment: Author uid' with setting up grouped filter using [current-user:uid] token. No success yet.

As I understand it, this is impossible with just the views module by itself.

You can easily filter for nodes that the user has commented on, but filtering for nodes the user hasn't commented on is difficult for reasons I'll go into later, so you're going to have to install additional modules or write your own code.

First of all, to get the nodes the user has commented on, you've already added the correct relationships ("Comment: Comments of the node" and "Comment: Author"). However, the filter you actually need to use is "User: Current" with your author relationship selected and the option "Is the logged in user: Yes". You probably also want to use the "Distinct" option in the view's "Query Settings", otherwise you'll get duplicate rows if the user has commented multiple times on the same node.

Now, the reason you can't easily get the nodes the user hasn't commented on is because you can't just change the filter option to "Is the logged in user: No".

Why not?

Because that will go through every comment on the node, and if any of the comments are not authored by the current user, the node will be included in the results, even if it has other comments that were authored by the current user.

So, what you'd actually need to be able to do is take the list of nodes which the current user has commented on, and then exclude them from the results of the view, which simply can't be done in the standard views UI.

Without writing your own module to modify this behaviour, the best option seems to be the OtherView Filter module.

With that module, you can create a second view of nodes, which excludes the results of the first view I described above, using a "Content: Other view result" filter. For usability you'd probably want to set this up as a grouped filter to avoid having the operator and view names exposed to the user.


Why Isn't #value valid for 'textfield' form types in Drupal 7? I can set #default_value but there is no #value for text fields?

http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/7#textfield

Is there a work around?

Form API is an abstraction over regular HTML form elements, so there are cases where attributes don't match up exactly.

In the context of Form API, #value is for values you don't want the user changing, and doesn't make sense with respect to text <input> controls.

Instead, you want to use #default_value, which is for values you do want the user to change. That is:

$form['mytextfield'] = array(
   'type' => 'textfield',
   '#default_value' => 'Foo',
);

is the same as:

<input type="text" value="Foo" />

If you want to mimic the behavior of Form API's #value (i.e. provide a default value and prevent the user from changing it), use the #disabled property:

$form['mytextfield'] = array(
   'type' => 'textfield',
   '#default_value' => 'Foo',
   '#disabled' => TRUE,
);

For more information about the internals, check out form_builder(), which constructs the render array for the form and _form_builder_handle_input_element(), which replaces #value with the value of #default_value prior to rendering.


Unwanted  tags inserted before and after a rendered $item First time creating a custom template for a field.

I've created the field--field_phone_number.tpl.php and know it's working.

I'm trying to make it so when a user enters a phone number, it displays as a link with the "tel:" prefix so that readers can click the link on their mobile phones to call directly.

Here's what I have:

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item): ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><a href="tel:<?php print render($item); ?>"><?php print render($item); ?>

    <?php endforeach; ?>

Only problem is that it actually prints out something like

3035551212

Where are those
 tags coming from?

I see many posts around about those tags coming from WYSIWYG editors and the like, but I'm not using one of those. I've also seen a suggestion that this is related to a default line-break converter, which I'd rather not turn off.

There can be some better solution of this question but as you are facing of this extra html tag issue inside href, here is solution for this.

<div class="<?php print $classes; ?>"<?php print $attributes; ?>>
  <?php if (!$label_hidden): ?>
    <div class="field-label"<?php print $title_attributes; ?>><?php print $label ?>:&nbsp;

  <?php endif; ?>
  <div class="field-items"<?php print $content_attributes; ?>>
    <?php foreach ($items as $delta => $item):
    $phone_link_data = render($item);
    $phone_link = strip_tags(html_entity_decode($phone_link_data));
    ?>
      <div class="field-item <?php print $delta % 2 ? 'odd' : 'even'; ?>"<?php print $item_attributes[$delta]; ?>><a href="tel:<?php print $phone_link; ?>"><?php print render($item); ?>

    <?php endforeach; ?>


Drupal for Facebook logout problem I can connect through this module, but i can't logout. I don't know how, but it doesn't clear the cache or something else. It still remembers my account details and relogin me again everytime.

First thing is that you should log out of your facebook account and then try the same.

It would surely work fine.


views NO RESULTS BEHAVIOR i18n Is there a way to show different no results behaviors for different languages in views 3.

Please check this link  as there is no way translate the views you just can filter the content of specific language of logged-in user. for enabling translation you check out the Internationalization Views module.

  Translate views using Internationalization. This is a work in progress and not all Views properties can be translated yet. Requires Internationalization 6.x-1.5 or newer.


How do I get the active theme path in a view? I need the active theme path in a view to use it in a field rewrite to display that particular image from my theme images folder.

How can I achieve this?

You can do by

global $base_url;
$theme = \Drupal::theme()->getActiveTheme();
$default_image_url = $base_url.'/'. $theme->getPath() .'/images/image.jpg';


Limit of 15 routes in module.routing.yml I have see when i want to create a new route they have an limit of 15 routes per module. In fact i have created an over route an i'm suprise to see of my road wans in route:debug. However they are in the module.routing.yml

I have cout the number of routes i have , and after 15 the routes arren't seen.

It's me or it's normal?

The YAML file :

 //empty line is not comment on the code
 unicef42.unicef_controller_index:
   path: '/unicef42'
   defaults:
     _controller: '\Drupal\unicef42\Controller\UnicefController::world'
     _title: 'Unicef controller'
   requirements:
     _permission: 'access content'

 //...the other routes

 //The 15th routes , no comment in the real code,1 empty road between the 14th and the 15th routes
 unicef42.accueil_controller_index:
   path: '/accueil'
   defaults:
     _controller: '\Drupal\unicef42\Controller\AccueilController::index'
     _title: ''
   requirements:
     _permission: 'access content'

 //The 16th routes , no comment in the real code, 1 empty road between the 15th and the 16th routes
 unicef42.accueil_controller_index:
   path: '/accueil2'
   defaults:
     _controller: '\Drupal\unicef42\Controller\AccueilController::index'
     _title: ''
   requirements:
     _permission: 'access content'
 //empty line is not comment on the code

It's just you I'm afraid.

Take the system module's routing file for example; there are a few dozen routes in there, plenty more than 15.

Symfony doesn't impose any limits either, so I'd check that your YAML code is properly formatted and valid. If you're positive it's all good, you've probably hit a bug and the best course of action would be to report it.


How can I write SelectQuery for SELECT LAST_INSERT_ID()? Is it possible to run the following query with SelectQuery ?

SELECT LAST_INSERT_ID();

I would do this with db_query(), but I'm finding a way to use the query builder.

$last_id = db_query("SELECT LAST_INSERT_ID()")->fetchField();

Although the original query has no table name, db_select() would expect the table name.
The following works perfectly assuming the insert operation took place in another hook and the last insert id is not available into my hook:

$query = db_select('mytable');
$query->addExpression('LAST_INSERT_ID()', 'last_id');

$result = $query->execute()->fetch();
print $query;
echo '<br>';
echo 'Insert ID: '.$result->last_id;

Query output:

SELECT LAST_INSERT_ID() AS last_id FROM {mytable} mytable


How to attach custom CSS to a Views output? I created a View to list a custom entity content.
I'd like to add my custom CSS file to the generated page.
I tried to use a Text Area in the footer with {{ attach_library('amap/yyy') }} where amap is my custom module and yyy is my custom library.
And of course, the CSS is not loaded...
Any idea why?

You will need hook_views_pre_render().

And here is an example:

/**
 * Implements hook_views_pre_render().
 */
function base_views_pre_render(ViewExecutable $view) {
  if($view->id() == 'this_is_my_view_with_no_css' && $view->current_display == 'page_1') {
    $view->element['#attached']['library'][] = 'base/test';
  }
}


Integrating external web application I have an existing web application written in Flask. I want to create a Drupal site that integrates this existing web application, so that the existing webapp will just be a back end, and the Drupal site will contain all the forms that submit data to the web app and displays the results from the web app.
I was thinking that Drupal Services could do that for me, but it looks like it is more for the reverse use case: to use an external web app as front end to Drupal..

So my question is: What is the best way of using Drupal as a front end to an existing web application?

Or is this even possible?

Some extra info about the web app:

Web app is written in Python/Flask
It is a web shop like application that allows users to search for products based on various criteria.
Web app is highly modular and cleanly split into views, forms, model, so it would be fairly straight forward to change the web app in order to present data via another protocol/API. I figure it would be possible to create new views that present the data in JSON or something like that and I hope that Drupal can somehow pick that up and display it in its templates.
Database is PostgreSQL
Frameworks used: Flask, SQLAlchemy, WTForms

Update 2015-05-15: More details

I have considered using Drupal Services because it sounded like it was an API for this, however, it turned out that Services solves the reverse problem: Makes it possible to use an external app as front end for a Drupal site.

How I think this could be done: Make the existing Flask webapp into a REST server allowing the Drupal site to send requests to the app for search queries, product displays, etc. So the external app will respond with some JSON that contains all the content and URLs to images, etc. In Drupal there will have to be a template for each view on the external app. E.g.:

Search form
Search result
Product display
etc.

I have zero experience in doing this stuff from Drupal. I have some experience with using Drupal. But mostly vanilla Drupal.

I was hoping that there were either a plugin or framework or something that would make it easier to do this. that is something that will make it easy in Drupal to create the following kinds of elements:

A form/template that upon submit sends request to REST service and displays results (e.g. serach)
A template that renders a page according to some JSON data gotten from a RESTful service.

Regarding PDO, I am not sure what that is. I am using PostgreSQL. I was not planning on letting Drupal access the external web app's database directly. That would essentially require me to reimplement the entire application in Drupal.

As mentioned above, the external app is written in Flask. Flask is a Python framework for making web applications. For short introduction, see http://flask.pocoo.org/.

About What is the best way of using Drupal as a front end to an existing web application?: I leave it to others to decide if it would be the "best" way, but "a" way to do so is to continue to use your existing web application for maintaining the data of it, and then use Drupal as a frontend to actually visualize those data (read only operations).

Assume the DBMS involved is some type of PDO compliant DBMS, e.g. MySql (the question currently does not provide details on that). So similar to what is described in Python Web Application Development Using Flask and MySQL. In that case the Forena module would be a perfect fit to get the job done, i.e. build reports and/or charts about data stored in your existing web application. Here is a quote about Forena:

  ... built of the idea of using SQL to get data out of a database and use XHTML and CSS to format it into web reports.

Possible DBMSs that could fit this approach are the Drupal DB itself (of course), but also MySQL, Oracle, MS SQL, Postgress, Sqite, anything PDO compliant.

The advantage of this approach is that you get lots of Drupal features avilable, while the "bacckend-part" of your application continues to be the applicationn you already have (you don't loose the investements made in that).


How do I use field_view_field() to print a user profile picture? I'm trying to print a user profile's picture in a block that gets displayed on a node page. I have the nodes author be loaded as in the following code:

<?php
$node = menu_get_object('node');
$user = user_load($node->uid);
?>

This is the code I have come up with for the block:

Meet the author

  <?php print drupal_render(field_view_field('user', $user, 'picture', 'user-pic-style'));?>

This isn't working and doesn't print anything.
I want the user's picture be loaded if users have one, or the default user picture if they don't.
I have other custom user fields that are printing just fine using the field_view_field(), so I am wondering why I am not having luck.

Try this

Meet the author

  <?php print drupal_render(field_view_field('user', $user, 'picture', array('settings' => array('image_style' => 'user-pic-style'))));?>


Fast way to make all menu-links "Show as expanded"? Is there a way to automatically make all menu-links in all menus whatsoever "Show as expanded"?

I have about 4 menus that contain many links and it's not serious to pass one by one and click "show as expanded".

Is there a module or a script that will do that automatically? Thanks,

Try using menu block and create block what level you want to trail you menu. You can also use menu expanded as per your requirement. Menu expanded is not well maintained.


Page template suggestion per language? How can I add page templates for different Languages in my Drupal 6?

For example, if I want to make different page template for Bulgarian language, page-bg.tpl.php doesn't work.

A drupal.org groups comment shows examples how to allow use of multiple tpl.php file versions.

Using

<?php $vars['template_file'] ?>

it is possible to create your own template file suggestions.

Example:

function phptemplate_preprocess_page(&$vars, $hook) {

  if($vars['language']->language == 'bg') {
    $vars['template_file'] = 'page-bg';
  }
}


How do I implement "enable" or "disable feature" similar to Drupal Gardens? I'm interested in implementing something similar to the way Drupal gardens let you enable and disable features in the create-site interface. (I mean the term features figuratively, not necessarily the features module.) Is this just some sort of custom form that hooks into enabling and disabling modules?

What you see on that page is a Drupal form where the form fields have been heavily themed to appear differently from how you would normally see that type of form field on a Drupal site.

Looking at the HTML source of that page, it is clear those selectors are simply checkboxes rendered with a custom theme function.

 &nbsp;<input type="checkbox" name="features[28711]" id="edit-features-28711" value="1"   class="gardens-feature-checkbox" />Follow us
Gain a following. Provide links to your (or your users') profile on Twitter, Facebook or other social networks.

There is also custom JavaScript code that changes the appearance of the form field.

When I turn off a feature, I see a CSS class being added to a tag, and another tag value being changed. The value associated with the checkbox is not changed; it is 1 when the feature is enabled, and it is still 1 when the feature is disabled.


How to create a url/link preview? I'm managing a content sharing site built on drupal 7 and I would like to let users submit links as content.

Is there a simple way of creating a thumbnail / preview of the link (like on facebook)?

I think Opengraph Filter is a better solution than Facebook-Style Micropublisher since FBSMP relies on Statuses module and both modules are not very stable yet and also they serve for a more specific purpose. Opengraph Filter does only that what you need.


Services Entity REST Application - Update (via put) Field Collection Data I am trying to figure out what the format and required parameters are for an update request to a field collection via the Services Module's REST API. I have installed the Services Entity API Module to allow interaction via Services with additional entity types.

I was able to save to a field collection when I first set everything up, using a PUT request, the CSRF token and properly formatted JSON.

{"field_fivestar_value":[
      {
         "rating":"100",
         "target":"0"
      }
   ]
}

which gave me this to access: field_fivestar_value['und'][0]['value'] which seemed to work perfect in the past, but now it seems that something is interfering/wrong as i get a notice after submitting a PUT request that $revision_id and/or $field_name aren't set, which never happened before...

It appears that something to do with revisions is causing the problem as if I provide specific (required?) data in my PUT request it works. Working PUT request JSON:

{
    "field_primary_aircraft": {
        "und": [
            {
                "value": "1"
            }
        ]
    },
    "field_name": "field_aircraft",
    "item_id": "5929",
    "revision_id": "5929",
    "default_revision": true,
    "field_aircraft_registration": {
        "und": [
            {
                "value": "testing12355"
            }
        ]
    }
}

That JSON plus a working CSRF token allowed me to save data back to a field collection that  is part of a users Profile2 profile.

The revision_id and default_revision were the trickiest parts to track down and supply, I don't have revisions enabled as far as I can tell also, so why this problem started suddenly I have no idea...at least it is solved and hopefully this info helps someone else.


How to track user view of nodes presented in a view? Situation: I have a simple video player set up using views with a pager. Views loads a set of related nodes, each with an embedded video. By using a pager, the user can advance to the next or previous video in the list.

Problem: I'd like to track whether a logged in user has viewed a video or not, then use this information to help a user see what they have left to watch in another view (a view that simply lists the nodes with embedded videos). So, I need to be able to list viewed/not viewed nodes with views at the user level.

I realize there is complexity around tracking whether a user has really watched a video or not, so ideally the logic that decides whether a user has watched a video or not (custom code, a rule, etc) can be extended/updated later. For now, simply tracking that the user viewed the node is fine.

Related question: since the user is viewing nodes thru the views-based player, and not by clicking node links, where is the best place to execute custom code to mark a node as viewed? I think it could be done with hook_views_pre_render, but I'm not sure that's the right place.

Any thoughts on a simple lightweight approach for Drupal 7? I thought of trying the Flag module (with a user-level flag), using either Rules or custom code to flag a video as "watched", but I haven't tried it yet. There is also a module called path rules that can trigger a rule based on paths: https://drupal.org/project/pathrules

Are there other modules I should consider that already do some of this?

I've worked out a solution based on the message module (https://drupal.org/project/message) and I think this will solve the problem well. Here's the basic approach:

Install message and create a new message type to capture a specific event (i.e. lesson viewed in my case).
Add an entity reference field to the message type created in #1 (messages are fieldable entities) in order to store a reference to the node that was viewed.
Write a function to create the message type created in #1. There is example code in a example module that comes along with the message module.
Hook the view that needs to trigger message creation and call the function created in #3.
Create a view that lists messages. Messages have good views support.
Add additional message types and logic to capture other kinds of activities (a user completing a video lesson, which in this case will mean working with the wistia api, since the videos are hosted on the wistia platform).

One question: I'm not sure where best to hook views to create a message when a user views a node through the view described in the original question . I'm currently using hook_views_post_render, which seems to work well, since the view provides access to the node id needed to create the message.

Overall, I think message will be a good solution for this problem and will provide a nice foundation for tracking other activities as needed. There's a good video overview of the message module here: https://vimeo.com/63919900


Generate an internal URL in twig I want to generate an internal URL in my twig template
Here is my code but it's not working

{% if(is_admin) %}

                        Edit Menu

{% endif%}

To generate an internal url in Twig you can follow these steps:

Install the module Devel.
Go to Routes Info (/devel/routes) and search in the browser for the path :

Add the route name and the route parameter to url():

Edit Menu


Add a gallery for every user in a block I want to be able to add a gallery for each user.
I understand how to create a content type. I considered building an image content type. I then thought I could add a view which would only display each user.

Is this best practice for creating a gallery for each user?

I am using Drupal 7, if this makes any difference.

I can get it working in a view but it doesn't seem to work in a block

Yes, you are on a right path. The Views module, and content types can be used to build a simple gallery for a user.

Create a content type called Image Gallery.
Add a image field to above content type.
Create a view called user gallery.
Filter by Content Type Image Gallery.
Filter by Node author: Logged in user, if you want to show logged in users Gallery.
Add the contextual filter Author UID, if you want to dynamically pass the user ID from the URL and filter the Gallery Images.
For above your view page path should be user-gallery/% where % will be user id.


Manually selecting content for a view is it possible to manually select content for a view? I'd like to create a related content view but I want to add the links manually for every article, not using taxonomy.

Is it possible? Is their a certain module that exists?

Thanks for any help

You can use References module (https://drupal.org/project/references) and create Node Reference field, which will allow multiple values.

Steps:

Create the node reference field
Add Node:nid to the views contextual filters to know which node you are on
Add related content field to the views Relationships to filter out the correct related nodes


choosing image style during content creation I am seeking for a method to enable users to:

choose image style (thumbnail, medium, large, ...) during content creation
change this style anytime during content update

Right now, with "Image" module on, the image field style can be decided only during content type creation.

I tried to use "Media" module 7.2, and there is possibility to choose image style during content creation, but no possibility to change it later.

The Formatter Field module looks like the right one. Here is a quote about it (from the module's project page):

... provides a mechanism for specifying a formatter and formatter settings to be used for displaying a field, on a per-entity basis. By default, Drupal provides formatters and settings per entity bundle, but in certain situations it is necessary to choose the formatter at the entity level.
For example, say you have a page node with an image field. Normally, you would select an image style as the formatter, and all page nodes would use that same image style. With this module, you can add a formatter field to page nodes, which is hooked up to the image field. Then when the node is created or edited, the image style can be selected per-node.


Create link to node in specific language So I need to create links to specific translations of a node but am having issues.
This is my code:
foreach($entities as $entity) {
$urls[] = Url::fromRoute('entity.node.canonical', [
        'node' => $entity->id(),
        'language' => $entity->language()->getId(),
      ]);
}

$entity in this context is EntityInterface.
But this gives me /node/1185?language=es instead of /es/node/1185.

$entity->toUrl('canonical', ['language' => $entity->language()]);
Taken from this question thread


Adding a 'OR' condition to query I need to add a OR condition to my query so that I can get all nodes related to a particular term. Here is what I have done :

$query = \Drupal::database()->select('taxonomy_index', 'ti');
$query->fields('ti', ['nid']);

// OR CONDITION
$or_group = $query->orConditionGroup()->condition('ti.tid', $params[1], 'IN');

$query->condition('ti.tid', $params[0], 'IN');
$query->condition('ti.status', 1);

// Added OR CONDITION TO QUERY.
$query->condition($or_group);

$query->execute()->fetchAllAssoc('nid');

This is the how the query get build :

  QUERY

  SELECT ti.nid AS nid

  FROM {taxonomy_index} ti

  WHERE (ti.tid IN (:db_condition_placeholder_0))

  AND (ti.status = :db_condition_placeholder_1)

  AND (ti.tid IN (:db_condition_placeholder_2));

  PARAMS

  Array (

  [:db_condition_placeholder_0] => 170

  [:db_condition_placeholder_1] => 1

  [:db_condition_placeholder_2] => 227

  );

As you can see the last "AND" condition should be "OR".

Thanks.

The solution seemed to be putting the explicit "IN" in the query, making the simplified version:

$entity_ids = $query
    ->condition('attributes.color', array('red', 'green'), 'IN')
    ->condition('attributes.building_type', 'bikeshed')
    ->execute();


Pressflow online users stats does not show correctly I can not say enough of performance gain that my site gained through migrating to Pressflow + Varnish. However I have a rather annoying problem with Pressflow. After migrating to Pressflow 6, the statistics of online users does not show correctly. For example the forum shows 70 online users while there are actually over 1000 users online.

I am wondering whether it can be fixed or it is just a "collateral damage" that one should afflict to gain the performance. If it can be fixed, appreciate your hints to do so, and if not, how else can I show the correct stats.

Thanks

I believe this is because of how Pressflow handles anonymous sessions.  It implements what are called "lazy sessions", which only creates sessions when actually needed.

This behavior can be changed by putting a drupal_start_session() in a custom hook_init.  If you do this, though, you will likely take a performance hit.

I have had to do this with a few projects to fix session problems when moving from Drupal 6 to Pressflow 6.

EDIT TO ADDRESS COMMENT:

You can simply put the hook in a custom module, such as

function mymodule_init ()
{
  drupal_start_session();
}

Note that you should really profile before and after to see what the performance impact is.


Site gone offline after aborted mysql restart After trying new my.cnf, restarting  mysql took to long (apparently due to some incompatible commands in the experimental config) , so I restored to my original my.cnf and restarts mysql successfully. But now I see that the site has gone off line. I tried the 'desparate' solution, i.e. issued:

UPDATE variable SET value = 's:1:"0";' WHERE name= 'site_offline';
DELETE FROM cache WHERE cid = 'variables';

but had no effect. Then I changed my database admin credentials. then, to possibly counter a corrupted table, I tried to repaire the database (MyISAM enginge) using

mysqlcheck -uroot -pPASS --auto-repair --optimize --databases MYDB

I also rebuilt the file permissions on the server.

No cure either.

I'd seen before that the site went offline on whim, but now this seems to become persistent. really appreciate your help to overcome this nasty problem.

It sounds like your database is broken. Drupal can't work without a database, and will display site offline if it can't connect to the database. If you fix your database, (And the data is still intact) Drupal should work fine.

For questions about databases you should go to dba.stackexchange.com