How to detect when $form_state data have expired (and gotten deleted)?

Although this arrangement is probably more complicated than it needs to be, here's how I was able to achieve it. I'd be happy to accept another answer if someone has a more elegant solution.

/**
 * Implements hook_form().
 */
function my_module_form($form, $form_state) {

    if (isset($form_state['storage']['elements_to_append'])) {
    // If other functions want us to add elements to the form:
        $elements = $form_state['storage']['elements_to_append'];
        foreach( $elements as $key => $element ) {
            $form[$key] = $element;
        }
    }

    $form['submit'] = array(
        '#type' => 'submit',
        '#submit' => array(
            'my_module_submit',
            'my_module_submit_safety',
            // ^ Depending on your requirements, you may wish to switch the
            // run-order of these two functions. Having my_module_submit_safety()
            // put first prevents subsequent actions in the case that $form_state
            // was lost since last navigation, but your users may lose more pages
            // of work before this check becomes effective; it's a tradeoff
            // either way unless you want to run the safety-check twice.
        ),
    );

    return $form;

} // my_module_form() OUT

/**
 * Implements hook_submit().
 */
function my_module_submit($form, &$form_state) {

    $form_state['rebuild'] = true;

    $form_state['storage']['elements_to_append']['navigated'] = array(
        '#type' => 'hidden',
        '#value' => 1,
    );

} // my_module_submit() OUT

/**
 * Implements hook_submit().
 */
function my_module_submit_safety($form, &$form_state) {

    $form_state_cid = '';
    if (isset($form_state['input']['form_build_id'])) {
        $form_state_cid = 'form_state_' . $form_state['input']['form_build_id'];
        // ^ This is effectively the same way the CID is built in @see
        // form_set_cache()
    }

    $statement = db_select('cache_form','cf');
    $statement->fields( 'cf', array('expire') );
    $statement->condition('cid', $form_state_cid);

    $navigated = isset($form_state['input']['navigated']);

    if ( $statement->execute()->fetchAssoc() === FALSE && $navigated ) {
        throw new Exception("The state-information for this form has expired.");
        // ^ I just place an exception here because recovery-actions for this
        // case are going to be system-dependent. If you know what those are for
        // your situation, they'd go here instead of this `throw` statement.
    }

} // my_module_submit_safety() OUT

Above, we use $form_state['input'] rather than $form_state['values'] since the latter will not include the results of the hidden field sent from the client's stale page in the case that $form_state information has been deleted. The strange dance of appending elements from a '#submit' step is done so that we don't run aground of the fact that my_module_form() is actually invoked twice (once immediately before '#submit' functions are called, and once after, each time with different values).

To test whether it works:

Load the form.
Navigate once.
Do: mysql -u <userName> -D <databaseName> [-p<password>] -e\
"DELETE FROM <prefix>_cache_form";.
Navigate again. You should see the message appear after this step.

Note: for security purposes, one might actually want to encrypt the hidden field's value (salting, timestamping, and including it no matter what), then reject the form outright if the value is found to be missing or adulterated in some way.


How to integrate custom code into a "Features" feature

I think I've been at your spot before with a single D6 codebase running on different sites and using Features for managing exportables such as Views.

In our example we had site sections running off taxonomies and firing off contexts (which got exported via Features). The problem was that although the name of most of our taxonomy terms was the same across sites, their tids changed, and there where exceptions as well, resulting in the problem you expose above.

Our solution was to go directly into the Feature and substitute the hard-coded, instance-specific variables with our own dynamic code. So we had a custom function in a custom module that would determine the contents of a particular variable in the exported feature. Then after exporting the feature initially, we would go into the array that we wanted to modify, and substitute it with a call to our dynamic function. When reverting features on each individual site the dynamic value would take the place of the hard-coded value. The only drawback to this solution is that you need to copy/paste the call to your custom function every time you recreate the feature. But overall the solution was straightforward, easy to implement, and reliable.


How can I see the created date of a node in a view?

choose revision, created date as the field to add in the view


What is the equivalent of Drupal.settings.basePath?

In Drupal 8 this setting is:

drupalSettings.path.baseUrl

You find more in core/module/system/system.module:

function system_js_settings_alter(&$settings, AttachedAssetsInterface $assets) {
  ...
    $path_settings = [
    'baseUrl' => $request->getBaseUrl() . '/',
    'pathPrefix' => $pathPrefix,
    'currentPath' => $current_path,
    'currentPathIsAdmin' => $current_path_is_admin,
    'isFront' => \Drupal::service('path.matcher')->isFrontPage(),
    'currentLanguage' => \Drupal::languageManager()->getCurrentLanguage(LanguageInterface::TYPE_URL)->getId(),
  ];

  ...


Limit options when creating content according to selected value

I got this sorted (eventually...)

Rather than having Discipline as a content type (since it was only really storing the name) I created a taxonomy vocabulary called Discipline and added all the relevant discipline names as terms.

Removed the entity references to Discipline in Event and Championship. Added a term reference (field_discipline) to Event and the same term reference to Championship.

Using the Reference Option Limit module (and patch; see question) in the entity reference in Event to Championship added the 'Limit this field's options according to matching field values' and selected the matching field field_discipline.

So now when creating an Event node the user is presented with a list of checkboxes to select the discipline(s) involved and when each is selected the appropriate championships are added to the list of available championships.


How to check if field in Field Collection is required?

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

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

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

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

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


Modifying $view in hook_views_pre_render()

function hook_views_post_render(\Drupal\views\ViewExecutable $view) {
   if ($view->id() == 'viewid') {
    // Set the view title.
    $view->setTitle('NEW TITLE');
   }
}


Theme inheritance : blocks placement not inherited

Block placement per region is unique to each theme. Putting the search block in "right_sidebar" for theme_a doesn't put the search block in "right_sidebar" for theme_b.


Access denied for anonymous users clicking on download link

This was a bug in the file entity module and the latest stable version has the patch for this issue committed to it. If you had encountered this issue in the past, update file entity to the latest version.


Is there any alternative to devel themer?

Not really.

Since Drupal 7.33 release there is now simple support for alternative template support and themeing function alternatives listing in Drupal (core) by adding a setting in settings.php.

  Added a "theme_hook_original" variable to templates and theme functions and an optional sitewide theme debug mode, to provide contextual information in the page's HTML to theme developers. The theme debug mode is based on the one used with Twig in Drupal 8 and can be accessed by setting the "theme_debug" variable to TRUE (API addition).

So in settings.php you set:

$conf['theme_debug'] = TRUE;

Then view the source of your page and you will see comments in your HTML as <!-- THEME DEBUG --> that list out function and template suggestions for the current Node.

Example Output for /admin/structure/views:

<!-- THEME DEBUG -->
<!-- CALL: theme('html') -->
<!-- FILE NAME SUGGESTIONS:
   * html--admin--structure--views.tpl.php
   * html--admin--structure.tpl.php
   * html--admin.tpl.php
   x html.tpl.php
-->
... lots of HTML ...
<!-- THEME DEBUG -->
<!-- CALL: theme('region') -->
<!-- FILE NAME SUGGESTIONS:
  * region--page-top.tpl.php
  x region.tpl.php
-->
<!-- THEME DEBUG -->
<!-- CALL: theme('toolbar') -->
<!-- BEGIN OUTPUT from 'modules/toolbar/toolbar.tpl.php' -->

This is a backport of Drupal 8 Twig helper functionality built into Drupal 8 (largely I guess because devel_theme has no Drupal 8 release).


Can I recreate content types via db tables only?

If you have a full backup, you could get the old version running locally.

Then

Content: Migration (http://drupal.org/project/migrate) or Feeds (http://drupal.org/project/feeds)
Content Types and other code-ish stuff: Features http://drupal.org/project/features


What to do when saving nodes one-by-one and bulk resaving give different results

You are correct that function is attached to the actual edit form when using the field, and therefore is bypassed during a VBO node save. This allows the function to be attached to any entity type that has the field (there are other ways to do this, but this approach was almost certainly easier than other options).

You can get from a node to a form using drupal_get_form() and providing the node as the form_state:

$form = drupal_get_form('YOUR_NODE_TYPE . '_node_form', $node);

Note: I have not tested that solution in your use-case.


Wrap a field in a link conditionally in views

There's a lightweight module that lets you attach a custom link to any image using the image formatter setting: Image Link Formatter

It will automatically detect any link field and make it an option to set that link for the image.

I usually just go this route instead of dealing with tokens or template modifications every time I want to link an image.


module_enable is a Drupal 7 function - it would seem you're not running this command on a drupal 7 site.

Downgrading Drush won't have any effect, if you want to use this extension with Drupal 8 the code will need to be updated to satisfy the new API.

The new equivalent is:

\Drupal::moduleHandler()->enable(['civicrm']);


Drupal override search form: how to debug hook failure?

Clear cache.
Place some debugging code to see if the hook and then if statement is called.
Inspect the form variable, does it look correct?


Having you pages accesible both via /node/* and /somealias leads to duplicate content and should be avoided as this can cause an SEO penalty. Under normal circumstances you could take a look at the global redirect module

  GlobalRedirect is a simple module which…

  Checks the current URL for an alias and does a 301 redirect to it if
  it is not being used. ...

It saves you from alteting robots and comes with some additional benefits.

Related to your question:

Since they are different paths, blocking one does not affect the other. And as explained above it is advised to prevent crawlers from indexing both. It should be safe to block one of them.

However, for Google indexing your /node paths, they might be in use somewhere. So first check your existing links and make sure there is nothing linking to those paths. Then add it to robots. (If it is still in use when you block it, you risk certain parts of your site not getting indexed.)


What Commcerce event is fired when a payment is made?

You seem to misunderstand the term payment here. It should not be seen in the context of a regular payment that you make or complete in a store. In this context payments are entities and the events match those of database transactions (insert, update, delete, etc.).

Theoretically the combination of these 3 events should allow you to determine if a payment has been made or altered or deleted, but you need to subscribe to all of them to be updated on all changes. (If you only subscribe to inserts (new payments) but not to deletes (removed payments) you might miss data.)

The commerce_order.order.paid or the safer \Drupal\commerce_order\Event\OrderEvents::ORDER_PAID event has the following documentation:

/**
 * Name of the event fired after the order has been fully paid.
 *
 * Guaranteed to only fire once, when the order balance reaches zero.
 * Subsequent changes to the balance won't redispatch the event (e.g. in case
 * of a refund followed by an additional payment).
 *
 * Fired before the order is saved.
 *
 * @Event
 *
 * @see \Drupal\commerce_order\OrderInterface::getBalance()
 * @see \Drupal\commerce_order\Event\OrderEvent
 */
const ORDER_PAID = 'commerce_order.order.paid';

It is called from doOrderPreSave() in OrderStorage.php, but only if the event has not dispatched before:

  if ($order->getData('paid_event_dispatched') === FALSE) {
    $event = new OrderEvent($order);
    $this->eventDispatcher->dispatch(OrderEvents::ORDER_PAID, $event);
    $order->setData('paid_event_dispatched', TRUE);
  }

When a payment is made, the order is listed in the commerce_payment.order_updater service which during its destruct will update and save all listed orders. Those in turn will determine if the total order balance has been reduced to zero and emit the event. It looks sensible to me.

Could it be that you have been testing with the same order over and over and that event already fired once?


You can add any number of validation functions to any form in hook_form_FORM_ID_alter() like so:

function mymodule_form_article_node_form_alter(&$form, &$form_state, $form_id) {
  // There will already be some validate handlers added so you need to add to the
  // array rather than overwrite it.
  $form['#validate'][] = 'mymodule_article_form_validate';

  // As mentioned above you can add as many as you want
  $form['#validate'][] = 'mymodule_article_form_validate_2';
}

function mymodule_article_form_validate($form, &$form_state) {
  // Random example, if the title is 'test' throw an error
  if ($form_state['values']['title'] == 'test') {
    form_set_error('title', 'Title cannot be "test"');
  }
}


I am using node_save() to alter a node field, but HTML code is showing escaped

Drupal core does not modify the data you save in the database [*]. All filters are applied only when displaying the data - this ensures that you never loose any data.

Assuming that you are using Drupal 7, and that the field in question has filtered text enabled, then what is happening is that when you save your new field, you are not setting what the filter format should be - so it defaults to plain text. You need to set the format of the field when saving it. In your code, you would do this as follows:

$node->field_author_box[$lang][0]['value'] = $str;
$node->field_author_box[$lang][0]['format'] = 'full_html';
node_save($node);

[*] Though some contrib modules may do this. For instance WYSIWYG editors such as CKEditor do modify your data (though in that case only when using the UI).


Is in Drupal the way to cache whole region?

Rather cache the individual blocks. There is a module for that: Block Cache Alter

  Alter cache settings per block. Cache settings per block are now set
  in code, but if you don't like the default - usually none - you can
  now easily change this. Install this to speed up block rendering for
  authenticated users.

It will give you the optioon in the Block UI to alter the cache settings for that block:


Is there any sensitive data in the Configuration Management Export?

Well, it contains the complete configuration, like list of modules, views, roles and their permissions.

While those things are not directly sensitive, it would make it easy to check for misconfigurations for example, views that aren't access protected, roles that have administrative permissions and so on.

I'm not sure if core adds anything that is explictly sensitive in there, I don't know any examples.

It does depend on the modules you have installed though. Many sites store API Keys or passwords, when integrating with third party services. Those would also be stored in configuration. For example configuration to send mails through an SMTP server or username/password for a Solr server.  And you don't want to have that public.

But you probably also don't want those in git in the first place. You can solve that by setting them through configuration overrides in settings.php.


When adding a new product variation type no catalog options appear

Turns out that when adding a new Product Variation, a new content type linked to this variation is automagically created with the corresponding representations.

All I had to do is adding the Catalog term reference to the linked content type.


How to ignore opening quote in views sort

views_natural_sort is able to do this kind of sorting.

It might be currently in alpha state but it already has more than 250 installation for the alpha 3 release which means that  most major bugs should have already been ironed out.

Upon enabling you are able to choose title to sort with and you are given 2 extra options for natural sorting (sort natually ascending and sort natually descending)

It also has some handy settings at admin/structure/views/settings/views_natural_sort which you will allow you to chose what other characters you want to ignore (and other settings)

Following are the default settings


As far as I know, the easiest way to do this is with views. You can set up a user view with exposed filters for any user field that you need to search. If you want to get a link to your your view on the search page form then, a form alter in a custom module would do it. Obviously make sure your view has a page with a proper path setup. search/your_view etc will work.

Here is a quick example of adding a custom markup field to the search form in drupal 7.

function CUSTOMMODULENAME_form_alter(&$form, $form_state, $form_id) {

 if ($form_id == 'search_form') {

   $form['usercustomsearchlink'] = array(
  '#type' => 'markup',
  '#markup' => 'Search User Fields ',
  '#weight' => 1,
   );

   }
}

That should put a link underneath the search box on the form (after a cache clear). However, I havent been able to figure out how to make it appear only on search/user pages yet so, that link will appear on all search forms.


Want to display the validation error message above the webform

you can put the validation messages above the webform by -

1.put the generic element above the form

messages:
  '#type': status_messages

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

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

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


How do I change the uploading image file name

If you're uploading a file I'm assuming it's within a form, right? You could add a submit handler function using form_alter() (or override the submitForm() method) and change the file's name using the $form_state object's setValue() and getValue() methods I'm sure.


How to get the value of a datetime when form submitted

You can use the method getTimeStamp() to store the timestamp like this :

$form_state->getValue('timesave')->getTimeStamp();

Or you can use the format() function to store a formatting date.

$form_state->getValue('timesave')->format("Y-m-d H:i:s");


How can I evaluate the security of a contrib module?

Currently there is no correlation between project status and presumed security of code. From The Security Team Handbook page

  in general the team does not review core nor contributed code

The Drupal security team works to resolve vulnerabilities that others find. Any review that happens to sandbox modules would be part of normal project review (no guarantees). When code is explicitly reviewed for security, it is most likely because someone was hired to review it.

In general, you can use the Writing Secure Code guide as a starting point. Also checkout presentations from Cons and Camps.


How to change the default selection in views filter?

You can change it with custom code in a module or overriding your theme.
You can also use the Better Exposed Filters module. Change the Exposed form options in your Views to use that module option. Then in the further settings you'll be able to override what the options are called for each filter separately.
Drupal 7 also had Views Advanced Labels.

Use this field to rewrite the filter options displayed. Use the format of current_text|replacement_text, one replacement per line. For example:
 Current|Replacement
 On|Yes
 Off|No

Leave the replacement text blank to remove an option altogether.


You could use the track_changes option, ex.

source:
   plugin: d7_node
   node_type: article
   # Allows to import changed as well as new records from the source.
   track_changes: true

https://www.drupal.org/docs/8/api/migrate-api/migrate-source-plugins/overview-of-migrate-source-plugins#track_changes


hook_file_download working perfectly, List of steps which worked for me

I made File System to Private
Created a File Field in Article Content Type and marked it as Private In Settings
Uploaded a PDF File
Link to file is something link below

http://example.com/d7/system/files/**.pdf

Created a custom module with hook_file_download, When ever i access above URL and visit any page i can see drupal set message "Hi"

function drup_custom_file_download($uri) {
  drupal_set_message("Hi");
}


If for some reason you need multiple versions of jQuery you can use the jQuery Multi module:

(libraries module is also required)
and you put the different version in the libraries directory
then you wrap your JavaScript code in something like this:

(function($) {...})(jqxxxxx);

where jqxxxxx is the version of jQuery you are using (see the documentation of jqmulti for more info)

do not include jquery scripts like you did. JQury Multi will do it automatically for you


Getting "Additional uncaught exception thrown while handling exception"

Okay after this error, I ran www.mysite/update.php it applied a few updates after which I was able to access the admin pages but if i wanted to access my front page, I'd still get

Fatal error: Call to undefined function field_info_field_map() in /home/content/q/u/a/quaa7882/html/sites/all/modules/addressfield/addressfield.tokens.inc on line 92

instead. I then removed the module addressfield by ftp manually and my site was back up and running so that I can care about my module(s)  separately.


Constantly getting "The website encountered an unexpected error. Please try again later."

That exception is thrown by EntityTypeManager::getDefinition() when it doesn't find any definition for the entity with the ID passed as argument.

  if (($entity_type = parent::getDefinition($entity_type_id, FALSE)) && class_exists($entity_type->getClass())) {
    return $entity_type;
  }
  elseif (!$exception_on_invalid) {
    return NULL;
  }

  throw new PluginNotFoundException($entity_type_id, sprintf('The "%s" entity type does not exist.', $entity_type_id));

The ID of that entity could confuse: It's not the File entity Drupal core implements because its ID would be file, not file_type. That is the entity defined from the File Entity (fieldable files) project, in its FileType.php file.

I take you installed the module, and uninstalled it, but your site still have some instances of that configuration entity. I would try cleaning Drupal cache, and if that doesn't work, I would re-install the module, go to /admin/structure/file-types, delete any entity listed there, and uninstall the module again.


Completely Locked out of website via User Permissions

It sounds like the roles database table got randomly deleted, which should basically never happen under the circumstances you describe.

If you have a recent database backup, I suggest you grab the structure and content of the roles table from that database backup and restore that to your site database so you have the right content.

If you don't have a backup, I suggest you do a new installation on a separate site (or your local computer) and then export JUST the roles table from that new installation and import the roles.


More Node Access Product (nap.module) Problems

Try changing $purchases['product_vid'] to $purchases->product_vid on line 824. Issue has been created on the project.


Request to reset the password ask current password

No Current Password module allows you to make this field optional.

Also, there's an issue in core about this.


How to make my new administration page use my administration theme?

There's a permission named View the administration theme. This should be given to the accountant role to allow users with that role to view the admin theme instead of the site theme.

If that permission is granted, then check the URL for the page you've created. A last resort would be to check out the documentation for hook_admin_paths(). This hook allows you to specify paths that should use the admin theme and/or use the Overlay (if you've got it enabled). Something like the following would work:

/**
 * Implements hook_admin_paths().
 */
function MY_MODULE_admin_paths() {

  $admin_paths = [
    'my/new/admin/view' => TRUE,
  ];

  return $admin_paths;

}


How do I use the global class \Drupal static methods to access services?

\Drupal::service('config.factory') and \Drupal::configFactory() are equivalent; the second is just shorter.

There are many, many services provided by core, and only a few of them have a dedicated method. You can get a list of core services on the core.services.yml page. Note that this is not all services that core offers, for example, there are more services in user.services.yml.

Also note that when working with classes, it's better to use dependency injection rather than calling static methods. Static methods should be called in procedural code (in D8, this basically means hooks, or API functions).

This is a slideshow I used when doing a presentation on dependency injection at Drupal Camp Tokyo this month.


How to nest Rules, call a rule from another rule and how to choose between 2 Rules Actions?

Your question consists of multiple questions, so my answer also consists of multiple parts ...

Part 1

To implement conditional logic in Rules, your very first attempt should be to only use Rules Conditions, and try to use the AND and OR operators to combine multiple Rules Conditions. If no such operator is specified, then the default is that ALL Rules Conditions must be true for the Rules Actions to be executed (this is equivalent to using the AND operator).

For way more details about this, refer to my answer to "What's the difference between combining Rules conditions with AND and just have them follow one after the other?".

Attention, even though using these AND and OR operators may seem obvious, it is NOT! For an example of how confusing it can be, refer to the video tutorial about "Combining conditions".

Part 2

  Currently I can only figure out how to trigger a Rules Action based on a Rules Condition, but not how to choose between 2 Rules Actions.

You're right, to "choose between Rules Actions" is like performing Rules Conditions within Rules Actions, which you cannot do with only the Rules module. However, the Conditional Rules module allows you to exactly do that (execute Rules Conditions as part of Rules Actions).

My favorite example to illustrate this can be found in my answer to "How to check whether one's current User Points are negative with the Rules module?", which includes a rule that looks like so:

{ "rules_display_userpoints_after_updating_content" : {
    "LABEL" : "Display userpoints after updating content",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "userpoints_rules", "rules", "rules_conditional" ],
    "ON" : { "node_update" : [] },
    "DO" : [
      { "userpoints_rules_get_current_points" : {
          "USING" : { "user" : [ "site:current-user" ], "tid" : "all" },
          "PROVIDE" : { "loaded_points" : { "total_points" : "Number of points in all categories together" } }
        }
      },
      { "drupal_message" : { "message" : "You now have [total-points:value] points" } },
      { "CONDITIONAL" : [
          {
            "IF" : { "NOT data_is" : { "data" : [ "total-points" ], "op" : "\u003C", "value" : "20" } },
            "DO" : [
              { "drupal_message" : { "message" : "You have sufficient points (you still have [total-points:value] ...)." } }
            ]
          },
          { "ELSE" : [
              { "drupal_message" : { "message" : "You DO NOT have sufficient points (you only have [total-points:value] ...)." } }
            ]
          }
        ]
      }
    ]
  }
}

This rule retrieves, as the very first Rules Action (not Rules Condition!), the current amount of user points of a user. And after the Rules Action to display some message, you can see the Conditional Rules module at work (starting from CONDITIONAL): it will show a message that depends on the total amount of points.

For another example using the Rules Conditional module (for which there is not a lot of docu available), refer to my answer to the question "How to prevent a node being saved when using the Rules module?".

Bonus: Instead of using if/else (conditional) logic within the Rules Action, you can also use Switch logic. For another example using such Switch logic, refer to rule included in my answer to "How to set the values of some fields depending on the value of a list box?".

Be aware: the Conditional Rules module only has a beta release for D7, though it's used in over 8K sites (which makes it seem like a pretty robust module though).

As an alternative to using the Conditional Rules module, you can also create corresponding Rules Components, with similar Rules Actions to be performed, but also with additional Rules Conditions equivalent to any Rules Conditions you'd want to include by using the Conditional Rules module. And then perform that Rules Component inside your Rules Actions of your original rule. For more details on that, refer to the answer to "What's the alternative to using the Conditional Rules module?"

Part 3

  In addition, is there a way to call one rule from another?

That's what Rules Components is all about, which you can do for:

only Rules Conditions, using a Rules Component of plugin type "Condition set".
only Rules Actions, using a Rules Component of plugin type "Action set".
both Rules Conditions and Rules Actions, using a Rules Component of plugin type "Rule".

Rules Components may use variables, whereas there are 2 variations of them:

Parameters which are used as input that the Rules Component needs in order to execute.
Provided which are output (instead of input), and which can be used (after the execution of the Rules Component completed) in the rule that calls the Rules Component.

For more details about this, refer to:

the video tutorial about "Rules Components".
the community documentation about "Rules Components".

PS: I'm assuming this question is about D7.


How to perform join with multiple columns using db_select?

You can use the following code.

$query = db_select('digitaliq_flds_by_node', 'a')->fields('a');

$alias = $query->join('digitaliq_fld_category', 'b', 'a.fld_id = %alias.fld_id AND a.fld_collection_id = %alias.fld_collection_id AND a.fld_group_name = %alias.fld_group_name');

$terms = $query->execute();

Calls to SelectQuery::join() (like-wise SelectQuery::leftJoin(), SelectQuery::innerJoin(), and SelectQuery::addJoin()) aren't chain-able because those methods don't return a SelectQuery object, but the actual alias used for the join. If you execute the following code, you would get an error.

$query = db_select('digitaliq_flds_by_node', 'a')
  ->fields('a')
  ->join('digitaliq_fld_category', 'b', 'a.fld_id = %alias.fld_id AND a.fld_collection_id = %alias.fld_collection_id AND a.fld_group_name = %alias.fld_group_name')
  ->execute();

Strings in PHP are not objects, and they don't define the execute() method.

To verify the code is executing the right SQL query, cast $query to a string, and print it. You will get the SQL query that would be executed from your code.

$query = db_select('digitaliq_flds_by_node', 'a')->fields('a');
$alias = $query->join('digitaliq_fld_category', 'b', 'a.fld_id = %alias.fld_id AND a.fld_collection_id = %alias.fld_collection_id AND a.fld_group_name = %alias.fld_group_name');
print $query;

With this code, I get the following output.

SELECT a.*
FROM
{digitaliq_flds_by_node} a
INNER JOIN {digitaliq_fld_category} b ON a.fld_id = b.fld_id AND a.fld_collection_id = b.fld_collection_id AND a.fld_group_name = b.fld_group_name


Porting a multi-site setup to local (MAMP) server

Unless you've got MAMP pro, or have set it up as such (which you haven't mentioned) vhosts probably won't be enabled; Apache will be looking at MAMP > htdocs for the web root, not any folder underneath it.

Try moving the Drupal web root up one folder (i.e. directly under MAMP > htdocs) and try again


How to implement node access control with a simple field used during node creation?

You can get this to work using a combination of the Rules module and the Content Access module, whereas the Rules module will automatically (behind the scenes) trigger the logic that's needed. The logic itself is entirely hidden for the user (author).

Here are some more details to get it to work:

Start from a rule that is similar to the example I included in my answer to "How to specify a Rules condition related to select list values?".
This sample rule uses a field named field_optionlist, with 3 possible values A,B,C. In your case you should use the fieldname of your Role reference field, and you should tune the possible values for that field also. Some more tips to get you going:

Make sure to tune the fieldname of this field (so that it matches the name you already have) BEFORE importing the rule sample in item '1.' above (if not the import of the rule will fail).
Adapt the Rules condition related to "value = C" to the values that fit your case, and the message included in the Rules Action.

QA-test the intermediate result after completing step '2.': you should have an appropriate Drupal message show up when a node is created with.
Use the integration of the Content Access module with the Rules module to create a Rules Action that updates the access of the node, similar to the Rules Action I included in my sample rule included in my answer to the question "How to revoke edit access to the node's author after publishing a node?". The actual settings to use for the content access module should match with your settings of course.


Try to install i18n module then you should be able to create a new content type for this node and set the language to EN under the "Multilingual Settings" tab.


Paypal payments pro integration with drupal 6

For a quick win on this on Drupal 6 I would use Ubercart, it ships with paypal pro integration. And http://drupal.org/project/scheduler

It uses conditional actions to assign roles, give access to file downloads etc. A simple, if perhaps slightly inelegant way would be to pass the node ID of the unpublished content to a product as an free value attribute, then upon successful purchase use conditional actions to publish it, setting an expiry date time on the object properties scheduler uses before saving the node. You should not give users permissions to use scheduler, and I'm assuming you have cron up and running.

Sounds bodgy, but you could get it up and running very fast like that. Check if you like it and still have time to look at other solutions if not.

Commerce module might also be good but haven't used it on d6


Assuming they are straight up Blocks with body content (not View blocks or other contrib generated blocks), I would create a module that scripts and creates them on install. If you have many blocks, do them in small batches (breaking them up across update_n hooks).

That way you can also test them in small batches and get it right. Once up, you can disable the module and remove it.

See:

https://drupal.stackexchange.com/a/72946/57
https://www.drupal.org/node/1709954#comment-8592077


If all you are just trying to change is the layout of the form, and not the data contained in it, all you should need to do is change the CSS for the various wrappers.

In this example, that would be looking at

      <?php if ($block): ?>

<?php print $title; ?>:

      <?php endif; ?>
      <?php print $choice; ?>

    <?php print $vote; ?>

  <?php // This is the 'rest' of the form, in case items have been added. ?>
  <?php print $rest ?>

so, if in your theme CSS you added

.poll {
  color: red;
  background-color: blue;
}

this block would now be in red and blue.

and if you added

.vote-form {
  border: 2px solid green;
}

then the form would have a border of green.  etc etc etc.

Now, if you need to change things up more, add some more divs or change their order, etc, you can just copy the standard poll template to your theme directory, refresh your caches and drupal will pick it up and override the one from poll itself, no need to name it anything different.


You need to make sure your library declares a dependency on core/drupal.message, e.g.

foo:
  js:
    js/foo.js: {}
  dependencies:
    - core/drupal.message

Once you've done that, you can choose the message type by including options:

const messages = new Drupal.Message();
messages.add('test message', { type: 'status' });


How to set page/content title/header from a controller

You set the title in the route in the _title parameter:

mymodule.page:
  path: '/mymodule/page'
  defaults:
    _title: 'Page title'
    _controller: '\Drupal\mymodule\Controller\MyController::controller'

Or you can use a route callback:

mymodule.page:
  path: '/mymodule/page'
  defaults:
    _title_callback: '\Drupal\mymodule\Controller\MyController::title'
    _controller: '\Drupal\mymodule\Controller\MyController::controller'

And then put the title callback in the controller class, which receives the same parameters as the controller, so that you can determine a title on that information.


Assuming you have a boolean field which stores if event is rejected or validated, you can read this information from PHP and print the fontawesome icon based on a condition.

The standard way in Drupal 7 would be to use Views PHP module and do something like:

if ($data->field_field_event_validated['0']['raw']['value'])
  echo '';
else
  echo '';

This module still isn't ported to Drupal 8, and actually it's really bad in terms of security and stability to use this module as this article states. The same article describes how to include PHP in your views. In resume you have to create a module, generate a custom views field with the PHP code printing your icon and use this module in Views.


How can you put a user profile item in a category on the user's account information page?

In the meantime I've figured it out. The categories are also defined in the 'view' operation by using the type 'user_profile_category'. For example:

$account->content['my_cat'] = array(
          '#type' => 'user_profile_category',
          '#title' => 'Plants Summary',
         );


What advantages does Features offer in deploying changes

You seem to have mentioned the use-case of Features only as a configuration packer, probably with strongarm, or with structure - where you would not use the code once it is run and has made its changes in the database.

But one of the important uses of Features is ctools exportables, such as Views, rules, etc... Here, the settings are much more complex than '103 configuration options' and if you are dealing with multiple developers, a staging site and then production, you can't imagine doing all of this manually on all different servers and instances.


Drush feature-update updates the feature code with overwritten settings. So the function is used to export changes to code.

If you want to take those changes to another site, you will have to copy the updated feature to the other site unless they share the same code (and then revert the feature and clear cache (not always needed)).

In code it could look like this

$ drush fu feature_module
$ cp -r feature_module ./DIR
$ cd DIR
$ drush fr feature_module


I don't have time to fully flesh it out at the moment, but the approach I would take would be to:

In your product migration, which presumably is using the d7_node source plugin, override that source plugin and implement prepareRow() (not forgetting to call parent::prepareRow()!) to query the related ingredient terms and $row->setSourceProperty('ingredient_names', /* array of term names *?);
Use the migrate_plus entity_lookup process plugin to map those ingredient_names to existing (previously imported) ingredient node titles. You'll be looking at the example with full configuration for your use case...

Hope this helps!


How to create access permissions system similar to Organic Groups access, using Eck entities

If you'd be willing to use the Group module, then you could do like so:

You can configure a Group Type named "Project", so that this Group Type would replace your entity type project.
You can create 1 Group (of group type "Project") for each of your Projects (each Group probably labelled with the name of a specific project).
You can assign nodes to a Group (of group type "Project"), so that these nodes would replace your project content entity types.

Group is available as of D7, and has a D8 version also. It is designed to be an alternative to Organic Groups. The Group module creates groups as entities, making them fully fieldable, extensible and exportable.

With the above in place, you also have the permission system you're looking for, out-of-the-Group-box.

More info:

Refer to "What are the various roles supported by the Group module?" for more details about the supported roles.
Refer to my answer to "How to configure access to courses for teachers and students?" for a sample configuration.

Integration with various modules

The Group module integrates with various other (popular) modules, including:

Rules, as illustrated in the answer to the question "How to bulk assign existing content to a group created with the Group module?".
Views, as illustrated in the answer to the question "How to show the content of a group on the group page when using the Group module?".
Pathauto.

The beauty, IMO, of these integrations are that they are more or less out-of-the box (not dozens of extra modules needed to make those integrations work).

Resources

Community documentation for the Group module.
Video tutorial "How to use the Group module in Drupal 8 to manage editorial access control to different areas of a web site".


Applying patches is not actually a drupal specific issue and would be better on stack exchange, however there is a drupal documentation page so...

Check out the applying patches documentation.

However having said that, if you read that issue then you can see that patch was committed to that module 3 years ago and if you are using the latest release of the boron module (7.x-1.4) then that patch is already in there.

If you are applying the patch to something that isn't the boron theme then it will likely not work.


Add FILTER CRITERIA in Views Programmatically

Use the Devel module and dpm($view) and dpm($query) after you put like "test@email.com" into the "value" field found in your pic. See the object/array structure of the view and query from the devel output.

Then use the function hook_views_query_alter(&$view, &$query) in your module to target the WHERE condition filter condition and set it to the value you want.

Something like:

function MYMODULE_views_query_alter(&$view, &$query) {
  global $user;
  dpm($view, __FUNCTION__);
  dpm($query, __FUNCTION__);
  if ($view->name === 'your_view_machine_name') {
    // This will only work as-is if you always have something in the filter by
    // default, I guess. This hook runs always so you could just put
    // 'test@test.com' as the email to filter by in views and this
    // will always override it. I'm sure there is a cleaner way to put
    // the filter dynamically at runtime. But i think thats more complex
    // php that customizes a view.
    //
    // The index 2 below is the index of the condition for the email filter.
    // Your $query structure may be different in your dpm() of the View $query.
    $query->where[1]['conditions'][2]['field']['value'] = $user->email;
  }
}


How to use $form['#action'] in Views PHP field

Instead of this method, why cannot a new submit handler be written? so that you can use drupal_goto there and redirect.


How to change "Image style" of an Image field in a given view mode programmatically (as on "Manage display" tab after clicking the gear)?

Something like this should do it:

$entity_type = 'node';
$bundle = 'article';
$field_name = 'field_image';
$view_mode = 'default';

// Get the instance info
$instance_info = field_info_instance($entity_type, $field_name, $bundle);

// Change the image style
$instance_info['display'][$view_mode]['settings']['image_style'] = 'new_image_style';

// Save it
field_update_instance($instance_info);


contextual filters doesn't necessarily know when something is incorrect - it assumes the values are accurate and attempts to use them as you have it setup. You could do it this way:

create a custom views handler, or install Views PHP

assuming Views PHP:

for the second filter, provide a default php value that evaluates the url - if only two arguments are provided assume the second is missing and return all

Of course, this is quite presumptuous on the url information provided to Views, and will inevitably fail in some situations. Depending on how you link to the view and create the url, you are probably better off using a place-holder for the second value (international/--/06), with a similar default value set up as above whereby if the place-holder is found, it would return all


Different menu links depending on user account

Yes . You can use  Menu Token. (Menu Token module provides tokens, that could be used in title or in path of menu items. For example, if you create a menu item with path: "user/[current-user:uid]", the url will be changed "on fly" to: "user/1" )


check "checkbox is checked" before submit

All you need are Form API's #states.

function MYMODULE_MYFORM($form, &$form_state) {

  $form['radio_buttons'] = array(
    '#type'   => 'radios',
    '#options' => array(0 => t('Hidden'), 1 => t('Visible')),
  );
  $form['submit_button'] = array(
    '#type'   => 'submit',
    '#value'  => t('Click Here!'),
    '#states' => array(
      'visible' => array(
        ':input[name="radio_buttons"]' => array('value' => 1),
      ),
    ),
  );

  return $form;
}


<?php print '<' . trim(render($content['field_headline_format'])) . '>'; ?>


View which filters based on URL matching field value

I wasn't able to do exactly what I wanted but what I did instead was create an exposed filter for the field in the content type being searched & use the URL parameter it created when in use to filter search results.

The exposed form itself is hidden with CSS as just including the filter without exposing it won't allow it to be activated via a URL parameter.


a non existing subdomain is added to image urls

This is rather big guess, but I think you have everything configured so that your virtual host is responding to all subdomains for your primary domain.  In Apache terms this would be something like

ServerName mysite.com
ServerAlais *.mysite.com

And, you have old links that are getting crawled from the old subdomains, and the net result are some bad URLs are being cached.

My suggestion would be to add something like this to your .htaccess

RewriteCond %{HTTP_HOST} !www\.mysite\.com [NC]
RewriteRule ^(.*)$ http://www.mysite.com/$1 [R=301,L]

Make sure this goes right after the RewriteEngine on in the stock Drupal version.  I don't think the two example rules in the file will work, as they assume just adding/removing the www and don't take subdomains into account (though I am not 100% sure about this; I haven't looked at these closely in a while).  Make sure you clear Drupal cache, too.

Also make sure you back up the file after you change it, so you have the additions the next time you upgrade core.


Why is my custom theme template not found?

Try something like this:

function mytheme_preprocess_page(&$variables, $hook) {
  $variables['theme_hook_suggestions'][] = 'custombody';
}

to add a theme hook suggestion a template called 'custombody.tpl.php'.

However it sounds like what you really want to do might be to render the $body directly, before it gets passed to the default template. In that case you'd use a process or preprocess function to do that directly instead of doing it in the template itself.


Migrating a site with a module that doesn't have a version for latest core version

You simply cannot. If the module has a Drupal 8 version you can use it just after enabling the module. But if it doesn't contain a Drupal 8 version you cannot enable or use with your Drupal 8 site installation. Only thing you can do is find an alternative module for the unsupported module that you have used. Or you can change the unsupported modules codes with supported Drupal 8 syntaxes. But I never encourage to do so. Because

It effect authors copyrights.
You wouldn't be able to update anymore or if you update your module forcefully all the changes you have done will revert back to the original state.

So think twice before doing a change like that. Hope this helps for your question.


how to get banner image based on the role?

Considering you have created multiple Blocks for individual role  from Drupal admin UI.

You can restrict each block role wise.


I did some more digging around in the module and decided to not build to loop but just use the one existing in the module. So I created a patch for Geolocation modules adding this line
currentInfoWindow.open(map.googleMap, currentMarker);

To line 83 of the geolocation-marker-infowindow.js file.


Advise a Drupal Image gallery module with an option to put text nearby the image (for medical atlas)

Talking Drupal #083 is a great podcast about creating a Gallery, and includes a lot of recommended modules for it.

Just to mention a few of them (mentioned on the linked page):

  Gallery formatter.
  Views Slideshow.
  Flexslider.
  Node Gallery.
  Multiupload Filefield Widget.
  Multiupload Imagefield Widget.
  Field Focus.
  pl upload.


Feeds: Is it possible to set a unique field other than the title field?

For most of my Feeds, I import the Node ID and make that unique.


Computed field that displays the full username of the author

Not 100% clear what your use case is, but it's possible that the realname module will do exactly what you're after https://www.drupal.org/project/realname

under /admin/config/people/realname enter tokens for the fields you want eg [user:field_profile_first_name] [user:field_profile_last_name] then whenever the username gets printed it will display these fields instead


What is Calendar Legend block for? enabled but shows nothing

The Legend is used on the large calendar page view to help denote between content types or taxonomy. You can set the colours of the content types or taxonomy by editing the view at /admin/structure/views/view/calendar/edit and select Format > Show > Settings


How to perform automated testing of an entire site after core changes?

http://drupal.org/project/simpletest - it provides essentially the same testing API as the core D7 module and you still have to write the tests yourself. There is also http://drupal.org/project/simpletest_automator that apparently will help you 'record' your actions on a site into a SimpleTest for you.

Additional helpful links:

http://drupal.org/project/selenium
http://drupal.org/simpletest


Use the Field Group Module. It comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.
Field Group:

Fieldgroup will, as the name implies, group fields together. All fieldable entities will have the possibility to add groups to wrap their fields together. Fieldgroup comes with default HTML wrappers like vertical tabs, horizontal tabs, accordions, fieldsets or div wrappers.
The field group project is a follow-up on the field group module in CCK. The release will only exist for Drupal 7 release and higher, so since the existence of the Fields API in core.
By moving field group to a separate module, this may open some new perspectives.


Notice: Undefined index: driver in Database::openConnection() when trying to connect to sqlite db

The documentation is a bit misguiding as it states that the database array should be identical to the way it is declared on the settings.php file. This is wrong!

After digging a little bit the core module it shows that addConnectionInfo is expecting a array that defines the database and the driver.

Here is the correct implementation:

      $module_path = drupal_get_path('module', 'cw_ticketing' );
      $db1 = array (
        'database' => $module_path.'/247cinema_part1.sqlite',
        'driver' => 'sqlite',
      );
      $db2 = array (
        'database' => $module_path.'/247cinema_part2.sqlite',
        'driver' => 'sqlite',
      );
      // die(var_dump($databases));
      Database::addConnectionInfo('247', 'db1', $db1);
      Database::addConnectionInfo('247', 'db2', $db2);


Add the ajax callback in the submit button of the form like this:

Edit

$form['radio_buttons']['#ajax'] = array (
  'callback' => '_test',
  'wrapper' => 'nimportequi',
  'event' => 'change',
  'progress' => array('type' => 'throbber', 'message' => ''),
);

This will ensure that when a radio button is clicked your ajax callback will be executed. Selecting radio buttons will give alert message, therefore the ajax callback should be applied to radio buttons.

Your ajax callback seems ok.


How to force login before submitting webform?

Here is a simple example, you would place this in a custom module:

function hook_webform_submission_presave($node, $submission) {
  //test is user is anon
  if (user_is_anonymous()) {
    //tell user what is going on
    drupal_set_message("Please register before submitting form");
    //redirect to registration page, with path to send back to form when done
    drupal_goto('user/register', array('query'=>drupal_get_destination()) );
  }
}

Here are docs for hook_webform_submission_presave(), and webform.api.php within the webform module is also a great resource.

It seems to preserve form data with select components, but not 100% on that.


Using arrays when setting values in defaultConfiguration() of BlockForm in BlockBase

Are you looking for this?

public function defaultConfiguration() {
    return array(
        'plugins_string' => $this->t('Enter text here'),
        'layout' => array('pane-type-submit' => 1),
     );
 }


Is it possible to have 2 sources for migration?

You can't use two sources in the same migration. But if you can split your import into two separate migrations (e.g. taxonomies first, then nodes), you can use either migrate_lookup (if your 2nd source provides the same primary key as a previous master) or entity_lookup (if your 2nd source needs to look up the referenced entity by something else than the primary migration key).

Entity lookup is part of Migrate Plus.


it'll will work if you change the Widget type on the Comment Fields tab to "Stars (rated while editing)". Give it a try.


Where is the content of a node's body stored?

In Drupal 7 the body has been moved to the field_data_body table.


I think you have have a hard time doing this with caching, since you want to create two versions of the same page.

I haven't tried this, but it should be possible to let your style.css not be an actual css file but a drupal callback that returns the styles based on the cookie. You would need to include the "stylesheet" as you would do styles for IE. You wouldn't be able to cache this, but if you really need to performance, you could do it in a php file and skip the drupal bootstrap.

An alternative option would be to let the js itself execute the styles, based on the cookie.

None of these options are ideal, but they should work.


How do you inject dependencies in your classes from external packages?

You should be able to use the fully qualified namespace for the injection:

services:
  mymodule.example_service:
    class: path\to\Class


Is there a 'text or user reference' module?

The Entity reference module will relate any Drupal entities. These include:

Nodes
Users
Taxonomy Terms

So should be perfect for your needs.


You create a search box for Views by adding a filter and then setting it to be "exposed". This creates a form by which the user can set filter values such as tags.

You don't need any special module for tagging under normal circumstances as the core Taxonomy module works perfectly well.


How send argument to Services Module (Views+Contextual filters)

When making a jQuery ajax request to a Drupal Services 3.x module REST API endpoint, define the request type of your ajax request like this.

(function ($) {
  var request = $.ajax({
    "url" : "http://test.url/rest/viewname/555",
    "type" : "GET"
  });
}(jQuery));

Usually a RETRIEVE request would be done using the request type GET, but for an ACTION, like the taxonomy_term Resource action selectNodes (This method returns all nodes with provided taxonomy id.), provided in Services 3.x, you would set the request type to POST. All RESTful services use POST for ACTIONs. In this case, your jQuery Ajax request would look like this:

(function ($) {
  var request = $.ajax({
    "url" : "http://test.url/rest/taxonomy_term/selectNodes",
    "type" : "POST",
    "dataType" : "json",
    "data" : { "tid" : 555, "pager" : 0 }
  });
}(jQuery));

Each of the resource operations in a REST API use a specific HTTP Method or request type  (e.g., GET, PUT, POST, or DELETE). You need to use the correct one or it wont work. The Drupal Services 3.x module adheres to these strictly.

To learn more about REST API request methods and how they relate to resource operations, take a look at the Using HTTP Methods for RESTful Services on the REST API Tutorial site.


Set Default Value for Image Field contain Multiple Images

I think you need to use a managed_file form element.
$user_data = user_load($user->uid);
$form['my_imageGallery'] = array(
  '#type'             => 'managed_file',
  '#title'            => t('Image Gallery'),
  '#default_value'    => isset($user_data->field_galeria) ? $user_data->field_galeria : null,
  '#upload_location'  => 'public://user_galleries/',
  '#upload_validators' => array('file_validate_extensions' => array('png jpg gif')),
);


Filter "exposed filter" data based on another "exposed filter"

Try the Hierarchical Select module for that

  This module defines the "hierarchical_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.


I couldn't understand what you exactly need but i guess that "banana" is the title of your node, the same value that you are using when you set up the pattern in pathauto settings, right?

So in this case you would have to set Node Title has a contextual filter, and then on "When the filter value is NOT available" you have to set  Provide default value > Raw value from URL > specify the position of your argument in the URL.

It would be nice if you give us more information about what do you need, please


The header normally comes from the page, and the search field comes from the form.
In order to place the h1 under the search field I'm usually using the next steps:

Hide the title on the search results page using the theme_preprocess_page
Use the search-results.tpl.php to insert the title under the search field


How to fix rules which unable to evaluate action?

The error:

  WD rules: Unable to get variable X, it is not defined.

means that Rules can't load the variable X.

If you're using contributed modules, please check if your rules are in the right order and the configuration is right, otherwise check the module issue queue for possible bug issues.

If you're using custom modules, please make sure that these rule variables are passed in the correct way.

For example if you've the following sample rule in hook_rules_action_info:

'foo_rule' => array(
  'label' => t('Foo rule'),
  'provides' => array(
    'object_to_send' => array(
      'type' => 'data',
      'label' => t('Data Object to pass'),
    ),
  ),
),

The object_to_send needs to provide the matching array key, e.g.:

return array( 'object_to_send' => $object);

So the next rule in sequence will "see" that variable, so you can use it.


Adding variables to page--taxonomy.tpl.php

You can limit variables to certain conditions. Obviously only when the variables to measure these conditions are available.

function themename_preprocess_taxonomy(&$vars, $hook){
  var_dump($vars);
}

This will show you all the available variables, for example the $vid, which contains the vocabulary-ID. The simple version would be:

function themename_preprocess_taxonomy(&$vars, $hook){
  if($vars['vid'] == 12) {
    $vars['example'] = "Foo";
  }
}

A clean, and much better solution would then be:

function themename_preprocess_taxonomy(&$vars, $hook){
  $vars['example'] = ''; # Always instantiate a variable, and make sure
                          # it has a constant type
                          # e.g. always return a string.
  if($vars['vid'] == variable_get('themename_vid_for_example', 123)) { # Avoid Magic Numbers [1]
    $vars['example'] = "Foo";
  }
}

[1] http://en.wikipedia.org/wiki/Magic_number_%28programming%29#Unnamed_numerical_constants

EDIT: updated variable_get. tss.


How to create an autocomplete textbox in register page - Drupal 6

There's a full example for Drupal 6 here: [Textfield that uses autocomplete][1]. The code will probably be useful to people on this site as well so I'll post i here:

The following is based on a module with the name: 'cities'

In your form function:

$form['city'] = array(
  '#type' => 'textfield',
  '#title' => 'City',
  '#maxlength' => 128,
  '#autocomplete_path' => 'cities/autocomplete',
);

In your module file:

function cities_menu(){
  // path with autocomplete function for cities
  $items['cities/autocomplete'] = array(
    'title' => 'Autocomplete for cities',
    'page callback' => '_cities_autocomplete',
    'access arguments' => array('use autocomplete'),  //or whatever permission makes sense
    'type' => MENU_CALLBACK
  );
  return $items;
}

Also in your module file:

function _cities_autocomplete($string) {
  $matches = array();
  //search table `cities` for cities that begin with the letters the user enters in the form
  $result = db_query_range("SELECT city FROM {cities} WHERE LOWER(city) LIKE LOWER('%s%')", $string, 0, 10);
  // add matches to $matches
  while ($data = db_fetch_object($result)) {
    $matches[$data->city] = check_plain($data->city);
  }
 print drupal_to_js($matches);

}


First, create two fields-"Old price" and "new price". Second, use css text-decoration:line-through; on the old price field.

Edit:

Based on your comment and clarification, I would suggest using rules and rules bonus pack to look for the "new price field", then have it add a body class to the node.

Your rule will look something like

Event #1: "when content is created"
Event #2: "when content is updated"
Condition #1: "entity has field", then select your "new price" field
Condition #2: "Data value is empty" and enable "negate"
Action: "Add body class"

Then in your css add the strikethough based on the extra body class.

This is essentially how the Commerce price savings formatter module works, but without the overhead of using commerce.


How do I create a landing page that can go to page--front?

You should try the Panels module.

It has a "pages" feature that allows you to create pages from pre-existing layout templates that are included, or you can create and import your own layouts from .tpl files. Then you can dynamically add content to them (it stores the settings in the database, but you can use the Features module to store them in code).


Can I use Full-Text Search Functions in db_select()?

No. If you look at the internal Condition::match() function that's used when building conditional statements with the condition() method, you can see the list of operators does not include the MATCH() AGAINST() operators. The cost of having a DB abstraction layer that supports different DBMS, is you can only support the greatest common feature among them; these operators are MySQL/Postgres specific.

In order to utilize these feature of your database, you'll need to use the Connection::query() method to perform the query directly.


How to export custom module form content as PDF file in drupal 7?

TCPDF doesn't support all styling attributes.It only supports some of the features that are given below.it has a very limited CSS support.

font-family
font-size
font-weight
font-style
color
background-color
text-decoration
width
height
text-align

Basically, You can use tables to style your pdf data And styling pdf throught table attributes.like

colspan
rowspan
align
cellpadding
cellspacing
width
border

etc.

And Note That PDF and HTML and different formats that hardly have anything in common. If TCPDF allows you to provide input data using HTML and CSS it's because it implements a simple parser for these two languages and tries to figure out how to translate that into PDF. So it's logical that TCPDF only supports a little subset of the HTML and CSS specification and, even in supported stuff, it's probably not as perfect as in first class web browsers.


On linux, you could create a symlink to the other folder, or mount it over NFS etc..

On Windows you can actually create a symlink as well.

Something like this should work:

# Open a windows terminal and
mklink /J "C:\Webroot\Drupal\Mysite\sites\default\files" "D:\Data\Drupal\Mysite\"

That should create a hard link connecting the files folder across the two drives, with the data being stored on D:

More info:

http://en.wikipedia.org/wiki/NTFS_symbolic_link
http://en.wikipedia.org/wiki/NTFS_junction_point


I use the ccs_injector module to add css snippets to fix alignment issues like the one you described.

For example, the css I used to assign even widths on a 4 column grid and to vertically align the content:

td.col-1, td.col-2, td.col-3, td.col-4 {
width: 25%;
vertical-align: top;
text-align: center;
}


Results of autocomplete field in form depending on another field - Drupal 7

Keep a wild card in your autcomplete menu path something like

function mymodulename_name_menu() {
  $items['example/autocomplete/%/%'] = array(
    'page callback' => '_mymodulename_autocomplete_callback',
    'page arguments' => array(2, 3),
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
}

In your form

function mymodulename_my_form($form, &$form_state) {
// Your select field.
  $form['select_field'] = array(
    '#type' => 'select',
    '#options' => array(
      'option1' => 'Option1',
      'option2' => 'Option2',
    ),
    '#ajax' => array(
      'callback' => '_mymodulename_ajaxcallback',
      'wrapper' => 'replace_autocomplete_field',
    ),
  );
  // A container field
  $form['autocomplete_field_container'] = array(
    '#type' => 'container',
    '#tree' => TRUE,
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $query_parameter = isset($form_state['values']['select_field']) ? $form_state['values']['select_field'] : 'default_value_to_start_with';
  // Your autocomplete field.
  $form['autocomplete_field_container']['autocomplete_field'] = array(
    '#title' => t('My autocomplete field.'),
    '#type' => 'textfield',
    '#autocomplete_path' => "example/autocomplete/$query_parameter",
  );
}

You Automcomplete menu callback

function _mymodulename_autocomplete_callback($query_parameter, $string) {
  // Use $query parameter to decide autocomplete field behavior.
}

Basically I am trying to update the autocomplete field by attaching '#ajax' behaviour to select field, and while updating the autocomplete field we will change the query parameter which db_query will use.


"Authored by" field to be automatically filled

Personally I think that a module like Rules (powerful and awesome as it is) is overkill for something relatively simple as this.

Looking at node_form(), I see that the author is set by populating the author field with the username. I would create a custom module which implements hook_form_BASE_FORM_ID_alter, and set the default value of the author name field to the name of the current user. That would look something like this (disclaimer: untested code!).

<?php

function MODULENAME_form_node_form_alter(&$form, &$form_state, $form_id) {
  // Always set the username to the current user. An empty string means anonymous.
  global $user;
  $form['author']['name']['#default_value'] = !empty($user->name) ? $user->name : '';
}

An advantage of this solution is that the field is populated in advance with a default value, allowing user with sufficient permissions (eg. administrators) to override the author as they always can. It would be harder to do that in a rules-based approach which only kicks in after the form has been submitted.

update:

The topic starter mentions in another answer that he ended up with the following code:

function module_name_form_alter(&$form, &$form_state, $form_id) {
  // Always set the username to the current user. An empty string means anonymous.
  global $user;
  if ($form_id == 'content_type_node_form') {
    $form['author']['name']['#default_value'] = $user->name;
  }
}

Some feedback on this code:

Of course, the if-statement makes sense if you only need this behavior in certain cases. You could even place the global $user; inside the if.
I would recommend that you keep the !empty($user->name) ? $user->name : '' part, instead of simply using $user->name. It may be an edge case, but as you can see in drupal_anonymous_user, the global $user object does not necessarily contain a 'name' property. If, at some point in the future, this form would become available for anonymous users, they will end up with php notices on their screen.


Check if the user has read a node, if so give access to the next

I'd say you can use hook_ENTITY_TYPE_view to store the uid and the nid of the user into a custom table. That would solve the easy part, I believe.
You'd may start by something similar to
function yourmodule_node_view(array &$build, \Drupal\Core\Entity\EntityInterface $entity,
        \Drupal\Core\Entity\Display\EntityViewDisplayInterface $display, $view_mode) {

  $bundle = $entity->bundle();
  if($bundle == 'your_content_type') {
    $uid = \Drupal::currentUser()->id(); // get current user's ID
    $nid = $entity->get('nid');
    [...] // insert into custom table, etc
  }
}

For the long-term, complex solution regarding performance, that's a huge discussion. If your node list is just a simple queue that unlocks next node if previous has been read, then maybe storing just the current nid would work for you. If you need the history per user, then, as mentioned, some different solutions could do the trick. Other approach could be to do database sharding, for instance creating 1 table per node so table_read_nid_1 would just contain the users who actually have read this node and can unlock the second. table_read_nid_2 would contain the next and so on. Don't be afraid of sharding, lots of big companies use it daily! :)


Yes, I agree with Ivan.

Here is a blog post that recommends creating a new breadcrumb builder service. https://www.palantir.net/blog/d8ftw-breadcrumbs-work

The key pieces are extending BreadcrumbBuilderBase and defining the service in a yml file.

 # mymodule.services.yml
 services:   mymodule.breadcrumb:
   class: Drupal\mymodule\NewsBreadcrumbBuilder
   tags:
     - { name: breadcrumb_builder, priority: 100 }

While data can be manipulated in the preprocess layer it should be used for visual changes rather than behavioral changes.

Now to answer your more direct question of how to actually generate the links. I think what you want is something like

$node->field_tags->referencedEntities()[0]->id();

I recommend looking at BookBreadcrumbBuilder both for the Breadcrumb specific parts and the link construction. There you'll see links constructed like this:

$links[] = Link::createFromRoute($parent_book->label(), 'entity.node.canonical', array('node' => $parent_book->id()));


Update existing node (not created by Migrate) via Migrate 8.5.x

Updating existing content was possible by changing the default behaviour of a migration with the system of record concept in Drupal 7.

In Drupal 8 this concept has been revised & is available with the overwrite_properties option in the destination of the migration YAML:

...
destination:
  plugin: 'entity:node'
  # define the entity properties that are to be updated.
  overwrite_properties:
    - title
    - field_foo
    - field_bar
...


How can I tell what is causing commerce to throw entity wrapper exception errors?

sounds to me like the rules the old developer put in place are still firing for coupons and since you tried to downgrade from 2.x to 1.x they're firing and its killing your page ........ look for rules that might be lingering about??

More debugging can be found by installing devel, finding this path in the sourcecode of commerce_coupon /admin/structure/views/view/commerce_coupon_review_pane/preview/checkout/ajax and using dd() on func_get_args() throughout that pages' page callback function to debug where php is trying to get currency_code.

In general installing and hitting the page with xdebug debugger, and stepping through the code, could be very helpful too -- learn how to set some breakpoints in the debugger.


Contextual filter doesn't work with the name of the entity reference, it only works with its ID

Like Drupal 7 this configuration should work for you :

But for some reason it doesn't work, so your alternative is Views Taxonomy Term Name Depth module if you are working with Drupal 8.6 or higher version:``

Install and enable the module.
Add contextual filter Content: Has taxonomy term name with Depth

Save your changes.


Keep Footer at the Bottom of the Page w/ Andromeda Theme

You should be able to do this with CSS using

position: fixed;

On the footer and placing it on the bottom of the screen.


How do I remove the blank space that remains after removing "logo" and "site name" and "site slogan"?

You could do it in the CSS, {display:none;} or {visibility:none;}. As far as screen readers are concerned, I am not sure how they would work. I googled and found this Link.


How to perform a webform_submission query with a conditional based on a custom field in the submission data

You first need to select the Submission IDs (SIDs) from the table webform_submission_data:

$select = \Drupal::service('database')
  ->select('webform_submission_data', 'wsd')
  ->fields('wsd', array('sid'))
  ->orderBy('wsd.sid', 'DESC')
  ->condition('wsd.webform_id', $webform_id, '=')
  ->condition('wsd.name', 'paid', '=')
  ->condition('wsd.value', 1, '=')// Not sure how your BOOL value is saved
  ->execute();

// Get all the results.
$results = $select->fetchAll(\PDO::FETCH_COLUMN);

Then you need to use entity_load_multiple() or similar to load the entities:

if (count($results) >= 1) {
  $submissions = \Drupal::entityTypeManager()
    ->getStorage('webform_submission')
    ->loadMultiple($results);

  foreach ($submissions as $submission) {
    // Do something
  }
}

Drupal.org thread Reference for basis of my answer.


Core Updates after install with composer create-project drupal/drupal

You do in fact want to remove the drupal/core declaration (as it exists) in the replace section of composer.json, and then add the entry as you noted to the require section.  Then run composer update drupal/core --with-dependencies.

You can find Drupal's official process for a Core upgrade with composer here: https://www.drupal.org/docs/8/update/update-core-via-composer-option-4


Code to display multiple images using .tpl.php file in drupal 7

If you have multiple images from the content type, and you want to render them. The .tpl.php file must have $node variable and in that variable you will have the image path and image uri for each image with field name, which you want to render. Just save the image path or image uri of image in some variable and do as following:

$img_uri = <image uri path here>;
$image_url = file_create_url($img_uri);
print '';

In case your are using Image Styles then you will need to get the image's url and style name and use it like this:

$style_name = <image style name>;
$file_path = <image file path>;
$image_url = image_style_url($style_name, $path);
print '';

And I can see that are using Image Style in which your path is something like:

 /../../../default/files/styles/thumbnail/public/xyz.jpg

The rest I think that once you get different image file paths then you can easily loop them as you like.


Bootstrap dropdown parent link not clickable

A nice way that work with Drupal 8 would be to override in your subtheme:

menu--main.html.twig

And remove

 data-toggle="dropdown"

Cheers


Checkout this module Subscriptions

  This module enables users to subscribe to be notified of changes to
  nodes or taxonomies, such as new comments in specific forums, or
  additions to some category of blog. Once enabled, all nodes will have
  an additional link that allows the user to change their subscriptions.
  Users have tab on their user screen to manage their own subscriptions.
  Users can also set an auto-subscribe function which notifies the user
  if anyone comments on posts they have made. Admins can turn this on by
  default.


I don't understand why do you need that..

From your question I can assume you have both the discount module and coupons module..

If using discount in general, you don't need to apply a coupon, and the discount will be applied with rules only on the dates that you put in on the default discount creation form.

The same goes for coupon creation, when creating a coupon, you can set coupon criteria as date range and that will also be applied by default in coupon validation.


For one thing I would suggest no using #drupal_behaviours as a HTML element ID because it doesn't describe that element in any way.

It would more logically be called #chart or #highchart or something like that.

To add settings you can use drupal_add_js() (there are examples on that docs page) like this (in your custom module in PHP):

// add the series' to a javascript setting.
$series = array(
  array(
    'name' => 'Jane',
    'data' => array(1, 5, 4),
  ),
  array(
    'name' => 'John',
    'data' => array(3, 1, 2),
  ),
);
drupal_add_js(array(
  'moduleName' => array(
    'series' => $series
  )
), 'setting');

Then in the js you can access it like this:

(function ($) {

Drupal.behaviors.my_highcharts = {
  attach: function (context, settings) {
    $('#drupal_behaviours').highcharts({
      chart: {
          type: 'bar'
      },
      title: {
          text: 'Drupal.behaviors'
      },
      colors: ['#50b432', '#ed561b'],
      xAxis: {
          categories: ['Apples', 'Bananas', 'Oranges']
      },
      yAxis: {
          title: {
              text: 'Fruit eaten'
          }
      },
      series: settings.moduleName.series
    });
  }
};

})(jQuery);

Note how the settings object in the javascript mimics what you passed into drupal_add_js().


how to specify which region of panelpage can be displayed with php

Yes, $page['content'] is an associative array. You can pick, which parts of the array you'd like to display. However, I think calling print directly is not the right way. Call the render() function instead:

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


Simplest way to get a full set of favicons and touch icons

If you use the metatag module you can use the -favicon and -mobile submodules.

If you visit admin/config/search/metatags (Configuration > Search and Metadata > Metatags), you can alter a metatag set. And you'll get this section:

Here you can enter the paths to the files relative to your Drupal root. eg. sites/default/files/metatags/favicon.ico. Depending on where you've uploaded these files. (You need FTP for this.)

The -mobile submodule will add MS Application icons and in another section.


This is pretty simple. Create your module, then create a form "MyRegForm" where the user can input her email and (if needed) password (twice with the '#type' => 'password_confirm'). Then, in the submit() method create your user like this:

\Drupal\user\Entity\User::create([
            'name' => 'hGzfT54re39OpLLLk',
            'pass' => 'hGzfT54re39OpLLLk',
            'mail' => $data->mail,
            'status' => 1,
            'init' => $data->mail,
            'created' => time(),
            'changed' => time(),
            'login' => 0,
            'access' => 0,
        ])->save();

The change the username and add whatever roles you need with code like

    $tuser = user_load_by_name('hGzfT54re39OpLLLk');
    $tuser->setUsername('My super name logic');
    $tuser->addRole("whatever");
    $tuser->save();
    $rc = $tuser->id();

If you don't want to create your own form for registration, go for hook_form_alter and set the #access to the "name" field to false and add a #default_value.


How to change the order of fields in field account in the user profile form?

You're half-way there: just add something like

$form['account']['pass']['#weight'] = -6;

(event if you don't see the #weight key) and check the results - in this example you should see the current password field go right below password fields.


In terms of Drupal integration with solr or its performance it does not matter you host solr on same instance or not.

However, to decide you might want to consider following:-

Your server resources and its consumption: You need to evaluate if your server resources are well enough to serve the traffic on your website, since solr is going to share the same resources.
Maintenance of solr: Running solr instance will require some level of maintenance in terms of monitoring its running status, tweaking the solr  configuration as per your need, running it as background process.
Cost: Of course, it has cost implications hosting solr on separate instance or subscribing to paid solr hosting services will cost you extra bucks.

Hope that helps!


I've not gone in detail of the module code, but from brief overview it seems that module doesn't define any variable at template level. You can check if you're able to access $node->exclude_node_title variable in template file. If not, then to hide a node title, you can call _exclude_node_title() function which determine whether the node title should be excluded. Check the example usage of _exclude_node_title() function in _exclude_node_title_preprocess() function.

/**
 * Remove the title from the variables array.
 * NOTE : Example usage from module.
 */
function _exclude_node_title_preprocess(&$vars, $node, $view_mode) {
  // If node title needs to be excluded from display.
  if (_exclude_node_title($node, $view_mode)) {
    $vars['title'] = '';
    if ($view_mode == 'nodeform') {
      // Prevent access to the title field on nodeform view mode.
      $vars['page']['content']['system_main']['title']['#access'] = FALSE;
    }
  }
}


Why is my library not attached when programmatically rendering a block?

I think it's because attached needs to be a separate element than your markup.

This is one render element for markup, with the attached attached to it:

$build = [
    '#attached' => [
      'library' => [
        'mymodule/mylibrary',
      ],
    ],
    '#markup' => '<!-- see template -->',
  ];

The correct way to set up a build array is with the markup being a separate element:

$build = [];

$build['#markup'] = ['#markup' => '<h1>testing 123</h1'];

$build['#attached']['library'] = ['mymodule/mylibrary'];

return $build;


Image Styles not creating on one custom style only

The problem was that the image style was never being called to save the image in the first place. The following code forces the image to save for this use case.

function MODULE_node_presave($node){
  // Get some field items from a field called 'field_image.
  if ($image_items = field_get_items('node', $node, 'field_image')) {
    $image_item = array_shift($image_items);

    // Load the associated file.
    $file = file_load($image_item['fid']);

    // An array of image styles to create.
    $image_styles = array('emailthumb');

    foreach ($image_styles as $style_name) {
      // Get the location of the new image.
      $derivative_uri = image_style_path($style_name, $file->uri);
      $style = image_style_load($style_name);
      // Create the image.
      image_style_create_derivative($style, $file->uri, $derivative_uri);
    }
  }
}

credit here force image style generation on save node


Display taxonomy terms differently by content type

Since vocabularies are linked to nodes via fields you'd be best off handling this in hook_preprocess_node() in your theme file:

function MYTHEME_preprocess_node(&$vars) {
  $node = $vars['node'];

  // Only make the change if this is a certain node type
  if ($node->type == 'my_type') {
    // Extract the term IDs from the field
    $tids = array();
    foreach ($node->field_vocab[$node->language] as $value) {
      $tids[] = $value['tid'];
    }

    // This example adds the taxonomy terms to a simple list, you'll
    // want to replace this with whatever theme function you need
    $items = array();
    foreach (taxonomy_term_load_multiple($tids) as $term) {
      $items[] = l($term->name, "taxonomy/term/$term->tid");
    }

    // Replace field_vocab in the vars with the new content
    $vars['field_vocab'] = theme('item_list', array('items' => $items));
  }
}

That might need to be changed/added to depending on your needs but it should give you a place to start from. Once you've added the new hook to the template.php file make sure you clear Drupal's hooks so the registry will be updated.


You can use Apache's mod_rewrite to map all the old URLs shared on social media sites into appropriate new ones, including ignoring the latter part.  However, Drupal 7 have a quirk.  You need to rewrite to unclean URLs for it to work.

So first, turn off clean URLs (which also means turning off PathAuto) on your site.  Then look up one of your artist's pages and figure out what the real URL is.  Let's say that for artist 5 (Fabien Mérelle), it is:

domain.com/?q=taxonomy/term/5

Now you should be able to insert the following rewriterule:

RewriteRule ^artists/([0-9]+)/.*$ ?q=taxonomy/term/$1

(You must of course change the target to whatever your test showed the true query string to be.)

The above rule will change artists/5/fabien-m%25C3%25A9relle into ?q=taxonomy/term/5.

Verify that that the rule "works" (i.e. that the URL is really rewritten).  Then you should be able to turn clean URLs and PathAuto back on, and it should still work.

The rule consists of two parts.  The first (^artists/([0-9]+)/.*$) is the pattern to look for, the second (?q=taxonomy/term/$1) is the target.  They're separated by a single space.

The ^ in the pattern indicate the start of the local path, so it looks for a pattern starting with artists/ followed by a number ([0-9+]) followed by a slash (/) followed by anything (.*).  The final $ in the pattern is just a marker for the end of the local path. The parentheses around the number stuffs the number into the variable $1.  The target simply consists of the static string ?q=taxonomy/term/, followed by the value of the $1 variable.

Note: You must place the line with the rewriterule inside the .htaccess file for the site, inside the block that starts with:

# Various rewrite rules.
<IfModule mod_rewrite.c>
  RewriteEngine on


I solve this problem by adding new resource with index operation. So the path became 'rest/objectives-info', not he same but suitable.


How to set the value of a field when hidden from certain users/roles?

Ok it seems I can get around this error by setting:

$form['field_target']['#access'] = FALSE;

instead of ['#type'] = 'hidden'; and Drupal no longer freaks out.

If anybody has a better idea though I'll glady accept a different answer :)


Show fields content node according to its taxonomy using views 3

If the title and image you are showing in the block are the same as the title and image of the displayed node, then you do not have to relate the block to the node through taxonomy.

Delete the relationship, and the contextual filter. Set up a contextual filter on Content:NID, and configure it to Provide default value -> Node ID from URL.


Book: Drupal 7 Module Development (directions caused weirdness)

You just have to follow the steps which I am writing below to create a module.

Go to folder SITES/ALL/MODULES
Create a folder for module, suppose mymodule
Inside that folder create a file name mymodule.info
Write these lines in there:

name = My Custom Module

core = 7.x

description = Custom module created for testing.
Create another file named mymodule.module
Just open the PHP tag like <?php and save the created .module file
Visit your module list & you will find this module in the list over there. If not then clear the cache for once.

Problem with your process which I saw is with the path which you followed for creating the folder for your module which SITES/DEFAULT/MODULES, which is not correct.


Migration to localhost causes 404 errors

Recently had simmilar issue. If your Drupal site were set up with clean url-s , you might want to change

#   RewriteBase /

in .htaccess file

Try comment it out.
If commented, try to uncomment it.
Try to add subdirectory in that declaration, if drupal is installed
under any

Of course, check mod_rewrite as was suggested by optimusprime619


views exposed filters : how to trigger the submit on options click

Check out the Better Exposed Filters module.

Also, this related post: Where is the "auto submit" option?


The main problem is you are not passing the form array by reference so your values are never coming back into the form. Try this (note the ampersand on $form['submitted']):

function my_module_form_alter(&$form, &$form_state, $form_id) {
  $submitted = &$form['submitted'];
  prepopulate_form($submitted, $value_array);
}

Otherwise you are only modifying the $submitted variable and not the actual form.

Alternatively, you could also just pass $form['submitted'] into the prepopulate_form() function instead of using the $submitted variable and that would also work.

Plus, you are using $value_array, which does not exist, so you will need to pass actual values in.


List all available items with Apache Solr if the search keyword is empty

Thanks Letharion, to answer your question I have found this option in the Advanced options region for the search pages. Here is how to get there:

admin/config/search/apachesolr/search-pages

Create a new search page for Solr search with content type filter or enable one for taxonomy/term/%

Select "Show enabled facets' blocks in their configured regions and first page of all available results" under the Advanced options for this page


Create new table in existing module without affecting existing table data

Approach to generate a new table without affecting existing table's data.

Declare the table structure in hook_schema because for any new user who will install this module later should get this table so we have to code it here in hook_schema.

/**
 * hook_schema().
 */

function my_module_schema() {
  $schema = array();
  $schema['new_table'] = array(
    'description' => 'Table for storing information about static media
asset .',
    'fields' => array(
      'aid' => array(
        'type' => 'serial',
        'not null' => TRUE,
        'description' => 'Primary Key: Unique aggregator static media asset ID.',
      ),
      'asset_title' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'Title of the static media asset title',
      ),
      'asset_file_path' => array(
        'type' => 'varchar',
        'length' => 255,
        'not null' => TRUE,
        'default' => '',
        'description' => 'CDN url path for asset.',
      ),
      'status' => array(
        'description' => 'status field for the static media assets',
        'type' => 'int',
        'length' => 1,
        'not null' => TRUE,
        'default' => 1,
      ),
    ),
    'primary key' => array('aid'),
  );
  return $schema;
}

For the users who have already installed the module and want to create a new table can write a hook_update_n() as below.

/**
 * hook_update_n().
 */

function my_module_update_7001() {
  $schema = my_module_schema();
  if(!db_table_exists('new_table'))
    db_create_table('new_table', $schema['new_table']);
}

Here we will get all the schema and creating the 'new_table' by using db_create_table().

Hope this will resolve your issue.
Thanks.


What is wrong with my JQuery UI datepicker option code?

Put your datepicker options in via the Views UI rather than custom jQuery.


How can I link one drupal View field (an image) to a QuickTab?

I got it!
What I did:

Create 2 different content types for each image.
Then I did add each one as a field.
Then I played with Filter criteria, adding a taxonomy term previously in my content type.

Then I did rewrite the results of each field (each image) to land to the page that I wanted.
Finally I did create the basic pages inserting in each one the Quicktabs that I needed.

And voilá! that was all :D

Thanks


recaptcha not allowing login on localhost

For Google, your production site is not the same, as your devel one. But you can disable modules using drush, that does not require you to log in.


If you customize your submit buttons, you can set up access controls that only allow authenticated users to see the submit buttons.

@see https://www.drupal.org/project/webform/issues/2983024


make 2 views, first view (main view) with "yes" filter. second with "no" filter, then in first view add a footer (Global: View area), place there your second view, on each view set your title as needed. you can also pass parameters in view settings.


Well, there is a way to do this, without the need to create an extra role. The code below should give you at least a hint on how to do it. You will need to create a custom module if you don't already have one and modify the function names and code where appropriate accordingly. Be warned though: the code is not tested :)

/**
 * Implements hook_user_load().
 */
function my_module_user_load($users) {
  foreach ($users as &$account) {
    // Check if the user's profile is private
    if (_my_module_user_profile_is_private($account)) {
      static $drupal_static_fast;
      if (!isset($drupal_static_fast)) {
        $drupal_static_fast['perm'] = &drupal_static('user_access');
      }
      $perm = &$drupal_static_fast['perm'];

      if (!isset($perm[$account->uid])) {
        // If you want, you can add here a new "virtual role"
        // $account->roles[ROLE_ID] = 'custom role';

        // Make a copy of the roles array,
        // because we don't want to make changes on the user object
        $account_roles = $account->roles;

        // Remove the authenticated role, before querying all permissions
        if (isset($account_roles[DRUPAL_AUTHENTICATED_RID])) {
          unset($account_roles[DRUPAL_AUTHENTICATED_RID]);
        }

        // Get all permissions for user's roles
        $role_permissions = user_role_permissions($account_roles);

        $perms = array();
        foreach ($role_permissions as $one_role) {
          $perms += $one_role;
        }

        $perm[$account->uid] = $perms;
      }
    }
  }
}

/**
 * Helper function.
 *
 * Checks if a user's profile is private.
 */
function _my_module_user_profile_is_private($account = NULL) {
  if (!$account) {
    global $user;
    $account = $user;
  }
  // Check if the user's profile is private
  // ...
  return TRUE; // just for testing
}


Drupal Views argument menu - sending %! to end of URL

Each segment of the URL is it's own argument. So to get project/6/gallery you would have two arguments.

The first argument %1 (which you already have) is the organic group, the second argument %2 would be (I assume) a content type argument.


First you need to copy calendar-week-overlap.tpl.php from calendar/theme to your custom Drupal theme and add the following lines:

Add this code before html code - after line 30

$start_date = date_format($view->date_info->min_date, 'U');

After line 40 &nbsp;	 replace the following code

 <?php foreach ($day_names as $cell): ?>
    <th class="<?php print $cell['class']; ?>" id="<?php print $cell['header_id']; ?>">
      <?php print $cell['data']; ?>

  <?php endforeach; ?>

with this code

<?php $i = 0; foreach ($day_names as $cell): ?>
    <th class="<?php print $cell['class']; ?>" id="<?php print $cell['header_id']; ?>">
      <?php print $cell['data']; ?>, <?php print date('d/m/Y', strtotime("+$i day", $start_date)); $i++ ?>

  <?php endforeach; ?>