How to increase delta value of a multiple valued field +1? I would like to output the delta value of a multiple image field as a affix for the image title in a view, but increased with 1. So, it should start with 1 not with 0. How can I do this?

Why do I need this? I need to reference to the images from articles using the scheme Fig. 1, Fig. 2 etc. There for the view output should look like:

+----------------+
|                |
|    an image    |
|    delta 0     |
|                |
+----------------+
Fig. 1: Image Title

+----------------+
|                |
|    an image    |
|    delta 1     |
|                |
+----------------+
Fig. 2: Image Title

+----------------+
|                |
|    an image    |
|    delta 2     |
|                |
+----------------+
Fig. 3: Image Title

The first thing I tried is, to sort the view by delta and than output "Global: View result counter", but this does not work if a filter is applied to the view. If a filter is in action, the numeration would not be concordant with the delta anymore.

Do I have to write an custom formatter? And when, where do I start, I don't have an idea.

It depends upon what you're planning to do with that delta. Here's a possible solution for you:

Use Aggregation on the view and use "max" for the delta.  Hide the field and then do a math operation to add +1 to the value of the delta.

If you could expound on the "why" it would help.


Drush pm-update: How can I stop it from trying to update more recent dev releases? I'm using drush 5 to update the modules on my site.  Usually it works great.  However, when I have downloaded a dev release, even if there is no more recent point release it tries to update the dev release module to the last official "point" release.

For example, I have heartbeat-dev installed (2012-Mar-20).  Yet when I run the drush up command, it prompts me to update to heartbeat 1.0 (2011-Jun-25).

If there is a newer dev release, I want to update to that.  If there is a newer point release, I want to update to that.  But if I have a dev release and the point release is older, I don't want to update.  How can I do this?

I've been handling this manually but as the number of modules on my site grows it's getting harder to keep track of which to update and which not to update...

Basically, this sounds like a bug that should be addressed in the drush issue queue.  I'm guessing this is recent; it used to be that Drush would never go from dev to stable unless you used pm-download.  Now it is being a bit overzealous.

As a workaround, you can use the --lock option to stop Drush from updating the module at all (drush pm-update --lock=heartbeat), but this will also exclude newer dev releases as well.


Load disabled items in a menu I load my main menu programmatically with the following code :

    $menuTree = \Drupal::menuTree();
    $menuTreeParameters = $menuTree->getCurrentRouteMenuTreeParameters($name);
    $menuTreeParameters
        ->setMinDepth($minLevel)
        ->setMaxDepth($maxLevel);

    $tree = $menuTree->load($name, $menuTreeParameters);
    $tree = $menuTree->transform($tree, $this->getDefaultManipulators());

    return render($menuTree->build($tree));

I would like to get all my menu items, included thoses which are disabled. When I inspect $tree variable, I have all my menu items.

I don't know why but after the call to the build method, I get only my enabled items.

Check this line in buildItems() which is called by $menuTree->build($tree), in \Drupal\Core\Menu\MenuLinkTree.php:

  // Generally we only deal with visible links, but just in case.
  if (!$link->isEnabled()) {
    continue;
  }

It's designed to exclude links that are not enabled. I played around with something like this to get them all showing:

foreach ($tree as $id => $treeItem) {
    // Get the link definition.
    $definition = $tree[$id]->link->getPluginDefinition();

    // Skip links that are already enabled.
    if ($definition['enabled'] == 1) {
        continue;
    }

    // Change definition and enable link.
    $definition['enabled'] = 1;

    // Recreate the link.
    // I'm not 100% sure about the correctness of this part.
    // This is my first time playing with this stuff. Hopefully someone can fill in this blank.
    $pluginContainer = \Drupal::getContainer();
    $conf = [];
    $newLink = \Drupal\menu_link_content\Plugin\Menu\MenuLinkContent::create($pluginContainer, $conf, $id, $definition);
    $tree[$id]->link = $newLink;
}


How do I hide an article if it doesn't have an image? How do I hide an article if it doesn't have an image?

In Drupal 6, the setting is Block: Configure filter Content: (field_image), but I can't find this settings in Drupal 7.

You can put a condition on view filter. If image field is empty then row will not display.

  Content: field_image:fid (not empty)

OR

  Content: Slide image:fid (!= 0)


How to display the form submission results in a custom page? How to display the form submission results in a custom page or a view ?

I want to display it in a custom style with table , and want to do custom php coding too .

where i have to create custom page , or is there need a custom module for this ??

Display Webform Submission Data using Views is a bit challenging. As an alternative to installing Webform MySQL Views (which depends on Data and Schema), consider the Forena module. Here is a quote about it:

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

So in this case you'd use Forena to report about the Webform data stored in the Webform tables, which are contained in your Drupal database.

Disclosure: I'm a (co-)maintainer of this module,
I hope this does not violate the site's policy on self-promotion.


How do I calculate outstanding balance for product inventory? I have two content types, Product In and Product Out.
Content types Product In has the title as Product Code, and a field as Model.
The content type Product Out has a node reference (Product Code) to Product In, and a field as Customer Name.

I have a view, Product Inventory, with aggregation on. I have two fields:

Total Product In (By counting Content types Product In's title)
Total Product Out (By counting Content types Product Out's title)

How can I get the outstanding balance which I have inside my inventory?

Balance Tracker creates a balance sheet to display account credits and debits belonging to users. It can be integrated with views.

  It also provides UI tools, Views integration, and an API to allow the
  site administrators or other modules to credit or debit a user's
  account. This is intended for any website or service which credits
  users for accounts, sales, or other activities, and needs to track
  payouts.

I'm not using this before. Hope it helps you!!!


Custom form Edit, populate form field value by ajax (NOT dependent fields) I created a views page show the submission rec from custom form.
The SAME page, I embed a form block(add rec) after the views.

What I try to do is when I click the views row/record edit link.
it will populate the the field value to the form block WITHOUT
refresh the form. The "submit" value will change to update of
 course.

I find many examples on ajax just trigger event within same form.
Not by click the link outside the form, any idea ? Some direction please ?

You're going to have to trigger a javascript function, or a javascript event in your ajax callback
There are several different ways you can do that, some number of ways here:
How can I trigger a javascript function when a Drupal ajax call is complete?


Shared Multisite Settings Using a Drupal Multisite system, is it possible to have a base set of configuration settings shared across multiple sites?

That is, each site in Drupal has a settings.php file

default/settings.php
site1/settings.php
site2/settings.php
anothersite/settings.php

Is there a master settings.php where I could set a configuration value once and have it apply to all my sites?

Or is this normally handled at the deployment level?

so for what it's worth using the default/settings.php as the master and then having each of the sites do a PHP include (as @Alan mentions) does work well!  (I know this is an old question but I am working through multisite issues with Drupal 8 (8.6.13) and have come across this very thing...)

a couple of caveats:

1) I am managing the multisite installation and config manually so am creating my own settings.php files, not using drush site-install which will auto-generate the settings.php

2) you must do the include at the top of the site's settings.php and ensure that you are overriding only what you need to. (...or the inverse, that you are okay using the config in the default settings file)

I have this at the top of the settings.php for each site:

$default_path = "sites/default";
include $app_root . '/' . $default_path . '/settings.php';

and then override the database settings - setting the prefix etc:

$databases['default']['default'] = array (
  'database' => 'this_is_the_database',
  'username' => 'username',
  'password' => 'password',
  'prefix' => array(
    'default'         => 'site1_prefix_',
  ... etc

and the site name:

$config['system.site']['name'] = 'Site 1 Name will override default site name';

of course YMMV

tl;dr - yes you can, but be aware of the order in which your PHP will execute and apply the settings


Content pane of users related to node by field using panels, views (D7) I've created a Content Type of Service Page which is the same as a Basic Page.

I added a new field to Users called service_type and then added this field to Service Page. I set the service_type in both Users and Service Pages appropriately. When a Service Page is displayed I would like a list of the Users with the same service_type to appear below it.

I thought this would be a perfect place for Panels and Views so I made a Content Pane of Users:

Argument Input -> From context -> service_type

Contextual Filter -> Field: service_type

I added this Content Pane to my Panels Node and set Field: service_type to Node being viewed.

Doesn't work though; in fact, nothing appears. If I delete the Contextual Filter I do however get the full list of users, so clearly this is where the problem must be.

Can anyone point me in the right direction?

Views 7.x-3.1, Panels 7.x-3.0

The problem was that in the display fields section for my Content Type I had service_type hidden (because I only wanted to use it to filter Users without having to use a vocabulary), as such it wasn't featuring in the context and wasn't being passed into my View Content Pane.

I had to leave it displayed, then create a custom display for 'Full Content' and hide the field there instead.


How to display 12 grid for development purpose in bootstrap? I am using bootstrap theme and create child theme. i want to display 12 grid for development purpose.

Can any body tell me how to enable this?

Thanks

You could try adding a image of the grid as a css background image to the container class. This might fail if you are overriding it for any reason.

A more difficult way of achieving this would to try having a grid fixed position over your site that you can maybe toggle with JavaScript.


Why is my rules created shipping profile not being used? I've created a rule with the intention of pulling an address from the users account and creating a shipping customer profile type instead of showing the user an address field to enter shipping (The site is designed for customers to sell to their customers so someone might be looking over their shoulder and we don't want them to have to type their address in multiple times a day (even if it's saved)) while the rule creates a shipping profile type just fine if I don't have the shipping information pane in the process I don't get rates however I can look at the backend and have a properly (as far as I can tell) filled in shipping profile

A copy of my rule so far:

{ "rules_shipping_address_test" : {
    "LABEL" : "shipping Address Test",
    "PLUGIN" : "reaction rule",
    "WEIGHT" : "-10",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "commerce_shipping" ],
    "ON" : { "commerce_shipping_collect_rates" : [] },
    "DO" : [
      { "entity_create" : {
          "USING" : {
            "type" : "commerce_customer_profile",
            "param_type" : "shipping",
            "param_user" : [ "commerce-order:owner" ]
          },
          "PROVIDE" : { "entity_created" : { "shipping_info_unsaved" : "Customer Profile Shipping information Unsaved" } }
        }
      },
      { "data_set" : {
          "data" : [ "shipping-info-unsaved:commerce-customer-address" ],
          "value" : [ "site:current-user:field-primary-shipping-address" ]
        }
      },
      { "entity_save" : { "data" : [ "shipping-info-unsaved" ], "immediate" : "1" } }
    ]
  }
}

(it's not important now but in the future I'm planning on allowing the user to choose between 2 profiles on their account)

Update 1: After looking at a dsm of the order on a backend administration view that I was attempting to add shipping to I find that commerce_customer_shipping is an empty array which I assume is my problem that even though I'm creating and saving a profile it's not being set to the order?

It doesn't appear that you're assigning the profile you created to the order. You need to set the order's shipping profile to the one you just created.


Remove jquery script Possible Duplicate:
  How do I update jQuery to the latest version I can download?

In Firefox I get an unresponsive script error from Google hosted jquery but can't echo the problem on other browsers.

I just looked at the source of drupal and it's loading v1.4 of jquery automatically. I applied my own Google Hosted link to jquery v1.8 in html.tpl.php so in  the page is loading 2 versions of jQuery.

I think this could be the reason for the crash. In any case, I still want to remove the redundant script.

How would I go about removing the the automatically added jquery script? I want to print $scripts as some modules have dependents there.

You should use jQuery Update module. Here is a quote about it (from the module's project page):

Upgrades the version of jQuery in Drupal core to a newer version of jQuery.
Updates:

Drupal 5 to jQuery 1.2.6
Drupal 6 to jQuery 1.3.2
Drupal 7 to jQuery 1.5.x, 1.7.x, 1.8.x, 1.9.x, 1.10.x and jQuery UI 1.10.2
Drupal 8: TBD


Feeds Importer won't import autocomplete field I'm trying to use the Feeds Importer plugin. I have a field that's an auto complete and it maps to a NID. I have the NID in the csv file I'm trying to import but it doesn't ever populate that field. It does populate every other field correctly, though.

Any thoughts why this might not be working?

Found the bug... http://drupal.org/node/1426762


How to get list of activated and deactivated module using some script from database? How to show list of activated and deactivated module using some script from database?

For disabled modules:
SELECT * FROM system WHERE type='module' AND status=0

For enabled modules:
SELECT * FROM system WHERE type='module' AND status=1

If you need to do this using drupal functions, you can try something like:

    $query = db_select('system', 's')
    ->fields('s', array('name', 'weight'))
    ->condition('type', 'module')
    ->condition('status', 0);
    $result = $query->execute();

    foreach ($result->fetchAll() as $record) {
      // do something here...
    }

And process the results from $result.


How to access field in view template? I am trying to access from views-view-field--title.tpl template to another field...

I have this code:

<?php print $output;
  print $row->{$view->field['field_NAME']->field_alias};
 ?>

But it shows me just a number.. (1,2,3,4,5,....)

Can someone help me?

Thank you!

I'd suggest that you enable the Devel module on your drupal site (hopefully not a production version ;-).  Once you've enabled that module, you can use the dsm() function, within php tags in your templates to inspect in detail the variables that are provided in each template!

So enable the Devel module, then add the following to your template file:

<?php dsm($view->field['field_NAME']); ?>

Clear your cache and go to a page that contains a view... What the dsm() function should do is output your object in the 'Help' section of your page:

Just click on the object and start inspecting all the fields it has available.  You'll see that what it's returning with the 'field_alias' property is just the nid of that node...

Since you didn't specify what you're trying to get with the additional field, I can't be any more specific, but hopefully digging around will let you figure out how to get to the field property/properties you need.  Let us know if you figure it out!

p.s.  Since the 'title' field template is called for each row displayed in your view, you will get that 'field' object multiple times - once for each time the template was called.


How to set up the database for load-balanced Drupal 7 We currently run two Drupal instances (www1 and www2) behind a load balancer, and both instances are reading/writing the same mysql database. This seems like the wrong setup to me. Shouldn't we have it set up so that www1 reads and writes to db1, www2 reads and writes to db2, and db2 is a slave of db1?

db2 should never be written to if it is a slave of db1, because any write to db2 will never be propagated to db1, and they will quickly get out of sync.  The database must be shared and consistent.

There are 3 ways of getting a shared and consistent database experience: (1) Only have one database for all reads and writes.  This is the easiest, but provides a single point of failure, and unless the db is on a separate machine, it can result in unequal response times for the different servers.  (2) Use a Master-Slave setup and split your read and write requests between the master and slave.  Ideally, a master and slave databases are on different machines than the application servers.  (3) Use a multi-master so that writes to one are propagated to the other databases automatically, and vice-versa.  Again, usually the database machines are separate from the application servers.

The question is on how big does your system need to be?  If you are big enough to need more than one database server, then you should be looking at a cluster solution (MariaDB with Multi-Master Galera cluster, for example), but for that you need an odd number (minimum of 3) machines, which should be separate from your application servers.  Furthermore, in order to minimize bandwidth and cache rebuilding, you should also use a shared memcached server for cache tables.

As a point of reference, I implemented our system with a MariaDB Galera Cluster setup as a Multi-Master, but I treat it as a Master-Slave (which minimizes the chance of write conflicts).  I use AutoSlave to separate read and write requests, and send the read and write requests to different ports using HAProxy.  HAProxy then sends them to either a read or write server.  The "read" and "write" servers are really just part of the same Multi-Master cluster, but if my write master goes down, I have configured HAProxy to failover to the "read" servers until the "write" server comes back up.  The same thing happens for the "read" requests: Read requests are load balanced between the available read servers, but should they ever go down, HAProxy is configured to redirect all reads to the write server.  The end result is that Drupal thinks it is splitting up reads and writes, the cluster thinks that it is a multi-master, and it performs like a Master-Slave, with the advantage that it does not fail if either the master or the slaves go down.


Views slideshow from single node I'm trying to achieve working slideshow from images in single node. Images are uploaded from the image field. It's drupal 7. I made new content type and all I made now is slideshow from multiple nodes (with one image in every node). This works fine but thats too problematic to add new node for every single image.

In the views image field settings, under Multiple Field Settings, there is checkbox for "Display All Values in the Same Row" which is checked by default.  If you uncheck this box it will place each image in a new row and it will work as you require.  I know views has had this feature since at least version 2, but it might be called something slightly different in older versions.

I like doing it this way for simple slideshows, I can rearrange all of the images on one node/edit page. But for more complex slideshows, like where each image links somewhere or has alternate text, your best bet is probably still to use one node per row.


How to properly alter a field description in hook form alter I am altering a field description (help text) based on certain conditions. However, sometimes the description element to alter is set at $element['value']['#description'] = $new_description; And other times it's set at $element['#description'] = $new_description; I am doing this in a field widget alter hook:

/**
 * Implements hook_field_widget_form_alter().
 */
function my_module_field_widget_form_alter(&$element, \Drupal\Core\Form\FormStateInterface $form_state, $context) {
    // do the following based on some conditions:
    $html = \Drupal::service('renderer')->render($some_render_array]);
    /* @var Drupal\Core\Field\FieldFilteredMarkup $new_description */
    $new_description = \Drupal\Core\Field\FieldFilteredMarkup::create(t($element['#description'] . $html));
    // For some elements this works:
    $element['#description'] = $new_description;
    // For other I need to do this:
    $element['value']['#description'] = $new_description;
  }

}

Whats the difference? and do I have to use some logic to target the appropriate element?

The difference is that $element['value']['#description'] is the description for the property value. If you have a field with multiple properties you can set a description for each property. This is the common practice, but a field widget doesn't have to do it this way. Check formElement() of the widget to see how the element keys are used. Most widgets copy the content of $element to the subkey value, but not all.


Import images from Joomla com_exposé to Drupal 7 I'm transfering my website from joomla to Drupal 7, but I have about 500MB of images in the com_exposé in Joomla. The albums are organized in folders with the image files, and each folder, as a XML file containing the titles and such of each image.

<?xml version="1.0" encoding="utf-8"?>
<expose version="2.1">
  <picture _mngid="1">
    <title>FotoTitle</title>
    <image>
      <url>alb_100/img_1210610237_288.jpg</url>
    </image>
    <smallimage>
      <url>alb_100/img_1210610237_946_sm.jpg</url>
    </smallimage>
  </picture>
</expose>

Is it possible to import those images with the details from the XML file? I found a module to import the images but the data contained in the file isn't associated to the images.

Could I do this with a module, or could I code this myself? I have basic PHP programming skills, but no Drupal developing experience.

If all the page layouts has the same or similar kind of tags associated with them i would suggest you to write a custom scrapper and save the images locally.
If you are gonna use these images in you Drupal site, i am sure i can help you with a clear cut piece of code and implementation.


Can't set a default theme in a FunctionalJavascript test with $defaultTheme class property Trying multiple ways here to set a default theme to use in FunctionalJavascript tests and it is not working (I am watching them execute in VNC viewer). Bartik always shows.

I also tried setting $defaultTheme to stark, it does not appear either. It is always Bartik. According to the class and docs, this is supported in Drupal 8.8.2.

How can I make my theme default and load? This is the class my FunctionalJavascript class tests extend:

abstract class WebDriverTestBase extends CoreWebDriverTestBase {

  /**
   * {@inheritdoc}
   */
  protected $defaultTheme = 'MYTHEME';

  protected $profile = 'standard';

  /**
   * {@inheritdoc}
   */
  protected $strictConfigSchema = FALSE;

  /**
   * {@inheritdoc}
   */
  protected function setUp() {
    parent::setUp();
    $this->container->get('module_installer')->uninstall(['page_cache']);
    $this->container->get('theme_installer')->install(['MYTHEME'], TRUE);
    $this->container->get('config.factory')->getEditable('system.theme')->set('default', 'MYTHEME')->save();
  }

Edit: command being run:

docker-compose exec --user=$DOCKER_COMPOSE_USER php phpunit --testsuite unit,kernel,functional,functional-javascript

My phpunit.xml.dist file has limited those suites to my modules/custom folder.

Edit 2:

I have now done the following:

drush si --sites-subdir=testing.docker.localhost
drush then MYTHEME
drush cedit system.theme (set MYTHEME default)
drush pm-uninstall page_cache
drush en mymodule_user_auth
drush cr
phpunit ....

I had to set the block too (one test looks for the presence of a block). Now the tests pass. But why is the setUp() method not doing the above even though its being told to do so? Regular Functional tests adhere to this, why not FunctionalJavascript ones?

I wound up installing a barebones install with drush si and exporting certain configuration to an install profile. After adding this to drush si in CI and local, all functional javascript browser tests work without complaints.

I double checked and the parent BrowserTestBase class does have defaultTheme and profile properties, so I don't know why those were not installed.


CKEditor configuration is not working In my site it was not required to add color to text or change its size, but now we want to add formatting to our posts.

So I tried to configure CKEditor's Toolbar to add text formatting options in Drupal administration page, and after I added that, I see no changes in my CKEditor, new options weren't added.

How could I add that options?

Thanks in advance for your help

A few things you can try:

Make sure that when you are editing or creating new content that the "Text Format" selection box at the bottom of the WYSIWYG editor shows the same profile that you edited. On my site an advanced user can be allowed to choose from Filtered or Full HTML, and by default the Filtered HTML profile is loaded (thus they wouldn't immediately see changes to the "Full HTML" profile).
You can try clearing your cache if you haven't already.
I understood your question as not seeing the new options in the Toolbar, but if your issue is that you are not seeing something like bolded or larger font upon saving, it may be that you need to create an exception to a specific HTML tag in your "Advanced Content Filter" and/or the "Cleanup and Output" settings under your CKEditor profile options (/admin/config/content/ckeditor/ in Drupal 7).


How to output unlimited value Field Collection with dates into a Views table format with no duplicates? I have a Content Type called "Safety Training". It has various fields within it, including a Field Collection named "Dates & Locations", set to unlimited values so they can add infinite date/location pairs.

The two fields defined within the Field Collection are Date (a date ISO field with the ability to enter start/end date and times) and Location (taxonomy). The Date and Location fields are both only single value.

I have a Views page, where I am outputting the individual nodes and grouping them by category of Course Type. This is the format I need the Views table in (from the old site, static HTML):

This is what I have right now in Views (this is in the preview):

How can I separate the date, time, and location into individual table columns called "Class Date", "Location", and "Start/End Time" that will group them like in the old site?

I tried creating a Relationship, choosing "Content: Dates & Locations (field_safety_date_location)", but this immediately creates a duplicate of each item (so there's two Worker Initials, because there's two dates?).

This is the SQL query Views displays:

SELECT node.title AS node_title, node.nid AS nid, draggableviews_structure.weight AS draggableviews_structure_weight, 'node' AS field_data_field_safety_date_location_node_entity_type, 'node' AS field_data_field_safety_standard_fee_node_entity_type, 'node' AS field_data_field_safety_late_fee_node_entity_type, 'node' AS field_data_field_registration_link_node_entity_type, 'node' AS field_data_field_safety_category_node_entity_type
FROM
{node} node
LEFT JOIN {draggableviews_structure} draggableviews_structure ON node.nid = draggableviews_structure.entity_id AND draggableviews_structure.view_name = 'safety_environmental_training_schedule_and_fees' AND draggableviews_structure.view_display = 'page_1' AND draggableviews_structure.args = '[]'
WHERE (( (node.status = '1') AND (node.type IN  ('safety_environmental_training')) ))
ORDER BY draggableviews_structure_weight ASC

If anyone has any idea, please help! Thank you.

Revisiting this two years later after asking if I'd solved it. In short, yes, I did. :)

Here's a screenshot of the final product, still live:

Here's a screenshot of the view as of this morning:

Basically, I created two fields of the Field Collection item: Date, which I was able to access by creating a relationship to the Field Collection. I then changed the formatting of those Field Collections to be what I wanted them to be.

In the Table's settings, I used Grouping field Nr.1 to group them by Content: Category, using the rendered output to group rows. I also enabled sticky table headers so that the headers will follow the table down.

For the class date, I set the formatter to Date Range, and set the format to "F j" for single date, single date all day, single day date range. For Date format for single month date range, I set it to F j – {j}, for single year date range I set it to F j – {F} {j}. For multiple years date range, I set it to F j, Y – {F} {j}, Y

No aggregation or distinct functionality was used in the view, as all of the trainings can only be part of a single category, so I didn't get duplicates. You may need to factor that in. I've always had great results from the Views Distinct module when running into that problem.

The items are sorted first by the taxonomy term weight, and then by item. I also integrated DraggableViews so the editor can re-arrange them as they saw fit rather than alphabetically if they want. (I actually should remove the sort by start date bit, as that doesn't do anything.)

Hope that helps.


Sub-themes .tpl file is not overwriting parents In my sub-theme, I needed to adjust the HTML of a component that was part of the parent theme. To that effect I copied that components .tpl into my sub-theme's directory and made the alterations.

I then renamed it in accordance to theme debugs file name suggestions. I've done this many time before with no problem.

However, the alterations are not appearing on my site. I've run drush cc all and drush rr of course, but to not affect.

Would anyone know what's happening here?

Please try to see to follow same folder structure in base theme which parent theme have for .tpl files. Also check if you added base template file e.g. node.tpl.php for node--type.tpl.php link and also implement THEME_preprocess_page.

function THEME_preprocess_page(&$variables){
  if (isset($variables['node']->type)) {
   // If the content type's machine name is "my_machine_name" the file
   // name will be "page--my-machine-name.tpl.php".
   $variables['theme_hook_suggestions'][] = 'page__' . $variables['node']->type;
   }
}


How to prevent userpoints from repeating I need to grant points to users for updating their user profile with licensing info about their company. Right now I have the following rule:

Event: After updating an existing user account

Add event: NOT Data value is empty
Parameter: Data to check: [site:current-user:field_licensing]

Action:Grant reputation to a user
Parameter: User: [site:current-user], Reputation: 25, Reputation category: Reputation,
Operation: Insert, Moderate: Automatically approved

How can I stop Rules from adding points each time the user updates their profile? Since the rule checks if the field is not empty it currently awards 25 points with each update. How can I get Rules to check if the profile update added value for the field_licensing, or merely updated the profile and field_licensing has the same value?

You could put a field on the User entity called something like field_points_attributed and hide it from the authenticated users using Field Permissions.

Then set an action on your rule, so that as well as adding the user points, it also changes the value in the field to something like "yes" or "attributed".

Lastly, add a condition to check the value of that field, and ensure it doesn't say "yes" or "attributed".


What is the purpose of the "Links" field in the "Manage Display" UI? In admin/structure/types/manage/my_content_type/display, you can hide/show the fields to display.
There is a Links field that you can also hide/show.

What is the purpose of this field? Nothing is changing in my output when I hide it.

The Links section is used normally in Teaser section/display to display links like add comment, read more, etc.

On Node Full Display, it is depending on configurations we do. Such as "Add new comment" link will only be visible when we disable "Show reply form on the same page as comments" check-box in comment field settings. You can also give a try to Flag Module or other contributed modules which adds links on Node display.

Please check screenshot below (Teaser Display):

The above screenshot is of default Teaser Display of node type article, which is being displayed on site home page. When we hide Links from teaser display, these links are no more visible in node teaser.

Following screenshot shows links working in Node Full Display:
Depending on configuration we do in comment field (check screenshot below), comment link will be visible on Full Display.

Comment link visible, when checkbox is disabled.

Comment link is not visible, when checkbox is enabled.


Get the user uid (uid) from comment id (cid) If I have the value of the comment id (cid) ex: 5

how do I get the user id (uid)?

You need to load the comment object:

$comment = comment_load($cid);
$uid = $comment->uid;


share field template between node display and views Is there an easy way to share the same field template for both node display and views output?

Perhaps this requires a template.php template_files candidate addition?

Might have to do this: CCK Formatters, hoping there may be an easier way. Here is a quote about CCK Formatters (from the module's project page):

This package is a collection of add-on formatters for various CCK fields. Each provided sub-module in this package should be a self-contained single formatter.
CCK fields support an arbitrary number of "formatters", swappable code that renders a field. In Drupal 6 these are essentially theme functions, although in Drupal 5 they are not always. It is possible for any module to define new formatters for field types it doesn't define itself, which creates a very powerful way to extend and theme a field in any of the myriad ways that a field can appear.
This module is an "incubator" for new field formatters. Because each formatter may have its own development cycle, there will probably not be stable releases of the entire suite. If a specific formatter gets particularly popular or requires a more full-featured release cycle, it should likely be spun off to its own project.


How to theme a block with product list I'm trying to create a template for a block that I created at Views. So this View (block) has some filters in it, and if I use the default template layout lists my products as it should. My problem is that when I use a custom template, I don't know how to access to those products variables inside that block. I tried to find that variable using get_defined_vars() but was impossible because it display a huge list of vars, and yes, products are there, in an array called 'rendered_content', but I can't figure out the path to that variable in the huge list that is printed.

Please, help this desperate soul.

use devel module for better debugging option.Devel module provides dpm() which will make the array structure easy to see.When you know the exact array key where your content lies, its better to check the output with that key instead of dumping the complete vars.

so better you first do dpm(get_defined_vars());after installing devel module it will return the same what you are seeing now but in a well structure way, when you figure out the next better key of output holding the data,use dpm() on the returned array with useful key


Working of Views module in Drupal 7 I am very new to Drupal. I would like to know how Views module work.
I need clarification on my following understanding about the use of Views module,

"Views are not for creating new content or inputting data, I need to create content with page/article/field collection etc. then I have to provide views module to display those contents using views module."

To keep it simple,
Content types, Feeds, Webforms are like data input.
Views is like data output.

Views are specifically used to display the content nodes, feeds, etc. in various formats and can generate reports and exports. But You may also embed views in content types for example to keep track of previous data while entering new data.
Content types are used to input the data and we may also use feeds to import bulk data from csv or other file formats.


How do I auto-reset exposed filters? I am using views along with solr search api to display search results. Within results I need to add filters so I have used views exposed filter for the indexed fields. Now that I have exposed filter I am trying to reset all views exposed filters every time when someone tries to search something in the search field.

How do I achieve this?

I am using Search: Fulltext search (exposed) exposed filter to search for keywords using views.

In exposed form settings enable reset button and give label save it you will get reset button


Drupal 7 Batch Question I'm trying to set up a batch process and from the examples I see:

$context['results']['processed']++;
$context['message']

Is there a list of these, 'buckets' somewhere?

The array keys available in $context are listed in Batch operations:

  The following keys are provided:

  'results' (read/write): The array of results gathered so far by the batch processing, for the current operation to append its own.
  'message' (write): A text message displayed in the progress page.

  The following keys allow for multi-step operations:

  'sandbox' (read/write): An array that can be freely used to store persistent data between iterations. It is recommended to use this instead of $_SESSION, which is unsafe if the user continues browsing in a separate window while the batch is processing.
  'finished' (write): A float number between 0 and 1 informing the processing engine of the completion level for the operation.
  1 (or no value explicitly set) means the operation is finished and the batch processing can continue to the next operation.


Entity Reference - Not required to be in database I have a content type Proposal with a entity reference field Proposed by. This is an autocomplete field that targets Users in the application. You can give in multiple users that are in the application.

But now I would like to give the possibility to the user that they can give in user that are NOT in the application. So they can enter email addresses from random persons, they will receive an email with a link to register. But how can I get this data? Because it's not saved when the user isn't in the application.

I tried to do this with hook_node_validate but this is the result I get:

array (size=1)
'und' =>
  array (size=4)
    0 =>
      array (size=2)
        'target_id' => string '26' (length=2)
        '_weight' => string '0' (length=1)
    1 =>
      array (size=2)
        'target_id' => null
        '_weight' => string '1' (length=1)
    2 =>
      array (size=2)
        'target_id' => string '' (length=0)
        '_weight' => string '2' (length=1)
    'add_more' => string 'Add another item' (length=16)

So no email address that I gave in.. Just a target_id = null. How could I do this?

Entity Reference can reference entities only. It would be a really big hack to the module to allow non-entities to be referenced. But there is no need to.

There are dedicated modules for exactly what you are trying to do. Instead of Entity Reference, create User Relationships. Use User Relationship Invites submodule, it

  allows users to specify a relationship to a user that they invite to join the site.

Invitation is done by using e-mail, so it seems this will fully satisfy your use case.


menu callback path construction It seems there is hardly any documentation on page call backs using URLS

This being the case I have 2 questions:

What is a legal callback path?
and what becomes the URL to access that path?

Here is the code on my custom module:

  $menu['tipFeed/arguments/%'] = array(
'page callback' => 'tipfeed_create',
'page arguments' => array(2),
'access arguments' => array('access arguments page'),
'type' => MENU_CALLBACK,
);

Here is the function it refers to:

function tipfeed_create($first){
     return 'cool';
}

My module is called tipFeed.

why is the URL http://www.example.com/tipFeed/arguments/1 saying page not found?

Any help would be great, thank you

everything is ok, just try to clear cache and don't forget never, after any change in hook_menu clear cache


How do I choose the "date_popup" widget for custom date field from code? I have a custom field in a custom form element which is declared using the following code:

$element['data_da'] = array(
  '#type' => 'date',
  '#title' => t('Date from'),
  '#default_value' => isset($items[$delta]['data_da']) ? $items[$delta]['data_da'] : NULL,
  '#description' => t('Description for field Date from'),
);

When I insert data, I see three selects, one for year, one form month and one for day. I would like to use the "date_popup" widget.
How can I do that? What should I set?
Is there a '#widget' directive?

If you install the version 2.x of the Date module, you will be able to use more form fields, including a "date_popup" field, which shows a pop-up to select the date.
The module has an option that allows the user to decide if the pop-up should be shown; if you want to override that option, you should use variable_set('date_popup_timepicker', 'default'). That is the default option used by the module, but if the user selects "none," then the pop-up will not appear.

About setting a custom format with the "date_popup" field, the form field uses the "#date_format" attribute that, in the development snapshot 7.x-2.x, is said to accept most of the formats. The default value for that attribute is the one returned by variable_get('date_format_short', 'm/d/Y - H:i').
The complete list of the attributes used by the form field, reported in the comment for date_popup_element_info(), is the following one:

"#date_timezone"
The local timezone to be used to create this date.
"#date_format"
Unlike earlier versions of this popup, most formats will work.
"#date_increment"
Increment minutes and seconds by this amount, default is 1.
"#date_year_range"
The number of years to go back and forward in a year selector, default is -3:+3 (3 back and 3 forward).

Drupal core modules have only the "date" form field, and it doesn't use any "#widget" attribute. Third-party modules could define new attributes, though; as far as I know, no module defines "#widget" as attribute for form fields.


Drupal 8 Views or Pixture Reloaded paging/formatting problem Looks like I may have tripped over yet another bug in either Views or Pixture Reloaded in D8.

I created a view to show a simple content type I created called Newsletters. I can use the pager supplied by views to navigate to page 2 without a problem, but when I click page 3 or Next Page I get a screwed up display.

Excerpts from page 2 that displays properly.

Excerpts from page 3

View that I created.

Do you think this is a Views problem or a Pixture Reloaded problem?

Problem solved.

Looks like I had a corrupted instance of my Newsletter content type. When I deleted it the problem went away.


hook_menu_alter for taxonomy vocabulary My vocabularies machine name is vocab_ . $account_id .
First Funcs: too see the user $account_id is the same with vocab.. if yes then return TRUE.

function _term_account(){
  global $base_url;
  global $user;
  $account_id = custom_get_user_account_id();
  $tesr = explode('_', arg(3));
// admin/structure/taxonomy/vocab_21117 .. witch 21117 is $account_id
 if($tesr[1] == $account_id){
    return true;
 } else {
    return false;
 }
}

I use hook_menu_alter to alter the taxonomy url:

function custom_menu_alter(&$items) {
  // Works fine.. So every user has he's own and only vocabulary..
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/list']['access callback'] = '_term_account';
  // DOESN'T WORK.
  $items['admin/structure/taxonomy/%taxonomy_vocabulary_machine_name/add']['access callback'] = '_term_account';
}

UPDATE
When User edit term..

function _term_account_edit(){
    $account_id = custom_get_user_account_id();
    global $base_url;
    $term = taxonomy_term_load(arg(2));
    if($term->vocabulary_machine_name == 'branches_'.$account_id){
        return true;
    }else{
        return false;
    }
}

function custom_menu_alter(&$items) {
  $items['taxonomy/term/%taxonomy_term/edit']['access callback'] = '_term_account_edit';
}

The Delete Button dosen't Show up? Why?

The code looks good! However, try the following:

See if there is already a permission or a module which lets you control the things you wish to control. Maybe you can mention the desired outcome or the objective in the question?
Add a dpm() or something to the end of the function to see if the $items are being modified correctly.
Add a dpm() or something in the _term_account() function to see if it is being called correctly and that it is returning TRUE or FALSE correctly as per your requirements.


How to add 'add to cart' button to view based on a search index? Just got started with search_db and the search_api and facets. I have a view set on an index of my commerce products, but I don't have the option to add the 'add to cart' form as a field. There isn't an option to pull one in from a related field that I can see either. Any help would be appreciated.

thnx

I changed the index from the Commerce Products to the product displays, and this got me a different range of field choices. I could have probably achieved a similar result by adding a relationship, but I wanted this to be relatively clean and simple.


Best way to test if a commerce price field has a value So I have an entity called "Discount" with the following fields:

field_discount_percentage is an integer field.
field_discount_price is a commerce price field.

I can test whether the percentage field contains a value to avoid exceptions via:

if (empty($discount_wrapper->field_discount_percentage))

However this does not work for commerce price fields, as $discount_wrapper->field_discount_price is an object in itself and so the following is always true:

if (empty($discount_wrapper->field_discount_price))

Alternatively I tried:

if (empty($discount_wrapper->field_discount_price->amount))

However this produces an exception on zero values, and the following:

if (empty($discount_wrapper->field_discount_price->value()))

Which returns a PHP Fatal error as empty() can only take variables and not functions.

I am now resorting to:

if ($discount_wrapper->field_discount_price->value())

However this does not feel explicit and I was hoping there is a more conventional means to test price fields.

Adding isset() to that last if statement is a bit more explicit.

if (isset($discount_wrapper->field_discount_price->value()))


How to add a term ALIAS(!) to content URL pattern? I have latest Panopoly distribution installed (with Drupal 7).

What I need:

my content items of a certain content type to have the f-g URL:

"vocab term URL alias"/"Node-title"

(first part of the URL should be term alias(!), not the term name as I have my term names in Cyrillic).

What I did:

created the vocabulary with Terms
added the term field to the content type

What I managed to get:

I have a nice URL of that type: "term name"/"node-title". But I need
the term alias instead of term name.

I have looked for the answer but no dice so far.

Thank you in advance.

Did you try using the [term:url:path] token? This should grab the aliased path, there is also the [term:url:unaliased:path] token for getting the unaliased path.


Outputing a json file in drupal 6 I'm linking an android app with a drupal 6 server. Basically the app should be able to request information from the server to sync data and other simple functions. JSON is our preferred way of achieving this.

I've installed Service, JSON Server in drupal 6 and activated both node and view services. With views.get i'm able to get a JSON output of the default display from the view listed.

Question(s)

First thing I'd like to achieve is to have the JSON output in a separate file. Completely. Currently the JSON is being shown below the views.get page. I've googled solutions for this but only found for drupal 7.
I'd like the JSON to receive arguments from the android app using POST.

How can I achieve the two above.

Thank you very much.

Use Services Views

After enabling that resource you would be able to do call to

http://example.com/<endpoint path>/<resource name>

After enabling "views" resource in your services endpoint you can do GET request to:

http://example.com/<endpoint path>/views/<view name>

This will execute a view and pass results.

Possible arguments:
- display_id: views display
- args: array of view arguments
- filters: array of view filter values
- offset: views offset
- limit: limit views number of results
- format_output: boolean whether we would like to get themed view or data

Example of calls:

http://example.com/rest/views/articles?limit=5&offset=2&filters[tags]=5
http://example.com/rest/views/articles?filters[tags]=5&display_id=block_1&format_output=1


Is it a good idea to split a Drupal site into multi-site one for editors/admins and another for front end users? To illustrate:
I have a multisites with a shared db edit.example.com and site.example.com. They share many tables but do not share all (a work in progress to determine what exactly need to be share). For example, the system table is not shared in order to be able to control what modules need to be enabled across all, on edit.example.com only and on site.example.com only. Does this can help performance?
Is this a good idea or is it just adding an extra level of unnecessary complexity?For example I see caching becoming a problem because cache_page is not shared, or even if it is shared.

If there are any references out there please refer me to it.

Is this a good idea or is it just adding an extra level of unnecessary complexity?

There is no functional advantage of creating a multi-site for the purposes of separating content administration, as that will add an unnecessary level of complexity.

Some of the issues include determining what tables to share (which you've identified). Another common scenario is that content will be rendered differently depending on the site, leading to troubleshooting nightmares. An unscrupulous developer can have multiple versions of the same module in the site code, which creates head-scratching differences.

A single site is significantly easier to manage and ensure that administrative roles and permissions are logically set given your needs.

It can be helpful to have a distinct administration theme to visually enforce the difference between a normal and administrative roles. It's possible to specify a role per theme - https://drupal.org/project/role_theme_switcher for example.


Views issue: How to pull content from two different taxonomy vocabularies on same page I have two Content types:
Article1 with vocabulary1 with taxonomy terms: A, B, news;
Article2 with vocabulary2 with taxonomy terms: X, Y, news.

I need to create a /news view page that displays content from both Article1 and Article2 tagged with "news".

I tried to use Filter Criteria:
Has taxonomy term - vocabulary1 -> news
OR
Has taxonomy term - vocabulary2 -> news
Nothing shows.

Please note that I set up Pathauto to publish in /news/article_title both Article1 and Article2 tagged with "news".
Maybe a contextual filter could be used to pull all content from /news/*?

Thanks in advance,
Cosmin

I tried it myself and views filter OR group is not working.

I think you just hit on a known bug.

Follow the discussion in this issue and this one and apply the latest patches mentioned and see if you can make it work.  Make sure that you post back with your experience (did it work or not) so you can help this issue move along and eventually make it into a release.

As a workaround consider using 1 vocabulary (instead of 2) that holds all terms and your views filtering does not need an OR group.


Back button gets stuck in a loop after submitting a new comment I have a comment form shown below the comments list on a node page. I'm using pathauto for urls.

When I visit the page with the my-node-page#new link and then submit a comment it loads the node with a my-node-page#comment-1234. When I click the back button to get to the previous page I get to my-node-page#new. I click back again and get to my-node-page#comment-1234 and so on ...

I'll probably use Ajax Comments soon to avoid the page reload. Any ideas what I can do in the meantime? Looks like a bug in Drupal to me?

I did end up fixing it by using Ajax comments


Unpublish article based on non date type field So, I know that you need Rules to unpublish articles (after a certain time) based on date fields (https://groups.drupal.org/node/240678#comment-782543). But is this also possible with non date fields? When the user creates an article there should be a select list with items like 1 month, 3 months, 6 months. After submitting the article is saved as unpublished, it is moderated and published by an admin and should then automatically be unpublished after the period selected by the user.

If you don't want to write custom code you can use the https://www.drupal.org/project/scheduler module.

Quoting the description: "This module gives content editors the ability to schedule nodes to be published and unpublished at specified dates and times in the future "


How can I theme the Views Exposed Filter Results page? I'm trying to theme this page

http://208.87.22.137:50000/admin/rooms/bookings/list/kiosk/3?name=rest

which is the result of an exposed views filter. I have themed the node the views block is on but I'm not sure how to theme this page since it's not using node/NID.

Thanks.

You can use the devils module to get theme help. Also there is the <?php print $classes; ?> function that i have for instance on my div  with the class container div. And there I see for example the class page-searchresults. Giving away that I can use page--searchresults.tpl.php as a template file for theming that page.


PDF with print module and wkhtmltopdf - how to install? I try to generate pdf with the print module and have tried it with the PDF generators MPDF and DOMPDF. Unfortunately, the results are of no use, which is why I want to try wkhtmltopdf. I read good things about it.

Unfortunately, the installation guide is outdated. For instance, I read that you don't need a x server anymore since 3 years.

What I've done so far:

I have downloaded the latest version for Windows.
As described in the instructions I put the executable in the directory sites / all / libraries.
After I renamed the cryptic file names wkhtmltox-0.12.1.2_msvc2013-win32.exe in wkhtmltopdf, it was recognized in the print module settings.
When I try to generate a PDF on my local installation, a confirmation dialog appears where I have to give permission and then I have to install the executable. After installation a error message occurs (the problem is known, so I will not thematize it further).

My first problem is that I do not know how the .exe needs to be used properly. Whenever I want to generate a PDF, I have to install the program (via "Allow" - "Terms of Conditions" agree and then "Install below C: // Program Files / Files") to continue. There is something wrong. Does anyone of you see the mistake in my procedure?

Or can someone give me an advise how to make wkhtmltopdf work with the print module on a localhost (WIN7 and XAMPP), please?

I have downloaded the latest version for Windows.
  As described in the instructions I put the executable in the directory sites / all / libraries.
  After I renamed the cryptic file names wkhtmltox-0.12.1.2_msvc2013-win32.exe in wkhtmltopdf, it was recognized in the print module settings.

The executable you've downloaded is the installer, not the wkhtmltopdf executable. You need to install it to the sites/all/libraries.


Need help with how custom fields are displayed by article.html.twig file Noncoder here. After not poking my head under the hood of any CMS in years (not since Drupal 5, I think — and I wasn't very good at it even then), I'm working on a portfolio site. I suspect this question will be an easy one to answer for anyone with even modest coding experience; sadly, I can't claim to have even that.

This site will showcase previously published material, and it has to display the original publication date instead of the date that the content was added to the website. It also should display the name of the original publication.

I've created two fields for my article content type:

field_publicationdate
field_originalpublication

I would like the content to be displayed like this:

(Title field)
"Originally published in " (orginalpublication field) " on " (publicationdate field) [note: I'd like this to be consistent with the theme's custom date display format of 'F d, Y']
By (author)  (time to read)

It currently reads:

(Title field)
(date content was added to Drupal)    By (content creator)  (time to read)

I'm now in the node--article.html.twig file.

Someone who was helping me pointed me to lines 28 and 30 of the attached screencap, assuming I had enough basic knowledge to take it from there. While flattered in by this person's confidence in me, as I mentioned in my first paragraph, I'm an idiot when it comes to this stuff.

Can someone help?

If I understand correctly:

The node.createdtime in the screenshot comes from the content type setting "Display author and date information" on the content type edit page. Look at /admin/structure/types/manage/article.

If you need a different date shown, you can uncheck that setting to hide Drupal's author and date info display, then ensure your custom fields are displayed on the node instead. Look at /admin/structure/types/manage/article/display.

If the template node--article.html.twig renders content with just {{ content }}, your fields will show once set to display. If your template file is customized, you may need to add {{ content.field_publicationdate }}.

As @Kevin mentioned, use the field format options at /admin/structure/types/manage/article/display to control the output of your date field.

A more technical approach, and if your content is being imported, could be to map your field_publicationdate value to the node created time value. (But that's another question :)


footer link to a page with hash changed content ready I have set up the pages like this (using some php and jquery):

On this page, I have some tabs, using jquery to hide and display the content on click each tab. The url will change to #this_tab_name accordingly.

For example, www.mysite.com/thispage#tab1 will be showing the content of tab1 only when someone clicks tab1 on thispage.

Now I want to set up a footer site map, I want some of the menu items link directly to urls like www.mysite.com/thispage#tab1 and also display the right content while hiding the rest. Embedding "thispage#tab1" will only link to thispage, but without the right content.

Any suggestion? Many thanks!

You need to add your jquery to document.ready as well as click, that way when a user goes to the page it will load the proper tab for you.

Something like this:

jQuery(document).ready(
    function()
    {
        //bind click event
        jQuery("#tab1").click(show_tab);

        //handle document load
        show_tab();
    }
);

function show_tab()
{
    ...
}


How to add a field default to bulk user records I've added a field to the user profile page, and set the default. I can see that when I create a new user, the default is set, however for existing users the field is empty.

Is there a way to apply the default to all existing user records?

I've tried View Bulk Operations, but that didn't seem to have an action to update a field.

I'm about to write the mySQL script to update the field, but surely there is a better way........

Check out the answers to this question: Bulk field update? In particular the answer suggesting "Execute Arbitrary PHP Script".

(Looks like a duplicate.)


How to modify ds_bootstrap_layouts templates to add more layouts? I'm using the Display Suite Bootstrap Layouts module in Drupal 7, and I want to create additional layouts.

For example, I want the 4-4-4 stacked turned into a double 4-4-4 stacked. I know how to access the files and modify them, but it causes errors and it doesn't show up in the backend.

How do I add more layouts?

Implement the following hook

function MODULENAME_ctools_plugin_directory($module, $plugin) {
  return 'plugins/' . $plugin;
}

You can change the name of the 'plugins' directory, but cannot change the following.

Next you create a folder inside the 'plugins' directory and call it 'layouts' <--don't change. Then place your custom layouts in that directory.
Your .inc file will look something like this

$plugin = array(
    'title' => t('LAYOUT TITLE'),
    'icon' => 'ICON.png',
    'css' => 'CSS_FILE.css',
    'theme' => 'NAME OF TEMPLATE FILE W/O .tpl.php'
    'panels' => array(
      'top' => t('Top'),
      'top_left' => t('Top Left Column'),
      'top_right' => t('Top Right Column'),
      'middle' => t('Middle'),
      'bottom' => t('Bottom')
  ),
);

Panels will automatically scan your layouts folder for new layouts. DONT FORGET TO CLEAR THE CACHE. Your new layout will appear in the 'Miscellaneous' section when selecting a layout for your panel.


Adding group of fields in custom module I am trying to programmatically create a content type with 2 fieldsets, where the second one have an "Add more" option to create multiple set of fields. I looked for a working example to create multiple sets of fields, save, and edit them. Unfortunately, I couldn't find any. My module is creating, editing and saving the content type without 'add more' option.

Can anybody help?

I hate to say that there is an only way that I know to have multi-value field groups in Drupal 7 is Field Collection module. It is based on Entity API. It creates a new entity of which you can add any number of fields, and attaches that to the content type or any other entity you create.


Setting default parent item in Drupal 6 In Drupal 7 it is possible to set a default parent item at admin/structure/types/manage/article/edit.

Where is this option in Drupal 6?

If it isn't possible to do this in Drupal 6, is there a contributed module that will achieve this?

Node Menu Parent is the module you need to achieve this:

  The Node Menu Parent module gives us an extra option under the content
  type settings to choose a specific parent menu item per content type.


How to move VBO button to under view I'm just using Views Bulk Operations for the first time.

VBO augments Views  " ...by showing a checkbox in front of each displayed row, and adding a select box on top of the View containing operations that can be applied."

I have it all working as it should, however, I would like to move this select box and button to UNDER the view (under the table that I am making in my view). I've been looking at this for sometime, and haven't been able to figure out how to do this. Can anyone point me in the right direction? Thanks

You can modify the form by implementing hook_form_alter() either in a custom module or in template.php in your theme.

Here's a code snippet that brings the table above the other form elements by lowering its weight (source):

function mymodule_form_alter(&$form, $form_state, $form_id) {
  if (strpos($form_id,  'your_vbo_form_id') !== FALSE) {
      $form['output']['#weight'] = -99; //Decrease the weight of output to rise it above other elements.
  }
}


Window Title vs Page Title Can the Window/Browser title be set separately from the page title (which is displayed in an <h1>)?

I'd like to be able to do this in the most direct way possible from code, not using extra modules or configurations (unless that is the best route).

For example, I often use drupal_set_title() on a page definition.  I'd love to call a similar function right next to this to set a slightly different version as the window title.

The title set with drupal_set_title() is both the page title, and the browser window title.
If you are looking for a module that can change tHE window title, you can look at Page Title.

If you want to be able to do it from A CUSTOM module, you can implement hook_preprocess_page(&$variables) to modify the content of $variables['head_title'], which contains a modified version of the page title to use in the <title> tag.

function mymodule_preprocess_page(&$variables) {
  $variables['head_title'] = t("The new HTML title.");
}


install.php displayed instead of update.php This looks similar to

Drupal 7 keeps returning to install.php and reports no settings.php but it's all there

but I only just registered so can't comment.

This is a single site (still drupal 7.59). free_access is true, sites/defaults/settings.php is writeable by all (website on local machine to try to figure out solution.) Connection to mysql seems OK.

One clue: if I proceed to install, "Verify requirements" says things like:

  The Drupal installer requires that the ./sites/default/default.settings.php file not be modified in any way from the original download.

yet from within the nginx root directory:

# ls -l sites/default/default.settings.php
-rw-r--r--  1 root  users  26250 May  3 15:53 sites/default/default.settings.php

so where does drupal look? (I didn't find a mention of the root directory in the database...)

The script useful for tracking this down was:

<?php
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_CONFIGURATION);
print_r(getcwd()); echo '
';
print_r(conf_path()); echo '
';
$settings_path = DRUPAL_ROOT . '/' . conf_path() . '/settings.php';
echo "settings_path: $settings_path
";
$ret = realpath($settings_path);
echo "ret: $ret
";
?>

The clue was that $ret was empty. From the realpath documentation:

  Note:
  The running script must have executable permissions on all directories in the hierarchy, otherwise realpath() will return FALSE.

Changing

drwxr-x---  3 root  users  512 May 16 14:34 default

to have world executable permission worked around the problem.


Placing block from a module not working I've followed the tutorial to create a custom block from
https://www.drupal.org/node/2101565

My module installed fine and I can see the block in the list of available Blocks for placing, but as soon as I click "Place Block" I just see the ajax loader for about 1 second and then nothing happens, the dialog stays open and my block does not get placed. Cleared the cache etc. didn't help, the error log does not show any available messages.

My src/Plugin/Block/TestBlock.php file:

<?php
namespace Drupal\test_block\Plugin\Block;

use Drupal\block\BlockBase;

/**
 * Provides a 'Demo' block.
 *
 * @Block(
 *   id = "test_block",
 *   admin_label = @Translation("A Test Block"),
 * )
 */
class TestBlock extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build() {
    return array(
      '#markup' => $this->t('Hello, World!'),
    );
  }
}
?>

Drupal 8.1.1

You have an error in your block that causes a fatal error or exception.

Right click and open the place block in a new window and/or check your error logs.


Url length, how short it? Our website have a large Url when paste as a link, now we want to short it.

for example

http://www.awene.com/article/له%E2%80%8C-ژێرناونیشانی-ئه%E2%80%8Cو-شته%E2%80%8C-چیه%E2%80%8C-كه%E2%80%8C-ره%E2%80%8Cوشته%E2%80%8C؟-كۆرێك-بۆ-ئازاد-حه%E2%80%8Cمه%E2%80%8C-ساز-ده%E2%80%8Cكرێتوك

It looks like you're using path auto to create these urls but the problem is that the transliterated version of your title in the url is too long. Couple easy answers are to either use the shorten module as jimajamma suggests (which is probably the best answer since it helps users with these long, complicated URLs) or you can update your automated alias settings to remove the title and use something else (ex. article/[[nid]]).

However, if you really want to keep the long title, you're going to need to truncate it when used by pathauto. I ran into a similar problem with custom breadcrumbs and long titles so I created a quick token hook to truncate the title. Here's how you could do that:

In your site module (if you don't have one you can create one and name it whatever you like), add the following (this code below was for 6.x) to register a new token to the token list:

function MYMODULE_token_list($type = 'all') {
  $tokens = array();

  if ($type == 'node' || $type == 'all') {
        $tokens['node']['MYMODULENAME-truncate-title'] = t("A truncated title token.");
  }

  return $tokens;
}

Next, add a processing function to tell token what to do with this new token value:

/**
 * Implementation of hook_token_values().
 */
function MYMODULE_token_values($type, $object = NULL, $options = array()) {
  $values = array();

  switch ($type) {
    case 'node':
      $values['MYMODULE-truncate-title']  = _MYMODULE_truncate_title($object->title);
  }
  return $values;
}

Finally, we can add a function to do the operation:

function _MYMODULE_truncate_title($title) {

   if (strlen($title) > 30) {
       $title = drupal_substr($title,0,30)."...";
   }

   return $title;
}

Now, in your automated alias settings you can use this new token instead of the default title token, ex:

article/[[MYMODULE-truncate-title]]

A little more involved than the other options (again, checkout shorten) but thought this code might be of use to others with similar issues.


Anonymise Webform submission in database I am asked to modify the behavior of some webforms on a Drupal 8 instance; data who could identify a user submitting a form should not be stored in the database. Submissions must be sent by email though.

Webforms do have a "Disable saving of submissions" option, however, some of the forms have file fields; files that must be sent as attachements to the mail I mentionned, and those forms cannot work if I activate the option.

I tried creating my own Webform handler but I couldn't find a way to successfully alter submission there. I managed to alter data by using a custom validation class but as I suspected, the data is altered before it gets emailed.

Drupal 'Cron' tasks won't do it either. The legal team asks that the data does not persist in database longer than the time required by the processing of the form.

I may be blind, but am running out of ideas and cannot find a relevant documentation for my problem.

TL;DR: On webforms with file fields, how can I prevent storage of specific fields in the database or rewrite them while still sending the original data by email

I would intercept on the redirect/thank you page after form submission assuming the mail is send directly (is it).

See modules/webform/src/EventSubscriber/WebformSubscriber.php where $webform_submission = WebformSubmission::load($route_parameters['webform_submission']);
.

You probably need to override the service webform.event_subscriber defined in webform.services.yml


How can I create a page in Drupal that doesn't appear in the Drupal configuration menu? How can I create a page in Drupal that doesn't appear in the Drupal configuration menu? For example: admin/config/handler, but the only way is the direct link. There is no link in the configuration menu. Which hook function should I use?

$items['admin/config/handler'] = array(
    'title' => 'Handler',
    'description' => 'Just some info here.',
    'access arguments' => array('administer site configuration'),
    'page callback' => 'drupal_get_form',
    'page arguments' => array('handler_form'),
    'type' => MENU_CALLBACK
);

You want to use hook_menu() and define a path with the type element set to MENU_CALLBACK. The API docs linked above has an example for the path example/feed.


URL tags not converted to  HTML tags I have been using CKEditor, but didn't like the table editing capabilities so attempted to move to TinyMCE.  Having done this, all links now appear as plain text in the following format :

[url=http://somedomain.com/page]Page[/url]

It looks as if a filter has been dropped, or it is incorrectly configured, but I don't know how, or why. Can anybody help?

Disable the BBCode plugin in Tinymce settings.


How to Split content in drupal 7? I am new to drupal and drupal 7, I saw a video tutorial previous day regarding drupal 6, there they just used this:

print $content;
print $title;

to display post title and content separately however, in drupal 7 , I copied one of theme page.tpl.php file and there is only  this:

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

This shows full content inlcuding everything, how do I split them into parts like:

I want to customize my template like this

Welcome to My site // for header

                            Some text Portion //

This should be same for individual page and front page that shows 2 or 3 posts.

I tried making custom node.tpl.php file too, should I add some special function call to make it able to load content from node.tpl.php file ?

I pasted this code in template to render from page.tpl.php file of my theme

function connect_preprocess_page(&$vars) {
if (isset($vars['node']->type)) {
    $nodetype = $vars['node']->type;
    $vars['theme_hook_suggestions'][] = 'page__' . $nodetype;
}
}

In page.tpl.php leave where ever you wants: <?php print render($page['content']); ?> and then use node--YOUR_NODE_TYPE.tpl.php and put content where ever you want. You habe $node object print it and see what variables it has.
Make sure that you also have node.tpl.php - initial template file in your theme folder.


How to translate node programmatically with correct revision translation affected value? I have a question about create node translation programmatically.

First of all, the following is the database screenshot when we use drupal UI to create the translation.

The revision_translation_affected will be set to the language each time when the new one is created.

For example, I create an English article and then translate it with Chinese.

We can see the revision translation affected has been set with the Chinese version because of the translation is the latest created.

However, I use the following code to create a node and add the translation.

$post = \Drupal::entityTypeManager()->getStorage('node')->create(
        [
            'type' => 'page',
            'title' => 'test title',
            'langcode' => 'en'
        ]
    );
    $post->save();
    $source_translation = $post->getTranslation('en');
    $target_translation = $post->addTranslation('zh-hant', $source_translation->toArray());
    $target_translation->save();

I got the following database result

This result will cause the revision confusion when we want to see the revision record from each translation.

Does anyone have experience on how to handle this issue?

I just ran into this and this prevented my translated revision also appearing as a revision of my original:
$langcode = 'fr';
$node->setRevisionTranslationAffected(FALSE);
$node->addTranslation($langcode, ['title' => $node->getTitle()])->save();


How to make Views rows clickable with jQuery I am trying to follow Jimajamma's instructions here to make my Views rows clickable.

My View class =

.clickable-row .views-row {
border:12px solid purple;
}

My js file shows ok in the page source here

I am not sure which field is meant by "as long as one field in your view is a link" - I have tried Content: Link,
Content: Path and Content: Nid.

Result here - purple border rows are not clickable.

Can anyone please suggest what I am missing?

Please change your JS code to below given one and try again. It should be working.

Drupal.behaviors.clickableRowsOnViews = {
  attach: function() {

    jQuery('.clickable-row .views-row').each(function() {
      if (jQuery(this).find('a').length) {
        jQuery(this).click(function() {
          window.location = jQuery(this).find('a').attr('href');
          return false;
        });
      }
    });
  }
}


Can we write javascript code in twig template? Can we write javascript code in twig template?

Its needed to write javascript code in twig template.

When we are writting the same code in custom.js file that particular code is not working in it.

How to write javascript code directly into the twig template?

Yes, you can write JS code in a twig template. I can't think of any syntax crossovers so you should be able to literally write it as-is.

Indeed this works fine in html.twig.html:

<script>
  (function(val) {
    console.log(val);
  })('test');
</script>

If you're having syntax trouble, you can always escape it with raw, but it should be unnecessary:

{% raw %}
<script>
  (function(val) {
    console.log(val);
  })('test');
</script>
{% endraw %}


Linking two different content types with Views I was wondering if one can link up the data with views in this way:

I have two content types (current_state & desired_state), both have 3 fields (location, item, quantity)

How can I join the data, so that it displays in a table like:

location | item | desired_quantity | current_quantity

I separated those content types because people with other permissions are allowed to edit them.

Suppose we have 2 content types A and B and want to display the content of content type B which have a field reference ie both A and B both have a common field.
then:

We simply add B to the Filter Criteria of the view.
Add an nid of A using Contextual Filter in the advance Options.
Add a relationship of B in reverse order in the relationship field in advance options.


entityfieldquery, return several results I want get several entries of database. Im a entityfieldquery novice and I misunderstand how I do for get several results who contain certain fields (here, the fields that interest me are : delta, field_top_value and field_top_revision).

By example, I try this code :

$query = new EntityFieldQuery();
$query
    ->entityCondition('entity_id',$nid_device)
    ->entityCondition('entity_type','node');
$result = $query->execute();
dpm($result); //show just one only node...but I would like get the five entries, with field "delta, field_top_value and field_top_revision_id"

I "tried" to read the documentation, but my english reading isn't very good, and I don't find example for my case..

Thanks for help !

The table in your screenshot is a field table. It stores field data for entities, for both multiple and single cardinality fields.

When you use an EntityFieldQuery, you're querying for entities, not fields. It wouldn't make sense for you to receive data for anything else.

The connection you need to encourage your brain to make is that the fields are attached to the entities. So, if you want to know about multiple field values for a node, you just need to go and get them:

// Keep track of the delta, you mentioned you wanted it...
$delta = 0;
foreach (field_get_items('node', $node, 'field_foo') as $item) {
  $field_value = $item['value'];

  $delta++;
}

If that isn't what you're looking for, then EntityFieldQuery probably isn't the tool for the job. If that's the case, and you're using MySQL as the storage backend for fields, I'd recommend manually querying the field_data_field_foo table to get what you're after directly.


How to force Drupal search.module find "111-222" page by searching "111 222"? How to force Drupal search.module find "111-222" page by searching request "111 222" ?
For instance I have page example.com/111-222
about something, named 111-222
How to force Drupal to think that minus "-" and space is the same?

P.S. Famous search.module code modifications for partial search
( $query2 = substr(str_repeat("i.word LIKE '%%%s%%' OR ", count($arguments2)), 0, -4);
etc) is already applied.

thank you.

Looking at the API for search, it would seem that hook_search_preprocess will allow you to alter the way keywords are extracted, something like this:

function mymodule_search_preprocess($text) {
  return preg_replace('/(\d+)-(\d+)/', '$1 $2', $text);
}

I haven't tested this code, it's purely meant as a sample. It assumes your "words" are all digits as per the question.


Simple way to pull taxonomies I am building a module to that uses taxonomy, I would like to use drupal functions as much as possible vs going to the database directly. In addition I am using the Field Module to add additional information to each of the Taxonomy entities.  I would need to be able to dynamically pull back a given set of taxonomies and all fields used. Does anyone have a nice example for doing this. I know there is a function taxonomy_get_tree and there is the field APIs just not sure the best way to implement.

Thanks

here is an example of pulling all the terms in a vocabulary

$vid = taxonomy_vocabulary_machine_name_load("catalog")->vid;
//print($vid) . PHP_EOL; prints the vocab ID
$terms = taxonomy_get_tree($vid);
//print($terms) . PHP_EOL; prints "Array" if a vocab was grabbed
foreach ($terms as $term) {
   print($term->name) . PHP_EOL;
}


Blur text or words in posts for anonymous users How can selected text, emails etc be blurred and convert into image to completely hide it. Like what quora. com does for guest users. How can this be achieved?

How about the Blurry module?

  Overview

  This module can make your text fields blurry.


After doing a file_save_upload() how do you resize the images? I created a custom form in Drupal 7 with the ability to upload an image by using file_save_upload(). The image file has been uploaded and a fid has been assigned to it. How do I render this image into the different image styles I have setup?

print theme('image_style', array(
  'style_name' => 'your_style_name',
  'path' => $your_file->uri,
));

theme_image_style


change fields in content type after creation I know you "can't" do this, but hoping there might be a way.. Editing the database directly could work if I knew exactly what needed to be edited. Basically I want to change a file type to image because as fileI cannot enforce dimensions (this is on a site that was converted from drupal 6 to drupal 7 and already has a fair bit of data)

Have you tried to peek inside a database via PhpMyAdmin ? For every field you have field_data_field and field_revision_field table, containing several columns depending on the field type. And also some config tables like field_config and field_config_instance, so many things to be aware of.

This is more an advice than a clear answer, meddling with database may be risky task.

But I do understand if you have large data collections, you might try to risk to hack database to convert to other field type.

Beware that field tables may be referenced by other tables / modules, so backup your db first and test on clone.


Change certain parts of the layout Iam using Omega 4 and Drupal 7 and Iam wondering how to apply layouts just to certain parts to the website.
My website almost stays the same, header and footer never changes, just the content area.
I created a subtheme and applied a layout to it using panels or context, just to try both.

So whenever I create a new layout for instance for the basic article node, I need to setup the entire page structure within that tpl file again, how do I avoid such things?

I took a look in the omega theme folder under template, and there they just put the specific thing they want to change in the files, and dont rebuild the entire page strcuture.

Found a solution.
Just copy the entire templates folder of the omega base theme to your subtheme.
Within that folder, just edit or add new tpl files.
Those files will be injected to the specific block/content.


How can I obtain the "latest" vid when on Revisioning's "View latest" tab? I am using the Revisioning module to handle content revisions and I am creating a custom block that needs the vid of the node that the user is viewing to generate the appropriate content. I was trying to use menu_get_object() to obtain this and it works fine for a node with no revisions.

When I have a pending revision in Draft that I am looking at via the "View latest" tab, the node->vid I obtain from menu_get_object() is the vid of the "current" version, not the "latest". What would be the best way for me to obtain the vid of the version that is actually being displayed to the user?

I dug into the Revisioning module to see how they are doing the check and adapted it for use in a helper function in my module. I first load the node using menu_get_object() and then call the following:

function _get_correct_revision($node) {
  if (module_exists('revisioning')) {
    if (_revisioning_load_op($node, 'view') == REVISIONING_LOAD_LATEST) {
      $vid_to_load = revisioning_get_latest_revision_id($node->nid);
      $node = node_load($node->nid, $vid_to_load);
    }
  }
  return $node->vid;
}


How to implement three level mapping? I have several Schools and each School have 7 Domains. Each Domain has 3 unique forms. Here is a graphical representation of it:

I want an interface in which I can search a School by using Views (this I can do). When I click a School, the next window comes with a dashboard which has these 7 Domains and each Domain has 3 forms which is associated with the selected School.

Can anyone tell me how I can achieve this?

Your question seems like a variation of this Master Summary with drill down: change "Schools" by "States" and "Domains" by "Cities" to understand what I mean.

To illustrate the "drilldown" feature of it, just click, for any of the states included, on either the corresponding column (in the chart) or link (the Total in the tabular report below the chart). If you do so (e.g. for state "IL"), you'll get the details (another tabular report) for the state you selected. If on the last tabular report you want to switch to the details for another state (e.g. for state "Florida"), use the pull-down selection list within "Parameters" (near the top of the report), and change the selected value to "Florida".

Even though the sample here doesn't allow you to do so, it would be straight forward to replace the "number of users" for each of these cities to yet another hyperlink to another report (eg to provide the details of each of the users).

To further enhance the user experience, you can optionally combine this with the (amazing) dataTables jQuery plugin. A working sample of it (that you can use to experiment with it) is shown in the Customized Simple Table of States.

The magic behind this kind of drill down reports is NOT Views, but instead it is the Forena Reports module. One way of using it, is as a  Views display format.

For more details about this module, refer to its Community Documentation. Or have a look at the module's documentation that comes with it, as in this demo site also.

Disclosure: I'm a co-maintainer of this module.


Login menu which I added in main menu still displaying even after logged-in I have used login (user/login) as menu item in the main menu. While I am logged out, it displays login menu link properly.

When I am logged in, still displays me login as a menu item. But I dont want to be displayed or instead  'logout' over their.

I tried adding logout(user/logout) as seperate menu, but still no luck it shows as a separate menu item. Any suggestions?

Thanks in advance.

You need two have two menu items, login and logout.

For the login link the path is: user/login
and for logout the path is: user/logout

Make sure you don't enter a absolute URL to the links, just user/login and user/logout.

I have just tested this by adding two menu items to the primary menu.


Creating my own Sub-Menu / Parent in the Admin/Config menu Is it possible to create my own Parent / Sub-Menu in the Configuration tab in Administration?

Every resource I find seems to give an example of the yaml file placing a link under the Development menu, with system.admin_config_development, but I want one in (for example), system.admin_config_MYMENUNAME .

Example of current yaml file (hello_world.links.menu.yml) :

hell_world.admin:
  title: 'Hello module settings'
  description: 'example of how to make an admin settings page link'
  parent: system.admin_config_development # want this to be system.admin_config_MYCUSTOMMENU
  route_name: hello_world.content
  weight: 100

Just thought it would be easier to show a basic example that has both parent and submenu item in the mymodule.links.menu.yml.

Right now both links goto the same place (as I had to pick a default for the parent item, since I didn't have a admin page that lists all my custom links yet ... and also since having "route_name: <nolink>" did not work for the parent menu item even though some peeps said it worked for them [Note: using Drupal 8.6.12]):

mymodule.parent:
  title: 'My MainMenu Link'
  parent: system.admin_config
  description: 'Custom main config menu item under the Admin->Configuration menu.'
  route_name: mymodule.form
  weight: 100

mymodule.parent_child:
  title: 'My Submenu Link'
  parent: mymodule.parent
  description: 'This is the sub-menu item for my custom config form.'
  route_name: mymodule.form
  weight: 101


Having Views searchable by users I would like to be able to search my views by a field that is generated by an Entity Reference of users of the site.

Attempt #1 - Combine Fields Filter
I added this filter as exposed with the setting of "Contains" either from the "Title" field or the "Responsible Party" field (which is the Entity Reference field that is a list of users.  Here is a picture of the settings
The results of this were that the title field is filterable as pictured here
Yet the user generated field did not properly filter as shown here

Attempt #2 - Search: Search Terms filter
Same process and same issues using this filter.  Here is a picture of the settings

Then the same results as shown here.
Searching Title
Searching Users

Looks like you did all the steps correctly, How To Create Combined Search Filters In Views?, which leads me to believe that this is a bug.

Upon looking at the View's issues, I found Combined fields filter not working with entity reference.

Therefore, you will have to use it as a standalone, not combined, filter until this bug is fixed, which does not look like it will be any time soon.


settings and switching to external pgsql db I am working with Drupal 7.3.4 and attempting to follow the instructions of changing settings.php so that I can switch to a pgsql DB within a module and then switch back to the default mysql after doing a query.

I have set up in the settings.php file with the following format:

$databases = array (
  'default' =>
  array (
    'default' =>
    array (
      'database' => '',
      'username' => '',
      'password' => '',
      'host' => 'localhost',
      'port' => '',
      'driver' => 'mysql',
      'prefix' => '',
    ),
  ),
  'custom_db' =>
  array (
    'default' =>
    array (
      'database' => 'custom_db',
      'username' => 'dbuser',
      'password' => 'pass',
      'host' => 'urltoservice',
      'port' => '5432',
      'driver' => 'pgsql',
      'prefix' => '',
    ),
  ),
);

Now I am trying the process of switching to this DB in a module and verifying that the driver is changing.

db_set_active('custom_db');
//Get the currently active DB driver
drupal_set_message(db_driver());
db_set_active();

But, when I print the driver it is not switching to pgsql as expected.  I am pretty sure it is still pointing to the default mysql db.  Any ideas of what I may be doing wrong here would be greatly appreciated.

Thanks,
Derek

first check whether you are executing your query before  doing db_set_active(); because this function call will set your db to default drupal db.

so you should go like this:

db_set_active('custom_db');

// execute your query related stuff here

then at last switch to your default db by db_set_active();


User login API for social login from mobile apps I have installed HybridAuth module for social login (Only Facebook & Google) and It is working fine.

I need the same functionality for mobile apps. Like the user can able to login using the social accounts from mobile apps also.

Please suggest me how to do. Is it possible to do with HybridAuth module or I need to do different way?

I was also looking for functionality that you needs, but after wards i tried to implement service for social sign in using Hybridauth module and i succeed.

Try this https://github.com/rathodhiren9/hybridauth-service.git

Note : Its my own implementation and working fine using Poster/Postman. But you need to test in mobile application on your own.

Place this module folder in /sites/all/modules/custom and give full permissions if you are using Linux/Unix.
Look for Hybridauth Services in you all module list from Admin pannel of drupal 7 and install/activate it.
Now goto structure/services and add new endpoint if you don't have (remember Path to endpoint will be used in your URL call of service from mobile app).

After that you need to add Resources as per you requirement and for this service you need to check "hybridauth" resource and "connect" action from available resources and save the configuration.
Now this service will work from URL like /domainname/path-to-endpoint/hybridauth/connect. Be sure that url of your domain must match with your social media app's url that you are using for facebook or google
If your done well all the steps then you surly will test the service from Postman or Poster tools, But you need to get access token which will be an array of user data came from Facebook or Google and you will easily get it by debugging Hybridauth module's hybridauth.pages.inc file.

Hope this may be helpful.


Form state cache breaks dependency injection I have a class that extends FormBase and there are 6 services that are injected into the class via Dependency Injection (DI). My problem is when I submit the form it says to a class property that normally should be injected, it's NULL and can't be called the load() function on NULL. However when I debug, I clearly see all the dependencies are injected to the class and saved to the properties, but until the execution reaches the validation/submit function somehow it became all property to NULL. Why does this happen? How can I use DI in the form validation/submit phase? I'm really thinking if this class is not a deserialized cached version...
Extra info this form also has an ajax function where the DI works fine.

I went a bit deeper into the system, after the classfinder creates my form with the injected things and saved into this place: $form_state->getBuildInfo()['callback_object'], I found it out the problem is the cache. (/core/lib/Drupal/Core/Form/FormCache.php:149)

  protected function loadCachedFormState($form_build_id, FormStateInterface $form_state) {
    if ($stored_form_state = $this->keyValueExpirableFactory->get('form_state')->get($form_build_id)) {
      // Re-populate $form_state for subsequent rebuilds.
      $form_state->setFormState($stored_form_state);

      // If the original form is contained in include files, load the files.
      // @see \Drupal\Core\Form\FormStateInterface::loadInclude()
      $build_info = $form_state->getBuildInfo();

The system loads the formstate from the cache with the following lines, the $stored_form_state contains the cached state, without any dependencies, and the $form_state->setFormState($stored_form_state); line overwrites my formstate which contains the right properties with the DI classes... And that's a problem.

Haha, I've fount it finally. The problem was the properties were private. And the serialization trait wasn't able to save the values and when it loaded back it became null.


Download file after login I'm looking for direction with regards to how to get a file to download only after you are logged in, and to be prompted to login if you try to download it and then upon a correct submission, have that file automatically download.  The login form is to be presented in a modal dialog upon clicking the file when logged out.

Right now I have the modal form displaying when clicking the file download link, but I essentially need to reconstruct the login mechanism to work via AJAX I believe.  This includes validations and establishing the user's logged in session.  I'm not sure how to go about it... thoughts from the Drupal Answers community?

Private files download permission

  Version 1.x provided "two useful features which Drupal itself is
  missing: a simple permission to allow downloading of private files by
  role, plus the ability to combine both public and private downloads".

  Version 2.x removes the "global" permission and implements a
  per-directory by-user and by-role filter instead, to let the
  administrator better tweak the whole website and increment the overall
  security.

with this module you can achieve your requirement by following this tutorial source

Hope it helps you!