Customize Error/Success Messages in Drupal 7

This might be what you are looking for:

Using the String Overrides module replaces the current string with what ever given.


How to display custom news from other news providers?

You could import RSS feeds from cnn etc as nodes or aggregate the feed using the feeds module


Term reference on node edit to ALL vocabularies

The Vocabulary reference module might help you, but it doesn't even have a dev release.

A more involved solution would require adding a term reference field for each vocabulary, then placing a "controlling" list field on top of them, with an allowed value for each vocabulary.

You could then dynamically show and hide the right term reference field using the Conditional Fields module.

The module handles required fields, so you would be sure that one term is always selected.


Validating and Modifying Form Data Simultaneously

The $form_state variable is passed to your validation function by reference. This means you can indeed alter the value while validating it.

function mymodule_myform_validate($form, &$form_state) {
  if (...) {
    // Value is valid
    $form_state['values']['my_form_element'] = NEW VALUE;
  }
  else {
    // Set form error.
  }
}


That module has not been finished, yet. The function that should return the form for the settings of that module doesn't even allow to set any settings; it just output that Placeholder text you see.

  $form = array();

  // @TODO: Allow users to choose the image style used for media embeds.
  // @TODO: Allow users to choose which media plugins should be exposed.

  $form['whatever'] = array(
    '#markup' => 'Placeholder'
  );

  return $form;

The module is in a alpha state; don't consider it ready for production.


Get all users with specific roles using EntityFieldQuery

To be honest, I have no idea on how to achieve this. Good examples of how to use the EntityFieldQuery are hard to find. Since noone has answered this question yet and I'm also interested in the solution I'll try to help you out. Described below is my best guess.

A thing to keep in mind: roles are stored in a different table than users. They are added using UserController::attachLoad.

There seem to be three different conditions that you can use with an EntityFieldQuery:

entityCondition (Entity specific conditions:'entity_type',
'bundle', 'revision_id' or 'entity_id')
fieldCondition (Conditions on fields maintained by the Field
API)
propertyCondition (Conditions on entity properties)

The most logical option (if there is one) would be to use a propertyCondition, but as roles are added to the user in UserController::attachLoad I don't think the EntityFieldQuery has access to it. I think the EntityFieldQuery just uses the schema defined in hook_schema().

This leads me to believe that what you're trying to achieve is impossible. A workaround would be to get all the uids with a normal query:

I don't have access to Drupal right now, so the code below might be off. I'm sure somebody will edit the mistakes.

// Use $query for readability
$query = 'SELECT DISTINCT(ur.uid)
  FROM {users_roles} AS ur
  WHERE ur.rid IN (:rids)';
$result = db_query($query, array(':rids' => array(1,2,3)));

$uids = $result->fetchCol();

$users = user_load_multiple($uids);

If it is possible to achieve what you want with EntityFieldQuery, I'll be enlightened.


Is there a way to run hook_form_alter after themes implementation?

I think you cannot have a module hook executed the same hook implemented by a theme. If we look at the hook invoking code, we see that the theme hooks are invoked separately and after the module hooks.

The best bet would be to remove it from the theme and put it in a module, or trying with #after_build.

FormBuilder.php contains the following code.

$this->moduleHandler->alter($hooks, $form, $form_state, $form_id);
$this->themeManager->alter($hooks, $form, $form_state, $form_id);


Thoughts on best practices for user content management

If nodes are supposed to match 1:1, why not to make them one node, with different displays and access to different fields?
Or, actually, if you have only one restaurant per owner and one owner per restaurant (and it looks like that, when you say that changing author works) you could define restaurant info as a set of fields at user's profile itself. That way each user would be able to edit his own data, and data of his restaurant, and you can use views to decide what to show and where.


Correct Database settings for pushing a Drupal site live

If your connection parameters were incorrect, you would get a different error from MySQL.

I have seen connection problems on Drupal systems for a few different reasons.

Overloaded server
Low timeout values on a busy server
Low value for max_allowed_packet (this normally is a 2006 or 2020, though, in my experience).

Assuming other sites work, then the first two likely aren't the problem.  I would check your max_allowed_packet and see if that helps matters.  I typically use 32M; large values can help with restoring backups.


Passing Node Variables to Content and Blocks

Apparently I was just looking at my process wrong this morning. I went back to it after reading what you wrote and realized I could just use  in my html.tpl file and it would handle everything I need it to do.

But thank you for answering! I'm not sure how but what you posted led me in the right direction after I was reading your links :)


Updating core from 8.5.4 to 8.6.3, can I skip the releases in between?

You can skip releases and update directly to the latest release, unless you want to narrow down update issues by taking smaller steps.

You've mentioned the release note for 8.6.2:

  Sites on 8.5.x should update immediately to Drupal 8.5.8 instead, and
  plan to update to the latest 8.6.x release before May 2019.

This had a different background. This advice was for an urgent security update of versions < 8.5.8, because this wouldn't have been the right time to evaluate the update to 8.6.x if you hadn't done it yet, while the minor update from 8.5.7 to 8.5.8 was easy to apply, because it didn't require a database update.


In states you can use jQuery selectors. For example add form id to state selector:

$field_state = array(
  'visible' => array(
    '#form1 :input[name="field_a_name"]' => array(
      array('value' => 'H'),
    ),
  ),
);


Is there a way to trigger an image crop dynamically?

A module that you want to start looking at is Imagefield Crop. Details from project page:

  When the user uploads an image it is presented inside a cropping area. A cropping box is shown inside, and the user can resize and move it. Upon clicking "preview" or "submit", the image is cropped and the result is saved instead of the original image.

  Features
  - Seamless, intuitive cropping, almost like using a desktop photo editing app
  - All major browsers supported
  - Dynamic preview - you see how your crop will look like, in real time!
  - Original image is saved for recropping.
  - No matter what resolution the cropping area is, the original image is used for cropping (for highest quality)
  - The sizes of the cropping area, cropping box and resulting image can be controlled by the administrator

The problem with using this module however is that it only works with the imagefield module and the user picture.

If you already have a bunch of users that uploaded avatars using Drupal's core functionality then it would be best to rip the ImageField Crop module apart and see how it can be integrated into Drupal's user avatars.

If you have yet to have any users upload avatars then you can follow these steps....

Create a user field called "Pic" and use the "Image with cropping" widget on it.
When the user flags the image, you can redirect to the user edit page while passing the fid of the flagged image.
After that you can use hook_form_alter to chuck in the fid, uri and fileurl from the passed fid as the '#default_value' of the newly created "Pic" field from step 1.

The annoying thing about this solution is that you will have to modify user-picture.tpl.php to use your custom created field over the default avatar picture.


Go to Admin -> People -> Permissions & search View the administration theme check the checkbox for author role. Check screenshot below:


Could you use a rest endpoint? Because this is already handled by drupal core. See for example this or this
Otherwise I think you're just missing user_login_finalize after your check if the user is logged in.
user_login_finalize($user);
//Eventually redirect the user somewhere
$user_destination = \Drupal::destination()->get();
$response = new RedirectResponse($user_destination);
$response->send();


Does $element['#title'] need to be escaped with check_plain()?

It's user input and should be considered unsafe; you should always sanitise it.

For the specific example you've given where it isn't, the title is already sanitised before it's passed to the theme function containing the t() call. This happens in field_multiple_value_form()

$title = check_plain($instance['label']);

...

$element = array(
  ...
  '#title' => $multiple ? '' : $title,
  ...
);

As an aside, if you ever did need to preserve HTML in the title for whatever reason, you could consider using filter_xss() instead.


How to implement ORDER BY SUBSTRING in db_query

SelectQuery::orderBy() isn't particularly picky, you can just tack this on to the end of your code:

$query->orderBy('SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1))');

With the rest of your code that produces

SELECT n.nid AS nid, n.title AS title, n.uid AS uid, c.cid AS cid, c.pid AS pid, c.nid AS c_nid, c.uid AS c_uid, c.subject AS subject, c.comment AS comment, c.hostname AS hostname, c.timestamp AS timestamp, c.status AS status, c.format AS format, c.thread AS thread, c.name AS name, c.mail AS mail, c.homepage AS homepage
FROM
{node} n
INNER JOIN {comments} c ON (n.nid=c.nid)
WHERE  ((n.type=:type))
ORDER BY SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1)) ASC


Access forbidden 403 to homepage but the rest of website working Drupal 7

For reasons of module SiteMap, I needed to have folders called en, es, fr, which coincides with the suffixes of the language switcher. This was causing some problem in XAMPP while not causing any problem in Linux version. I have renamed the folders and everything is ok now.

I suspect that having an URL as example.com/fr/ which renders the homepage in french is not a good idea if you have a directory, that, if Drupal were switched off, would point to a folder example.com/fr.


The /blog path created by the blog module does not have an option sort by title. The easiest way to do this is to use the Views module to create a page view and just build a display of blogs sorted by titles.

Another way, if you're looking to alter the built in /blog path created by the blog module, you could use hook_menu_alter to alter the page callback from blog_page_last() that's in blog.pages.inc.

You can place this code in your custom module:

function mymodule_menu_alter(&items) {
  $items['blog']['page callback'] = 'mymodule_blog_page_title_order';
  return $items;
}

function mymodule_blog_page_title_order() {
  global $user;
  $build = array();

  $query = db_select('node', 'n')->extend('PagerDefault');
  $nids = $query
    ->fields('n', array('nid', 'sticky', 'created'))
    ->condition('type', 'blog')
    ->condition('status', 1)
    ->orderBy('sticky', 'DESC')
    ->orderBy('title', 'ASC')
    ->limit(variable_get('default_nodes_main', 10))
    ->addTag('node_access')
    ->execute()
    ->fetchCol();

  if (!empty($nids)) {
    $nodes = node_load_multiple($nids);
    $build += node_view_multiple($nodes);
    $build['pager'] = array(
      '#theme' => 'pager',
      '#weight' => 5,
    );
  }
  else {
    drupal_set_message(t('No blog entries have been created.'));
  }
  drupal_add_feed('blog/feed', t('RSS - blogs'));

  return $build;
}


How can I export all my blog posts as CSV?

If I was going to try to create a CSV of my sites content I would try to use the Views Data Export module and filter on your blog content type and include all the fields you want.

  This module is designed to provide a way to export large amounts of
  data from views. It provides a display plugin that can rendered
  progressively in a batch. Style plugins are included that support
  exporting in the following types:

  CSV
  Microsoft XLS
  Microsoft DOC
  Basic TXT
  XML


How to do push data to datalayer after Ajax callback?

I had the same problem. Events were only sent first time and then never.
I solved it purging completely cache, and fixing my google tag.


Hook into node operation from theme template.php?

You want to create a custom module. Note that nothing stops you from creating content types through the user interface, it is in fact the suggested way to do so nowadays with fields and stuff (instead of using hook_node_info())

Node API Hooks contains an overview of all hooks that can be used to interact with nodes at different events like create, view, delete..


how to get views field names/values for hook_views_pre_render?

How do I get the available values to work with?

To get values from result you can do something like:
$value->_entity->title->getValue()[0]['value'];
Here is example to get body and title you can do the same with other fields.

/**
 * Implements hook_views_pre_render().
 */
function mymodule_views_pre_render(ViewExecutable $view) {
  if ($view->id() == 'viewname' && $view->current_display == 'page_1') {
    foreach ($view->result as $key => $value) {
      //- Get title value
      $title_value =  $value->_entity->title->getValue()[0]['value'];
      //- Get body value
      $body_value =  $value->_entity->body->getValue()[0]['value'];
     //- Get Other field values ...
    }
  }
}


The best way to generate buttons and apply visibility restrictions based on roles

you can simply create different class for each type color and based on the role you can add the class to the button.


Alter Views query limit using views_query_alter

If it's only about the number of results to return, I think you could simply implement hook_views_pre_build() and do the following:

function track_click_views_pre_build(&$view) {
  if ($view->name == 'click_list_days') {
    $view->set_items_per_page(YOUR_NUMBER_OF_RESULTS_HERE);
  }
}

Or inside hook_views_query_alter() you should be able to do:

$query->set_limit(LIMIT);


To directly answer the question, there is no simple way in Drupal 8 to modify the schema for a field once it's been populated with data.

But, there is a more complicated way to manage it.

We've used the work done here by J-P Stacey to update a field in our platform.

ALTER the database tables directly using raw SQL.
Change the site configuration for the field.
Force the current, "desired" schema records in Drupal to match.
Force the "most recently installed" schema records to also match.

Additional information can be found in this article written by Marcus Bernal.


How to use composer for installation profile?

You need to use the Composer Manager, which search the composer.json file in any module add the dependency on the core composer.json

How to handle the dependency ? By writing a composer.json file that contains all the php libraries that are been load it.

Here is an example of a good composer.json

{
  "name": "drupal/mobile_detect",
  "description": "Mobile_Detect is a lightweight PHP class for detecting mobile devices.",
  "type": "drupal-module",
  "homepage": "http://drupal.org/project/mobile_detect",
  "authors": [
    {
      "name": "Matthew Donadio (mpdonadio)",
      "homepage": "https://www.drupal.org/u/mpdonadio",
      "role": "Maintainer"
    },
    {
      "name": "Darryl Norris (darol100)",
      "email": "admin@darrylnorris.com",
      "homepage": "https://www.drupal.org/u/darol100",
      "role": "Co-maintainer"
    }
  ],
  "support": {
    "issues": "http://drupal.org/project/mobile_detect",
    "irc": "irc://irc.freenode.org/drupal-contribute",
    "source": "http://cgit.drupalcode.org/mobile_detect"
  },
  "license": "GPL-2.0+",
  "minimum-stability": "dev",
  "require": {
    "mobiledetect/mobiledetectlib": "~2.8"
  }
}

This composer.json is for the mobile_detect drupal module. Once you run the core composer.json this will download the mobile_detect library into the vendor directory and support autoload. And you can do the same thing with your libraries.

For more information about D8 and composer I will recommend reading this article - https://bojanz.wordpress.com/2015/09/18/d8-composer-definitive-intro/


Theme hook suggestions are made based on these factors, listed from the most specific template to the least. Drupal will use the most specific template it finds:

taxonomy-term--tid.tpl.php
taxonomy-term--vocabulary-machine-name.tpl.php
taxonomy-term.tpl.php

Note that underscores in a vocabulary's machine name are replaced by hyphens.


How do I render contextual links for blocks I render in my code?

$block = block_load('module', 'delta');
print drupal_render(_block_get_renderable_array(_block_render_blocks(array($block))));

Too bad we have to use private functions from the block module (_*()) to achieve this.


Create a view field that contain the sum of specific fields for a specific user

Try View Aggregation setting:

Goto Advanced tab, scroll down below and set "Use aggregation" to
'Yes'.
Filter Your View with Name field (user reference).
Now there must be "Aggregation settings" inline with your field
"the amount of the donation"
Goto "Aggregation settings" for "the amount of the donation"
field and select 'Aggregation type' to 'Sum'.

  Thats it, you are good to go now.


User's field autocomplete/autosuggest widget

In your field setting, you can choose a view for node or user references:

To create this kind of view-reference, you have to previously create a view with a reference page like this :

Note that every field you'll choose for the view, will appear in the autocomplete input

Hope this can help


Add ability to add bundles to an entity that does not currently have bundles?

Possible yes, although not trivial. Not having a bundle means internally, Drupal exposes a default bundle that has the same name as the entity type. So the by far easiest approach would be to create a bundle entity type, create a default bundle with the same id (possibly only in the update path for existing sites) and then allow to create additional ones.

What's hard is changing the bundle of an entity type, that's not officially supported. file_entity does it for the file entity type, you can have a look at its entity class and the methods it overrides the detect the file type and based on that, sets the bundle.


How to calculate the sum for each option of all webform results in a Drupal webform grid?

Create a 'webform submission' view. By using the Views Calc module you can display the sum of each field at bottom of the table/grid.

This module adds simple calculations to a views table. Requires the Views module.
You can SUM, AVERAGE, COUNT, MIN, MAX, or AVG selected columns. A plug in theme makes the view look more spreadsheet-like (right justifies numeric fields, shades calculated columns and rows, and underlines calculated rows).

Image from module page


To get the data from a field in an entity be it a node or something else is pretty straight forward.

It can usually be done doing something like this.

$data = $node->field_name['und'][0]['value']

But it depends on which field type you are using ect. A more convenient way is to use the entity module. With that installed you can do:

$node_wrapper = entity_metadata_wrapper('node', $node);
$data = $node_wrapper->field_name->value();

This giv give you the value, for reference fields like term reference, you will get the actual loaded term instead of the raw id which is pretty handy and allows chaining.


Theming / modifying the markup of default search block form

First of all nothing is "magical" and if you are new to drupal then you have not looked into the Form API or ignored it.

What you are trying to do resides on hooking into the form api using the hook_form_alter or hook_form_FORM_ID_alter functions.  The "magical" inline elements on your form are being handled by the form API I spoke of.  You are trying to enter form elements and a button into a template file which is not only a security issue but is not the way that drupal handles forms.

You will need to create a custom module and add your hook_form into there and use the form api I spoke of to handle what you are trying to do.


function hook_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
   if($form_id == 'views_exposed_form'){
      $form['field-name']['#attributes']['placeholder'] = t('Placeholder Keyword');
   }
}


This part of your original question isn't quite clear:

  Simply setting it as the default selected profile is not enough.

However, all you have to do is to add exclusive = TRUE in the .info file of your installation profile.
This will automatically select your installation profile, and the user will proceed to the language selection screen.

Note 1: the setting above will be ignored if there are 2 or more installation profiles marked as exclusive. This might happen only if you downloaded another installation profile and are keeping it in the /profiles folder (e.g. Commerce Kickstart).

Note 2: this has been committed to Drupal 7.22 and is based on this issue/discussion.


Completely hide/remove views exposed form?

If you're using hidden exposed filters instead of contextual filters, then you're already on a bit of a hacky path so you might as well just hide the filters with css.
If you think the contextual filters won't work which is sometimes the case, then the elegant solution is using the Global:Null contextual filter + Views Argument Substitutions to use parts of the url in the normal filters.
But really, just hide it with css.


The only reason I can think of is that the viewing user does not have access to the linked node. Internal menu links that point to unauthorised content do not appear in menu.

Make sure the node has been published and your user can view it.

Some people actually consider dolbydolby's work around a bug :-) http://drupal.org/node/483150


Can you filter nodes in a view by the last date of one node referencing that node

The following steps should set this up...

Create a view of tours
Add a relationship of type "Entity Reference: Referencing entity" to the concerts
Make sure "Require this relationship" is ticked
Add a filter for the date field on the concert type
Select "Text" under "Date selection form element"
Ensure the relationship you set up is selected in the "Use relationship" dropdown
In the filter settings, change Operator to "Is greater than"
Change "Select a date" to "Enter a relative date"
type "now" under "Relative date"


Change node author on node save with rules

I think you can do this by adding a new action - "Fetch entity by ID", then selecting users and using that to update the node.


See the comment from @Clive, you can only add single objects as dependency. But you need to add a list tag as well, because the entity query may change because of entities added or modified that are not in the cached list.

$list_tags = \Drupal::entityTypeManager()->getDefinition('entity_type')->getListCacheTags();
$response->getCacheableMetadata()->addCacheTags($list_tags);


Difference between hook_query_alter and hook_views_query_alter?

HOOK_QUERY_ALTER:

Perform alterations to a structured query.

ONLY queries that have already been tagged (at creation time) can be caught by this hook.
If the query you are hoping to alter doesn't already have a tag (which effectively 'publishes' its willingness to let you mess with it) then you can't alter it using this method.

To find out - inspect the source code of the query you are trying to modify.

HOOK_VIEWS_QUERY_ALTER :

Alter the query before executing the query.

It took me a good bit of time to figure out how to use hook_views_query_alter to modify my view query so I just want to pass on some small bit of knowledge to others who may find it helpful. I wanted to create a view/block that displayed a list of books on my site. I only wanted to list the names of parent book pages not all book pages just book titles. Out of the box, the views module can create a view to display nodes of type "book" but that includes all book pages. The query looked like this:

SELECT node.created AS node_created, node.nid AS nid
FROM
node
WHERE (( (node.status = '1') AND (node.type IN  ('book')) ))
ORDER BY node_created DESC
LIMIT 10 OFFSET 0

What I really wanted was below query (that joined on the book table using book.nid):

SELECT node.created AS node_created, node.nid AS nid
FROM
node
LEFT JOIN book ON node.nid = book.nid
WHERE (( (node.status = '1') AND (node.type IN  ('book')) AND (book.nid = book.bid) ))
ORDER BY node_created DESC
LIMIT 10 OFFSET 0

I was able to create the latter query using the hook_views_query_alter. I spend most of the day reading about the views_plugin_query_default api and views_object and tried several query object function calls. Along the trip, I learned how to use the devel module and dpm to display my query in the admin. I tried all kinds of stuff and ended on this two line module.

function my_hook_views_query_alter(&$view, &$query){
  if ($view->name == 'my_hook') {
    $alias = $query->add_table('book','node');
    $query->add_where_expression(0,'book.nid = book.bid');
    dpm($query); //dumps object to admin with devel module
  }
}

The add_table call automatically analyzed the relationship and created the LEFT JOIN above. I had played around with the views_plugin_query_default::add_where but the result was only a simple where clause that only allowed a scalar value (e.g. book.nid = 'book.bid'). The add_where_expression uses the condition type 'formula' to create a complex where. The resulting where clause that just joins on book.bid was :

WHERE (( (node.status = '1') AND (node.type IN  ('book')) AND (book.nid  = book.bid) ))


How to define another data table to join for views (ie from csv file)?

Views can do some clever things. But I think that joining a sql query to a csv file may be a bit beyond it. (not that I'll be surprised if someone has a solution).

The issue is that within a data engine (sql, mongodb, sparql), views can work well providing that everything you want to work with is also in the same engine. If you wanted to say join a sql table to a sparql query you would have to try and do the join in code. Bring back results from sql and use in sparql or vice versa. This is not a scalable solution. It may work for a few rows, but beyond that you are going to hit some serious performance buffers.

In this case you may have more luck importing the csv file to mysql and using the data module. that should allow you to define joins and use it in your view.


No, you can not call Settings::set. You should get an

Error: Call to undefined method Drupal\Core\Site\Settings::set() in ...

Maybe there's something wrong with your error reporting or you imported any other Settings class (check your namespace). Check your php.ini for this. The Settings Class is for read-only access to the settings in settings.php.

If you need to set some system settings do it like this:

// themes
\Drupal::configFactory()->getEditable('system.theme')
->set('admin', 'bartik')
->save();


Email notification based on purchased item

Have you tried rules? The trigger would be when new content is added, and the condition would be that the content type is appropriate. Not sure how you've stored the data connecting subscribers to their magazine, but that will be needed for the action. I don't think you'll be able to do this out of the box (specifically I'm not sure if you can send an email to multiple addresses using rules) - so you might need to write a custom action.


How to get Drupal 8 View to Accept Parameter as argument?

You can do it with a contextual filter. In the "Configure contextual filter" menu select "Provide default value". For type choose Raw value from url.

There is more info on contextual filters in this article.

http://redcrackle.com/blog/adding-contextual-filter-view-drupal-8

If you are using taxonomies and want to use the name instead of id in the url you need to setup the relationships first and use name as the contextual filter.


All ajax logic placed in construct form function (ajax_example_simplest), ajax callback just return part of form (replace_textfield) or ajax commands. Its Drupal architecture. This form can be validate and altering.


If your source plugin extends SqlBase, you need to make sure you have the database configuration set up correctly. Otherwise Migrate will silently ignore the migration.

In your settings.php or settings.local.php, add the following database configuration:

$databases['migrate']['default'] = array(
  'driver' => 'mysql',
  'database' => 'NAME OF YOUR SOURCE DB',
  'username' => 'YOUR DB USER',
  'password' => 'YOUR DB PASSWORD',
  'host' => 'localhost',  // change this as necessary
);

By default, Migrate looks for a DB connection named "migrate". If you use any other name, the migrations won't appear when you run drush migrate-status.

Note: The "migrate" connection is in addition to your "default" connection. You should have two connections in your settings if you're migrating from a MySQL database.

In case anyone's curious, the DB connection check occurs in the method SqlBase::getDatabase() in drupal/core/modules/migrate/src/Plugin/migrate/source/SqlBase.php.

This is documented in https://www.drupal.org/node/2830031 and apparently will be fixed in Drupal 8.4.


Combining 2 drupal 7 sites - how to move modules?

I don't know for the menus, but for modules that doesn't implement any export functionality (either custom or contrib), take a look into the 'variables' table.

for how unpractical it may sounds, export the table data, keep only the 'module_*' entries of the module you need and insert the in the new site database, after you install the modules. You will have to change the sql from inserts to updates too.

yes, extremely unpractical, but i can't think to an automated routine for it.

also, probably you are forgetting to export users too (and custom roles).


hook_node_presave() can help you making the changes

  Act on a node being inserted or updated. This hook is invoked from node_save() before the node is saved to the
  database.

so inside this hook you can get the created time and can change the title.

As an example code: Here I am making node title as the time article node is created.

function mymodulename_node_presave($node) {
  if($node->type == "article") {
    $node->title = $node->created;
  }
}

Make sure you do not call node_save() inside this function, else this will turn out to non breking recursion.


Module or template mod for making development site look different from live site

The Environment Indicator works well for that.  It works best with a local_settings.php file, in my experience.


Looking for something similar to "Views selective filters", just with "inactive" instead of "removed"

How are you going to gray out items in a combobox? If using Better Exposed filters module to replace the combox with some other widget, you can easily use Views Selective Filters and some Javascript to do the magic.


Importing existing users into a new Drupal site

It sounds like you're after the Feeds module! It supports mapping fields sources to destinations, and will auto-create entities in some cases.

After installing & enabling the module, you'll want to create a Feeds Importer (under Structure) and go from there. Navigate to /import to upload a CSV file to a feeds importer for processing.

There's a sandbox module Drush Feeds Import that should allow you to run some of this from the command line if necessary.

Check out:

  The site builder's guide to Feeds:

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

If the stock Feeds modules don't quite solve your problem, you could use the Feeds API to define your own processing class that manipulates and inserts the data into the new site.


You have to be a bit more concrete when you ask for how to theme a view. One thing to note is that views help you with template suggestions (names for templates) which is one of the most common and easiest ways to alter the output of Views.

Pagination can be setup from within the interfacer. There is a pager link you can click on to set that up, if you look around a bit I'm sure you'll find it. The location depends on the Views version you use.


workbench access warning message when I click preview

You can find the related bug here and the patch here.

You can then download the patch into the workbench_access directory and execute

patch -p1 < 1935190-wa-array-keys_0_1.patch


Make a views listing of nodes in Search API with multiple parameters to sort and more

In Search API you can assign a 'boost' for results depending on defined field:


DrupalGap response is HTML instead of JSON

We found the solution for our problem.
Under admin -> settings -> commons uncheck the box "Force users to login".
Now it is possible to get json responses from connect and login actions.


Please go to views admin interface and check the views name as Recent post(display type block), views gives  you flexibility for adding any number of fields your content type has, also it will allow you to have custom classes to fields that you will be needing to theme.About classes and ids already there, they are coming from views theming you do not have to touch there all you have to do is add fields you want, while adding it will allow you to style it by adding wrapper divs or other html element.Once you finish with editing the view,check the block in firebug you will see your calsses and ids working there, then add css for it in your Danland theme .css file.

Key Points which may help you:

how to add/remove fields from view
how to add custom classes to the fields in views
Once done style it using your theme css file.


I find the Devel Themer module to be very helpful.

From the description:

  popup display shows which theme function/template outputted the HTML, and what other files could have done so.


What version of Drush are you using?  Recent versions of Drush will notice that there is a copy of Drush included in your Drupal site, and will redispatch (exec) to use it instead.  If you are using an old, unsupported version of Drush (e.g. Drush 6 or earlier), then it will not do this, and the error you see above would be the likely result.


CSS\JS Aggregation "Shuts down" Firebug indication

Advagg has a built in feature to bypass aggregation for a single request.  You can append ?advagg=0 to the query string to load the page without aggregation.  I haven't personally used this feature, but it seems it could be useful in your situation.

From the module description:

  Url query string to turn off aggregation for that request. ?advagg=0
  will turn off file aggregation if the user has the "bypass advanced
  aggregation" permission. ?advagg=-1 will completely bypass all of
  Advanced CSS/JS Aggregations modules and submodules.

This would help with your problem of having readable css in firebug, but any changes you make to your sites css would still need a cache clear to take effect.


Commerce checkout, check if checkbox is checked

You shouldn't add the field directly to the checkout form, but rather create a new checkout pane and add the field to that.

e.g:

/**
 * Implements hook_commerce_checkout_pane_info
 */
function MODULE_commerce_checkout_pane_info() {
  $checkout_panes = array();

  $checkout_panes['contact_settings'] = array(
    'title' => t('Contact settings'),
    'file' => 'includes/commerce_checkout.checkout_pane.inc',
    'base' => 'MODULE_checkout_contact_settings_pane',
    'page' => 'checkout',
    'callbacks' => array('checkout_form_validate' => 'MODULE_checkout_contact_settings_pane_validate')
    'fieldset' => TRUE,
  );

  return $checkout_panes;
}

Put your form builder in includes/commerce_checkout.checkout_pane.inc > MODULE_checkout_contact_settings_pane

You can then use the Commerce API to validate your checkout form in

/**
 * Checkout pane validation for contact_settings
 */
function MODULE_checkout_contact_settings_pane_validate(&$form, &$form_state, $checkout_pane, $order) {

  // Do some validation tests here... omitted for brevity.
  if (empty($form_state['values']['thisfield'])) {
    drupal_set_message(t('Some validation error message'), 'warning');
    return FALSE;
  }

  return TRUE;

}

More info: hook_commerce_checkout_pane_info


PDOException when creating the table: Base table or view not found

I had the same problem, and in my case the issue was the database tables engine: By default it is InnoDB and (for some reasons I still don't have to understand) Drupal reports this error.

You must change the database engine to MyISAM. First off, you must be sure the tables that are going to be created by Drupal have MyISAM as engine: In /includes/database/mysql/schema.inc, look for createTableSql($name, $table), and change InnoDB to MyISAM; then, save it.
Since you have a few tables in your database they must be changed to MyISAM as well, so simply export the database as .sql file open it in a text editor and replace Engine=InnoDB with Engine=MyISAM. Now in the server phpmyadmin delete all the tables of the DB and import the new .sql file in there. In this way, all your tables and the tables that will be created by Drupal are MyISAM.


Add Google Analytics to track a button press

take a look at Google Analytics Event Tracking:

  Event Tracking is a way to track user interaction with out registering
  a page view. Using Google Maps as an example site, event tracking
  would allow the user to track Zoom, Drag, and View Change events
  without contaminating the page view statistic.

  This module allows an interface for Google Analytics event tracking
  capabilities. It provides a hook for other modules or "glue code" and
  also has some handy drush commands.


I suggest you use Custom breadcrumbs module for defining overriding breadcrumbs: it supports Token, which helps defining complex breadcrumbs (e.g. defining breadcrumbs from related taxonomy terms, etc.).

With this module, you can define custom breadcrumbs for the following entities: node, path, term, Views, vocabulary (on admin/structure/custom_breadcrumbs).
On admin/config/user-interface/custom-breadcrumbs, you can also set to append current page title by default too.

Its admin interface is really simple.

In your case, you should go to admin/structure/custom_breadcrumbs/views/add, set things like this (it's just an example):

Save, then go to admin/config/user-interface/custom-breadcrumbs, and check "Append page title", hit "Save configuration", ready.


The patch from
https://drupal.org/comment/8195767#comment-8195767
seems to solve the problem.


use drush command to login, it will print the login URL.

drush uli;


Drupal Feeds XPath Parser html parsing form IMDB

The context XPath expression is for finding a context of all other (variable) expressions. These queries do not have the context prepended, but evaluation starts with (one of the) results as context.

Thus, you may not start your query with /, otherwise search starts at the root again – and the root element is <html/>, not <title/> or any of the others.

For example, the query for the title has to be h1/span[1]. Anyway, I'd better go for the @itemprop attribute instead of a positional attribute: h1/span[@itemprop='name'] or even decouple further from the underlying structure: .//*[@itemprop='name'] and use the Movie schema properties whenever possible, as they are designed for scraping the data and will make it much more robust.


Default date field values like "today +10 hours 30 minutes"

The best way to control the default output of form elements is through the drupal Form API.

You have two scenarios:

If you created the form with the form api and have a date popup in your form, you can use the method described in this post to set the #default_format of the #default_value of the form element.
If you didn't create the date popup in the form element with the form api, meaning you added it as a field to an entity through site configuration, you can still make a small custom module solution.  Make a custom module and implement hook_form_alter, find the field in question and set the #default_value using the method mentioned in #1


Site index removes "www" from url and files (e.g., '/about') don't work with "www."

The following rules remove the www everywhere on your domain.
Put it in .htaccess file:

  RewriteEngine On
  RewriteBase /
  RewriteCond %{HTTP_HOST} ^www.yourdomain.com [NC]
  RewriteRule ^(.*)$ http://yourdomain.com/$1 [L,R=301]


Memcache Admin not showing up in Modules

The Drupal 6 version of memcache requires enabling the Memcache Admin module:

Once this module is enabled, there is an option at admin/settings/memcache to display memcache statistics on a page-by-page basis:


open a lightbox2 containing a flowplayer video from a menu link

Add rel="lightvideo" tag, it will popup the video, It also have the option to set the size of the modal window, for more information see the readme.txt

Google video example


Display field content in views single field template.. STUCK!

Ok, so how I solved it... Maybe there is other, better solution?

I rearrangement my fields in view: first with content, title, pictures and links,
I've added one more custom text field with rewrite - then I put in this rewrtite all fields above with some twig function to display this in different ways and hide this field to.
Then I've added  last field, field_background which is one with slide background picture. I turn it to display just URL of picture and write rewrite inside to display:

{{ field_background }}  )">  {{ nothing }}

wher nothing is my field with all content stuf inside.

I've edited twig template for last field and write something like this:

<.div style="background-image: url( {{ output }}

so when views start rendering content it create code from my last field which is wrapprer with background image around content form other fields above.

Well, it's work, my slides run with background picture. But I dont fell good with that, I think there is better way to get it in one field.


you could just get the current page with request_uri() and then use some logic to style a view on the home page differently.

Or just create a second view and use the front module to show that view on the home page.


How to change Taxonomy admin page title?

Could someone tell me where to go and which static route to change?

It's not a static route.  Like other entity collection routes, it is built with the aid of the comment annotations above the Vocabulary entity class.  VocabularyRouteProvider also comes into play, and it sets a _title_callback into TaxonomyController::vocabularyTitle for good measure.

At any rate, this is all a bit moot because you don't want to go modifying core files, because then when you update core you will have to patch them all over again.  Very tedious.  Instead you could implement your own RouteSubscriberBase::alterRoutes.


how to insert the See All link in a drupal view block

In the footer section of the view add a global text area with the link of the See all news.

STEP 1:

STEP 2:

STEP 3:

Once you are done adding a field in the footer, save the view and the See all news link would work as expected.

For creating the Read more link

Go to the body field of the news.
In the Rewrite Result, you have a checkbox "Trim this field to a maximum length".
Once you check the checkbox, you have the option to "Add a read-more link if output is trimmed.".
Add the Read more text and use the [path] token for getting the path of the node.
Save the view and the Read more link would be there for all the news that you have.

Adding an image to help you in a better way:


I think the module Field Permissions allows you to do what you're looking for. Or at least in the documentation it write "Create own value for the field".


Entity reference view display is not displaying fields as expected

You could use the realname module (which now has a D8 release). Or, you could alter the user name as displayed in Drupal:

function HOOK_user_format_name_alter(&$name, $account) {
  // Load the full user account.
  $account = \Drupal\user\Entity\User::load($account->id());
  // Get the full name from field_name.
  $full_name = $account->get('field_name')->value;
  // If there's a value, set it as the new $name.
  if (!empty($full_name)) {
    $name = $full_name;
  }
}


joining 2 form, but submit handler can not work

I'd sugest to build your own form using FAPI and create the nodes programmatically in the submitthandler.

Looking at what you get in hook_form_alter has of course a good learning effect.


unable to edit content created by user 1

I think, you did not assign "edit any [contenttype] content" permission to newly created admin user, so this user does not have access to edit content created by other user.

You can follow below step for configurations.

Go to Administer ->  User management -> Permission
Assign "edit any [contenttype] content" permission to newly created admin role and save the permissions.

Kindly see that [contenttype] is content type in your website. If you want to allow newly created admin user to edit all content created by other user, you need to give permission for all content type.


Submitting Data / Updating Data into Webform programmatically

You can do this by adding following code in your custom module

  // Submit a webform
  module_load_include('inc', 'webform', 'webform.module');
  module_load_include('inc', 'webform', 'includes/webform.submissions');
  // Load node by webform id
  $node = new stdClass();
  $node = node_load($webform_nid);
  // Get next serial number
  $serial = _webform_submission_serial_next_value($webform_nid);

      $data = array(
        1 => array('Guest user'),
        2 => array('guest@example.com'),
        3 => array('Final testing of webform'),
      );

  $submission = (object) array(
    'nid' =>$webform_nid,
    'uid' => 0,
    'submitted' => REQUEST_TIME,
    'remote_addr' => ip_address(),
    'is_draft' => FALSE,
    'serial' => $serial,
    'data' => $data,
  );

  $sid = webform_submission_insert($node, $submission);


How can I create a hook into an external module

PHP offers no mechanism to do that.

If the external function isn't a hook (i.e. it doesn't use module_invoke() or drupal_alter() to gather data from other modules) then the only thing you can do is patch the function in the external file.


Infinite Redirect Loop with PURL and spaces_og

This issue occurred because I didn't have a path prefix set for purl.  I created the group prior to enabling purl and spaces.  After adding the path in the group node edit form, the redirect loop was no longer present.


How to put two blocks inline in menu bar

This is really a question on how to align blocks horizontally in a region, which calls for a CSS solution.

There are a few things to consider before you start:

Blocks have no defined width. Normally the outer wrapper is just a
div, as determined by the block.tpl file, and it is precisely because of
this that they take up all the horizontal space given to them. That
is why they stack vertically.
Each theme might be slightly different in handling floats. Some
themes are fixed width, some are fluid, some have a built in
framework for handling layout, most don't.

For a theme that has a fluid layout without a built-in layout framework, and showing two blocks inline, you can do this:

@media screen and (min-width:761px) {
    .region-featured:before,
    .region-featured:after {
        content: " "; /* 1 */
        display: table; /* 2 */
    }

    .region-featured:after {
        clear: both;
    }

    /**
     * For IE 6/7 only
     * Include this rule to trigger hasLayout and contain floats.
     */
    .region-featured {
        *zoom: 1;
    }
    .region-featured .block {
        width:50%;
        float:left;
    }
}

This will float two blocks side by side when the overall width is greater than 760px. If you have a fixed width site, then remove the media query. Also note the clearfix styling (when using a layout manager it will just be a class) which ensures that the region wrapper grows vertically to enclose the blocks.

The width of the block was set to 50% because there are two blocks that I wanted to float next to each other (100% / 2 = 50%). For three blocks you will set a width of 33.333333% etc.

When using a layout framework (recommended, and mostly baked into the theme), then it will all just be a matter of assigning proper classes, so you would then need to assign a region-class in the page template to the region, and assign classes to the blocks, perhaps using a module like Block Class, or also inside the block or region template file.

For a theme with a baked-in layout framework, look at Bootstrap, amongst numerous others. It is extremely easy to use, but you must familiarise yourself with the official bootstrap documentation. Bootstrap is not Drupal specific. It is just a framework that the Drupal Bootstrap theme developers adopted.

For more CSS solutions on aligning Divs horizontally, How to Align Divs Horizontally in CSS


Problem is in your  pathauto Patterns, go to admin/config/search/path/patterns1 and check your pattern, it seems you have a pattern that when each time  the content edited Url  added to your Url Alias again.

I guess something like this exists there

 products/[node:url]


How to remove orphaned actions if you get not authorized access as uid1?

Relative path /admin/config/system/actions shows a list of the actions available in the site.

If a site has orphaned actions, then relative path /admin/config/system/actions/orphan will provide the opportunity to remove them.

If you enter relative path /admin/config/system/actions/orphan and get redirected (automatically) to /admin/config/system/actions/manage, then that is an indication that there are no orphaned actions.

And if everything else fails, and you're willing to take the risk (+ a backup of your database first!), you might want to give it a try to edit the Drupal database using an SQL which looks like so:

delete from actions where aid = "views_bulk_operations_archive_action";


How to use Google and Ubuntu fonts on Zen theme

You can also try Google Fonts.

  This module enables you to add Google Fonts to your site using the Google Font API.

  Benefits of the Google Font API

  A choice of high quality open source fonts.
  No Javascript needed, pure CSS!
  Works in most browsers.
  Extremely easy to use.


How to use Represenstive Views to display users representative nodes?

The error has to do with a bug related to User: Representative node. Checkout https://www.drupal.org/node/1417090. Comment #35 has a patch for the latest dev version of views that will possibly fix the issue.


How do I use a template file for preparing HTML message body for emails?

So here is the answer:
Inside the hook theme function of your module use this code

function get_price_theme() {
  return [
    'mail_to_eberhard' => array (
        'template' => 'mail-to-eberhard',  // TWIG File
        'variables' => array('submitted_data'=>[]),
    ),
  ];
}

where variables is the array of parameter you want to send to the template file. Now create a template file named as mail-to-eberhard.html.twig inside your modules template folder.
Then inside the hook_mail() alter function use this code.

function get_price_mail($key, &$message, $params) {
  switch ($key) {
    case 'mail_to_eberhard':
      $message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';
      //$message['from'] = \Drupal::config('system.site')->get('mail');
      $message['subject'] = t('Factory Purchase - ').\Drupal::config('system.site')->get('name');;
      //$message['subject'] = t('Article created: @title', array('@title' => $params['node_title']), $options);
      // Render the template to HTML
      // Set up email template
      $body_data = array (
         '#theme' => 'mail_to_eberhard',
         '#submitted_data' => $params['message']
      );
      //$message['body']['#theme'] = 'mail_to_eberhard';
      $message['body'][] = \Drupal::service('renderer')->render($body_data);
      break;
  }
}

now inside you template file you can use the array variables like this

You have received one new message from the Get Price Tab.

Full Name : {{ submitted_data['user_full_name'] }}

Email : {{ submitted_data['user_email'] }}

Phone : {{ submitted_data['user_number'] }}

State : {{ submitted_data['user_state'] }}

Product SKU : {{ submitted_data['product_sku'] }}

Product URL : {{ submitted_data['product_url'] }}

Message : {{ submitted_data['user_message'] }`


Services Module Authentication with Username and Password in URL

By adding the following argument entries to my retrieve operation for my custom service I was able to achieve the desired effect.

                'args' => array(
                    array(
                        'name' => 'none',
                        'type' => 'string',
                        'description' => 'Function to perform',
                        'source' => array(
                            'path' => '0'
                        ),
                        'optional' => TRUE,
                        'default' => '0',
                    ),
                    array(
                        'name' => 'version',
                        'type' => 'int',
                        'description' => 'Function to perform',
                        'source' => array(
                            'param' => 'version'
                        ),
                        'optional' => TRUE,
                        'default' => '0',
                    ),
                    array(
                        'name' => 'username',
                        'type' => 'string',
                        'description' => 'Function to perform',
                        'source' => array(
                            'param' => 'username'
                        ),
                        'optional' => FALSE,
                        'default' => '0',
                    ),
                    array(
                        'name' => 'password',
                        'type' => 'string',
                        'description' => 'Function to perform',
                        'source' => array(
                            'param' => 'password'
                        ),
                        'optional' => FALSE,
                        'default' => '0',
                    ),
                    array(
                        'name' => 'id',
                        'type' => 'string',
                        'description' => 'Function to perform',
                        'source' => array(
                            'param' => 'id'
                        ),
                        'optional' => TRUE,
                        'default' => '0',
                    ),


You have created a Custom block and the custom block was placed in a region, then you lost the custom block maybe was deleted or you made a Config Export from one environment and a Config Import in other. So the custom block is no longer exists but in the Block layout page (admin/structure/block), the references exist.

So, remove the missing Block from the Block layout page (admin/structure/block) and create again the Custom block and place it again in the region.

There is a core issue open discussing this problem: https://drupal.org/project/drupal/issues/2756331

This can also be overcome by using this module: https://www.drupal.org/project/recreate_block_content


Drupal 7 - Anyway to make Facebook Picture take place of User Picture if not available

You can use the Views PHP module and use PHP to create whatever logic you want for this image output.

  This module allows the admin account (user 1) to add fields, filters
  and sorts to views which use PHP code. It also supports additional
  accounts when the core PHP Filter module is enabled.

  This is the successor of Views Custom Field for both D6 and D7. The D6
  version supports both Views 2 and Views 3.

  Note

  While this module allows you to directly use PHP inside views
  which may be useful for quick and easy solutions, it is highly
  advisable to use regular handlers and plugins when available (or even
  to create one yourself). Take note that filtering and sorting a view
  using PHP always has a considerable perfomance impact.

So in your view you can have:

3 fields, user profile picture, facebook picture and the php field used to display a picture.
for the user profile picture, make it a default image display and exclude it from the output.
for the facebook picture make it a default image display and exclude it from render output.
in the php field you simply want to check if a file exists for user profile picture and then drupal_render() or return the profile or facebook picture Views will have already formatted for you using the other 2 fields.
be sure the 2 image fields are higher up in the field list of the View than the PHP field, so the PHP field can make use of those values in code.

EDIT

An alternative that is slightly less magical and tied to Views is to use Display Suite and add a Custom Field in display suite for a User. This custom field does basically all the logic between the 2 fields and it's literally a pseudo-field for Users. Views can then use the view_mode for Users that you've provided by DS.


show results for a view with certain node reference

This is what views is particularly good at, in my opinion. You should be able to get started by creating a subdivision page view. Then you should be able to create a relationship based on the reference field. This would give you access to sort based upon whether the home appeared in that subdivision.


Sorting rows and return the value as a simple array using EntityFieldQuery

fieldOrderBy is for ordering by a Field API field.
You want propertyOrderBy('updated' 'ASC').

And the return structure can't be changed, it's always the same (a stub entity in technical terms). You use the id from that return structure to load your entity and get the data you want. I see you've already figured that one out, judging by your code.


You can add placeholders in hook_form_alter().

/**
 * Implements hook_form_alter().
 * @param $form
 * @param \Drupal\Core\Form\FormStateInterface $form_state
 * @param $form_id
 */
function ThemeName_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  if ($form_id == 'user_login_form' ) {
    // Add placeholders.
    $form['name']['#attributes']['placeholder'] = t('User name');
    $form['pass']['#attributes']['placeholder'] = t('Password');
  }
}

Use the Devel module functions to print out the form using kint, this way you can visibly see the entire structure of the $form array.


Does Drupal distinguish types of error messages?

This setting is for server errors, the drupal form errors will still be shown.

Here is some more information on this topic:
https://www.drupal.org/node/1036982


Some templates are not properly compiled to Twig

OK!
So I have figured it out. I think this is a Windows-specific bug because, on another project where I have experienced this as well, people with macs do not have this issue.

Anyway, what is causing it is \Drupal\Component\PhpStorage\MTimeProtectedFastFileStorage::getFullPath, specifically return $directory . '/' . hash_hmac('sha256', $name, $this->secret . $directory_mtime) . '.php';

If the template name is too long, which can easily happen with theme suggestions, it will cause PHP to fail to perform the rename() operation successfully. I don't know why it stores the code in a temporary file and then it copies it into target directory instead of creating it directly in the target directory and/or file but that's how it is.

I have no idea why we need so freaking long directory and file names when they only hold a single file but beside this, Drupal 8 is great.


Page Navigation issue after executing a jQuery

Disable the click function for the more links div.

$('.div-classname a').on('click',function(){.....});

$('.more-link a').off('click');

This is the perfect solution.


What you're looking for is Contextual Filters. Rather than creating many views, you create one view that accepts an argument to change the value of one or more filters. In your case, the filter is the card number.

There are many ways to do this. One way is to pass the value of the card to the view by URL argument. This can be done with query string parameters at the end of the URL (which you can set as hard links in HTML that the user clicks on. Another option is using a very specialized configuration of Panels module, where it will pass a URL argument to a view which is contained in one of its panel panes. See https://drupal.org/node/1584046

Those options are only necessary if you need the value to be pre-populated when the user visits the page. They are a bit tricky to implement, but something that Drupal does very well once you know how to configure it.

The other option is to set an exposed filter on your view. On the view configuration page, click on your filter and check the box to expose the filter. Then, there will be an input area when you load the view on your page, which will accept any valid values for your filter.


How to eliminate access to page based on the user ID?

You will probably need to add a custom hook_node_access code.  In this you can use the view operation to check:

Is the current user the owner (yes - done - allow access)
Is the user an admin (yes - done - allow access)
Does the node have your user access list field (No -done - allow access)
Is the current user's uid in the field values? (Yes - allow access / No -deny access)

This should handle the basic access issues.  You may need to look at how to hide / show links based on access as well.


Module that will display certain facebook content?

I think that you can use this jquery plugin http://www.neosmart.de/social-media/facebook-wall to put an specific wall inside a block or node, and then you can improve the javascript code (I guess in Parse feed data / wall section of jquery.neosmart.fb.wall.js file) to show only items with specific content, in this case, for example, a content using uiVideoThumb class (according my review uiVideoThumb is one class used to thumbns that link to videos).

specifically, in the js, in the section Parse feed data / wall line 81:

for(var k=0;k<max;k++){

you can add some lines to detect the specific content, for example:

var pattern=/uiVideoThumb/g;
var stringContent = JSON.stringify(data[k]);
if(stringContent.match(pattern)){

do not forget close this new IF declaration (near line 162).

Acording my test, only content with these condition is displayed.

one note: seems that the code has a Drupal´s module version http://drupal.org/project/fb_walls but not was clear to me how this module works over Drupal.


D7 - Print node taxonomy terms including custom term field as CSS Class

Are you cool with using views?   I do this type of thing all the time on my site.  If you are then reply back and I'll post an example.


UPDATE: install Commerce Multistore module and have store/ID/edit, store/ID/products, user/ID/stores views tabs created by default for you

UPDATE: Add store/ID/edit, store/ID/products, user/ID/stores views tabs

Tabs can be automatically created for you by Views.

WDTutorials video: Tabs With Views in Drupal 8

You have to create a views' page having /some-path  which lists some entities (nodes, fields or products as in your question). Then you need to make it a Default menu tab (parent menu tab). So, if no any child tabs are present then the content for this tab will be displayed. It might be seen a bit confusing but you should choose Already exists option while creating this (newly created) menu tab. After that just create as many duplications of this page as you need and choose for each duplication a Menu tab option (child menu tab). Again, you might be confused which menu or menu entry to choose for children menu tabs. Actually, it does not matter a lot. For your view you may choose Products entry though <Main navigation> menu might be also a good choice. Do not ignore weight option assigning a proper value for each child tab. It helps to place tabs in the exact order you want. Leave 0 weight for the parent tab increasing it by 1 for each next tab.

Then, edit the path so it looks like /some-path/child-1 and add a filter criteria for a child tab (page). In the video the filter criteria is a node's published/unpublished status and in your case it should be a store ID. The ID of a particular store might be found on the /admin/commerce/stores by hovering over a store's Edit tab.

See more on the relative drupal.org issue:
https://www.drupal.org/node/2880510#comment-12185171


Mouseover overlay for images using Views Photo Grid

As the arrays line up, added an index and combined the arrays

$index = 0; foreach ($items as $key => $item):
print $raw_result[$index]['title']; $index++
print $item;

Works


How to choose multisite instance inside script running from main Drupal directory?

Since you know the database name, you can dynamically set a database name which you will call with db_set_active().

This is copy/pasted from the link below.

  $other_database = array(
      'database' => 'databasename',
      'username' => 'username', // assuming this is necessary
      'password' => 'password', // assuming this is necessary
      'host' => 'localhost', // assumes localhost
      'driver' => 'mysql', // replace with your database driver
  );
  // replace 'YourDatabaseKey' with something that's unique to your module
  Database::addConnectionInfo('YourDatabaseKey', 'default', $other_database);
  db_set_active('YourDatabaseKey');

  // execute queries here

  db_set_active(); // without the paramater means set back to the default for the site
  drupal_set_message(t('The queries have been made.'));

More about this can be found here.


Why can't i get simple form theming to work?

I think it's the simplest of things...

$form['#theme'] needs to be a string, not an array, so change

$form['#theme'] = array('uncoated_user_register_form');

to

$form['#theme'] = 'uncoated_user_register_form';


Is there a drupal 7 module for webform password and password confirmation fields?

Well, actually there's an issue posted for Drupal 7 webform_password module.

Checkout the issue here

You can download webform_password module for Drupal 7 from here


Is it possible to create a template (tpl) file for comment view mode?

With take look at  Template Comment Preprocess You find out that you just need use  $vars['elements']['#view_mode'] instead of $vars['view_mode'].


Filter input, escape output. You can't be sure that everything in your database is safe.


Create Drupal 7 Multi Site on Mac OSX 10.10

It sounds like you don't have your directories configured properly.

Assuming that you have this file structure:

/users/
    /drupal/
        /sites/
            /drupal1.localhost/
                /settings.php
            /drupal2.localhost/
                /settings.php

Note that the folders under /sites must match the http.conf server name.  (unless alias's are set up).

With the above structure, your http.conf would look like this:

DocumentRoot "/users/drupal"

<Directory "/users/drupal">
    AllowOverride All
</directory>

NameVirtualHost 127.0.0.1:80

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/users/drupal"
    ServerName drupal1.localhost
    <Directory "/users/drupal">
        Require all granted
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

<VirtualHost 127.0.0.1:80>
    DocumentRoot "/users/drupal"
    ServerName drupal2.localhost
    <Directory "/users/drupal">
        Require all granted
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

Note that the document root points to the base Drupal folder, not /sites.  Drupal will handle this part automatically.

Your hosts file would remain the same:

127.0.0.1     drupal1.localhost
127.0.0.1     drupal2.localhost


Module installation in D8.3.6 was possible, using D8.3.7 the same module couldn't be installed

is this requirement raised in D8.3.7 first and in D8.3.6 still was possible w/o ..yml?

No, YAML has been the format for Drupal 8 info files right from early dev versions, way before even the 8.0 release.

  I have installed the "Serial field" module with the file serial-7.x-1.8.zip in D8.3.6

Unless the naming of the archive is an error, and despite being labelled as containing 7.x code, it actually contained 8.x code, I’m afraid you’re mistaken.


How to put a view generated slideshow as a page background?

I'd recommend the Backgroundfield module with Views Slideshow. Create a View with display option Slideshow and the only field to display as your background field. Violá, no coding required.


Well if you want a Drupaly solution you could try installing the CiviCRM Entity module along with the Views in Contact Pages module

With CiviCRM Entity you can add Drupal fields to CiviCRM entities, so you could add you a normal Drupal image field and get all the wonderful goodies Drupal provides such as image styles.

Now this field data would live in Drupal field table not in CiviCRM custom field tables.

You add your field on the CiviCRM Entity Contact entity Manage Fields page at admin/structure/civicrm-entity/civicrm_contact

If you can live with the data being in the Drupal DB, not the CiviCRM db, then this can work for you.

Then if you want to display the image on the CiviCRM backend admin contact summary page, you use the Views in Contact Pages module to create a view that displays the image, along with any other data you want, and put that view either as a tab on the contact page, or a pane on the Summary tab.


How to hide Fivestar field when editing a comment from another user?

The code in the edit doesn't work, because $form_state['values'] isn't present before the submit. This is the correct code:

function hiderating_form_alter(&$form, &$form_state, $form_id) {
  global $user;
  if ($form_id == "comment_node_article_form") {
   if ($form['uid']['#value'] != $user->uid AND $form['uid']['#value'] != 0) {
    unset($form['field_stars']);
   }
  }
}

Using dpm($form), I discovered that $form['uid']['#value'] returns the uid from the user who wrote the comment. The value is only different from 0 if a comment is edited. When a user writes a new comment, the uid from the form is 0. That's why the AND in the second if is necessary.


How do I remove all references to the Sample DB when using the Forena reports module on a server without PDO Sqllite?

Quote from Dave's (Forena maintainer) comment in a related Support Issue:

  ... You might uncheck permissions associated with accessing sample reports to make sure other users don't see this error.

Using this approach you should be OK when upgrading to future versions.

Disclosure: I'm a co-maintainer of Forena (and contributed quite a bit of the content of that forena_help repo you seem to be strugling with).


How to show a field value instead of the node title for nodes displayed through an entity reference field?

No code necessary, Drupal has built-in features for this:

Create a new view mode singlefield for the referenced content type foo, showing only the field value
Optionally, create a very minimalistic template for this node--foo--singlefield.html.twig
In /admin/structure/types/manage/foo/display change the view mode of the host entity reference field to Rendered entity, using view mode singlefield


The solution for this will be to do the same thing with the code below.

$region = _block_get_renderable_array(_block_render_blocks(array($block)));
print render($region);

After changing your code make sure that you clear your cache. And try refreshing. Also make sure you have made this changes every where.

So you know what the problem is:
The render() function takes a parameter by reference. In that case you must pass in a variable, not a function call, because the function call is not something that can be passed as a reference.


Rearranging subfields with the Address Field module

I have two solutions for it:

hook_field_widget_form_alter()
Ctools plugin

Solution 1. hook_field_widget_form_alter().

/**
 * Implements hook_field_widget_form_alter().
 */
function MYMODULE_field_widget_form_alter(&$element, $form_state, $context) {
  if(!empty($element['#addressfield'])) {
    $element['country']['#weight'] = 100;
  }
}

Use $element and $context arrays and implement own IF statement. You can find all the information about the field and user here.

Solution 2. Ctools plugin

It's possible with ctools plugins. Review addressfield/plugins/format/ or https://drupal.org/project/addressfield_vn as an example.

Just add your custom plugin with addressfield alter in 5 steps:

Step 1: Create MYMODULE/plugins/format/ folders structure.

Step 2: Add next code to your MYMODULE.module file:

/**
 * Implements hook_ctools_plugin_directory().
 */
function MYMODULE_ctools_plugin_directory($module, $plugin) {
  if ($module == 'addressfield') {
    return 'plugins/' . $plugin;
  }
}

/**
 * Implements hook_ctools_plugin_type().
 */
function MYMODULE_ctools_plugin_type() {
  $plugins['format'] = array(
    'load themes' => TRUE,
  );
  return $plugins;
}

Step 3: Add file with alter code. E.g.: MYMODULE/plugins/format/address-alter.inc:

/**
 * @file
 * Move country field to the very end.
 */

$plugin = array(
  'title' => t('Alter addressfield'),
  'format callback' => 'MYMODULE_format_address_alter_country',
  'type' => 'address',
  'weight' => -80,
);

/**
 * Format callback.
 *
 * @see CALLBACK_addressfield_format_callback()
 */
function MYMODULE_format_address_alter_country(&$format, $address, $context = array()) {
  // Move country field to the very end.
  $format['country']['#weight'] = 100;
}

Step 4: drush cc all

Step 5: Enable your plugin for addressfield in customer profile fields settings. E.g. at /admin/commerce/customer-profiles/types/billing/fields/commerce_customer_address

In the current example all the alter code will be inside the MYMODULE_format_address_alter_country() function. Just play with weights of your fields and you'll get the form rearranged.


How do I query for content that has not been updated (no revisions)?

Content that has not been updated would only have one revision, so you could count the number of revisions and use a having condition.

First you'll have to join the node_revision table to the node table

$query->leftJoin('node_revision', 'r', 'n.nid = r.nid');

Count the number of revisions

$query->addExpression('COUNT(n.nid)', 'revision_count');

Filter rows with a revision_count higher than 1

$query->havingCondition('revision_count', 1, '<=');


How to redirect to a different URL based on node content while loading a node

Ah ha... and I just learnt about row and field level templating in Views... isn't views incredible?!

I followed the instructions here http://drupal.org/node/352970 and can alter the link and it's text based on the context of each row.

Super!


You could do this with Context. Set the Context condition to be either path or view based (depending on what suits your site structure) and then have the Context reaction take care of block placement (presuming your sidebar will collapse if empty).


Is it possible to divide a field into fields?

It's definitely possible, but will require some coding. I can't work out the whole thing for you but I can point you in a direction.

You would have to create three new fields for 'first name', 'last name' and 'title' in the content type.

Then create a script that loads all of the nodes of that type with node_load_multiple then iterates through them, taking the old value of 'title' and splitting it using regex or the php 'explode' string function. Then using entity_metadata_wrapper, stick the individual values into the new fields and save the node.

Using drush, you can run the script like this: drush php-script scriptname.php


Some general advice:

I had a similar situation on a project. I first tried various options for importing orders from the separate sites into a central site using modules like:

commerce_order_ftp_export
commerce_export
commerce_export_csv
commerce_feeds with patch for orders

But you will need custom code to resolve order IDs etc. Depending on the number of sites, this may be workable.

However, I eventually opted for a solution as follows:

Using a mobile POS app for sales
Sending sales from each instance of the app into a central drupal installation running maceij’s version of commerce_marketplace
This way,sales can be separated and/or aggregated by location, POS, etc.


Are there any Drupal 7 modules for creating organizational charts?

The Google Charts module for Drupal 7 now has support for organizational charts.


Create a menu block with images in Drupal 8 & keep menu order

I finally had time to come back to this, so I'll answer my own question as I believe the following solves it. This code could for sure use some refactoring & cleaning up. I'm very new to Drupal 8 & I'm fairly new to Drupal in general. Feel free to suggest improvements.

<?php
/**
 * @file
 * Displays children pages as a block
 */

namespace Drupal\child_pages_display\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Url;
use Drupal\Core\Path;
use Drupal\Core\Menu;
/**
 * Provides a 'Next Previous' block.
 *
 * @Block(
 *   id = "child_page_block",
 *   admin_label = @Translation("Child Page Block"),
 *   category = @Translation("Blocks")
 * )
 */
class ChildPageBlock extends BlockBase {
  public function build(){
    $menu_tree = \Drupal::menuTree();
    $menu_name = 'main';

    // Build the typical default set of menu tree parameters.
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
    $expandedParents = $parameters->expandedParents;
    reset($expandedParents);
    $root = current($expandedParents);
    $parameters = new \Drupal\Core\Menu\MenuTreeParameters();
    $parameters->setRoot($root);
    $parameters->setMaxDepth(3);
    $parameters->setMinDepth(1);

    // Load the tree based on this set of parameters.
    $tree = $menu_tree->load($menu_name, $parameters);

    //Set Cache for block
    $cache['max-age'] = 3600;
    $cache['contexts'][] = 'url.path';
    $cache['tags'][] = $root;

    //Get node IDs from menu
    $nids = array();
    foreach($tree as $item){
      $nids[] = $item->link->getUrlObject()->getRouteParameters()['node'];
    }

    //Load nodes & generate content from nodes
    $nodes = (!empty($nids)) ? entity_load_multiple('node', $nids) : array();
    if (!empty($nodes) && is_array($nodes)){
      foreach($nodes as $key=>$val) {
        $nodeContent = array(
          '#prefix' => '
',
          '#suffix' => '
'
        );
        $url = \Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$key);

        //Get image thumbnail from content & use specified image style
        if(null !== $val->get('field_thumbnail')->entity){
          $imgPath = ($val->get('field_thumbnail')->entity->uri->value);
          $imgCroppedPath = \Drupal\image\Entity\ImageStyle::load('basic_page_thumbnail')->buildUrl($imgPath);
          $img = ($imgPath != '') ? '' : '';
        }else{
          $img = "";
        }
        $nodeContent['#markup'] = '' .
            '
' . $val->getTitle() . '
' .
            $img .
          '';
        $content[] = $nodeContent;
      }
    }else{
      //Menu has no nodes
      $content['#markup'] = '';
    }
    //Add cache & css library to block
    $content['#cache'] = $cache;
    $content["#attached"] = array('library' => array('child_pages_display/child_pages_display_css'));
    return $content;
  }
}


add name field with email to invite block

I'm not exactly positive if this is what you're asking, so if I misunderstood the question, just let me know.

You can add any field you want to the user registration forms if you go right here on your site: /admin/config/people/accounts/fields

So even though there are not any 'First name' or 'Last name' fields by default, you can add anything you want and then get to those fields through views...

Does that help?


Can I use --remote-host without a site-alias?

Drush internally converts site aliases into command line options before doing a remote dispatch, so I would expect that you should be able to make --remote-host work without creating an alias.

Here is something that I tried.

$ drush @live sql-conf -v
Calling proc_open(ssh -o PasswordAuthentication=no user@server.org 'drush  --verbose --root=/srv/www/drupal/htdocs --uri=http://site.org  sql-conf 2>&1' 2>&1);

$ drush --remote-host=server.org --remote-user=user --root=/srv/www/drupal/htdocs --uri=http://site.org sql-conf

The first version, with an alias, worked, but the second invocation with cli options got confused, and tried to execute the command locally.  I got the same result in 6.x and 5.x, so I guess this has been broken for a long time.  I created a bug report on GitHub for this:

https://github.com/drush-ops/drush/issues/369

Fortunately, there is one more option.  Drush will let you craft an alias on the command line, by combining the different elements of the alias record in a special form, "user@server/path#site".  So, I did this:

$ drush user@server.org/srv/www/drupal/htdocs#site.org sql-conf -v

That worked.


How do you include a Dev module in a make file?

You're almost there - what you need to add to your make file looks like this and you have to specify the git url and commit identifier.

projects[path_breadcrumbs][version] = "3.x-dev"
projects[path_breadcrumbs][download][type] = "git"
projects[path_breadcrumbs][download][url] = "http://git.drupal.org/project/path_breadcrumbs.git"
projects[path_breadcrumbs][download][revision] = "c9c570b0b4bde1df0e5a322ab90197d7fc1cf9c6"

To find this, go to the project page on drupal.org and select 'view commits', ex

On the next page, select the one you are interested in that reflects the state of the module you want to add to your make file. For this example, I'm going to grab the last commit:

and I'm clicking the 'commit bdcf88a' link which takes me to:

http://drupalcode.org/project/path_breadcrumbs.git/commit/bdccf8a

Now I know that the the [download][url] is:

http://drupalcode.org/project/path_breadcrumbs.git

and the full hash for the commit I am looking for is:

bdccf8a901b6d2359b6da195d23cadf7dd90c4ec

--

Further updates as requested -- if you're looking for a specific dev branch you may want to switch to the command line to do a --recursive clone to make sure you're getting all the branches. Following this question:

How do I git pull a dev branch?

I'm going to do a recursive pull of the git 7.x-1.x branch

git clone --recursive --branch 7.x-1.x http://git.drupal.org/project/fences.git

Now I can see what branches are available:

git branch -r
  origin/1343724-region
  origin/7.x-1.x
  origin/HEAD -> origin/master
  origin/master

Now I can checkout this branch for 7.x-1.x and check the log, which will give me the last commit and the one that was used to generate the development snapshot.

git checkout 7.x-1.x
git log

  commit 67206b5220cbebf52e8e6a290ccb977b2420b2ad
  Author: JohnAlbin <virtually.johnalbin@gmail.com>
  Date:   Tue Sep 4 13:44:40 2012 +0800

      Fix code comments on figcaption.

The date is different from what you may see on the project home page only because this is an automatic development snapshot created by the Drupal.org git bots but the development snapshot is always created from the branch with the same version number and the '-dev' part is never used in the branch name.


Is it safe to protect the images only with a watermark image style?

This is probably not as secure as you would like it to be.
Basically if a user has access to view the image they can view any derivative image (image style), so long as they can work out the url to that derivative.

There is a module image style access that allows you to set up access rules per image style.

That should give you the extra protection you need.


Remove menu item in template.php drupal 7

I think you're looking for:

$element['hidden'] = 1;

Using:
http://api.drupal.org/api/drupal/includes%21menu.inc/function/theme_menu_link/7

check that it's the element you want, and set the "hidden" value to 1.   I have not tested this.


Panels everywhere is like it says, a way to use Panels all over your site. This means that whats normally outputted by page.tpl.php will now be run through a Panel.

Enable the site template (if not already done) here: /admin/structure/pages
Edit the site template and add the page elements as you want your site to be built. Eg. add the site header, then the page title, page content etc.

There is also a setting to create a sample site template variant for you here /admin/structure/panels/settings/everywhere.


How to set the value of a Fixed amount Commerce Coupon using Rules?

After much digging, i was able to resolve this using a rules component. The trick is, after generating your coupon code using rules, that is,

  event: completing the checkout process

  condition: your condition (e.g order contains a particular product
  etc)

  action: create new entity => commerce coupon action: set data value
  (do this for the coupon code, max number of uses, coupon type (human
  readable name), etc) action: save entity => (your created entity)

  action: create new entity => commerce line item => commerce coupon
  (set your values) action: save entity => (your newly created coupon
  line item)

  create component:

  component plugin: rule name: name your component here (e.g "set gift
  coupon value") data type: commerce coupon label: (give a label that
  you can identify it easily with) machine name: (give a machine name
  that you can identify easily) save component.

  Under conditions: entity has field: (identify your coupon fixed amount
  field here e.g "coupon-fixed-value-component") action: set a data
  value => (here you identify the fixed amount coupon field and then set
  the value you want)   save component

  Come back to your earlier created rule,

  add loop: (it should automatically capture that you want to loop into
  the commerce line items e.g "commerce-order:commerce-list-item"  save
  loop inside the loop, add action = > (here you'll select the component
  you created, it should automatically detect that you want to fire this
  component on your created coupon entity initially created within this
  rule e.g "entity-created" save the action.

  perform any other action if you want, like send email to referenced
  user in the gift card.

  That would do. each time you complete the checkout for the product
  referenced in the rules condition, a gift coupon will be created and
  the amount would be set based on your rules component action value.

  Limitation: You have to do this whole process for every different
  amount of gift coupon you create.

  Possible improvement: Allow a user to specify the amount at product
  creation time, then use rules to capture this amount and then set the
  coupon value based on the set amount of the product

  More improvements welcome..


How do I use arguments with the Path Breadcrumb module?

As an last option you can implement theme_breadcrumb() in your theme template.php

Something like below sample code.

function themename_breadcrumb($variables) {
  if (arg(0) == "galery" && is_numeric(arg(1))) {

    // Get event title of the  event
    $event_nids = mymodulename_get_back_refernce_value(arg(1));

    // Note since a gallery can be referred by multiple event nodes so you have add logic which one you need to pick here, for now I am picking with array index as 0
    $event_node = node_load($events_nids[0]);

    $links[0] = l(t('Home'), '<front>');

   // inplace of 'events' add internal link path to events page.
    $links[1] = l(t('Events'),'events');
    $links[2] = l(t($event_node->title),'node/'.$event_node->nid);
    $links[3] = t('schedule');
    drupal_set_breadcrumb($links);
  }
}


When to use a module vs. writing own code?

The way I go about deciding whether to use a module or write my own code is roughly the following:

If the functionality I need can be written with a couple of lines of code I don't even start looking for a module to do it. Using a module for every little thing often gets you a good portion of extra code and other data that you don't need. All the unnecessary extras could:

negatively affect performance
make the site more complex and harder to maintain
result in more bugs

If there would be a considerable amount of code to write I'll look for possibly existing modules to make the task easier. Good reasons to use a existing module in my book:

it fits the requirements fairly well: using the module (and altering it with hooks, adding extra functionality via a custom module where needed) to get exactly what's needed is easier/faster than writing everything from scratch.
the site administrator needs to be able to change specific settings via the GUI and the module already offers that.


How to export format settings (label, weight, etc) for body field, image field, and tags field

I figured what I was doing wrong. Since I was working with Features for some reason the Article Content Type originally got exported out into another module and was clashing with mine.


copy content-profile elements to another page

In the end I used the content-profile edit page, with the following modifications:

It did copy the event handlers but the ajax call was calling the
wrong url becasue of relative path problems. Using an absolute path
instead fixed this issue and the event handlers worked perfectly.
Used JavaScript to add a css class to the elements I wanted hidden, and styled in css that this class should have display:none.
I needed to install a patch on the CCK module to solve an issue with a hidden on/off checkbox.

Thanks!


Include multiple blocks in one responsive menu?

You may want to investigate Mega menu options.

http://megadrupal.com/blog/7-mega-menu-modules-for-drupal

I've used OM Maximenu before when I wanted a ton of content on the dropdown:

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


How can I programmatically delete a custom menu?

Since menus are configuration items, my poking into \Drupal\Core\Menu\MenuTreeStorage::delete() was wrong. You delete a custom menu thusly:

\Drupal::configFactory()->getEditable('system.menu.name-of-custom-menu')->delete();

Note that I'm assuming the menu is empty. I don't know what would happen if you deleted a menu that had menu items in it, whether they'd be orphaned or deleted.


field_image_cache missing from all content types

Just thought I would update this one, just in case anyone else has a similar problem.

Turns out that the database was erroring and running out of disk space. Which meant the queries couldn't be completed. This ended up corrupting the database and I had to restore from a backup.

Once the restore completed all images and ability to Edit them returned to the site.

Hope that helps.


make sure hook cron is only run once a day setting

I would check the implementation of hook_cron() in the Examples module.

The exact implementation is here, it's pretty straightforward!

Basically, you're setting the next execution time (in the example code as cron_example_next_execution) of your cron run as the very last step in your hook_cron() implementation, and then checking it as the very first thing.

If the variable doesn't exist, then cron will fire off your task, and then set it!


The Global Redirect module doesn't store paths on a per-node basis. That's the role of the core path module which stores aliases that map to system paths in the url_alias table (in both D7/D8).

The Global Redirect module could broadly described as settings (set on its administration page) that drive logic for 301 redirecting (in a hook_init() invocation) while setting the rel="canonical" metatag (a signal that tells the search engine to index that path). Thus, there really isn't anything to migrate from the module besides various globalredirect_settings variables that store redirect settings.

That said, you can run the Migration module which will import your node path aliases (and thus the paths you're concerned with 301 redirecting to) and adjusting the settings for Global Redirect module so that it matches the settings in your D7 installation.


Custom field values are not importing with Features

To clarify, the custom fields of nodes that reference to Taxonomy elements did not export/import via features. The reason is that Taxonomy term references(tid) are stored by ID instead of UUID with stable version of uuid_features and uuid as of Feb, 2014

The solution was to use dev version 7.x-1.x-dev for uuid as well as uuid_feature module. This will export/import custom fields (term reference) into UUID instead ID that solved the problem


Allowed range for date input - down to the day level rather than the year level?

Ok, so this is our "solution". Not tidy, but we didn't want to edit the date module directly.

My module:

<?php
function modulename_form_alter(&$form, &$form_state, $form_id){
  if(substr($form_id,-9) !== "node_form" ){
    return;
  }
$jsPath = drupal_get_path('module', 'modulename');
  $jsOptions = array(
    'group' => JS_THEME,
    'weight' => 20
  );
  // Load this JS late, so that it happens after the main date module
  drupal_add_js("$jsPath/js/modulename_datepicker.js", $jsOptions);
}

My colleagues code for the modulename_datepicker.js file:

jQuery(document).ready(function(){
    for (var id in Drupal.settings.datePopup) {
        if (Drupal.settings.datePopup[id].func == "datepicker") {
            var defVal = jQuery('#'+id).val();

            jQuery('#'+id).datepicker();
            jQuery('#'+id).datepicker( "option" , {
                changeMonth: Drupal.settings.datePopup[id].settings.changeMonth,
                changeYear: Drupal.settings.datePopup[id].settings.changeYear,
                firstDay: Drupal.settings.datePopup[id].settings.firstDay,
                defaultDate: Drupal.settings.datePopup[id].settings.defaultDate,
                dateFormat: Drupal.settings.datePopup[id].settings.dateFormat,
                minDate: 0,
                maxDate: "+1Y"
            });

            if (defVal == '') {
                jQuery('#'+id).datepicker( "setDate" , "+1Y");
            } else {
                jQuery('#'+id).datepicker( "setDate" , defVal);
            }
        }
    }

});

Better solutions welcomed :)


How to alter/hide the label of the input element in form (create/edit)?

You can do this with hook_form_alter() or hook_form_FORM_ID_alter() in your custom module or also in your theme's template.php file.

function YOURMODULE_form_alter(&$form, &$form_state, $form_id) {
  // Check the form_id
  if ($form_id == 'YOUR_FORM_ID') {
    // To hide the label
    $form['your_form_element']['#title_display'] = 'invisible';
    // To alter the label
    $form['your_form_element']['#title'] = t('Your new title');
  }
}

If you use hook_form_FORM_ID_alter() instead, you don't need to check the form_id.

You can find more information on the Form API Reference for the #title and #title_display attributes, and also all the other form elements and their attributes.

In case of Field Collection, it can be a bit complicated. Below is an example code:

function YOURMODULE_form_YOUR_FORM_ID_alter(&$form, &$form_state, $form_id) {
  $your_field_collection = element_children($form['your_field_collection'][LANGUAGE_NONE];
  foreach ($your_field_collection as $key => $value) {
    if (is_numeric($value)) {
      $form['your_field_collection'][LANGUAGE_NONE][$val]['your_field_collection_field']['#title'] = t('Your new title');
      $form['your_field_collection'][LANGUAGE_NONE][$val]['your_field_collection_field']['#title_display'] = 'invisible';
    }
  }
}

Explanation of the above code:

First I assigned the field collection itself to a variable, to make it a bit readable. I used LANGUAGE_NONE for simplicity but a better practice would be to use $form['your_field_collection']['#language'], admittedly it makes the whole code more complicated to read.

Second, I used a foreach, since most of the time we use a field collection if we want to have multiple values of some collection of fields. So the foreach loop would take care of all instances of the field collection.

Third hack, is a dirty trick I learned from someone on Drupal.org, maybe there would be a better approach, but it just works so I didn't dig into. I check if the $value is numeric, to exclude all other meta attributes and loop only through the elements.

Then, finally, in each element I alter the field in the field collection.


You can use similar code as below to hide pass and mail field with optional value.

//drupal_set_message('not admin!');
$form['account']['current_pass']['#required'] = FALSE;
$form['account']['current_pass']['#access'] = FALSE;
$form['account']['mail']['#required'] = FALSE;
$form['account']['mail']['#access'] = FALSE;

$form['#validate'] = array_diff($form['#validate'], array('user_validate_current_pass'));
$form['#validate'] = array_diff($form['#validate'], array('user_validate_mail'));


MSAccess to SQLite install and setup custom content types?

** Full Disclosure I've Not Tried This Using the Requested Setup!! **

I've migrated Joomla -> Drupal and CSV to drupal ... so I have some experience with this. But having not tested your exact request I'm not 100% this will work.

You can install PDO and PDO support for ODBC drivers. I assume your PHP environment is Windows so you can also install MSAccess, which supports an ODBC driver connection. Here is a blog example of how to install/use MsAccess ODBC for a plain PHP webapplication.

You can then configure your settings.php file to include a custom database connection using PDO to use an ODBC driver to talk to your MSAccess database. This could look something like:

   $databases['remote_msaccess_db']['default'] = array(
     'driver' => 'odbc:DRIVER={Microsoft Access Driver (*.mdb)}',
     'DbQ' => 'C:\some\path\to\your\db.mdb',
     'uid' => '',
     'pwd' => '',
     'host' => 'localhost',
     'prefix' => '',
   );

That's actually the hard part :). Which may not work. Assure you have the same 32bit or 64bit ODBC drivers for PHP as whatever version OS MSAccess is running.

After that you can use a tool like Migrate to move the data from MSAccess into Drupal content types, Entities or even a plain old table based migration which Migrate supports (and I've used).