Check if a field is empty How to you check that a field is empty, when you have the $node object?.

I found this as possible solution:

$field = field_get_items('node', $node, 'field_post_image');

I can check now:

UPDATE.Ups! This not reliable, althought I promise that it worked for me yesterday.

isset($field);

but I wonder if there is a better way.

Enlighten me

If you read up on the documentation the function returns FALSE if there is no data. isset() would actually fail because you are assigning FALSE to the variable so it's actually been set to something. The correct syntax would be:

$field = field_get_items('node', $node, 'field_post_image');
if ($field) {
   //Do something with the field
}
else{
   //There are no results
}


Replace 'page' twig template for controller/url I have a page generated with custom controller.
It's special page, so i need to remove all sidebars, headers and logo, for that page, and use custom design/layout.

How can i replace 'page' twig template for that url/controller?

Just create new twig template in the template folder of your theme page--your-url.html.twig and clear the cache.


Redirect After Creating New Taxonomy Term I am new to Drupal. I am trying to figure out if it is possible to redirect back to the Taxonomy page right after adding the new vocabulary term instead of being directed to the manage page of the newly created term. Would this have to be changed in the controller for the taxonomy module? Or in another file?

Any help is appreciated, Thank You.

To add a redirection after creating new Taxonomy Term I suggest using the hook_preprocess_HOOK() in the MYTHEME.theme file.
E.g. here is code that add redirection back to the Vocabulary - list of all terms - for the Add term button:
/**
 * Implements hook_preprocess_HOOK() for menu-local-action templates.
 */
function MYTHEME_preprocess_menu_local_action(array &$vars) {
  if ($vars['link']['#title'] == 'Add term') {
    // Add redirection to the Terms list after creating a new term.
    $destination = Url::fromRoute('<current>')->toString();
    $vars['link']['#options']['query']['destination'] = $destination;
  }
}


Why am I not seeing CKEditor buttons on prod? Okay, so I configured the Full HTML text format and added some buttons to CKEditor locally in a Lando environment. Then I exported the configuration with drush cex, committed it, pulled and imported on production with drush cim. However, even though changes can be seen in admin/config/content/formats/full_html, buttons aren't there when creating content. Any ideas? I also cleared caches. I even changed permissions on sites/defaultrecursively to 777 before clearing caches through the UI.

Which version of Drupal are you running?
Since the new button appears in admin/config/content/formats/full_html I guess the Config Import/Export worked but the connection between the new config and the CKEditor in the content didn't update?
I will try that on my setup since im working with drush cex and drush cim regularly.


How to disable delete once the thread has been started in advanced forum module in drupal 7? If there are no comments on the current topic then user can delete the post.

If there are one or more comments on the forum-topic then user will not be able to edit or delete forum-topic.

Which module should i use or which hook needs to be implemented?

You're looking for hook_node_access() where $op == 'delete'.

http://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_access/7


Search nodes with paragraph I have the following query:

$query = \Drupal::entityQuery('node')
            ->condition('type', 'case_study')
            ->condition('status', '1')
            ->sort('changed', 'DESC')
            ->pager(4);

$query->condition('title', "%QUERY%", "LIKE");

$nids = $query->execute();

This works fine, however it obviously only searches on the title of the node. My case study nodes' fields are structured like this

- Case Study
    - title
    - field_page_banner
    - ...
    - field_rows <-- this is my paragraphs field

The paragraphs can contain multiple types and are chosen by the user when creating the content.

I want to be able to alter my query so that it searches the content of the paragraphs. For example, if the user adds a 'Rich Text' paragraph type, it will search the text.

This works fine for the built in search functionality, I just want to create a page of case studies with search functionality.

I am using Drupal 8.2.4 and Paragraphs 8.x-1.0.

The \Drupal::entityQuery object doesnt support JOINs I believe:
https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Entity%21Query%21QueryInterface.php/interface/QueryInterface/8.2.x

If it did you could Join onto the Paragraph bundle and LIKE across that all you want.

I recommend the following approach with Views, a small chance exists it may not work:

Create a View of your case study Nodes
add a relationship to the Paragraph bundle (if needed)
assure the field list for the View includes title and field_rows (you can Exclude field_rows from showing in your view if you want).
add a Grouped Filter and Expose it and select it to use your title and field_rows values.

That should do the trick...


Migrating compound data structures from XML How would you migrate a complex data structure in XML format, such as:

<products>
  <product>
    <name>Product 1</name>
    <price>3.99</price>
    <colour-options>
      <colour>red</colour>
      <colour>blue></colour>
    <colour-options>
  </product>
</products>

How would you migrate data in this format, into a content type? I'm guessing that the best way would be using the Migrate module.

Migrate can help you with this.

You can extend XMLMigration and use MigrateSourceXML.

I have a partial stack exchange data import which uses this with code on github.


Locations using GMAP A client has asked us to look at extracting information from an MS Access DB to designate where his products have most recently been delivered.

The end result is to output a variety of maps based on the last known delivery date, from which we can then specify what colour to designate each location marker on the map, based on the date they were last delivered to.

The other variable would be locations that they know are always stocked (regulars).

We can format the data from MS Access either at the point of origin, from our server or in Drupal. This DB will not change in its structure for a long time I expect, so we're happy treating this as a data 'Stub' to work with.

What we've also established is that the frequency of this data update isn't too critical, but since we're going to link our VPS to their system and then into Drupal, we think that regular updates (e.g. on each cron run) would be a good thing to offer.

Can anyone point us in the right direction for how to achieve this?

Its right on the cusp of our knowledge and we're a little bewildered by what approach to take.

Thanks!

It's not totally clear what you're asking, but here's a stab:

It doesn't sound like the data will be updated frequently enough to justify processing it on every cron run - you mentioned recent deliveries... what do you mean by recent? In the last hour? Last day? 30 days? Find the right balance based on the freshness of the data itself, and only update what's new, especially if you're doing it on every cron run.
Get the data out of Access in a reasonably ready-to-consume format - don't expose the ugliness of your Access data structures to Drupal. This could mean setting up a custom view in Access to summarize and reformat the data you need for Drupal.
Setup a scheduled export from Access.
Use Drupal Feeds to import/update the data from Access into Drupal, either on demand or periodically.

HTH.


How to render ctools_custom_content_type_edit_form with ctools_modal_form_wrapper() I have a scenario where I would like to reload/re-render the ctools_custom_content_type_edit_form after closing another ctools modal. To do so, I've bound an ajax object to the .close element within the open modal that will fire an ajax callback to open the ctools_custom_content_type_edit_form again.

My ajax callback looks like this, where the parent form is an argument in the menu callback. In this particular scenario, that form id is ctools_custom_content_type_edit_form.

The form is rendered, but it seems to be missing fields: Administrative Title, Title, Body. Any help would be appreciated. Let me know if you need more information.

function mymodule_parent_modal_callback($js, $parent_form_id) {
  // Convert parent form id
  $parent_form_id = str_replace ('-', '_', $parent_form_id);
  $path = '' . drupal_get_path('module', 'wysifield');

  if ($js) {
    ctools_include('modal');
    ctools_include('ajax');
  }
  else {
    // Someone navigated to the AJAX endpoint.
    drupal_access_denied();
  }

  $form_state = array(
    'ajax' => TRUE,
    'title' => t('Parent Modal Form'),
  );

  $commands = ctools_modal_form_wrapper($parent_form_id, $form_state);

  // If form has been submitted, execute other ajax commands.
  if (!empty($form_state['executed'])) {
    // Add the responder javascript, required by ctools
    ctools_add_js('ajax-responder');

    // Create ajax command array, dismiss the modal window.
    $commands = array();
    $commands[] = ctools_modal_command_dismiss();
  }

  print ajax_render($commands);
  drupal_exit();

}

Look at if ($settings['custom_type'] == 'fixed') condition in ctools_custom_content_type_edit_form(). Problem in it I think. Also, look at ctools_custom_content_type_get_conf() and do all needed to this function return $settings['custom_type'] equal to 'fixed'.
Maybe this will fix problem, change this value before ctools_modal_form_wrapper() like this: $form_state['subtype']['name'] = 'custom';


How can I convert character entities to display as 'normal' characters in Drupal? I have a customised module that imports items from feeds accessed via a third-party API. The items are used to create nodes for each instance. All the content appears to be importing correctly, but the feed includes character entities like '&amp' in some of the text imported. I've checked the CSVs being imported and the character entities are already in the feed content, so it isn't the module that's causing normal characters to be converted to character entities.

I'd like to know how I can get Drupal to convert the character entities to display as normal characters. Is there a module or setting that can do this?

Edit your import module to http://php.net/manual/en/function.html-entity-decode.php the text before importing.


metatag_display_extender plugin does not exist I am migrating a Drupal site over, the following error is being received... I have clear cache, did a rebuild and no luck. Any suggestions

The website encountered an unexpected error. Please try again later.
Drupal\Component\Plugin\Exception\PluginNotFoundException: The
"metatag_display_extender" plugin does not exist. Valid plugin IDs for
Drupal\views\Plugin\ViewsPluginManager are: default in
Drupal\Core\Plugin\DefaultPluginManager->doGetDefinition() (line 53 of
core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php).
Drupal\Core\Plugin\DefaultPluginManager->getDefinition('metatag_display_extender')
(Line: 16)
Drupal\Core\Plugin\Factory\ContainerFactory->createInstance('metatag_display_extender',
Array) (Line: 83)
Drupal\Component\Plugin\PluginManagerBase->createInstance('metatag_display_extender')
(Line: 161)
Drupal\views\Plugin\views\display\DisplayPluginBase->initDisplay(Object,
Array) (Line: 91)
Drupal\views\DisplayPluginCollection->initializePlugin('default')
(Line: 38) Drupal\views\DisplayPluginCollection->__construct(Object,
Object) (Line: 728) Drupal\views\ViewExecutable->initDisplay() (Line:
1754) Drupal\views\ViewExecutable->access('page_1') (Line: 60)
Drupal\views\Element\View::preRenderViewElement(Array)
call_user_func_array(Array, Array) (Line: 100)

I had this issue when trying to add metatag_views to an install profile.
I fixed this issue by adding a config dependency on metatag_views to the top of views.settings.yml:
dependencies:
  module:
    - metatag_views

There's more information on this Drupal.org issue.


How do I use "drush qd"? In Drupal 7, I use drush qd -y and php -S localhost:8000 almost weekly to get a fresh development copy of Drupal 7 to build modules or test modules before I put them into our actual development boxes.

I'm looking at Drupal 8 without much prior knowledge. Can I still use drush qd as I do with in Drupal 7?

drush qd still works fine with Drupal 8, provided that you are using the 8.x or master branch of Drush. In fact, I just used the latest Drush to download, install and open Drupal 8.1.1, and it worked like a charm.


Exposed Post date filter on views When you expose a filter date on views you get something similar to the following:

When you expose the post date you get:

The former is a lot more useful. Is there a way you can get the post date to look the same?

Sure therefore add a date: filter not a node: post date.

On the date filter configuration form you can select the node: post date field and that's all you need.


Counter is always set to 1 and not incrementing I want Anonymous users to redirect to login page if they have read three articles as trail. I wrote this code but the counter on any article is always set to one.I guess its initializing again and again. Can anybody please help with code.

<?php
function track_node_view($node, $view_mode) {
if (user_is_anonymous()) {
  if($node->type == 'article' && $view_mode=='full'){
      static $counter = 0;
      if($counter <= 3) {
        $counter += 1;
        dsm($counter);
        drupal_set_message($counter);
      }
      else {
        drupal_goto("user/login");
      }
   }
  }

The problem is that you failed to grasp how HTTP is basically stateless.

static $counter = 0;

This value will be kept during one run. But one run is one page load. Obviously, it will be fresh and new at all page loads - ie all article reads.

If you need to keep value in one user session, see Session API, that's what it is for.

If you don't need any extra functionalities, just use $_SESSION['mymodule_counter']. If you want to make sure session is started, use drupal_session_start()


Users cannot log in to new site in multisite I am working with the Drupal multisite functionality. I have been asked to implement the following architecture:

mysite is a Drupal site with several angular pages.
mysite/backend is a separate site with a separate user store that mostly acts as a headless Drupal system. For political reasons, it is very important that the users in mysite/backend not be stored in the same database as the users in mysite .

Anyway, from what I have read about Drupal multi-sites, I have taken the following steps.

I started with a working site and performed the following steps to add a second one
Create a symlink, making the /backend a symlink to the web root:

ln -s backend .

Add entries to my sites.php (because with our deployment workflow, the site name cannot always match with the domain name. Also allows us to test with xip.io).

$sites['mysite.dev'] = 'mysite';

$sites['mysite.dev.backend'] = 'mysite.backend';

I created a directory named mysite.backend .
In mysite.backend, I created a directory corresponding to all directories in mysite.
In mysite.backend, I created the following settings.php file:

$databases = array (
   'default' =>
   array (
     'default' =>
     array (
       'database' => 'XXXXXX',
       'username' => 'XXXXXX',
       'password' => 'XXXXXX',
       'host' => 'localhost',
       'port' => '',
       'driver' => 'mysql',
       'prefix' => '',
     ),
   ),
 );

 $update_free_access = FALSE;
 $drupal_hash_salt = 'k_vtgGjzCyq0mp0dsxDk1gILuEs6G5ODP5aJuQsAUuc';
 $base_url = 'http://mysite.dev/backend';  // NO trailing slash!
 ini_set('session.gc_probability', 1);
 ini_set('session.gc_divisor', 100);
 ini_set('session.gc_maxlifetime', 200000);
 ini_set('session.cookie_lifetime', 2000000);

I go to /backend/install.php and go through the install process. Everything goes smoothly
I click the link to view the new site, and enter the admin login credentials (for the new site. I made it a point to have separate logins for each site)

My problem is that when I go to the /backend directory of my test site and log in with my credentials, I get the standard authentication error behavior if I login with an invalid username or password, but when I supply the correct credentials, I get redirected to /backend/node, but I see no indication of being logged in. If I try to go to the admin pages, I get an access denied error. I still see the login block. If I click the reset password link, I get a one-time login link in my email, but when I click it, I get a message that says that the link has expired.

Forgive me if this is too verbose or missing details. This seems to be a messy problem. Has anyone run into similar issues with Drupal?

This issue might be a variation of the question about "drupal /?q=user is working but /user not working". So verify if you can use an URL containing ?q=user or ?q=admin. If that gets you going, then probably tuning RewriteBase in your .htaccess (as described in the accepted answer of that question) should help.

It might be worth trying to further enhance your .htaccess file, by adding a line after that existing RewriteBase, which looks like so:

RewriteRule . index.php [L]

For more details on the above line, refer to the (accepted) answer in this question on StackOverflow.

Another option for debugging is to retry using another browser. If via that browser you are able to login, then it's probably a cookie problem (in your original browser).


Is it possible to dynamically disable a module at runtime? Background:
I've got a multi-user/multi-channel project. Some channels are "classic" websites, but I've also got a channel that targets a non-interactive TV display. All channels are rendered using Drupal's templating (Technically a "channel" is just a theme, selected by a custom ThemeNegotiator acting on the current subdomain.) The problem is that some modules like e.g. Google Tag Manager or EU Cookie Compliance are unnecessary and disruptive on my TV channel.
Is there a simple way to dynamically disable certain modules at runtime?
The module should not be uninstalled, just inactive/dormant for the current request. I know that I could write module-specific hooks for each module I want to suppress. But I was wondering if - instead of writing a couple of different hooks - there is a single universal shortcut, something like the pseudo-code below:
if ($isMyCondition) {
  $modulesToDisable = ['eu_cookie_compliance', 'google_tag', 'foo_module', 'bar_module'];
  foreach ($modulesToDisable as $module) {
    \Drupal::something()->disableModuleForThisRequest($module);
  }
}

The concept of disabling modules (separate to uninstalling them), did exist in Drupal 7, but it was removed in Drupal 8.
You will either need to uninstall the modules, or find a different way to disable the specific behaviours which are causing you problems, via events/hooks/etc.


Migrating input formats causes errors I am trying to write custom migrations to migrate my Drupal 7 website to Drupal 8. I am currently using Drupal 8.6.7 and Drupal 7.61 for a copy of the production website.

So far I have set up the D8 website with composer (docroot is path/to/web) (https://www.drupal.org/docs/develop/using-composer/using-composer-to-manage-drupal-site-dependencies )

I have always used Drush for maintenance actions on the D7 site
and I am using Drush 9 for most of the actions including the migrations on the D8 site.

I have installed the most relevant modules in the D8 site so that I can start the migration,
most notably all the D8 equivalents of the modules I used in the text formats/filters as well as migrate_plus, migrate_tools and migrate_upgrade.

The migration files are generated with the Drush command:

drush @dev migrate-upgrade "$LEGACYDB" "$LEGACYURL" --configure-only --migration-prefix=osn_custom_

So far I have successfully migrated the users and their roles so I have some knowledge on how migrations work.

The problem I am currently working on is the migration of a custom content type called 'classified'. This type has a default Drupal 7 body field and a field 'field_image'. So quite ordinary.

When I use the default generated migration file, it looks like everything is migrated, but the text is not visible. After research I found this is caused by the fact that the input format is set to the D7 code (in my case 2 aka 'full html') while there is no filter code in D8 that is called '2'.
(src: https://www.drupal.org/docs/8/upgrade/known-issues-when-upgrading-from-drupal-6-or-7-to-drupal-8#d7_to_d8 ).

I decided that I might as well convert 2 to 'basic html' and use the D8 configuration and not migrate the D7 text filters at all.

I created a migration lookup plugin with a static map that converts all D7 codes to the preferred D8 code.
It might work well, but I am running into the problem that I can't get the migration plugin to work with the migration of the 'classified' migration configuration. So I decided to simplify it and set the format to a default value 'basic_html'.

Here is what I tried in the migrate_plus.migration.osn_custom_d7_node_classified.yml
The code snippets below only show the body configuration, because the other field configurations are generated with the drush command and not altered.

body: body

the default. Content is migrated, input format is set to '2'.

According to this: https://www.drupal.org/docs/8/api/migrate-api/migrate-process-plugins/migrate-process-overview#nested

and this: https://medium.com/drupal-stories-an-insiders-view/migrate-api-custom-drupal-to-drupal-migration-3bab05da4686

and this: https://www.phase2technology.com/blog/drupal-8-migrations

it should be done like this:

  'body/format':
    plugin: default_value
    default_value: basic_html

  'body/value': body

However, this results in the following error:

  [error]  InvalidArgumentException: Placeholders must have a trailing
  [] if they are to be expanded with an array of values. in
  /path/to/dev/web/core/lib/Drupal/Core/Database/Connection.php).

  [error]  Placeholders must have a trailing [] if they are to be
  expanded with an array of values.
  (/path/to/dev/web/core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php:783)

I have no clue what is wrong and what I should do instead. I also don't know how to debug this to find out what it's expecting.

Can someone please give me some pointers?

Thanks to @Jdrupal I finally found the solution in this link.

  body:
    plugin: sub_process
    source: body
    process:
      value: value
      format:
        plugin: default_value
        default_value: basic_html

(sorry I can't seem to get the mention appropriately formatted)


How to add menu links to a node created within a test? I want to create a test where a few nodes are created, and on those nodes are menu links.

The most I have found so far is:

    $options = array(
      'menu_name' => 'menu_test',
      'bundle' => 'menu_link_content',
      'link' => [['uri' => 'internal:/']],
    );
    $link = MenuLinkContent::create($options);
    $link->save();

How do I tie it and the node together? Just provide the node uri in the 'link' property? Would that just be internal:node/(nid)?

Yes, you have just to provide an uri that identifies the node, for example entity:node/1

Use

'link' => ['uri' => 'entity:node/' . $nid],


When the admin changes(Add/Remove) roles of the user, how to get assigned and removed roles of that user? There are more than 20 user roles(Editor,approver,new admin..) in the  project. Whenever the admin assign/delete the role to user then the user should be notified with email. Email should say Hey Prabhakar You have been assinged to following roles or you have been removed from following roles.

Implement hook_user_presave:

/**
 * Implements hook_user_presave()
 */
function yourModuleName_user_presave(&$edit, $account, $category){
  foreach ($account->roles as $role_id => $val) {
    $user_roles_existing[] = $role_id;
  }
  foreach ($edit['roles'] as $role_id => $val) {
    // $edit['roles'] contains all roles ids as key and selected role id as val. If not selected then value is 0
    // ex. $edit['roles'] = array(5=>5, 6=>0) here role id 5 selected
    if ((int) $val > 0) {
      $user_roles_form[] = $role_id;
    }
  }
  $user_roles_new = array_diff($user_roles_form, $user_roles_existing);
  $user_roles_removed = array_diff($user_roles_existing, $user_roles_form);
  //roles added
  if (count($user_roles_new) >= 1) {
    /**
     * Required code...
     */
    drupal_set_message('Testing new roles count' . count($user_roles_new));
  }
  //roles removed
  if (count($user_roles_removed) >= 1) {
    /**
     * Required code...
     */
    drupal_set_message('Testing Removed roles count' . count($user_roles_removed));
  }
}


Disable CkEditor to body field of a content type I enabled the CkEditor module, which is affecting all the text-area fields with summary and input format. How can I exclude the CkEditor for some fields?

The problem you experienced with configuring the field is that in core there is no option to select the allowed text formats. When this module is installed

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

you can select the text format that is available for a specific field and then you can choose in the settings of the text format whether to use ckeditor or not.

There is work going on to put this in core: https://www.drupal.org/node/784672


Ajax working on 1 page I have a form that is using ajax to filter from a dropdown to another dropdown and then I have ajax setup on the submit button to submit the whole form via ajax.

Everything works fine in the main module page, but the ajax does not work on other module pages.

I don't see any javascript errors in the console, and it seemed that all the javascript files related to drupal's ajax were loaded with the page.

What could the problem be?

Thanks!

Update:

I am using Drupal 7.9. The code that I am using to submit the form in ajax is:

$form['submit'] = array(
        '#type' => 'submit',
        '#value' => t('Transfer'),
        '#submit' => array('ajax_create_transaction_submit'),
        '#ajax' => array(
            'callback' => 'ajax_create_transaction_callback',
            'wrapper' => 'user_transfer_panel',
            'effect' => 'fade',
            'progress' => array(
                'type' => 'throbber',
                'message' => t('Processing transfer. Please wait...'),
            ),
        )
    );

This code is working but only on 1 page within my module.

So the problem was that I have various pages in my module which are each separated in their respective files e.g. mymodule.module, mymodule.page2.inc, mymodule.page3.inc etc

The issue was that the form of the block was in mymodule.page2.inc so when the user navigated to page3 the methods of the form where not being loaded.

The solution was to copy all the form methods into mymodule.module since it is like the parent of all the pages, so then the methods were accessible from all the pages.


How to display link to the next/previous most recent node from current node (if it does not belong to a book)? I would like to display the next and the previous most recent node from the current node (if it does not belong to a node).

It is somewhat similar to the pager available to the book page, except here the current node as well as the links to the next/previous nodes are not in a hierarchy and do not belong to a book.

Assuming I have 4 nodes - node1,node2,node3,node4 (all belonging to a set of node types I want to use) and each published consecutively one after the other. Then if the user is on node3, he/she should see the links for node2 and node4. If currently on node2 then node1 and node3 links should show up. If they navigate to node1, then a link for node2 should be displayed and so on and so forth.

Also, the  next and previous nodes can only belong to a pre defined set of node types.

I am using D7 and wouldn't mind using either a custom function or a views block to implement this. Any ideas on how to go about it?

You can do it with db_query in your node--content_type.tpl.php. Get all nids for content type in array. Match the current nid position in array. Like if Position is array[3] the Previous nid link should be array[2] and next should be array[4].


I want to display the all true/false questions in same page using quiz module. Is it possible? I have installed drupal 7 quiz module in my project.I want to display the all true/false questions in same page. Is it possible?

Try using  Quiz Progress module .. It offers nice User Experience to track status of questions and navigation..
Project page says

Quiz 6.x has the limitation of displaying only one question at a time.
This makes it hard to navigate from one question to other especially
when you have a skipped question in the beginning and you have your
current question at the closure of quiz.
The "Quiz Progress" module tries to overcome this problem, it provides
a block that prints the list questions in the quiz referenced by title
or number (with tooltip) depends on the widget configured in module
settings, highlighting their status skipped, answered or unanswered as
a link.

Here is the final output using above module which lists all questions...

If you are looking for Solution from Quiz Module itself take a look at this issue in Quiz Module.. Seems like #106 works in above issue..


Is it possible to leverage browser caching? I have ran a site through Google Page speed insights and one of its recommendations is to leverage browser caching for https://www.google-analytics.com/analytics.js.

Is this possible on a Drupal site?

If you have a .htaccess file, you can add the following code at the top of it:

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>
## EXPIRES CACHING ##


How to change the default logo size in the OpenChurch theme? I'm trying to upload an image for the logo with a slightly higher resolution than the default logo, but I don't find any way to change the default logo size in the OpenChurch theme. I don't need the text beside the logo there, but I need a bigger logo.

Any suggestions?

In your Admin toolbar, click on appearance, then click on settings.

Scroll down to LOGO IMAGE SETTINGS and uncheck Use the default logo supplied by the theme and upload your own logo.


How To Wrap Drupal Form API in html div structure [in my Drupal theme files (.tpl file)] I have a webpage which is being rendered from my page.tpl.php , it has a login page at top - right of page.
I am kind of struggling to wrap my LOGIN HTML FORM in Drupal Form API

Below Links did not help me that much even though it gave me general idea

1. should-i-put-input-tag-inside-label-tag

2. drupal-7-forms-how-do-you-wrap-an-input-in-a-label

3. how-to-put-two-form-elements-in-a-row-using-drupal-form-api
 Below image shows my Login form

theme_form_element , drupal-form-api-prefix-suffix, using-prefix-and-suffix-form-api-layout and drupal-form-wrap-div-tag-custom-html-prefix-suffix gave me some idea but I am still puzzled about this things.

{
found some more helpful links for this :

how-to-create-multiple-forms-in-drupal-7.html
page-user-login.tpl.php
page-template-for-custom-form
Printing a form on a page with drupal_get_form
}

Can some one guide me for this.

I am not sure if I should go with Drupal form or just use the normal HTML Login in PHP way.

For Better Understanding of the scenario I am adding screen shots and details of my task below, it is purely just for example, all I am looking for is some guidance for the task I am doing, answer does not have to be exactly FORM API of my HTML but I need to know how to achieve this in page.tpl.php.

[Do I have to create new custom module or I can manage this in my page.tpl.php- sorry if it is very simple question, I am little new here in drupal ]

  Here is the HTML

            <button class="primary_btn">Download Guidelines</button>
            <button id="loginPopup" class="primary_btn">Login</button>

Email address

<input type="text" placeholder="Enter your email address">

Password

<input type="password" placeholder="Enter your password">

Not registered?

<input type="checkbox" vlaue="ss">Tick this box and click 'Register'

                    <button class="primary_btn">Login</button>
                    <button class="primary_btn">Register</button>
                    <button class="primary_btn">Cancel</button>

I need to create a Login and Registration Module. I have this whole form in basic html not in form, I am struggling to convert this to Drupal From

Also I am not sure if I should go for Drupal Form or not. Since my requirement is to show the error message in the same place
 . see below

Thanks :)

It will be hard to implement this html as it is. You have to create a custom form using form api of drupal and use its arguments to make the html nearly same like your design. But still there will be css changes respectively. Let me edit Email field for you

    function mycustomform($form, &$form_state){
    $form['email'] = array(
      '#type' => 'textfield',
      '#title' => t('Email address'),
      '#size' => 60,
      '#maxlength' => 128,
      '#required' => TRUE,
      '#prefix'=>'

',
      '#suffix'=>'

',
      '#attributes'=>array('placeholder'=>'Enter your email address')
    );

    $form['password'] = array(
      '#type' => 'password',
      '#title' => t('Password'),
      '#size' => 60,
      '#maxlength' => 128,
      '#required' => TRUE,
      '#prefix'=>'

',
      '#suffix'=>'

',
      '#attributes'=>array('placeholder'=>'Enter your password') // No use because it will show dots or *
    );
    $form['login'] = array(
      '#type' => 'submit',
      '#value' => t('Login'),

      '#prefix'=>'
',
      '#suffix'=>'',
      '#submit'=>'custom_user_login',
      '#attributes'=>array('class'=>array('primary_btn')) // No use because it will show dots or *
    );
    $form['register'] = array(
      '#type' => 'submit',
      '#value' => t('Register'),
      '#submit'=>'custom_user_register',
      '#prefix'=>'',
      '#suffix'=>'
',
      '#attributes'=>array('class'=>array('primary_btn')) // No use because it will show dots or *
    );
return $form;
}

function mycustomform_validate($form, &$form_state){
    //Add checks for already registered user
}

function custom_user_login($form, &$form_state){

      if($uid = user_authenticate($username=$form_state['values']['email'], $password=$form_state['values']['password']))
    {
      user_login_submit(array(), array('uid' => $uid));
      return true;
    }
    else
    {
        return false;
    }
}

function custom_user_register($form, &$form_state){
    $new_user = array(
  'name' => $form_state['values']['email'],
  'pass' => $form_state['values']['password'], // note: do not md5 the password
  'mail' => $form_state['values']['email'],
  'status' => 1,
  'init' => $form_state['values']['email'],

);

// The first parameter is sent blank so a new user is created.
$user = user_save('', $new_user);
if($user->uid){
drupal_set_message('User saved successfully');
}else{
    drupal_set_message('Error in saving user','error');
}
}

Hope it will help you.


Unable to get through to the custom form using hook_menu page callback? Inside the hook_menu I have ,

$items['abc/def/%node'] = array(
    'page callback' => 'drupal_get_form',
    'page arguments' => array('heart_form',2),
    'access arguments' => array('modify  heart status'),
    'type' => MENU_CALLBACK,
  );

Inside my custom form I have the foll code..

function heart_form(&$form_state, $node) {
   $form['notes'] = array(

    '#type' => 'textarea',
    '#required' => TRUE,
    '#description' => t('Please give an explanation'),
  );
  $form['submit'] = array('#type' => 'submit', '#value' => t('Save'));

  return $form;
}

But when I try to go on the link , www.example.com/abc/def/18 I get a page not found message
What is the error ?

Sanity checks first:

Make sure you're returning $items from hook_menu()
Make sure you've cleared the caches since making changes to code in hook_menu()
You probably don't mean to have two spaces between the first two words in your permission string.
Make sure there's a node with an ID of 18 in the system; if not the %node load argument will fail and you'll get a 404.

The only other problem (but not one that would causes a 404) is the signature for your form function; it should be

function heart_form($form, &$form_state, $node) {


hook_views_pre_execute() query not running (or being overwritten) I'm trying to completely overwrite the query that's created by Views UI by using hook_views_pre_execute() in a custom module. I know about the new database API and how this function expects a SelectQuery object, but I've also read (in a posting from Lullabot, so I think it's legit) that if you're just writing a single query and don't need to do anything conditional, it's perfectly OK to skip that and just use db_query() with raw SQL.

So here's my function - the drupal_set_message() line is executing, but the output of the view is still sorted in ascending order, which is what is set in the Views UI. My understanding was that this function was supposed to completely overwrite what's in the UI, so how do I get it to work? (Right now I haven't done anything funky with the SQL except change the order by just to see if it would work. There really is other stuff that needs to be done which justifies using a module instead of the Views UI.)

function group_speaker_carousel_views_pre_execute(&$view){
    if ($view->name == 'speakers_carousel')  {
      drupal_set_message("view is {$view->name}");
       db_query("SELECT DISTINCT node.title AS node_title, node.nid AS nid, field_speaker_node.title AS field_speaker_node_title, field_speaker_node.nid AS field_speaker_node_nid,  'node' AS field_data_field_job_title_node_entity_type,  'node' AS field_data_field_company_node_entity_type
      }
FROM {node} node
LEFT JOIN {field_data_field_speaker} field_data_field_speaker ON node.nid = field_data_field_speaker.field_speaker_target_id
LEFT JOIN {node} field_speaker_node ON field_data_field_speaker.entity_id = field_speaker_node.nid
WHERE (((node.status =  '1') AND (node.type IN ('speaker'))))
ORDER BY field_speaker_node_title DESC");

    }
}

The reason nothing's changing is because you're just running db_query(), not actually assigning it to anything. If memory serves you need to assign your new query to $view->build_info['query'] (but that might be for Drupal 6).

Also you won't unfortunately be able to use a vanilla db_query for this (as far as I know), because Views is expecting a db_select() object.

You can test this pretty easily by running the following two statements:

// Breaks the view.
$view->build_info['query'] = db_query('SELECT nid FROM {node}');

// Does not break the query (but results are wrong obviously).
$view->build_info['query'] = db_select('node', '')->fields('n', array('nid'));

I would look at re-working your query into a dynamic db_select() and then assigning it as in the above example, you should get more joy.


Feeds: solution with most frequent/real time/push notification update of feeds (e.g. for twitter tweets)? Which module (or solution) provides the quickest update of feeds after their source is updated? E.g. with Twitter if a new tweet is posted, which Drupal feed or twitter solution updates the quickest following that tweet? (I'd also be looking for general feed solutions for youtube etc).

I currently use feed aggregator which has minimum refresh interval of 15 minutes.

Do solutions require/work better if linked to a cron task?

Are there any real time genuine (i.e. not pseudo*) push notification solutions out there? Please give examples for particular feeds (e.g. twitter, youtube etc.) *by pseudo I mean a high frequency polling solution that appears to be near real time but is actually a pull on the feed from the drupal site rather than a push from the feed source.

Can feed sources like twitter be configured to know about subscribed external sites such that they can push updates to them?

By the way, currently evaluating the following as part of a solution for e.g. twitter (any specific advice on these welcome as is general advice on other solutions including for other feed sources such as youtube).

http://drupal.org/project/twitter
http://drupal.org/project/oauth
http://drupal.org/project/twitter_pull

It looks like Twitter's "Streaming API" is your solution. However, I would look closely at their Pre-Launch Checklist before going down that route. They have 10+ things that you should comply with before becoming a stream or push consumer of their API.

Maybe a solution that would fit you is to develop a twitter stream client (that would be your server), and then to have your application users connect to your server via node.js, since node.js provides a "persistent" connection suitable for chat rooms and push-like notifications.

This is an interesting (and probably doable) suggestion, but not something that you would find pre-packaged in a Drupal module.


Is it normal for a database to have 3600 tables? I recently inherited a Drupal site and while trying to migrate the site and DB I noticed that the DB is 1GB+ and had 1000s of tables. This is the first time i work with Drupal so I'm not sure what these tables are.

A lot of them are exactly 128KB and named something like drupal_field_data_style_abc or drupal_field_revision_abc. Is it safe to delete these? Not really sure what they are for at the moment.

Those tables are tables for fields. Whenever you add a field to a content type Drupal creates two tables, one to store the field value and another one to store historical data of that field.

Deleting those table will break your site.

This just means that you have a lot of fields. Usually, in drupal 7 it is a watchdog table that contributes to the size of your database unless you want to keep historical log data feel free to clear some data from watchdog table.


Call counter module in a page How can I place visitor stats in a page from Counter module in Drupal 6?
I'm looking for the php Code. Maybe it can be done with:

<?php print theme(); ?>

but I don't know the exact code.

I believe Counter creates a block that you can then position. If you need to do it programmatically, see this question and answer: Programmatically printing a block


Adding menu with description like mega menu I would like to create a menu with a description of the menu like megamenu. My menu looks like the following model:

How can I create this?

You can try TB Mega Menu, it's got very nice user interface (WYSIWYG) and also multiple built-in styles.

http://drupal.org/project/tb_megamenu


Deleted all the content... but it's all still there? I wanted to start from scratch so deleted all the content from my Drupal site. Now I am getting the following error:

Notice: Undefined index: name in system_sort_modules_by_info_name() (line 949 of /Applications/XAMPP/xamppfiles/htdocs/drupal/modules/system/system.admin.inc).

Also, even though I deleted all the content, it is still appearing under the Menus. Do I need to manually remove it from the menus as well? I was hoping that deleting the nodes/content would automatically remove it from the menus...

I deleted the content by going to Administration » Content, selected all the pages/nodes and them selected the "delete selected content" option.

That Undefined index: name in system_sort_modules_by_info_name() error sounds like a broken module not defining its name in its .info file

One possibility is from coder/coder_sniffer/Test/bad.info

see: http://drupal.org/node/1015368


Is it good practice to override simple db_query or EntityFieldQuery with a View I am using several autocomplete fields in a form. To retrieve the data, I have used db_query for very simple queries, EntityFieldQuery for more complex, until I found one that is somehow convoluted, so I used a View and views_get_view_result to retrieve the list of suggested terms. Is it a good practice or am I consuming too many resources instead of digging a little more in my code?

There is no simple answer possible to this question because it very much depends on circumstances. The customary response to such fears is to invoke the spectre of Premature Optimization and to advise you not to worry until you know you have a performance issue.

However, from an educational perspective it's probably worth at least looking at the query Views is executing and considering whether it is efficient: is it scanning every row of a large table because of the lack of an index, for example.

On the Views settings page there's an option to display the SQL for a query. You can copy and paste it into a tool such as PhpMyAdmin (removing the curly brackets peculiar to Drupal SQL queries) then put "EXPLAIN" in front of it to see what's happening under the hood.

But in general I would not bother to rewrite a query like this until there's a proven need to do so.


Show create content menu item to ananymous users but call URL for login/register popup on click I thought it would be simple to do, but after lots of searching I couldn't find exact solution for it.

So the issue is, I have 2-3 main menu items which I have to show to anonymous users but have to call a URL(for login/register popup) & prompt for login or register if they click on them.

Best solution I found for create content link "node/add/node-type" was something like --

function THEME_preprocess_page(&$vars, $hook) {
    global $user;
    # if url starts with "add" and current user is anonymous
    if (arg(1) === 'add' && $user->uid === 0) {
          # redirect to login page
          drupal_goto('user/login');
          exit;
    }
}

It didn't work & it says - "$base_path has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer."

This is a very important functionality thing & I don't know how people resolve it. Can I get any suggestion for it ?

I had the same problem, and solved it without coding.

Manually set the menu path with absolute URL, ie. http://yourdomain.com/node/add/node-type
Install and enable the module r4032login
Done!


how to resolve ajax call once issue Drupal code

function form_example_form($form, &$form_state)
{

    drupal_add_js(drupal_get_path('module', 'form_example') . '/js/test.js');

    $form['price_form'] = array(
        '#type' => 'fieldset',
        '#title' => t('Add Item'),
    );

    $form['price_form']['item'] = array(
        '#type' => 'textfield',
        '#title' => 'Item Name?',
        '#size' => 10,
        '#maxlength' => 25,
        '#required' => TRUE,
        '#ajax' => array(
            // #ajax has two required keys: callback and wrapper.
            // 'callback' is a function that will be called when this element changes.
            'callback' => 'form_example_simplest_callback',
            'wrapper' => 'listDiv',
            'effect' => 'fade',
        ),
    );

    $form['price_form']['textfields'] = array(
        '#prefix' => '
',
        '#suffix' => '
',
        '#markup' => '',
    );

    $form['price_form']['price'] = array(
        '#type' => 'textfield',
        '#title' => 'Item Price?',
        '#size' => 10,
        '#maxlength' => 10,
        '#required' => TRUE,
    );

    $form['price_form']['submit_button'] = array(
        '#type' => 'submit',
        '#value' => t('Click Here!'),
    );
    if (!empty($form_state['values']['item'])) {
        $result = db_query("SELECT * FROM {item} where item_name='" . $form_state['values']['item'] . "'");
        if ($result->rowCount() != 0) {
            $form['price_form']['textfields'] = array(
                '#markup' => 'Already exist',
            );
        } else {
            $form['price_form']['textfields'] = array(
                '#markup' => 'New Item',
            );
        }
    }

    return $form;
}

function form_example_simplest_callback($form, $form_state)
{
    return $form['price_form']['textfields'];
}

On blur of item textfield,I am showing status of item whether item_name exist in database or not.But It is showing perfectly for first time.

As it replaces a form name with 'form_name-2' after first ajax callback,it is not working afterwards.

How can I resolve this issue?

Thanks in advance

The problem is that you set your wrapper div in $form['price_form']['textfields'], but in the AJAX callback you are replacing it with the $form['textfields'] that does not have it defined. To be safe, keep these guidelines:

Never use the same identifier at 2 different depths of an form array, as it leads to mistakes. Be sure to set '#tree' => TRUE if you need to use identifier twice, to avoid conflicts.
In AJAX callback always return the same element you set '#prefix' => '
 on.
Be sure to only define each element once. If you are using

$form['price_form']['textfields'] = array(
  '#prefix' => '
',
  '#suffix' => '
',
  '#markup' => '',
);

to define element, don't reset it with $form['price_form']['textfields'] = array( later in code. Using array() creates new empty array effectively deleting everything set earlier. Write directly to it's members like this:

$form['price_form']['textfields']['#markup'] = t('Already exist');

Of course they are not set in stone, but don't break them unless you know why and what you're doing. In your case, you have 'textfields' twice, you are setting wrapper on one and returning another. That's why it only works once. Second time there is no element FAPI's AJAX is supposed to replace.


Drupal commerce: how to force user to pay with specific payment method? I Have written a shipping method (name:X) and a payment method(name:Y) for drupal commerce. the problem is that I want to force user to pay with Y if he selects X and I want to disable other payment methods on this condition.

it can manually be done with rules! but I want to programmatically add this limit.
how can I do it? is there a hook or something else?

You've already realized that you need a rules condition, since the available payment methods are determined through rules.

The selected shipping method is stored on the order entity ($order->shipping_rates), so you can just check that.
You might need to write a custom Rules condition (which is just a PHP function declared by an implementation of hook_rules_condition_info()).


Can you create a new block region using just a module? I am writing a module that will, using javascript, create a slide down container at the top of the page. (modelled on the login here http://xenforo.com/community/).

Rather than hardcode the content in this slide-down region, I'd rather just create a new block region, and let the user put whatever blocks into it he/she sees fit.

The thing is, this sort of thing would normally be done with the theme, not with a module. Is it possible to define a new block region using a module, and if so, how?

hook_system_info_alter is your friend.

<?php
/**
 * Implements hook_system_info_alter()
 * Adds a new "tray" region to the current theme
 */
function MODULE_system_info_alter(&$info, $file){
  global $theme;

  // If non-default theme configuration has been selected, set the custom theme.
  $custom_theme = isset ($theme) ? $theme : variable_get('theme_default', 'bartik');

  if ($file->name == $custom_theme){
    $info['regions'] = array_merge($info['regions'],  array('tray' => t('Tray')));
  }
}


How to add checkbox to subscribe newsletter in webform I'm using D7, and I want to create a newsletter subscribing page with simplenews module.
Other than email column, I want to have fields like name, address, contact number, select field (checkbox) in the form, like in the link below

http://bsgproperty.com/registration_form.php

However, I found that simplenews is hard to add in fields, so I decided to use webform to create fields and add in a checkbox to subscribe newsletter.

I had successfully created a checkbox, but how can I link this checkbox to newsletter module?

I want the email address entered in webform to be added in newsletter subscriber list after users check the checkbox and submit.

Is there anyway to do this?

If you want to add a checkbox field using the Webform module...

Choose the "Select options" type, enter the value and label, then choose the "Multiple"  setting (even if you just want one checkbox to appear), and make sure "Listbox" option is not on.


D7 views 3, display content based on path I have a block that displays results of the nodes i have created but i have those nodes on a specific path, anyway to put this short im trying to make a block from views that displays content based on the url it is on.

For example, if i am on page green, it displays all content from the path green/whatever or if im on red it displays content from red/whatever, im trying to achive this without making a bunch of blocks is there another module or something for this?

Any help is greatly appreciated.

Please watch Learn Views with NodeOne, part 19: Contextual filters with paths.


Fresh Drupal Install, UnmetDependenciesException Has anyone ever ran into this, UnmetDependenciesException? From googling there is quite a bit of talk about this, but so far no concrete solution.

and at the bottom (you can't see it in the screenshot) it says

dependencies in Drupal\Core\Config\UnmetDependenciesException::create() (line 84 of core/lib/Drupal/Core/Config/UnmetDependenciesException.php).

Drupal\Core\Config\UnmetDependenciesException::create('standard', Array) (Line: 460)
Drupal\Core\Config\ConfigInstaller->checkConfigurationToInstall('module', 'standard') (Line: 132)
Drupal\Core\ProxyClass\Config\ConfigInstaller->checkConfigurationToInstall('module', 'standard') (Line: 141)
Drupal\Core\Extension\ModuleInstaller->install(Array, ) (Line: 83)
Drupal\Core\ProxyClass\Extension\ModuleInstaller->install(Array, ) (Line: 1571)
install_install_profile(Array) (Line: 661)
install_run_task(Array, Array) (Line: 539)
install_run_tasks(Array) (Line: 116)
install_drupal(Object) (Line: 44)

I got this when I did a fresh install of LAMP.

I do not get this error when installing Drupal 8 in another LAMP server that I setup a long time ago.

This leads me to believe that it could be some php extension missing or some other package, but according to the installer, it doesn't say that I am missing anything.

Suggested solutions that have not worked:

Using a different browser with all history & cookies cleared.
Made sure no Core files are missing, since I did a wget and then unzip. Even tried diff core versions.
Selecting Minimal install.

I did another LAMP install and it worked. So IDK why it didn't before.

Although accidentally I managed to break it when using a bad php.ini file, so I guess that's one possibility.


Trouble redirecting users after implementing LDAP We had a feature on our site where we redirected users with certain roles to a particular landing page upon logging in. In a custom module, we implemented hook_user_login(\Drupal\user\UserInterface $account) to examine the roles the user had, and redirect them to a particular landing page, depending on the user's roles.

Recently, we installed and configured the ldap module, so that users could log on with their LDAP credentials, and Drupal accounts would be auto-generated. However, we quickly found out that users with particular roles were not getting redirected on their very first login. Users belonging to other groups were correctly redirected upon creation of their Drupal account by means of _hook_user_login(), so it's strange that it only affects particular groups.

What happens is that, the first time you authenticate with LDAP credentials, the LDAP module creates a new Drupal user after successful authentication, then looks at your LDAP groups and assigns your user corresponding Drupal roles, mapped in the module's configuration.

I haven't been able to figure out why the redirection works for some roles but not others. Obviously, those roles are attaching to the account object earlier in the process than others. But where or why this happens, I haven't been able to figure out.

The second time the user logs in, the Drupal account has the roles at that point, and the redirect (running on hook_user_login) happens correctly. I am wanting to say that this works well enough, but my stakeholders want it to work correctly the first time.

My attempt to address the issue was to look at hooks implemented in the LDAP module, and see if any of those give me a user object with all of the assigned roles, from which I can figure out which landing page I should redirect the user to. I couldn't find robust documentation on the hooks, so I implemented each one in a custom module and debugged their arguments to see if any one gave me what I wanted. I found that hook_ldap_user_edit_user_alter($account, $ldap_user, $context) gave me an $account object. However in testing, at the time the hook fires, the account object only has the role anonymous. So, this attempt to use hooks defined in the ldap module seems stymied.

Is there a hook later on in the login/authentication process where I can get a fully fleshed-out user object, with all the roles that the LDAP module is assigning the newly-created user? Or is there another way I can redirect the user?

I was not able to find a hook that gave me what I wanted, but as a sort-of work around, I created an event subscriber that uses checkAuthStatus() to check the user and path, and redirect when necessary.

This is sub-optimal, because this event fires on every page load, as far as I can tell, but at least we got our feature.


How can I add template suggestions by UUID? I'm looking for a solution to migrate content between environments (dev->staging->production) and currently I think I'll use UUID and Node Export (as far as I see UUID Features is still in alpha and isn't recommended by the community).

Sometimes I want to use template files or hooks (e.g. theme_preprocess_node) specific to a node created on my dev and then to upload the changes to production - this thing is impossible with the use of nids, but must be possible with uuids.
Is there any way out of the box to add theme_hook_suggestions by uuid, or do I need to implement it on my theme?

Thanks.

You should add a hook in your template.php, like this:
function MYTHEME_preprocess_node(&$vars) {
  if ($vars['node']->uuid == '12345') {
    $vars['theme_hook_suggestions'][] = 'my-best-tpl';
  }
}


Filter a view by the URL I’ve a page, called Jobpage, where I’m listing all my members within a specific content type. Then I’ve at the right sidebar a list of geographical locations which each member has entered when signing up. I want my users to filter the Jobpage but instead of getting all the members for that content type, I want only to list the members which have that specific location.

Right now I’ve tried to create the links and filter by that like so:
Normal Jobpage with all members is: www.mydomain.com/jobpage
Filtered Jobpage is: www.mydomain.com/jobpage/Dublin

I’m using Views for my Jobpage and is there any way to “filter” by creating a link URL structure as described and how do I set this up??

Any suggestion or help is very much appreciated.

Sincere
- Mestika

You can use an argument on your view to apply the filter from the URL. If you set the "action to take if argument is not present" to display all values then your standard job page will continue to function as before.

In Drupal 7 arguments are called "contextual filters" and are hidden amongst the "advanced" view options.


drupal 7 block to show if page has taxonomy term I want to have a block to show only if the current page has a certain taxonomy term and was planning on using the block visiablity settings.

where Pages on which this PHP code returns TRUE (experts only). and need php code to find out how to tell check if taxonomy term is on the page and then the block will show up on nodes with that term.

The code posted by Triskelion did not work for me. Here is the code that I used and worked:

<?php
$term_id_to_trigger_show_block = 14; // show this block on nodes with this term id.
$taxonomy_to_search = "field_machinenameofvocab"; // The 'field_' + machine name of the vocabulary to search for the terms
$make_block_visible = FALSE;

// Show this block on nodes with the right term id
if (arg(0) == 'node' && arg(1) && is_numeric(arg(1))) {
  $node_obj = node_load(arg(1));
  $taxonomy = $node_obj->$taxonomy_to_search;
  foreach ($taxonomy['und'] as $term) {
    if ($term['tid'] == $term_id_to_trigger_show_block) {
      $make_block_visible = TRUE;
    }
  }
}

return $make_block_visible;
?>

Note that $taxonomy_to_search should be set equal to the machine name of the vocabulary prefixed with field_. So if my vocabulary machine name is animal_species that line would be $taxonomy_to_search = "field_animal_species";

UPDATE:
After using the above code on a site for quite some time I realized that it was giving me PHP errors in my logs. My solution was to give up on displaying a standard block and use views instead.

Create a new block view, set it to display fields. For your only field use "Global: Custom Text," entering your desired block content in the custom text field.

Under "Contextual Filters" add "Content: NID" and then "Provide default value" of "Content ID from URL."

Finally under "Filter Criteria" your only filter should be "Content: Has taxonomy term." Set it up to look for your term.


Order of search results for exact match content I am using Search API module with Search API DB module to use drupal database for search indexing.

Issue is when I do a phrase search as following "test content" I get results having "test"(let's say nid:1) or "content"(nid:2) or "test content"(nid:3) in them but the content having exact match which is "test content" which is node 3 shows down in the search results.

I do not have any fields for sorting in my search view.

My question is why I am not getting search results on phrase match on top of those who have partial matches?

Database search doesn't support phrases searches as stated here by the maintainer of the module (cf. https://www.drupal.org/node/2043339#comment-7654017) :

  Are you using the Database Search backend? In this case it's clear, because that backend currently doesn't support phrase searches due to technical restrictions.
  However, results should always contain both words, though not necessarily next to each other.

In order to sort your results, see this related question/answer I have no fields available for sorting with Search API sorts module


Feeds tamper fetch data from external API I am using drupal_http_request and drupal_json_decode to retrive and parse json from an external API in the feeds tamper by using the execute php code plugin. My code is as follows:

$json = "https://api.coursera.org/api/onDemandSpecializations.v1?ids=".$field;
$response = drupal_http_request($json);
$data = drupal_json_decode($response->data);
return ($data['elements'][0]['name']);

This returns a null value.

The json is as follows:

If I'm not mistaken {} indicates that it is an object and [] means that the variable is an array, therefor, I would expect $data->elements[0]->name would be the way to get the value in your return statement.

To improve your code, I would advise to use the empty() (or isset()) functions to check whether the elements in $data exists


How to include a Google font not available in @font-your-face module? I want to use a Google Font on my site. I saw the @font-your-face module and installed it. Unfortunately, it does not offer the version of the 'Pacifico' font I want.

Google suggests adding the following:

<link href='http://fonts.googleapis.com/css?family=Pacifico' rel='stylesheet' type='text/css'>

Is it possible to add it to all my Drupal page without fiddling with core code? Or is there are better way to add a font to my site?

You can add it by using drupal_add_css() in your template.php file's template_preprocess_html() function:

function mytheme_preprocess_html(&$variables) {
  drupal_add_css('http://fonts.googleapis.com/css?family=Pacifico', array('type' => 'external'));
}


User Registration to appear in a block I want the user registration to appear in a block in some other page than home, let's say a page called "Sign up." What I want to achieve is the following.

Well there is Form Block

  Enables the presentation of user registration, site wide contact, or
  node creation forms in blocks. This is particularly useful for
  including forms on panels.

Download and install the module.
Navigate to admin/structure/block You can see Registration form as a block there.


global webform submissions admin page per user I have a site where users fill diferent webforms and they can visit formX/submissions to view/edit their own submissions for every particular webform.
Now I need to give users something like a submissions administration page, where they can have a global view of their submissions to all webforms and be able to edit which one they choose.
is it possible to build this global submissions page with webform?

You literally read my mind because I just added this feature to latest dev release of the Webform module for Drupal 8

@see Users can view all their submissions across all webform instances.


Tax rate select missing from product price in commerce 8 I installed drupal commerce 8 rc2 and created a tax type of "European Union VAT".
When I create a new product, near the price field, I can't find the tax rate select.

How can I associate 10% or 22% vat rate to the price of product?

Try these 3 references:

1) Need to modify tax type based on user field in Drupal 8 Commerce 2

Here you can see an example of creating your own service in a custom module to interact with the default TaxOrderProcessor or writing a simple module to override the tax order processor service at all.

2) https://www.flocondetoile.fr/blog/apply-vat-rate-product-drupal-commerce-2

Here you can see how "to vary an applicable VAT rate according to a product, or a product type, we just need to implement a service that will declare the trade_tax.tax_rate_resolver tag with a priority at least higher than the default TaxResolver provided by Drupal Commerce."

3) https://www.rapiddg.com/blog/modifying-product-prices-drupal-commerce-2-drupal-8

Here you can see another example of application of "resolvers", the concept that do the work done bu Rules at Commerce 1, which is the key of the previous comment (link 2).

Ps: At the moment, poor documentation about this stuff, and no UI to manage this BASIC feature :-(


How to give access custom module to individual users? I have a custom modules name "Employee Entry" and i want that module show only some of the users under a specific role. Like if i have a role office then i want there is few people who can access the content of that module. There is a by default option to give access to whole role but there is no option to give access for specific users.

The correct approach here would be to implement hook_permission to define permissions/a set of permissions to give your user roles specific access.

The Example module has some good info on how to use and validate permissions with hook_permission in your code.

If you want to restrict certain users, the easiest approach is to create an additional role with those specific things and assign the desired users to that role.


How can I use Migrate Extras to get custom media fields to migrate? I'm a bit at the end of my rope in trying to get file fields to show up as possible destinations for my Media module migration.  I have Media 7.1.x installed because as best I can tell, that must be the version that Migrate Extras was supporting.  I'm trying to import files into the Other file type, so I have the following:

$this->destination = new MigrateDestinationMedia('other');
$this->map = new MigrateSQLMap($this->machineName,
      array(
        'id' => array(
          'type'        => 'int',
          'length'      => 11,
          'not null'    => TRUE,
          'description' => 'File ID',
          'alias'       => 'f',
        ),
      ),
      MigrateDestinationMedia::getKeySchema()
    );

Unfortunately I cannot get the field I added to the Other file type to show up as an available destination field in Migrate UI.  Any help on what I'm doing wrong here, or even a code snippet where someone has successfully done a media migration (for files, not youtube or anything fancy like that), would be greatly appreciated!

Update: I'm most of the way there, but my fields still aren't coming in.  Here is the array I created:

I create a $row->fields_array that looks like:

[fields_array] => Array
    (
        [0] => Array
            (
                [field_doc_public] => 1
                [field_testing_testing_testing] => UE2_3009.pdf
            )

        [1] => Array
            (
                [field_doc_public] => 0
                [field_testing_testing_testing] => UE2_3009.doc
            )

    )

I really only need the field_doc_public field to be filled in, but I added field_testing_testing_testing to test as you might guess from the name.  The field machine names are field_doc_public and field_testing_testing_testing.

The code in the actual migration looks like:

    $this->addFieldMapping('field_doc_pub_files', 'file_source_file');
    $this->addFieldMapping('field_doc_pub_files:file_class')
        ->defaultValue('MigrateEntityFileUri');
    $this->addFieldMapping('field_doc_pub_files:fields', 'fields_array')
        ->description(t('Populate the fields.'));
    $this->addFieldMapping('field_doc_pub_files:destination_dir')
        ->defaultValue('private://pub_docs');
    $this->addFieldMapping('field_doc_pub_files:destination_file', 'file_dest_filename');
    $this->addFieldMapping('field_doc_pub_files:file_replace')
        ->defaultValue(MigrateFileBase::FILE_EXISTS_REUSE);
    $this->addFieldMapping('field_doc_pub_files:preserve_files')
        ->defaultValue(FALSE);
    $this->addFieldMapping('field_doc_pub_files:display', file_public);

Any help on that last little push over the finish line would be greatly appreciated.  (Note: no destination for the fields shows up in Migrate UI either)

The following will allow you to use Migrate to import files as File Entities (used for Media 2.x) and populate the File Entity fields when importing Nodes (MigrateDestinationNode). No Migrate Extras needed.

Add the following to your custom migrate module's .info file:

files[] = includes/MigrateEntityFileUri.inc

Download/save the following code in an "includes" subfolder of your migrate module. (Strip the .php extension)
https://gist.github.com/dmsmidt/6f0f498a9dbaea8602fb

Then in your Migration class you can use 'MigrateEntityFileUri' as file_class.

Example code:

$this->addFieldMapping('field_media', 'your_file_uri_source_array');
$this->addFieldMapping('field_media:file_class')
  ->defaultValue('MigrateEntityFileUri');
$this->addFieldMapping('field_media:fields', 'fields_array')
  ->description(t('Populate the fields.'));
$this->addFieldMapping('field_media:destination_dir')
  ->defaultValue('public://your_file_sub_dir');
$this->addFieldMapping('field_media:file_replace')
  ->defaultValue(MigrateFileBase::FILE_EXISTS_REUSE);
$this->addFieldMapping('field_media:preserve_files')
  ->defaultValue(TRUE);

Note the sources: 'your_file_uri_source_array' and 'fields_array'.
You may need to do some processing in prepareRow() depending on your source to get your data organized like this (pseudocode):

public function prepareRow($row) {
    $row->fields_array = array(
      array(
        'field_one' => 'value_field_file_one',
        'field_two' => 'value_field_file_one'
      ),
      array(
        'field_one' => 'value_field_file_two',
        'field_two' => 'value_field_file_two'
      ),
    );
    $row->your_file_uri_source_array = array('file_one_uri', 'file_two_uri');
  }


Is there a way to limit how much storage users have to store their content? I have a video sharing site where members can upload and embed videos.

When members upload videos, is there a way to limit how much storage they have to store their content? Is there an existing module or one that can be modified in order to achieve this functionality?

It uses FFMPEG to convert the videos in the format that is required and I believe it is using the video module. The storage API sounds like it has promise.

With a support request and a little bit of work, Storage API could probably do this for you. In Storage API terms, I believe what you would do is create a "container" per user, and then use the sub-module "audit" to check how much space is being used. This number in turn could be used by the field widget you are using to limit uploads.


Allowing users to choose between two sort options in a view I have a view of user accounts.

I want to allow visitors to the site to choose to sortthis view by login date or by account creation date in a view (Views 3, Drupal 7).

It's easy to expose the sort operator to users, but is there a way to let users select which sort is applied first (creation date or login date)?

I thought about just cloning the view, and then changing the sort on the second view and linking them together, but if possible I would like to avoid duplication.

You can do that with Better Exposed Filters. I've combined two sorts together that way before, one selected with Ajax refreshing sort, then having the secondary sort tied in with the same. I would checkout the handbook links on that page for more direction, they have some pretty extensive recipes there that you could use as a base to start from.

handbook page for further reference


Check if the page is the front page in a template How do I make a simple front page check wich only shows a  in my template when the user is on the front page of the drupal website?

I tried this but it ended up crashing:

<?php function drupal_is_front_page() {?>
TEST
 <?php } ?>

Is this possible with a if instead of this function wich i found on the drupal website?

Thanks!

You should not declare a function in a Drupal template. Instead, you should just refer to that function:

<?php
if (drupal_is_front_page()) {
    ?>
Test
<?php
}
?>


Use multiple choices of CSS class in Insert If using Insert module, in the field editing, we can put Additional CSS classes to the image being inserted.

I need the images float right. So I type floatrimg in the field editing, and .floatrimg {float:right;margin:0 0 10px 10px;} in CSS. It works fine.

But if I need to have 2 images in one post: one image float right, another one float left, I need 2 image fields.

I hope I can have one image field, where multiple choices of CSS class can be selected when submitting. So that with one image field, I can insert image float right and float left.

I would suggest you to create two presets. Each preset can then be styled and positioned with CSS and the .imagepresetname class. You just have to activate the presets you like on the field in the "Insert" settings.


node_delete and caching Why is it that node_delete (which calls node_delete_multiple) empties all node cache even though it has the list of specific nids?

I have 200K+ records, all of which I would like to cache pre-emptively by entitycache module + Drush Entity Cache Loader (ECL). This is (obv) an expensive operation - but deleting even one node empties entire cache.

I realize that I can simply modify entitycache module to do exactly what I want - but I am just wondering about the rationale behind emptying entire cache.

One reason i see is Entity Reference...

For Example -

A block which lists some nodes part of your delete list.
A node which has entity reference to your deleted node
A view page which has some of your deleted nodes

Reason for clearing all the caches: When a node is created/updated/deleted there can be many pages in the site which are dependent on the current node in question. It is next to impossible/very difficult identify all the dependencies and clear the caches only for those pages. For this particular reason, to make sure that no stale data is served to the end user drupal by default clears all the caches.

So, It makes sense to Clear the page and block and node_load_multiple caches as documented in node_delete_multiple function.


How can I export users, forums and comments to another Drupal site? I need to move Forums containers and topics and their associated comments and users to another Drupal site.  I am exporting it into an already existing site.  How can I do this?

If you want to export into a live site where there already exists forums, topics, nodes, comment users that you not want to overwrite, I suggest you check out the
Drupal-to-Drupal data migration module.  It will let you move the data and refactor it in the process.


URL alias in view with subfolder of the Drupal installation I've never seen this before:

This D7 installation runs in a subfolder of my dev server. The same way as all the other installations.

In a view I have a field with the node alias path. But this path I get with the subfolder.

Drupal runs in: myserver/subfolder/mydrupal
The path is: this-is-my-node

I should get: this-is-my-node

I get: /subfolder/this-is-my-node

When I overwrite the output of this field with [path] all works fine.

What could be happened?

Open your root .htaccess file and uncomment RewriteBase /

This should set the new root for your Drupal installation when operating out of a sub folder. This is usually required when enabling Clean URL's.


can we change block title using template_preprocess_block? I am having a need to dynamically change the title of a block. Here is what I am trying but no avail.

function MYMODULE_preprocess_block(&$variables) {

  if ($variables['elements']['#id'] == "views_block__weekly_schedule_all_blocks_block_2") {

    //$variables['elements']['content']['#title']['#markup'] = "Foobar";

    //$variables['elements']['content']['#title'] = 'foibar';
  }
}

Any help is appreciated.

See the block_example.module. It's hook_block_view_alter you can use to do this programmatically. You can probably use it in a *.theme as well.

Source block_example_block_view_alter.

use Drupal\Core\Block\BlockPluginInterface;

function MYMODULE_block_view_alter(array &$build, BlockPluginInterface $block) {

  // We'll search for the string 'uppercase'.
  $definition = $block
    ->getPluginDefinition();
  if (!empty($build['#configuration']['label']) && mb_strpos($build['#configuration']['label'], 'uppercase') || !empty($definition['subject']) && mb_strpos($definition['subject'], 'uppercase')) {

    // This will uppercase the block title.
    $build['#configuration']['label'] = mb_strtoupper($build['#configuration']['label']);
  }
}

Most often you find answers to questions like that really fast when you google for Drupal X how to X programmatically or similar.


Edit the classess applied to a field from outside the field template I am creating my own Panels Style Plugins.

The styles are applied to a Panel Pane which contains a field.

From the Style, I can add a wrapper DIV to modify the display of the field.

However, I would like to be able to modify the actual class on the field itself (this would negate the need for a wrapper DIV).

In my field.tpl.php file I have placed a PHP variable for the class, but I'm not sure how I can access and modify this variable from outside the field.tpl.php file. Could some one give me some pointers.

Thanks!

Check out Semantic Panels. It lets you choose HTML element and classes for wrapper, the field and the label. The module provides the same options that are available to customize the field output in Views.

Here's a screenshot from the user interface when you customize the field.


Update a Referenced Node with a value from the node referencing it In Drupal 7, it was easy to update a referenced node with a value from the node referencing it, using rules: https://www.drupal.org/node/1836240

But how could I do the same in Drupal 8? This code is for updating a node programmatically:

use Drupal\node\Entity\Node;
$node = Node::load($nid);
$node->setTitle('MY NEW TITLE'); // This is a special meta field
$node->set('FIELD_NAME', 'THIS IS DATA'); // This is a Field added in to the content type
$node->save();

What hook should I call and place this code inside? I need when the user creates a new node or updates an existing node, then a field from the referenced node been updated with the value of a field from the current node. Should I use a form alter function? Is it possible with hook form alter to update, not only the current node, but also a field from the referenced node, or is there another hook for that?

Thank you both @GiorgosK and @4k4, for pointing me to the right direction! Here is the solution:

use Drupal\node\Entity\Node;

function my_module_entity_insert(Drupal\Core\Entity\EntityInterface
$entity) {
 if ($entity->getEntityTypeId() == 'node' && $entity->bundle() ==  'iamoriginal') {
   if (!$entity->field_my_reference->isEmpty() &&   !$entity->field_number->isEmpty() &&
 !$entity->field_hide_me->value) {
  _my_module_update_parent($entity, 'add');
 }
 }
}

function my_module_entity_update(Drupal\Core\Entity\EntityInterface $entity) {
 if ($entity->getEntityTypeId() == 'node' && $entity->bundle() == 'iamoriginal') {
$original = $entity->original;
if (!$entity->field_my_reference->isEmpty() && !$entity->field_number->isEmpty() &&
  $entity->field_hide_me->value != $original->field_hide_me->value) {
  $operation = ($entity->field_hide_me->value) ? 'sub' : 'add';
  _my_module_update_parent($entity, $operation);
}
 }
}

function _my_module_update_parent($entity, $operation) {
 $ref = $entity->get('field_my_reference')
   ->first()
   ->get('entity')
   ->getTarget()
  ->getValue();
 if ($ref->hasField('field_number_of_originals') &&        $ref->hasField('field_total_value')) {
$total = $ref->field_total_value->value;
$count = $ref->field_number_of_originals->value;
$number = $entity->field_number->value;
switch ($operation) {
  case 'add':
    $total += $number;
    $count++;
    break;
  case 'sub':
    $total -= $number;
    $count--;
    break;
}
$ref->set('field_total_value', $total);
$ref->set('field_number_of_originals', $count);
$ref->save();
 }
 }

If a user adds a new node of the post type "iamoriginal" then the value of the field_number is added to the refrenced node's field_total_value and +1 to the field_number_of_originals. If he later wants to disable the original node ,he gives a value to the field_hide_me and the previously added values to the referenced node are abstracted. Thank you again for your help!!!


How to check if field in Field Collection is required? I'm running into a problem of programmatically checking fields in a field collection.

What I want to do is loop through all fields within a field collection and check which ones are required.

I've tried these codes so far but haven't got any positive results.

$collections = field_collection_item_load_multiple($collection_ids);
foreach ($collections as $collection) {
   foreach($collection as $key => $va) {
        if (strpos ($key, 'field') !== false) {
            if (isset($va['und']) && is_array($va ['und']) && isset($va['und'][0]['value'])) {
                print "Field ".$key." ".$va['und'][0]['value'];
            }
        }
    }
}

This shows me the data and the label of the fields, not really their properties.

Thank you for your help.

Great Question :-) After re-engineering Field UI module found a simple way to retrieve above details...

  $bundle = field_extract_bundle('field_collection_item', 'field_my_collection_fields');

  $instances = field_info_instances('field_collection_item', $bundle);

  foreach ($instances as $field_name => $field_properties) {
   if ($field_properties['required'] == 1) {
     drupal_set_message($field_name . " is  required");
   }
   else {
     drupal_set_message($field_name . " is  not required");
   }
  }

Replace field_my_collection_fields with your field collection field name in above code ...


How can I add a CSS class to the body tag based on the current path alias? Is it possible in Drupal 8, to add a CSS class to the <body> tag based on the current path alias?

In your theme, you can add the following code in template_preprocess_html:
$current_path = \Drupal::service('path.current')->getPath();
$path_alias = \Drupal::service('path_alias.manager')->getAliasByPath($current_path);
$path_alias = ltrim($path_alias, '/');
$variables['attributes']['class'][] = \Drupal\Component\Utility\Html::cleanCssIdentifier($path_alias);


Second Contextual Filter on Calendar Module I'm attempting to add a second contextual filter to a Calendar view generated by the Calendar module.

I'm using the entity reference module to reference all my 'Events' to 'Clients'. My desired outcome is to go to a url like example.com/client/[client-nid]/calendar/month and for the calendar to only display events that reference that client.

My Event content type has an entity reference field 'Client'. In my view, I have added a Contextual Filter for this field and set it to validate against 'Content', specifying 'Client' as the content type and Filter Value Format is Node Id.

When i use this view though example.com/client/182/calendar/month I only see a calendar with a single event on it, even though there are many nodes that reference node 182. What am i doing wrong?

Entity reference field can not provide content id to your view through contextual filter by default. You'll need to define a relationship to your entity reference field so that view is able to pick up Client node id ( content:nid) as contextual filter.

Remove contextual filter that you have now and add relationship to the entity reference field 'Client'. Then add contextual filter to Content:nid. In relationship setting select the alias of relationship that you added previously. In the section " When filter value is not available" check 'Provide default value -> raw value from url -> path component = 2'. Also check "use path alias".


How to uninstall OAuth2 OR fix it i'm new in Drupal.
I tried on my site to mount the OAuth2 world but I can't get to the top. The website shows an error that is

Error: Interface 'League\OAuth2\Server\Repositories\AccessTokenRepositoryInterface' not found in include() (line 13 of modules/simple_oauth/src/Repositories/AccessTokenRepository.php).

same applies if I try to manually uninstall the module via ssh with drush pm-uninstall simple_oauth oauth2_server it is impossible:

In Connection.php line 896:
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'site_drupal.oauth2_token' doesn't exist: SELECT "base_table"."id"
AS "id", "base_table"."id" AS "base_table_id" FROM
{oauth2_token} "base_table"
LIMIT 1 OFFSET 0; Array
(
)
In StatementWrapper.php line 116:
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'site_drupal.oauth2_token' doesn't exist

Basically: the site (or the admin section to uninstall the module) cannot be accessed unless this module presents this kind of error, and via ssh I can't figure out how to remove it.
I thank you for any kind of help.

You can do the following:

Run drush cex to export your configuration to the config directory.
Find the core.extensions.yml file in the configuration directory. Edit it, and remove the line that says: oauth2_server: 0
Run drush cim  to import your configuration. It should disable that module.


How to get all parent nodes from a menu item? Imagine the following menu structure:

Page 1 type: article
Page 2 comes from a view

Page 3 type: desirable < want this

Page 4 type: random

Page 5 type: random

Page 6 type: article

Lets say I'm on Page 5. I want to know if any parent menu item's node has the content type desirable.

I got a menu item id menu_link_content:uuid for Page 5. My current approach is the following:

<?php

$values['menu_parent'] = 'main:menu_link_content:uuid';
list($menuName, $entityName, $uuid) = explode(':', $values['menu_parent'], 3);
$menuLinkManager = \Drupal::service('plugin.manager.menu.link');
$parents = $menuLinkManager->getParentIds($entityName . ':' . $uuid);

foreach ($parents as $parentPluginId) {

  $mlc_ids = \Drupal::database()
    ->select('menu_tree', 'mt')
    ->fields('mt', ['route_param_key'])
    ->condition('route_name', 'entity.node.canonical')
    ->condition('id', $parentPluginId)
    ->execute()
    ->fetchCol();

  // menu_tree gives back node=nid
  if ($mlc_id && strpos($mlc_id, 'node=') !== false) {
    // split node=nid into separate values
    list($entityString, $nid) = explode("=", $mlc_id, 2);

    // load the respective node and see if it is a project
    $parentNode = \Drupal::entityManager()->getStorage('node')->load($nid);

    if ($parentNode) {
      $parentType = $parentNode->getType();

      // we found the parent project node
      if ('project' == $parentType) {
        $node->set('field_project_ref', $nid);
        $node->save();
        drupal_set_message(
          t("The content was automatically added a project reference due to it's parent menu items."),
          'status'
        );

        break;
      }
    }
  }
}

So I would go on and load the node if the database statement found something and check the node type etc. I just wonder if there was a more performant/ better, out of the box way of doing that?

Something like

$menuLinkContent->getTargetEntity()->getType()

or

entityManager()->loadEntityFromMenu()

would be nice.

I don't think there's anything as simple as $menuLinkContent->getTargetEntity()->getType(). Though that would be nice and I'd love for someone to correct me on that.

Below I wrote a method that loads the menu, loops through the menulink objects, grabs the url objects from them and loads the nodes based on the path of the url object. Once it has the node it gets the content type from it. I doubt it's better performance wise, but it does take advantage of more of the out of the box stuff and might be a bit easier to read.

$menu_tree = \Drupal::menuTree();
$menu = reset(\Drupal::entityTypeManager()->getStorage('menu')->loadByProperties(['uuid' => $uuid]));
$menu_parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu->id());
$menu_tree_elements = $menu_tree->load($menu->id());

foreach($menu_tree_elements as $menu_tree_element){
    $path = $menu_tree_element->link->getUrlObject()->toString();
    $node = self::nodeFromPath($path);
    $contentType = $node->getType();
    foreach($menu_tree_elements->subtree as $subtree_menu_element){
        $path = $subtree_menu_element->link->getUrlObject()->toString();
        $node = self::nodeFromPath($path);
        $contentType = $node->getType();
    }
}

function nodeFromPath($path){
        $path = \Drupal::service('path.alias_manager')
            ->getPathByAlias($path);
        preg_match('/node\/(\d+)/', $path, $matches)) {
        $nid = $matches[1];
        return Node::load($nid);
}


AJAX button on table rows to delete rows I have a standard form with a table. I can add lines to the table via AJAX.
I also like to delete the lines using AJAX. But I don't know exactly where and how to add the buttons.

Here is my code to build the table inside the standard form building function:

  ...
  $aPersonsTable = array();
  foreach ($aPersons as $key => $value) {
    $row = array($value['dname'],'HERE IS THE PLACE WHERE THE BUTTON SHOULD SHOW UP');
    $aPersonsTable[]=$row;
  }

  $form['persons']['ptable'] = array(
    '#theme' => 'table',
    '#header' => $pheader,
    '#rows' => isset($aPersonsTable)?$aPersonsTable:null,
    '#disabled' => TRUE,
    '#title' => 'Users currently assigned',
    '#empty' => t('No users assigned yet!'),
    '#prefix' => '
',
    '#suffix' => '
',
  );
  ...

I'd like to have the button at 'HERE IS THE PLACE WHERE THE BUTTON SHOULD SHOW UP' :-)

I tried something like:

$row = array($value['dname'],array(
  '#type' => 'submit',
  '#value'=> 'Delete person',
  '#attributes' => array('id'=>$value['id']),
  '#ajax'=> array(
    'callback' => 'delete_person_ajax_callback',
  )
));

Any ideas?
I googled and stackexchanged a lot, but did not find the right solution.
Thx.

I found the answer using drupal_render(). The buttons are now generated in each row, havin their own ids, so that I can read the triggering element in the callback function.
Now I only have the problem whe I click one of the buttons, the complete form is submitted. There seems to be no ajax callback. I will search further an will the edit the answer...

  foreach (aPersons as $key => $value) {
    $form_button['button'] = array(
      '#id' => 'del_'.$key,
      '#type' => 'button',
      '#value' => 'Delete',
      '#ajax' => array(
        'callback' => 'delete_person_ajax_callback',
      )
    );
    $deleteButton = drupal_render($form_button['button']);
    $row = array($value['dname'],$deleteButton);
    $aPersonsTable[]=$row;
  }


problem when adding jquery.js file I need to run jquery code in my content type form so i added jquery-1.8.0.min.js file in info file of my theme.

after clear all caches something wrong happened, the "add more" button on date field stop working, i'm sure it's from adding the js file.

Any suggestion?

Drupal already includes jQuery. You should not add another jQuery library because this can cause conflicts with the existing one.

I suggest you to use jQuery Update if you want to use another version of jQuery.

If what you want is to run your own javascript code, you could add it using drupal_add_js().

Hint: Try first with alert('hello world'). See Working with JavaScript and jQuery.


Translating strings to English from a second language It seems that Drupal 7 doesn't provide a function to translate a non-English string to its English equivalent. I'd like to do this for a project I'm working on, but the absence of a reverse-translation function suggests that perhaps I shouldn't. Is there any reason for the absence of a function that translates strings back to English? And how should I achieve this functionality with my project?

t() function

By Drupal architecture English is a system built-in language which is used as a source language in code.
t() function allows to translate from system language to any other language. It is simple and expected behavior.

UI

There are UI improvements in Drupal 8: http://hojtsy.hu/blog/2013-aug-20/drupal-8-multilingual-tidbits-12-english-can-now-be-translated

Comment about Drupal 7 "Custom English" and problems with default language:

  Using Drupal core alone, this was possible to achieve in Drupal 7 by
  configuring a "Custom English" language on the site with a language
  code different from "en", which then allowed you to replace text with
  your choosing. This quickly gets confusing though because then both
  the old "en" English language and your new "Custom English" will show
  up in language selectors, etc. If you disable the "en" English, then
  your old content saved with that langcode will not display properly.
  Its a whole can of worms. You may also use String overrides, but if
  you are using interface translation from core anyway, using one more
  module for the same task for a specific language is overkill.

i18n features

More complex translation features (like Content translation from core or i18n package) less depend on system language but often depend on default language. Usually you can add content piece in any language and then translate it to English without any problems.

Summary

In code use English only and translate it to other languages in UI.
Select default language once and do not change it.
For changing built-in English strings check out “Translating English strings” section in this article: http://www.packtpub.com/article/setting-basics-drupal-multilingual-site-languages-ui-translation (String Overrides / Custom English / settings.php)
Discover i18n package tools.


Add a link on to /cart on /cart/checkout, using uc_cart_checkout_form. necessary or not? I am trying to add a link or button from the checkout page
http://dev.hearst.gotpantheon.com/cart/checkout

To the update cart page
http://dev.hearst.gotpantheon.com/cart/

Right now there are only two buttons showing up, "review cart" and "cancel"

strangely enough if I press "enter" on my keypad I get redirected to the desired update cart page.
http://dev.hearst.gotpantheon.com/cart/

I am thinking of using

function MyThemeName_uc_cart_checkout_form($form) {

}

To add a simple link to 'update cart' into the html or as a form element, I am new to Drupal. How would I do this using the form API? Or is there simply a setting I can set to make the "update cart button" appear http://dev.hearst.gotpantheon.com/cart/

The cancel button will take the user back to the cart page, which is why you are redirected there when you hit enter on the form.

You could indeed add the link by theming the checkout form.

The alternative would be by modifying the form itself, and adding a new markup type element:

$form['cart_link'] = array('#value' => l('Cart', 'cart'));

You can modify the form using hook_form_alter

But using the theme hook is fine too!


Rule is not changing field value I am new to Drupal.

I have created a rule on specific event, and changing the value of node:field-seat-limit

Event

After updating an existing order product

Conditions

Content is of type event
uc-order-product:node:field-seat-limit (negate)

Action

Decrement uc-order-product:node:field-seat-limit by using $value= $value-1;

Result: I am displaying field-seat-limit in a view, where it is showing the decremented count but when I go to the node, it shows the count that I entered first time.

What is causing the node to fail to reflect the updated value?

You may have to save the changes after you make them.  After your decrement action, add another action to save the entity.


Change secondary menu id How can i change the secondary menu id, by default it has the same id like primary menu. My primary menu id is menu-main-navigation and when i print in twig the secondary menu like {{ page.secondary_menu }} it prints with same id.

No need to change the id, i am printing the region not the block, just change the block from secondary menu region and will print the new block.