User relationships. Override mysite.com/relationships page with views Is there any chance to override mysite.com/relationships page with views? I guess the answer would be yes. But how? Can somebody explain to me in details. :)

P.S. I've tried to create my own page view, with path /relationships, but there's so much settings... messed up me :(

I'm not sure if it's the best solution or the best practice. There is a low overhead, small module called Empty Page that strips the content from a page. Use that and then put blocks in regions. It's great for creating elaborate front pages too.


Link To Already Defined Path In Menu Using hook_menu() I'm sure this is an obvious answer but I seem to be missing something important.

How can I add a link to a menu using hook_menu() to an already defined path?

I'm trying to add a direct link to a node/add page that already exists.

I need to use hook_menu() instead of the control panel.

You can best use hook_menu_alter(), which should be used when "Additional items may be added, or existing items altered."

In custom_node_add.module :

function custom_node_add_menu_alter(&$items) {
  if (aray_key_exists) { //some sanity checking;
    $items['node/add']['page callback'] = 'custom_node_add_page'
  }
}

function custom_node_add_page() {
  return t("Hello World! This is content on my node/add page");
}


Is it safe and correct to run Drush under the same user account that the webserver runs on? I've found following informaion:

  It's usually considered best practice to run Drush under the same user account that the webserver runs on (such as www-data). Some modules, such as XML Sitemap, Advanced Aggregator and cTools, often try to alter or generate files.

I also have some problem with Ctools cache.
I can use following command to run Drush under the www-data user:
sudo -u www-data drush....

But is it safe and correct to run Drush under the same user account that the webserver runs on?

In general, the answer is "yes", it is safe and correct.  However, the specific answer here depends on (a) your security policy, and (b) what you want to do with Drush.  Some people prefer to make the code files not writable by the web server.  If you had a setup like that, then you would not be able to run drush dl as the webserver user.

The other thing of note here is that any time you run any Drush command, all Drush commandfiles are given the opportunity to alter the command's behavior.  This means that it is generally NOT considered safe to run drush via sudo to root, unless you trust all of the code in your Drupal site to run as the root user.  This is not generally a concern for sudo -u www-data, though, as you are already trusting the code in your Drupal site to run as the web user.


How can I get the URL to the public files directory? I can get the path to the public files directory by using Filesystem::realpath:

$path = $filesystem->realpath('public://');

But how can I get the URL of public://?

$my_path = file_create_url("public://");

Will definately work, however it's not coming from a service. Let me investigate more on this!

Okey I found it! This is how file_create_url works:

And this is the corresponding line specific to "public://" resolving (if you are sure you are trying to resolve a "public://..." uri):

  if ($wrapper = \Drupal::service('stream_wrapper_manager')->getViaUri($uri)) {
  return $wrapper->getExternalUrl();
}

Which means you will have to use StreamWrapperManager service, and after calling the getViaUri, you will able to get the external url. So this is service based solution!


location fields are not appearing on feed mapping while location module is used inside field collection I want to import field collection through feeds but since I’m using location module inside the collection module due to this it’s not appearing on target list as you can see the below screen short.
Field collection

Feeds Mapping

Guy can you please help me and I'm using Drupal 7.

I found the solution, in location_feeds.module under function(location_feeds_feeds_processor_targets_alter) under first 'if statement' there is only mention that when node is selected in feeds on that case show all location fields so for solving this issue we just need to add when node or field_collection_item is selected on that case location fields should be appear...
steps:
Go to

  path= modules/location_feeds/location_feeds.module

add $entity_type == 'field_collection_item' || to first statement of "if condition"
like this:

function location_feeds_feeds_processor_targets_alter(&$targets, $entity_type, $bundle_name) {

if ($entity_type == 'field_collection_item' || $entity_type == 'node') {

// location.module logic

$settings = variable_get('location_settings_node_'. $bundle_name, array());

// Only add fields when collecting locations

if (isset($settings['multiple']['max']) && $settings['multiple']['max'] > 0) {
_location_feeds_location($targets, $settings);
}

Save and clear all caches(admin/config/development/performance) and then check it...


Registering User Programatically with only Email Address My Drupal 7 site utilizes the email_registration and logintobbagan modules. It works fine to register users with just their e-mail address. However, on a separate page I am using a newsletter subscribe form called 'news_subscribe' which is of the following form:

function news_subscribe_form($form, &$form_state) {
    $user = $GLOBALS['user']->mail;
    $email = "";
    if(!empty($user))
    {
        $email = $user;
    }
    $form['email'] = array(
        '#type' => 'textfield',
        '#title' => t('E-mail'),
        '#required' => TRUE,
        '#default_value' => $email,
        '#size' => 20,
        '#maxlength' => 20,
        '#element_validate' => array('news_subscribe_email_element_validate'),
    );
    $form['id'] = $id;
    $form['submit_button'] = array(
        '#type' => 'submit',
        '#value' => t('Subscribe!'),
    );
  return $form;
}

By default this then submits the data to the drupal databases and saves the values for the given user if they are already registered in our system via hook_form_submit().

function news_subscriptions_form_submit($form, &$form_state) {
    //Get the values
    $email = $form_state['values']['email'];
    $id = $form_state['build_info']['args'][0];
    $uid = $GLOBALS['user']->uid;

    //Get the database information
    $collection = variable_get('mongo_user_preferences_collection',DEFAULT_USER_PREFERENCES_COLLECTION);
    $savedarrayname = variable_get('mongo_saved_data_array',DEFAULT_SAVED_DATA_ARRAY);

    //Generate the conditions and queries
    $where = array("uid"=>intval($uid));
    $query = array($savedarrayname=>$id);

    //Insert the data into the datbase
    upsertData($where,$query,$collection,$database=NULL);
}

If the user is not currently registered in the system I need to first automatically register them and then retrieve their user id. I know that normally I can use a function such as

$new_user = array(
  'name' => 'JohnDoe',
  'mail' => 'john.doe@email.com',
  'pass' => 'password123',
  'status' => 1,
  'field_custom_first_name' => array(LANGUAGE_NONE => array(array('value' => 'John'))),
  'access' => REQUEST_TIME,
  'roles' => array(), // No other roles than Authenticated
);
user_save(NULL, $new_user);

However, I want to integrate it with the current setup which requires just an email address, auto generates a password and then sends a mail to the user with a temporary login link where they can change the password. This is the current setup on the user registration form. I have been looking for a hook into the email_registration module but cannot find one. Can anyone provide some insight?

Basically I am trying to register a user from a non-registration form (if they are not already registered). I then need to retrieve their assigned uid which is used in subsequent post-processing.

In your custom submit function you can do the following,

$email_entered = $form_state['values']['email'];

$query = db_select('users', 'u');
$query->fields('u', array('uid'));
$query->condition('u.email', $email_entered);
$row_count = $q->countQuery()->execute()->fetchField();

if ($row_count == 0) {
  // User doesn't exist, Save the user.
  $parts = explode("@", $email_entered);
  $account = new stdClass;
  $account->is_new = TRUE;
  $account->name = $parts[0];
  $account->pass = user_hash_password('bar');
  $account->mail = $email_entered;
  $account->init = $email_entered;
  $account->status = TRUE;
  $account->roles = array(DRUPAL_AUTHENTICATED_RID => TRUE);
  $account->timezone = variable_get('date_default_timezone', '');
  user_save($account);
}
else {
  // User exists.
}

As you can see there is no way that you can get the name of the user so you have to use the email as the username. This will be stored in users.name field.
You also might want to mail the password to the user.


Single value "db_query": How to SELECT value that related to the node From this page, if what we need is SELECT single value, we can use fetchField method like below:

$nbr_records = db_query("SELECT count(nid) FROM {joke}")->fetchField();

I've created single value Integer field type with machine name field_subscription_period attached to node type yearly_rent.

I'm using this in Rules Action.

I've tested many db_query example with no luck.

Below is what I'm using, which it will get value of entity_id 2:

$result = db_query("SELECT field_subscription_period_value FROM {field_data_field_subscription_period} WHERE entity_id = 2")->fetchField();

Above query will get value of entity_id 2... but I want to SELECT field_subscription_period value that related to the node. So, how to get value that related to the node?

-newly added-

I still don't understand how to use $node = node_load($nid);. Lets say I want to use the value as variable to be calculated in date field.

I've tried below with no luck:

$node = node_load($nid);
$values = field_get_items('node', $node, 'field_subscription_period');
$newdate = strtotime("+$values year","$value");
return $newdate;

..and also I got error:

Notice: Undefined variable: nid in eval() (line 1 of /var/www/testd7/sites/all/modules/rules/modules/php.eval.inc(146) : eval()'d code).
EntityMalformedException: Missing bundle property on entity of type node. in entity_extract_ids() (line 7539 of /var/www/testd7/includes/common.inc).

You should not use direct queries to the database tables used for fields, for the simple fact the fields could not use database tables to store their value; this is what happens by default, but if a different storage implementation is exposed by a module, the information will be saved in another place. That is actually what happens with the Mongodb module.

If you know the node ID, and you want to get the value of a field associated to it, you can use the following code.

$node = node_load($nid);
$values = field_get_items('node', $node, 'field_subscription_period');

$values is an array whose structure depends from the field. It contains at least an item, but the exact number depends from how many values the field can have. (It is normally set in the setting page for the field.)
To see the structure of that array, you should install the Devel module, and use test code similar to the following one.

$node = node_load($nid);
$values = field_get_items('node', $node, 'field_subscription_period');
dsm($values);

For example, the first screenshot shows the structure used for a node body, while the second one shows the structure used for an image field.

If you need to find all the nodes of a specific content type, and filter out the list basing on the value set for a field, you should use the EntityFieldQuery class, as in the following code.

$query = new EntityFieldQuery();

$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'yearly_rent')
  ->propertyCondition('status', 1)
  ->fieldCondition('field_subscription_period', 'value', $minimum_value, '>')
  ->addMetaData('account', user_load(1)); // Run the query as user 1.

$result = $query->execute();

if (!empty($result['node'])) {
  $nodes = node_load_multiple(array_keys($result['node']));
}

addMetaData('account', user_load(1)) is necessary because the EntityFieldQuery class respects the access permission associated with fields; if the current user doesn't have access to the field, fieldCondition() would fail.
Once you have the node object, you can use field_get_items(). If you want to obtain a value to render, you should call field_view_field().


Accessing node#ID in node save process I just realized hook_node_presave($node) does not yet have a NODE#ID associated with the new node.

Can anyone tell me if there is a hook in the node creating process where I can access the new nodes' nid?

hook_node_insert() is the one you're looking for...

  This hook is invoked from node_save() after the database query that will insert the node into the node table is scheduled for execution, after the type-specific hook_insert() is invoked, and after field_attach_insert() is called.


Zen theme - recommended way to display 2 blocks next to each other in a region I'm using a zen subtheme and I want to display 2 blocks next to each other.

I don't want to create 2 more regions in the info file because it will only be displayed on the home page. (Maybe even 3 blocks on another page)

Trying to move away from panels due to added markup and extra loading times during dev.

Would the correct way be to.

Add blocks to content region
Add css aka (width:50%) on the blocks to get the desired layout

or
Is there another theme layer of some-kind I can use for layouts inside of zen?

Plain old CSS

Plain old css will work. Set your widths with those two blocks and float them.

Zen Grids

If you create custom classes the zen grid sass extension can be used as well to set up layouts using sass

More on zen grids:

http://zengrids.com/help/
http://thinkshout.com/blog/2013/10/candice/getting-started-sass-drupal-and-zen

Block class

Block Class is a good way of setting blocks up to line up accordingly next to each other:

  Block Class allows users to add classes to any block through the block's configuration interface. By adding a very short snippet of PHP to a theme's block.tpl.php file, classes can be added to the parent  element of a block. Hooray for more powerful block theming!


How to trigger/run/execute scheduled task manually? Is there a way to run a scheduled task manually without any programming?

If not, this way seems not to work properly Manual execution of scheduled rule.
After executing a rule, having another one on the list, clearing caches and running the cron, this feature automatically disappears somehow. There is something wrong in the code.

This is how i do it, I use flags module, i create a user flag for each  "run manualy my special rule" assigning flag/unflag access only to admin user and i display link on user profile page, flagging or unflagging myself to trigger my special rule, then, most of the time i use views rules module to load content, products, orders or users and perform any kind of stuff with it.


Average value of integer field using views I set up a multi value cck integer field for rating purposes. It has values

 1|good
 2|bad
 3|dont know

Users voted like so:

3 votes for good
2 votes for bad
4 votes for dont know

I want to make an average from all values. In views 3 I checked grouping and set group type average on cck field inside views. Unfortunately, Instead of 1 result I get 3 results - for every value set in cck field. Results are 1, 2 and 3 which is useless. How it is possible to get only one average number? Thank you

EDIT: the average value works the same way using simple text fields. Views group by in views 3 counts only values that are the same.
And it looks like it is known issue http://drupal.org/node/903768

You could use something like Computed Field to display the average, but I would suggest going to the Voting API and something like the Fivestar module which will handle the voting and the averaging for you.


How to display field collection items left to right in views grid I created a content type as follows:

Content Type > field collection field > accepts unlimited values.
Field collection field > text field, Image field. > Each accepts one value.

Add content > content type x > added 5 field collection items. So I have one content with 5 field collection items. Each item has one text field value and one image value.

Views:
Created views grid > number of columns equal to 3.
Fields > added field collection field.

I see all the items in a single column. I would like to display items left to right. How can I do it?

Click on Content: MyProducts (within fields).

Then scroll down a bit, until you see MULTIPLE FIELD SETTINGS, click on it to expand it and then uncheck the Display all items in the same row box.


Where do I find extensive taxonomy repositories? Where might one find an extensive repository of taxonomy terms divided into different vocabularies?

Cheers,

Take a look at Open Calais (http://www.opencalais.com/) They have an extensive tagging system that is free to use. They even have a Drupal module you can use: OpenCalais. Details from its project page:

  The Calais Collection is an integration of the Thomson Reuters' Calais web service into the Drupal platform. The Calais Web Service automatically creates rich semantic metadata for the content you submit – in well under a second. Using natural language processing, machine learning and other methods, Calais analyzes your document and finds the entities within it. But, Calais goes well beyond classic entity identification and returns the facts and events hidden within your text as well. The web service is free for commercial and non-commercial use. It requires registration to obtain an API Key.

You can use such a service to find/suggest tags for your corpus of content.


hook_page_alter in Drupal 8 I am trying to append a twig template on every page .
In drupal 7, we basically append it using hook_page_alter

      function hook_page_alter(&$page) {
      $page['page_bottom']['devel']= array(
            '#type' => 'markup',
            '#markup' => '
' . theme('TEST') . '
', );  //add test template on every page at bottom position
 }

but in drupal 8 there is no hook_page_alter i think.

How to do this??

hook_page_alter in Drupal 8:

According to the change record Added hook_page_attachments(_alter)() and removed hook_page_build/alter() you should use hook_page_bottom:

function hook_page_bottom(array &$page_bottom) {
  $page_bottom['mymodule'] = ['#markup' => 'This is the bottom.'];
}

You have another issue, theme() is no longer available. But this is another question as it is unclear what you are trying to do with it. Probably you should use the template in a render array $page_bottom['mymodule'] = ['#theme' => 'TEST'];.

In D8 all page elements are in blocks now. The best approach would be to provide the extra content in a custom block and place it in the block layout in the bottom of the page. See comment from @Kevin.


After updating the metatag module I am unable to edit the metatag section of a taxonomy term Today I have updated the Metatag module to the latest version (7.x-1.0).
However, I try to edit the metatags of a taxonomy term and, after saving the change, nothing changes (it doesn't save the changes).

I have been researching into the issue and I have read that this can happen when the metatag module is not up to date.

A new development version (7.x-1.x-dev) has been released today. I have tried downloading and using the development version (7.x-1.x-dev) and I still have the same problem. Is the problem related with database corruption? What do I need to do to solve the problem?

Please try updating to the latest version, there were a few issues in 1.0 that were fixed in subsequent releases.

Disclaimer: I'm the module's maintainer.


Open user login in lightbox How to create a link, which will open user login in lightbox, I have installed lightbox2 module in Drupal 7.

Or try using Ajax Login/Register, a complete solution. Here is a quote about it (from the module's project page):

... provides a smooth way for the user to login, register and request new password via AJAX at any Drupal site.
Features:

This module provides a block with 2 links (Login, Register) for the anonymous user.
When the user clicks on Login or register the requested form appears in a nice ajax popup.
The login and register forms can validate using ajax and not redirect on error.
On success the module redirects to the user page.
When user is logged in, the block provides a Welcome !username message and a link to the user page and a logout link.
This module integrates the thickbox plugin with the Ajax module and provides a simple, easy to use and cool login and register block.


Remove the default value Is it possible to remove the default value an exposed filter (implemented by the Better exposed filter module) in a view? I would like to have users choose a value.

I tried using this in the template file, but nothing changed.

function custom_theme_form_views_exposed_form_alter(&$form, &$form_state) {
  // dpm($form);
  if ($form['#id'] == 'views-exposed-form-betterexposed-page-1') {
    foreach(element_children($form) as $key => $value) {
      if (isset($form[$key]['#type']) && $form[$key]['#type'] == 'select') {
        array_shift($form[$key]['#options']);
      }
    }
  }
}

The HTML markup is now the following.

<form action="/be1" method="get" id="views-exposed-form-betterexposed-page-1" accept-charset="UTF-8" class="jquery-once-1-processed">

            Published

 <input class="bef-select-as-radios form-radio" type="radio" id="edit-status-1" name="status" value="1" checked="checked">  Yes

 <input class="bef-select-as-radios form-radio" type="radio" id="edit-status-0" name="status" value="0">  No

      <input type="submit" id="edit-submit-betterexposed" name="" value="Apply" class="form-submit">

</form>

I also tried the following code.

function custom_theme_form_views_exposed_form_alter(&$form, &$form_state) {
foreach(element_children($form) as $key => $value) {
    if (isset($form[$value]['#type']) && $form[$value]['#type'] == 'select') {

      $options = $form[$value]['#options'];
      $newOptions = array();

      for ($i = 0, $optionsCount = count($options); $i < $optionsCount; $i++) {
        $optionsKey = array_keys($options[$i]->option);
        $optionsValue = array_values($options[$i]->option);

        $newOptions[$optionsKey[0]] = $optionsValue[0];
      }

      unset($form[$value]['#multiple']);

      $form[$value]['#type'] = 'radios';
      $form[$value]['#options'] = $newOptions;
      $form[$value]['#theme'] = 'select_as_radios';
    }
  }
}

I now get the following notice and warning messages.

  Notice: Trying to get property of non-object in
  custom_theme_form_views_exposed_form_alter()
  Warning: array_keys() expects parameter 1 to be array, null given in
  custom_theme_form_views_exposed_form_alter()

May be something like this (with hook_form_FORM_ID_alter function):

function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  // dpm($form);
  if ($form['#id'] == 'MY_EX_FORM_ID') {
    foreach(element_children($form) as $key => $value) {
      if (isset($form[$key]['#type']) && $form[$key]['#type'] == 'select') {
        array_shift($form[$key]['#options']);
      }
    }
  }
}

EDIT:

Ok, it seems that better exposed filter doesn't allow to remove default value from radio if settings are default (with default settings, filter -> is one of, BEF Settings -> checkboxes/radio buttons). I realized that in my project radios have been made from checkboxes type (with alter function), that's why in my example it's working fine..

here is a working example:

in hook_form_form_id_alter function:

foreach(element_children($form) as $key => $value) {
    if (isset($form[$value]['#type']) && $form[$value]['#type'] == 'select') {

      $options = $form[$value]['#options'];
      $newOptions = array();

      for ($i = 0, $optionsCount = count($options); $i < $optionsCount; $i++) {
        $optionsKey = array_keys($options[$i]->option);
        $optionsValue = array_values($options[$i]->option);

        $newOptions[$optionsKey[0]] = $optionsValue[0];
      }

      unset($form[$value]['#multiple']);

      $form[$value]['#type'] = 'radios';
      $form[$value]['#options'] = $newOptions;
      $form[$value]['#theme'] = 'select_as_radios';
    }
  }


What is "Sticky to top of lists" value? I'm creating a view, and I've pulled in the sticky to top of lists field, as well as a view conditional field. I want to determine if "sticky" is true, and set a value (so I can add it to a custom field as a css class, for styling purposes) i.e., "stickyitem" if true, nothing/null if false.

I can't seem to get that in the conditional field. I've tried:

Not empty, which makes it show everywhere
Equal to 1, which seems like the correct choice, but it doesn't work
Equal to true
Equal to yes

What else could it possibly be? Maybe using equal to is the wrong choice.

oh dear lord.. Didn't dawn on me to make the field visible so I could see it.

The answer is "on"


alter the exposed form , make field hidden and accept it through node form field can it be possible to alter the exposed form , make field hidden and accept it through node form field.

for example

Both node and views exposed filter will have the common date field and this view is shown on node/add pages. Instead of showing exposed filter field (date field) I

want to pass node form's field as filter to views which is in block.This will inform user what has been created on that date and prevent duplication.

Is this possible with just hook_form_alter ?

Yes its possible we do it like this

 function module_name_form_alter(&$form, &$form_state, $form_id) {
    if ($form_id == "views_exposed_form"){
        $formId1 = "views-exposed-form-view-name-block-2";
        if($form_state['view']->name == "view_name"){
            if($form['#id'] == formId1){
                $form_state['input']['field_name'] = $value_field_name;     //set value
                $form['field_field_name']['#default_value'] = $value;//set default value
                $form['field_field_name']['#value'] = $value;//set the field value
            }
        }
    }
}


Restrict publishing to certain Taxonomy Terms Greetings and salutations. I am struggling to find a solution to the following matter:

Goal:
A Taxonomy named Sections has terms like Term 1, Term 2, Term 3. The goal is to only allow users to publish content under 'Term 1' and 'Term 2' and any content posted under 'Term 3' will not be automatically published and put to the moderation queue.

Modules tried (with no success):
Taxonomy Access Control
Taxonomy Tools

I have found a solution with the Rules module.

Here's how I managed to get it to work:

1) install the module
2) activate it
3) GO to /admin/config/workflow/rules and add a new rule
4) set post type to my post type
5) Added an OR condition
6) Under that OR condition added Data Comparision to [node:field-section:tid] to my term's ids
7) in Action added unpublish content

Seems to be working so far.


The "X" plugin does not exist I've exported features in a multisite setup in site A, which I now want to import into site B. Though, I keep getting errors like:

The "entity_embed" plugin does not exist
The "bef" plugin does not exist

I've checked if the modules are enabled in advance, but still, I keep getting this error.

I'm afraid I've been short sighted: I've checked the existence of these modules through drush en MODULE assuming that Drush connect to the site basing on the site folder. It seems you now have to explicitly tell it to connect to a specific site: drush -l SITENAME en MODULE.


Install drupal without node module? I know this is achievable in Drupal 8 but is there a way to do this in Drupal 7? I've looked into drupal modules, core files but couldn't find anything reliable. I'm asking this because I might want to have a light installation with custom entities and I don't need Node module.

The node module is marked as

required = TRUE

in the node.info file, so the developers are basically saying that as far as they're concerned the node module is imperative for Drupal 7 to function correctly.

You could try patching the info file to remove that line, then disabling the node module to see what happens...in fact if you do that you should write a blog post about it or something, it would be very interesting to find out the effects; I've never heard of anyone trying to do this before :)


Showing "New content" form on main theme I'm using drupal 8
I have a page with diferent content types like "beers, wines, etc". I want to let users publish their own content inside this content types, but I want a form in the main theme, no administration theme. How can I do it?

In Drupal 8 there is the entityform_block module which gives you the option to display an entity form as a block.
You just need to go to Blocks, select Place block in the region you want and select Entity form.
When you add your from you can select Entity Type + Bundle, where you have to select your content type and also in which pages you what this block being visible.

Keep in mind that using this way, on submit the user will be redirected to the content page but you can write your custom handler using hook_form_alter.


Custom styling TB-Megamenu I'm attempting to custom style the TB-Megamenu because there are a lot of color changes I would like to make. I would also like to change how when the mouse leaves an item it stays that color for a moment before changing back to it's default state. I understand that I can always change the css in a custom stylesheet that's also included like

#main-menu-wrapper .tb-megamenu .mega-nav > .active a, #main-menu-wrapper .tb-megamenu .dropdown-menu .mega-nav > .active a {
    background-color: #000;
    color: #fff;
}

But hunting down everything I need to change is quite the task. Especially when trying to hunt down what selections I need to make for things elements are active, or elements that the mouse just left. The fact that the TB-Megamenu is changing the classes also makes it difficult. At the same time the TB-Megamenu is being used elsewhere, and I'd like to keep the default style for them, without affecting other sites that are on the same instance of drupal.
Is there a better way to accomplish this? Or do I need to continue trying to search and override each element?

TB Mega Menu module has a CSS folder. Use that as your reference. It also has a styles sub-folder that IMO would be of greatest benefit. Just copy one of the whole styles/*.css files over and adapt it. No need to hunt it down.

To target a menu on a specific page you will need to inject a CSS class into that page via a preprocess_page hook or Context or some other preferred method. You need to set it closer to root level (ie html or body tag) than that of .tb-megamenu class occurence in the html. Having done that all you need do is prepend your injected class to every single selector that you use, as in:

.tb-megamenu.style-black .nav > li > a:focus,
.tb-megamenu.style-black .nav > li > a:hover {
  background-color: #222;
  color: #7bb9e0;
}

becomes:

.my-page-class .tb-megamenu.style-black .nav > li > a:focus,
.my-page-class .tb-megamenu.style-black .nav > li > a:hover {
  background-color: #222;
  color: #7bb9e0;
}


Results page template of Search API module In Drupal 8, the default Search uses template file 'search-result.html.twig' to display results.

I have disabled the default search and enable module 'Search API' and Search API SOLR(used for Backend) to perform search in Drupal 8.

I need to customize the search results page of Search API not default search. How can I do this? The search-result.html.twig template doesn't work, with the Search API module.

Search API filters and results are displayed using views - so you need to override the views template.

So if you create a view page for your search called "Search API" (search_api) - and the machine name of that view is page - then you can add the following file to your theme:

my_theme/templates/views-view--search-api--page.html.twig

You probably want to start by copying in the contents of core/modules/views/templates/views-view.html.twig into the above template file and start tweaking it from there.

For help creating the actual view you may find these links helpful:

https://www.drupal.org/docs/8/modules/search-api/getting-started/search-forms-and-results-pages/searching-with-views-0
https://sweethoneycode.com/custom-search-with-search-api-and-views-drupal-8/


How can I calculate product price based on product attributes? I would like to calculate prices for all of my products based on value of the length or weight attribute multiplied by price per meter/g of the material selected for the product.

What is the best way to do this?

I have created content type material which has price per unit attribute. Each product when created is a assigned a material and length/weight.

When I tried to use the pricing rules i discovered I can only do simple things to the existing price and not calculate a brand new price :(

Once I have solution to this I want to be able to allow the user to select the weight/length and for the price to update accordingly.

Best Regards, Atta

The pricing rules give you the basic mathematical functions to manipulate a price (add, subtract, multiply), but they also give you the ability to set it to a specific amount. The rub just comes in calculating that amount you want to set it to first. : )

Rules allows you to calculate a value and then use that in subsequent actions, so that would be the course of action you might take ... you could, for example, ensure the rule knows about the fields you need to access on the product to make the calculation, multiply it out into a calculated value, and then set the price amount to that calculated amount.

However, this is a scenario where I'd typically expect a custom action to be created. Complex mathematical operations should be handled in code where they can be tracked, tested, etc.


What's the difference between using Drupal's jQuery library and adding it in html.tpl.php? I'm recoding one site (D7) where I stumbled upon statically added jquery (using a script tag inside html.tpl.php that pulls jquery library from google CDN). I installed "jQuery CDN" module that does the same and expected that when I loose statically added script tag everything would stay the same, but the menu and slider don't work (menu is implemented using some internal jsddmenu.js file, also slider using slides.jquery.js). What's the difference between those two implementations, when both of them add:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js" type="text/javascript"></script>

to the html code?

Its better to add javascript using your:
a) theme's .info file using scripts[] = "some/filename.js"
b) in the theme dynamically ... such as mytheme_node_view() { drupal_add_js('file', 'some/filename.js'); }
c) or in a custom module ... (similar to above)

depending entirely on your site's needs.

the reason its better to approach this this way is:
1) the theme's scripts[] array is cacheable and will attach the javascript to every page.
2) dynamically attaching it allows the script to be used only when needed.
3) you don't force the client to load anything they don't need.
4) if its attached in one of the above ways, it can be minified if needed --- allowing the client to download one big javascript file instead of a dozen separate ones.


How do I display a modal dialog on page load, with working title and dialog options, using OpenModalDialogCommand? I'm trying to display a modal dialog containing some simple markup on page load. I'm getting the expected markup to load, and the dialog appears. However, the dialog title always displays "Loading..." and the options (width, specifically) don't appear to work.
I've got the following in my controller:
public function modal() {
  $config = \Drupal::config('popup.settings');
  $title = $this->t('Fnord');
  $content = [
    '#type' => 'processed_text',
    '#text' => $config->get('content')['value'],
    '#format' => $config->get('content')['format'],
  ];
  $options = [
    'dialogClass' => 'popup-dialog-class',
    'width' => '75%',
  ];
  $response = new AjaxResponse();
  $response->addCommand(new OpenModalDialogCommand($title, $content, $options));

  return $response;
}

...and the following javascript:
(function ($, Drupal, drupalSettings) {
  $(document).ready(function () {
    var ajaxSettings = {
      url: '/popup/modal'
    };
    var myAjaxObject = Drupal.ajax(ajaxSettings);
    myAjaxObject.execute();
  });
})(jQuery, Drupal, drupalSettings);

The result:

The width should be about 1152px on my screen, but is instead an even 600px; I assume that's a default, and that my $options array isn't overriding it as I would expect.
On the theory that this is only expected to work if the dialog is opened by a click event, I tried setting the dialog options in the javascript:
var ajaxSettings = {
  url: '/popup/modal',
  dialogType: 'modal',
  dialog: { width: 300 }
};

...however, the result was identical. What am I doing wrong?

It turns out the code above was working fine -- the problem was that the site was using a Bootstrap subtheme, and Bootstrap was configured to override the standard dialog behavior. Turning off Bootstrap's dialogs solved the problem, enabling both width and title settings.


+1 user field after comment is made I created a new user field to keep count of comments. I want to increase it by 1 after a user posts a comment and decrease it by 1 when comment is deleted.

Is there any way I can use rules to do this?

I know I can use views aggregation to get comment count, but I don't want to use this method.

It's worth noting the comment table has a 'uid' column so you could potentially query that to get the comment count for a user.

e.g:

$user_comment_count = db_select('comment', 'c')
->condition('uid', $account->uid)
->countQuery()
->execute()
->fetchField();

However, if you want to increment a field on comment insert, you could use Rules or hook_comment_insert

e.g: Rules export (Increment field_comment_count for current logged in user on comment insert)

{ "rules_increment_comment_count" : {
    "LABEL" : "increment_comment_count",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules", "comment" ],
    "ON" : { "comment_insert" : [] },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "site:current-user" ], "field" : "field_comment_count" } }
    ],
    "DO" : [
      { "data_calc" : {
          "USING" : { "input_1" : [ "site:current-user:field-comment-count" ], "op" : "+", "input_2" : "1" },
          "PROVIDE" : { "result" : { "result" : "Calculation result" } }
        }
      },
      { "data_set" : {
          "data" : [ "site:current-user:field-comment-count" ],
          "value" : "[result:value]"
        }
      }
    ]
  }
}

You'll need to tweak the Rule to match your conf, but something like that should work.


How to programmatically create a View on a node that displays SQL Query content? How can I programmtically create a View on node(s) that displays the content from a specific query?

For example I would like to display the following:

$args = array(':nid' => $node->nid);
$results = db_query('SELECT USER_ID FROM USER INNER JOIN node ON USER.OFFICE_ID =
  node.title AND node.nid = :nid', $args);

Essentially, I would like to grab the 'nid' from the current node and I would like the View to display all 'users' associated with the current node, as the query would return.

I have been able to achieve this through a custom module. But I have been requested to use Views instead.

EDIT:

I've done what Johnathan Elmore suggested and got the View to display the correct information if I manually enter the 'nid' in the 'Preview with contextual filters:' space. However, if I go to the node itself, it will not display the query content.

For example:

I have nid == 123 with url alias 'office-123', if I enter 123 in 'Preview with contextual filters:', it will display the correct query information. However, if I go to 'mysite/office-123' nothing is displayed.

How can I get this View to display when I go to the node url?

You can create a View block to show on the nodes, and use a contextual filter (Content: Nid) in the View to figure out which node to reference.

Then you can display the related user (user reference field?) for that node in the block.

In case you are using pathauto to auto alias your node URL's, you can setup the Contextual Filter field (Content: Nid) to determine the Nid from the URL:


Single document, multiple filetypes for download: how to manage? I want to upload/attach several documents to a book node. Each document will be offered in a number of file formats, for example:

Report2010.pdf
Report2010.rtf
Report2010.doc
Agreement11.pdf
Agreement11.rtf
Agreement11.doc

Given this, in order to:

Offer a sensible upload interface (like FileField) that allows an unlimited number of files to be uploaded.
Present these files for download, for example:

Report 2010 - Download as: pdf, rtf, doc
Agreement 11 - Download as: pdf, rtf, doc

Is there a robust way to relate the different file formats for each document to each other? By robust, I mean something that (for example) doesn't rely on the user naming the files in a particular way for it to work.

node-[type].tpl.php

$fields = array('field_reports', 'field_agreements'); // you should to create 2 fields for different filenames
$items = array();
foreach($fields AS $field){
  $exts = array();
  foreach($node->{$field} AS $file){
    // delete real extension from file name
    $filename = explode('.', $file['filename']);
    $ext = array_pop($filename);
    $exts[$ext] = l($ext, $file['filepath']);
    $filename = implode('.', $filename);
  }
  ksort($exts);
  $items[] = t('!filename - download as: !links', array('!filename' => $filename, '!links' => implode(', ', $exts)));
}
print theme_item_list($items);

Hovewer, this code must be in template.php in phptemplate_preprocess_node function.


Webform Computed Data Display Grade and Text based on result I am building a quiz using webforms and the computed data twig and have a question if something is possible and if there is documentation on how to build this.
The quiz is 20 questions and each answer has a value of 1-5, I have all of the computed data working and it is able to show the final score properly, but was wonder if I could assign a grade and give short text feedback based on the score.
For example:
A user scores less than 70 they would receive a grade of "Below Average", 70-80 Average and 81-100 "Above Average" and then some text giving them feedback on their score depending on this range they scored in. Is this possible to do in webforms?

Yes, this is possible. Computed elements can trigger condition logic.  In your use case, you could hide/show a text field based on the score.  You might need to trim the computed element's whitespace to get the condition to trigger properly


How and where to add google analytics tracking code? Creating a single page responsive site in drupal 7.While trying to enable google analytics module,came through certain doubts. While registering our site with google analytics they gave us a tracking id (a js snippet)
Can anyone tell me after enabling module is it necessary to add the snippet ?
If its necessary ,then where to add the snippet in which .tpl file in drupal?

Easiest and most admin-friendly way is to use Google Analytics module:

  Adds the Google Analytics web statistics tracking system to your website.

Just install it, turn it on and configure.

(source: drupal.org)


Field value not coming in template.php for published node I am trying below code to get node field value into template.php.

$field_items = field_get_items('node', $node, 'field_read_more_title');
$variables['readmoretitle'] = $field_items[0]['value'];

But $variables['readmoretitle'] is empty for published node, for unpublished node I am getting correct value.

How can I get the published node field value in template.php?

The right way to doing this is hook_node_view_alter(&$build) where you can alter teaser link or any other $links. You reference from here


How do you set the #options paramater for checkboxes and radio buttons? I'm attempting to create a a form using the Form API and I'm unable to get checkboxes and radio buttons working properly. Although they show up in the form, only the first option of each one is displayed, that option is displayed with the title of the form:

I also have a select box on the page which is displaying fine, and I'm passing through the values to the select the same way I'm passing it through to the radio/checkboxes, with an array.

How do you pass values through to the #options parameter for checkboxes and radios, or do I simply having a careless error somewhere in my code (featured below)?

Code for the radio buttons and checkboxes:

 $facts = array(
        'Ponycon' => t('Attended Ponycon'),
        'PurhcaseMerch' => t('Purhcased My Little Pony: Friendship is Magic merchandise (dolls, cards, shirts, et cetera)'),
        'PurchaseShow' => t('Purhcased Episodes'),
        'Meetups' => t('Attended Brony meet-ups'),
        'Fanclubs' => t('Part of a MY Little Pony: Friendship is Magic fanclub (Facebook, local, et cetera)'),
    );

$form['fan_activities'] = array(
    '#type' => 'checkbox',
    '#title' => t('Which of the following have you done?'),
    '#options' => $facts,
    '#description' => t('Brony activities'),
);

$fdisc = array(
    'friend' => t('A friend told me about it'),
    'ads' => t('Advertisments (commercials, billboards, et certera)'),
    'Internet' => t('The internet, but not through an ad (forum, website article, et cetera)'),
    'Other' => t('Other'),
);

$form['discoverry'] = array(
    '#type' => 'radio',
    '#title' => t('How did you first hear about My Little Pony: Friendship is Magic?'),
    '#options' => $fdisc,
    '#description' => t('How you discovered the show'),
);

Code for the working select box:

        $fchoices = array(
        'RainbowDash' => t('Rainbow Dash'),
        'TwilightSparkle' => t('Twilight Sparkle'),
        'Rarity' => t('Rarity'),
        'PinkiePie' => t('Pinkie Pie'),
        'Fluttershy' => t('Fluttershy'),
        'Applejack' => t('Applejack'),
    );

    $form['favpony_area']['favpony'] = array(
        '#type' => 'select',
        '#title' => t('Who is your favourite Pony from the mane six?'),
        '#options' => $fchoices,
        '#default_value' => variable_get('favpony', 'RainbowDash'),
        '#description' => t('Your favourite Pony frmo the mane six'),
    );

The only thing I could suggest would be to try using '#type' => 'radios' and '#type' => 'checkboxes' instead of radio and checkbox. I believe radio and checkbox without the s on the end only show one option as more of an on off option.

Try having a look at Forms API for more explanation


Views: Ranking users by pageviews this month, last month I have created a view to rank Users by the total numbers of pageviews their nodes have received. I now want to clone that view and create 2 blocks:

Totals views their nodes have received this month
Total view their nodes received last month.

I have tried using contextual filters and I can create a view to show total pageviews in a date range, but, that would mean me updating the filter every month. Is there another way I can do this? I don't want to limit the results to "last 30 days". Rather, January, December etc

Thanks!

Take a look at the "archive" example view, which is provided by default (though disabled) as part of the views module.  It can be found under "Archive" on the admin/structure/views page.

This view groups the content created on the site by year and month; the contextual filter, filter criteria, and sort criteria are already configured and working correctly.  Study this example view and hopefully it will help you create what you want to do.


Show comment author e-mail in comment.html.twig Anonymous users can leave their e-mail when posting a comment but how can I display this e-mail as a plain text value in the comment.html.twig?

If you have a fresh Drupal 8 standard install, go to: 'People >
  Permissions' and Allow anonymous users to 'Post comments' and 'Skip
  comment approval'. Then go to: 'Structure > Content Types > Article >
  Manage Fields' and edit the 'Comments' field. Go to 'Anonymous
  commenting' and select 'Anonymous posters may leave their contact
  information'. Click 'Save settings'. Now when you go post a comment as
  an anonymous user you can leave your e-mail.

You can print that e-mail value in plain text like this:

{{ content.comment_body['#object'].getAuthorEmail() }}

Now, this will print the e-mails of logged in users as well. If you don't want that, then you will need to add a conditional to check if their User ID is 0, which means they are anonymous.

{% if attributes.toArray()['data-comment-user-id'] == 0 %}

    {{ content.comment_body['#object'].getAuthorEmail() }}

{% endif %}


Add image by pasting URL with media module In the screenshot, you can see I have the option to upload a video by URL. This is provided with the media module and the video embed field module.

Is there a similar module for adding images by pasting a URL. Or will this need to be a custom solution?

I found a module for your need.

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


Limit the number of registrations by field I am using Entityforms to take registrations for events. There is limited space and the form allows users to select which event they would prefer to attend.

Is there any way (rule, etc.) to disable or remove certain dates once the limit has been reached?

You can disable specific dates in date popup by implementing some custom code as per shown in jQuery UI DatePicker: Disable Specified Days. To work with jQuery in Drupal you can check the date popup alter example here.

OR you can try Work Calendar Module with Date Restrictions Module (both are in dev and not suggested to use on Production unless working without any error).


How do I translate British English strings into US English? I have created my own custom module. All of my outputted strings are wrapped in t functions. I have enabled Locale in core. I need to alter some of my module's strings and some field labels too, slightly, just a word here and there, form British English into US English.

What I'm trying to acheive is: if my site is being viewed in the US I want that to be automatically detected, and the adjusted strings/field labels displayed.

Thanks.

Solution: Install ip2country module. This provides a function called ip2country_get_country which returns an ISO 3166 two-character country code based on the user's IP address. Create a helper function that returns a boolean TRUE/FALSE is the country code is 'US'. Then just use if-else constructs to translate the required text.

First, I'm not sure about what this means "I cannot see any of the strings from my custom module." ... so my answer here may not be useful.  but here goes:

Machines don't care about what the similarities are, variations of english might as well be chinese and spanish.. which works in our favour here!

Assuming (US) english is your primary/default language,  translate only the strings you want in to the Queen's English:  admin/config/regional/translate/translate

You may have to do some interesting stuff to make detection/selection work,  but I think that's a new question.


How to silently prevent Webform spam (specific names, email addresses)? I am using Webform on Drupal 8; I have a few spambots that fill out the exact same form in the same way every day.

I want to do some kind of validation that automatically blocks these postings.  For example, if the name given is "Spambot 1", I want to discard the webform submission automatically.

Drupal 7 has the Webform Validation module but this has not yet been ported to Drupal 8.

I found a code snippet on adding custom validation to a webform element, but this seems to be for providing helpful errors to allow the user to re-submit the webform, whereas I want to make it seem like the form was submitted but silently discard the submission.

All the available SPAM protection modules for Drupal 8 are listed on the Webform Add-ons documentation page.

Text inputs now support patterns, you could explore creating a negative lookahead pattern like ^(?!.spam).$,


Concatenate fields in a view with comma when values may be empty One can easily concatenate fields in views with a re-write rule.. However, I have two fields, age_range and warning, the second of which may be empty. I want to display them like this:

Ages 2+
Ages 4-10, choking hazard

If warning is empty, I don't want to show a comma. If I make a rewrite rule like this
[age_range], [warning]

Then I get a result like this:

Ages 2+,
Ages 4-10, choking hazard

How can I avoid a trailing comma?

I would actually suggest doing the reverse of the answered question that you linked to for just the scenario you are describing.

Add Field B and Exclude it from the display.
In the Rewrite results area of Field B, enable Rewrite the output of this field.
On Field B, add a comma and the token for the raw value: ', [field-b]'
Under 'No Results Behavior' for Field B, make sure that 'Hide if empty' and 'Hide rewriting if empty' are checked.
Then rewrite your Field A to include Field B: '[field-a][field-b]'. Make sure there is no space, so that the comma will immediately follow Field A if Field B has a value.


Change views pager programmatically I'm adding nodes to a view programmatically and i'm altering the pager 'x out of y' by setting the folowing in hook_views_pre_render:

$view->query->pager->total_items = $count;
$view->query->pager->current_page = isset($params['page']) ? $params['page'] : 0;
$view->query->pager->options['total_pages'] = ceil( $count / $lim );
$view->total_rows = (string) $count;
$view->items_per_page = (string) $view->query->pager->options['items_per_page'];
$view->current_page =isset($params['page']) ? $params['page'] : 0;

Let's say there are 10 pages but even with this code nothing seems to happen, nothing get's altered. When on the second page, it doesn't display the next button. How can this achieved with code? What object, array should i alter to have this result?
Any help would be appreciated.

Thanks

Try some thing like this and see if it helps

function views_pag_views_pre_build(&$view) {
    if ($view->name == "pagination") {
            $view->init_pager();
            $view->set_items_per_page('10');

    }
}


How do I create a table when a module is installed? I want to add a custom table when a module I develop is installed. The code I am using doesn't seem to work, as the post table isn't created.
What is wrong with the code I am using?
/**
 * Installs the database schema.
 */
function mymodule_install() {
  drupal_install_schema('post');
}

/**
 * Uninstalls the database schema.
 */
function mymodule_uninstall() {
  drupal_uninstall_schema('post');
}

/**
* Creates the tables using the schema API.
*/
function mymodule_schema() {
  $schema['post'] = array(
    'description' => 'description pour la table post',
    'fields' => array(
      'pid' => array(
        'description' => 'post id',
        'type' => 'int',
        'not null' => TRUE,
      ),
      'title' => array(
        'description' => 'title',
        'type' => 'varchar',
        'not null' => TRUE,
      ),
      'body' => array(
        'description' => 'body',
        'type' => 'varchar',
        'not null' => TRUE,
      ),
      'created' => array(
              'description' => 'created',
              'not null' => TRUE,
              'mysql_type' => 'timestamp',
            ),
      'primary key' => array('pid'),
    ),
  );
}

I see two problems with your hook_schema implementation.

You are missing a return statement at the end of your function to return the schema.
primary_key needs to be outside the fields array on the same level as the fields and the description.

/**
 * Implements hook_schema().
 */
function MYMODULE_schema() {
  $schema['post'] = [
    'description' => 'description pour la table post',
    'fields' => [
      'pid' => [
        'description' => 'post id',
        'type' => 'int',
        'not null' => TRUE,
      ],
      'title' => [
        'description' => 'title',
        'type' => 'varchar',
        'not null' => TRUE,
      ],
      'body' => [
        'description' => 'body',
        'type' => 'varchar',
        'not null' => TRUE,
      ],
      'created' => [
        'description' => 'created',
        'not null' => TRUE,
        'mysql_type' => 'timestamp',
      ],
    ],
    // primary_key needs to be outside the fields array.
    'primary key' => ['pid'],
  ];
  // Don't forget to return the schema.
  return $schema;
}


Visit counter for anonymous visits? I would like to keep track of the number of visits for each anonymous user. I want to be able to show special messages, for example when they visit the site the 10th time.

Incrementing a cookie variable will just be fine in this case. How do I find out when a new session has started?

This would be difficult I believe, because every anonymous visitor is essentially treated as the same, as one account.


How to replace flag text with custom icon? I am using flag and views to show a "like" flag in a view. The machine name of my flag is "like". I want to replace the text of the flag with a heart icon. When it is not flagged, it is empty and when flagged, it is filled with red color as happens generally. I do not want to show icon besides text and neither I want to transform my flag into a button. If you have used instagram, you must know that there is a heart icon for a "like" flag. When someone clicks it, it becomes red. Like when you favorite a tweet on twitter.

I found this code, but do not know how to use it for my case. I am not sure whether it is the right code to use.

function Your_theme_preprocess_flag(&$vars) {
  $class = ($vars['action'] == 'flag') ? '<i class="fa fa-heart-o">   </i>' : '<i class="fa fa-heart"></i>';
  $vars['link_text'] = $class;
  $title_wishlist = ($vars['action'] == 'flag') ? 'Add to wishlist' : 'Remove from wishlist';
  $vars['link_title'] = $title_wishlist;
}

Note: I know I have to put it in template.php file of my theme. If you see the post, I took this code from there, but I have multiple flags on my site for example "like" "follow" "bookmark" etc etc. So I want to use this code for the "like" flag. How can i do that
I am also interested in learning how to add any icon other than heart and any flag I want.

This code is needed in your template.php and a font-icon lybrary added like this one: http://fontawesome.io/icons/ There is a module for that to


Rendering Module Code to HTML Semi-new to Drupal. I'm trying to find a way to render HTML inside my custom module.

Right now I'm using this method

$page = 'hello world';
return $page;

Which can get pretty dirty once you had some logic into it.

Is there a better way to do this? Maybe render it to some kind of template file and pass an array of vars?

Any help is appreciated :)

Clive is right that using the drupal theme system is your best bet if you're going to be doing significant variable manipulation but if you just want to load a big blob of HTML into your module you can do it a couple of ways in PHP.

For short blobs, try the EOF method

$str = <<<EOF

Hello

$world

  ... etc.
EOF;

For longer blobs, use file_get_contents()

$myhtml = file_get_contents(path_to_module().'/my_html.tpl');


How to set admin theme for a route? According to Drupal handbook route definition accepts parameter called _theme. Unfortunately this parameter is documented as "TODO".

Can this be used to force admin theme for the route? Is it possible to inject config parameter with admin theme name here?

It appears that other solution is to use Theme negotiator however the _theme parameter looks very tempting and way simpler to use.

You're looking for the _admin_route option:

aggregator.feed_add:
  path: '/aggregator/sources/add'
  defaults:
    _controller: '\Drupal\aggregator\Controller\AggregatorController::feedAdd'
    _title: 'Add feed'
  requirements:
    _permission: 'administer news feeds'
  options:
    _admin_route: TRUE


Drupal 8 service dependency injection I am trying to build a service that will leverage the Pathauto service so my class looks like this.
namespace Drupal\some_system;

use Drupal\pathauto\PathautoGenerator;
use Drupal\pathauto\AliasCleaner;
use Symfony\Component\DependencyInjection\ContainerInterface;

class ProcessUrl
{
  /**
   * @var PathautoGenerator
   */

  protected $pathautoGenerator;

  /**
   * @var AliasCleaner
   */
  protected $aliasCleaner;

  /**
   * ProcessUrl constructor.
   * @param PathautoGenerator $pathautoGenerator
   * @param AliasCleaner $aliasCleaner
   */

  public function __construct(PathautoGenerator $pathautoGenerator, AliasCleaner $aliasCleaner)
  {
    $this->pathautoGenerator = $pathautoGenerator;
    $this->aliasCleaner = $aliasCleaner;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('pathauto.generator'),
      $container->get('pathauto.alias_cleaner')
    );
  }

  public function testurl(){
    dump("Need to reach Here");
    exit();
  }

}

and my services.yml file looks like this.
services:
 some_group_system.process_url:
    class: Drupal\some_system\ProcessUrl
    argumrnts: ['@pathauto.generator','@pathauto.alias_cleaner']

Now when I call this service  \Drupal::service('some_group_system.process_url')->testurl(); it throws an error to me saying
Too few arguments to function Drupal\some_system\ProcessUrl::__construct(), 0 passed in /var/www/html/web/core/lib/Drupal/Component/DependencyInjection/Container.php on line 265 and exactly 2 expected

I cleared cache and reran but not sure why it is saying this. Please help on this.

You have a typo in your services.yml file, you misspelled arguments.
Additionally, for a service, you don't need to (and shouldn't) define the create method. Your dependent services are injected from services.yml, but keep your constructor as is.
The only time you need to define the create method to inject dependencies is when working with plugins, controllers, forms, etc as mentioned in the dependency injection documentation on d.o.


Subpage of a URL Alias and hook_menu Im slowly getting back into Drupal after much time away and beginning to pick it up and the learning curve is building back up.

So much so I always like to throw out pre-defined conventions as too restrictive while keeping the rough framework to build something bigger for what I want to do.

In my case, it's a scheduler program. But mine is in the context for a church, but could work equally well elsewhere

However the idea is that each type can have a sub type, a schedule gets applied to the type and the back end calendar generates the calendar entries for the schedule. This then gets displayed in a number of ways, from an eventually RSS feed to hook into an Android application, to a Calendar and everything else in between.

Each calendar item needs to be overwritable in that it's a generic item that may have additional certain applicable details rather than being a unique entity in its own right.

This list of types should be output with a link then to each type while I alter the page then to generate a list of next upcoming schedules for that item. Click on a date and get entries for that date. etc

It's all going pretty well until I realise I need to start referring to things by database Id instead of having a nice URL because frankly, database calendar entries don't as such have a nice URL.

One of the things I would have liked to have done is to have a URL alias against a node for my event type, eg, somecategory/sometype but then to be able to use the hook_menu system to get somecategory/sometype/% (where % could be sun, mon, tue, wed etc). Bearing in mind somecategory, sometype will be variable depending on user input, only % will have a list of specific possible - sun throu sat.

Trouble is, it doesn't look like you can do it, so I've just had to use an alias such as calendar/type/%

Any thoughts on this hook_menu issue, and any thoughts overall? 2000 lines of code into this thing and Im wondering why Im doing this (oh yeah, I like doing things my way).

Simon

I had a similar (not quite so flexible) issue.

Basically a node lives at node/NID or a url-alias path. I didnt want to write a custom hook_menu to make something so flexible as somecategory/sometype/% -- but i really think you should be able to.

I used the module view_mode_page

  On the manage display page for a given content type, you can assign
  patterns for view modes so that they will become a page at the given
  path. For instance, if you want to show the teaser at a specific URL,
  you could do node/%/teaser. If you also use Display Suite or other
  modules that allow you to create new view modes, you can use these
  modes to display one or more fields from a node at a separate URL.

  Restrictions: currently, the node path must be contained in the URL.
  This means view mode pages must follow the form [node path/node
  alias]/[view mode url]. These pages are added via hook_menu. Multiple
  wildcard characters can be used.

I used it to set many urls for a node of the form:
'url_pattern' => 'instructors/%/'.$val

where instructors/% IS a node alias and $val is a value from a Taxonomy Term field attached to the node. Eg, I get N-subpage urls for however many terms are in this vocabulary for each node of this content type.

I then use Display Suite to create a dynamic field for a custom view mode I associated for this node and url path; I also used Display Suite to create the custom view_mode (or maybe it was the FieldUI I forget). The dyanmic field a View that takes an argument that is the wildcard in the url.

Here's a snippet of code using the view_mode_page API:

  /*
   * Implementation of hook_view_mode_page_get_patterns() from module
   * view_mode_page.
   *
   * This lets me define additional node urls (per NID) with a custom
   * view mode.
   *
   * I then use this view_mode along with Display Suite and custom Fields
   * to completely alter how the node is viewed on that page, and only
   * show a View of related downloadable course files.
   */
  function MYMODULE_view_mode_page_get_patterns($results, $content_type,  $view_mode) {
    $results2 = array();
    $defaults = array('content_type' => 'course', 'view_mode' => 'course_materials_list_view', 'show_title' => 0, 'title' => '');

    // TODO: change this to like a Taxonomy Tree lookup.
    $terms = array('activities-and-handouts', 'administrative', 'assignments', 'data-recordings-and-transcripts','lectures','quizzes-exams','readings-and-reading-handouts');
    foreach ($terms as $pos => $val) {
      $results2[$pos] = (Object) array_merge($defaults, array('url_pattern' => 'instructors/%/'.$val));
    }
    return $results = $results2;
  }

This basically works for me. Breadcrumbs aren't totally happy. It's NOT exactly what you're asking but might help as it's very related. Good luck.


How to add a Library as a dependencies in another Library? I'm building D3 libraries to visualize data. The visualizations require the topojson Javascript library to manipulate geo shapes.

I want to include the topojson javascript library as a dependency in my custom libraries and right now I'm simply including it in the .info file for the each library:

files[js][] = 'js/topojson.v0.min.js'

However, this adds the topojson file to <head> section of the page more than once when I have several of these includes.

I want to be able to load the file once and use it in anyone of my D3 libraries. How do I do that?

You can add another dependency by using custom module

function hook_library() {
  // Library One.
  $libraries['library-1'] = array(
    'title' => 'Library One',
    'website' => 'http://example.com/library-1',
    'version' => '1.2',
    'js' => array(
      drupal_get_path('module', 'my_module') . '/library-1.js' => array(),
    ),
    'css' => array(
      drupal_get_path('module', 'my_module') . '/library-2.css' => array(
        'type' => 'file',
        'media' => 'screen',
      ),
    ),
  );
  // Library Two.
  $libraries['library-2'] = array(
    'title' => 'Library Two',
    'website' => 'http://example.com/library-2',
    'version' => '3.1-beta1',
    'js' => array(
      // JavaScript settings may use the 'data' key.
      array(
        'type' => 'setting',
        'data' => array('library2' => TRUE),
      ),
    ),
    'dependencies' => array(
      // Require jQuery UI core by System module.
      array('system', 'ui'),
      // Require our other library.
      array('my_module', 'library-1'),
      // Require another library.
      array('other_module', 'library-3'),
    ),
  );
  return $libraries;
}


How to implement node access control with a simple field used during node creation? I have multiple roles on the site. I have used Role reference field in Nodes to choose which Role should see Nodes. Then I have set Views to show content based on roles and Role reference field in Node.

Now I'm facing issue with Search. Search shows all content and users in different roles can see all the content.

I was looking for solution to set access per node, but Content access and Nodeaccess modules only allow access to be set after node is created. And in these case user need to set access to two fields: Role reference field AND Content access/Nodeaccess tab.
Not good. I do not want to create own content type for each role.

Is there a way to use Role reference field to set access control to node?

I did install both Content access and Nodeaccess modules and tried to use the Rules module to achieve this, but seems that neither of the modules support Rules.

Any help/tips appreciated.

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

Here are some more details to get it to work:

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

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

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


Adding zip archives to the Document File Type I have many PDF documents in my site, assigned to the Document File Type by the File Entity Module.

I have added a few fields to the content type, thus allowing nice interface in showing all PDF files on the site, with nice filtering.

Now I want to include Zip archives in this interface. (Zip archives are not by default added to any Document type). I have updated the Document type definition to include the mime type application/zip on this page: /admin/structure/file-types/manage/document/edit

Is there any way I can automatically update the existing zip archive files so they are assigned to the Document File Type? As mentioned, there are quite a lot of them and I'd prefer not to have to upload them all again.

If I understand correct and it is only an interface / layout issue, I suggest creating a view of that file with views and then put it in a block under the node and filter the block with content type and/or node conditions (or to put the block inside a paragraph layout piece).

If you mean you want the zip files to be in the also considered by Drupal as a Document file type so it would appear together with the PDF than what I suggest is to see how the module you use categorizes PDF files and then initiate this same code-level categorization to the PDF, for example, by adding the file extension PDF to the list of allowed extensions if there is one.


Why is JW Player not working in custom Content Type? I am having a weird problem.

I downloaded JW Player and used it on my page (Default Page Content Type) to show video. It worked seamlessly. Now there was one requirement that there would be a page with different fields. I hence created a custom Content Type with different fields (including video of-course).

Now I am attaching a VIDEO normally in both the fields, but one page with the custom content type weirdly doesn't show the video. What it shows it blunt listing of the Video Link.

How can I make JW player in my custom content type page (making it show <object> tag).

Below I'll list both the outputs:

Default Page (Correct Output)

        <object type="application/x-shockwave-flash" data="http://player.swf" width="100%" height="100%" bgcolor="#ffffff" id="a76593f3ee69e066" name="a76593f3ee69e066" tabindex="0"><param name="allowfullscreen" value="true"><param name="allowscriptaccess" value="always"><param name="seamlesstabbing" value="true"><param name="wmode" value="opaque"><param name="flashvars" value="netstreambasepath=page24_2.mp4&amp;skin=glow.xml&amp;autostart=1&amp;controlbar.position=none">

        </object>

Custom Template Output of a Video (Wrong)

      page24.mp4

There are many ways you can do this

Jwplayer Drupal Module

Video : http://www.youtube.com/watch?v=mAAIfi0pYHw

Embedding jwplayer in HTML5

http://www.longtailvideo.com/support/jw-player/28839/embedding-the-player/

For your example :

WRONG CODE (dont use)

page24.mp4

Try This


using hook_form_FORM_ID_alter with #states I am trying to use checkboxes to display inline entity form elements only when the boxes are checked. However, my code doesn't seem to be working. It will hide the element, but when I toggle the checkbox, it won't display what was hidden.

Here is my code:

function lodestar_form_user_profile_form_alter(&$form, &$form_state) {
    dpm($form);
    $form['field_your_nonprofit_connections']['und'] = array(
        '#states' => array(
            'visible' => array(
                ':input[name="field_affiliation_type[und][#options]"]' => array('value' => 'Nonprofit'),
            ),
        ),
    );
}

Here is a screenshot of the field_your_nonprofit_connections field:

And here is one for the field_affiliation_type field:

Based on what I have been reading in this related question (When using hook_form_alter to modify a content type's node add / edit form, where do I put the #states property?),
I have now realized that my form is not even including the #states element at all.

How do I add the #states element into an already existing form via
hook_form_alter?
And, how do I get the checkbox field to toggle the visibility?

Okay, I figured it out. Here is what I ended up with:

    function lodestar_form_user_profile_form_alter(&$form, &$form_state) {
    dpm($form);
    $form['field_your_nonprofit_connections']['und']['#states'] = array(
        'visible' => array(
            ':input[name="field_affiliation_type[und][Nonprofit]"]' => array('checked' => TRUE),
        ),
    );
}

This code got the element to toggle appropriately. Whew! I'm glad I finally solved it. Hopefully this question and answer will help someone else. It looks like the main thing I did wrong was having the incorrect ":input[name." The way I finally figured it out was by looking in the HTML itself via the element inspector. I should have tried that a long time ago.

Interestingly, the #states element never did show up in my dpm($form) output. I'm not sure why that is the case, but, apparently it doesn't need to show up there, because it is working fine without it.


Result accessibility based on field value for specific group Is there a way to hide nodes or results if it has field "restricted" type bool with value 1 if the logged in user not in admin group without writing custom code.
i could do that with views hooks like "hook_views_post_execute" with writing custom code but it will decrease the performance because i will load the node field in "foreach", so is there module can handle that from the back end !?

The field permissions module lets you assign permissions to individual fields.


How to increase a scheduled time using a new field and rules component scheduler I am working on Drupal 7 on a custom content type that is called Event.

Each created Event is programmed to be displayed for 1 hour before been deleted. I am using rules component scheduler for that and it works well.

Now I need to be able to increase that display duration.

I already created a numeric field called duration that take the value of the duration from the user. That value that I want to add to the initial display duration.

I need to use that duration field in the Scheduled evaluation date. But rules denied using the + with an identifier.

Can anybody help ?

How do I increase the duration of a tasks that has already been scheduled on node creation. How do I do that using a field that take the value to add?

What you'll have to do to get this to work, consists basically of these steps:

Create a new rule using event "After updating a node of content type Event, in which you add a Rules Condition to check that the value of the duration field was changed (I suppose you know how to write such Rules Condition).
The Rules Actions to be performed in this new rule to be created, consist of these 2 Rules Actions (in the order specified):

Delete the scheduled Rules Component that got scheduled when the node (Event) was created. That way the node will not get deleted as originally planned. For way more details on that, refer to my answer to "How to delete a scheduled task using Rules Scheduler?". Make sure to understand that it is extremely important, for this to work correctly, that you usve a unique identifier of the scheduled rule ... using the node title for it is asking for trouble (what if 2 nodes have the same title???), which is why I always make the node's nid part of such identifier.
Schedule the same Rules Component you already have (to delete the Event later on) AGAIN, using your "duration field".

What this really means is that your implementing logic that reads something like so "Don't delete this node (Event) after one hour yet, instead give me X more time (as indicated in your duration field) from now on (= the moment the updated node (Event) is updated with that duration field update)".


IE conditional comments for HTML class? I need to have the following html classes with IE conditional comments in my Drupal 8 site:

<!--[if lt IE 9]>      <html class="no-js lt-ie10 lt-ie9"> <![endif]-->
<!--[if IE 9]>         <html class="no-js lt-ie10"> <![endif]-->
<!--[if gt IE 9]><!-->
<html class="no-js">
<!--<![endif]-->

Ideally I would use html_attributes.addClass see this question: Safe to add a class attribute to the HTML element via the theme?

I tried this:

<!--[if lt IE 9]>      <html{{ html_attributes.addClass('no-js lt-ie10 lt-ie9') }}> <![endif]-->
<!--[if IE 9]>         <html{{ html_attributes.addClass('no-js lt-ie10') }}> <![endif]-->
<!--[if gt IE 9]><!-->
<html{{ html_attributes.addClass('no-js') }}>
<!--<![endif]-->

But it seems once you add a class to html_attributes then its printed every time, so my final instance which should only have a class of no-js instead has this:

no-js lt-ie10 lt-ie9 no-js lt-ie10 no-js

Your best bet is to print the class attributes separately, and use the without twig filter, then hard code the IE stuff, e.g.

<!--[if lt IE 9]> <html{{ html_attributes|without('class') }} class="{{ html_attributes.class }} lt-ie10 lt-ie9"> <![endif]-->
<!--[if IE 9]>    <html{{ html_attributes|without('class') }} class="{{ html_attributes.class }} lt-ie10"> <![endif]-->
<!--[if gt IE 9]><!-->
<html{{ html_attributes.addClass('no-js') }}>
<!--<![endif]-->

https://www.drupal.org/node/1823416
https://www.drupal.org/docs/8/theming/twig/filters-modifying-variables-in-twig-templates


How to use template_preprocess_views_view to pass a variable to a views tpl file Since the case re-occurred to me for the second time recently, I decided to ask the question so to perhaps learn something.

In Views, the main display title (the one that usually gets rendered at the top of the view) is available in display output as $title but does not seem to be available in style output at all. Instead, the $title variable in style output means the name of a group if grouping is used.

What I want is to have that display title ('human name') available in any template as $display_title. So what I did was putting this code in my template.php:

function MYTHEME_preprocess_views_view(&$variables){
  if($variables['name'] == 'studios' && $variables['display_id'] == 'block'){
    $view = $variables['view'];
    $variables['display_title'] = $view->human_name;
  }
  dpm($variables);
}

...hoping to have the human title handy:
<?php print $display_title; ?>

...but no joy. What am I doing wrong?

As you would also know, a view has several templates, which can vary depending on the style, for example:

Display output: views-view.tpl.php
Style output: views-view-STYLE.tpl.php
Row style output: views-view-fields.tpl.php
Field content: views-view-field.tpl.php

etc.

Each of those templates has its own preprocess function. What you do in your code is only affecting the display output since you are preprocessing only the views-view.tpl.php (template_preprocess_views_view)

To find out which template files are available to your specific view, you can go to view edit page and under 'Advanced' section at the end of the column click on 'Theme: Information'. You will see which template files your view is using (in bold) and which template files you would use to override them.

The preprocess functions should be named after the template file, replacing the dashes with underscores. For example for views-view-STYLE.tpl.php would be template_preprocess_views_view_STYLE().


How to use negative number as argument value in a drush command? I'm trying to create a drush command that need negative and positive numbers as argument, all works fine with the positive numbers, but once I tried to use the negative number I get this error:

[error]  Unknown option: --1.  See `drush help mw-reorder` for available options. To suppress this error, add the option --strict=0.

Is like there is no way to use a negative value because drush think that this is an option.

I looked inside the drush code but I didn't found anything.

Maybe the solution is use a special option in the command to says that the argument will be consider as a negative value or I'm missing something here?

It looks like it is not possible since the '-' is always picked up as an option being passed to the drush command.  I'd suggest evaluating why you need a negative value and if it could be handled with an absolute value and/or some other creative way of indicating a negative value.

If this is not an option, I found this work around in several different articles/blogs:

php -r "print json_encode("-1");" | drush vset --format=json some_var_name - --y

The drush command docs also suggest a technique using arrays for passing a complex data structure to the command: https://drushcommands.com/drush-7x/core/variable-set/ (See the last example).  This would let you pass in almost anything you wanted.


Ability to flag each uploaded image separately after doing multiupload I want to create some kind of photography website where users will be able to flag some images for later use.

This is the user story:

Photographer upload images of the client event on the website
Page with a gallery is created
A client comes to the gallery page and marks few items using Flag module
A view is created with a list of flagged images so Photographer can get a list of images for further manipulation

The problem is if I use multiple image field there is no way to use Flag module as it works only with nodes, and I have all images in a single node.

There is this issue in Flag module where it says why is not possible.

So I'm wondering if there is a way to convert images to nodes after creating an initial node that contains all of the images?

Or do you have any other suggestion how to handle this?

It's easily possible to create a node per uploaded picture using a custom module. Alternatively, you could use https://www.drupal.org/project/node_gallery to let users upload every picture to its node from the very beginning.


Private Files on drupal I am using drupal 7.

I have uploaded pdf files into

files/private

Now I want that when I try to access

www.site.com/sites/default/files/private/q1-2014-fs.pdf

It will open. Only if user is activate then he can able to see file

I have created a .htaccess file too

in that

Deny from all

# Turn off all options we don't need.
Options None
Options +FollowSymLinks

# Set the catch-all handler to prevent scripts from being executed.
SetHandler Drupal_Security_Do_Not_Remove_See_SA_2006_006
<Files *>
  # Override the handler again if we're run later in the evaluation list.
  SetHandler Drupal_Security_Do_Not_Remove_See_SA_2013_003
</Files>

# If we know how to do it safely, disable the PHP engine entirely.
<IfModule mod_php5.c>
  php_flag engine off
</IfModule>

Can anybody tell me, where am I doing wrong.

Use Private Files download permission module to set permission to download to certain users.

Also you can go for Field Permission Module


Theming custom field directly in custom module folder? we're trying to build a template for the custom field we developed. We don't want to put the template into our theme folder since the template should work between different themes. As far as we know we have the option of putting a custom field.tpl.php somewhere or override theme_field() in our module. What we've been trying with naming these files/functions kind of didn't work out and now we need your help. :-)

What's best practice with building templates / templating for custom fields, where to put it and how to name it?

Thanks! :)

When you define your module's theme info in theme_hook(), you can use drupal_get_path() to find the path to your module, and the path array key in your theme implementation array to point to the directory your tpl is in.

A working example would be:

function field_collection_theme($existing, $type, $theme, $path) {

  $path = drupal_get_path('module', 'field_collection');

  return array(
    'field_collection_op_links' => array(
      'path' => $path . '/includes/theme',
      'template' => 'field-collection-op-links',
      'render element' => 'op_links',
    ),
  );
}

Where the field_collection_op_links.tpl.php is in field_collection/includes/theme/, no matter where field collection is installed.


ServiceProviderBase override "winner" - can this be done with module weight? It is noted that modules implementing ServiceProviderBase to alter defined services can 'lose' to other modules overriding the same service as there is no way to know which one should overtake in that situation.

Is this 'fixable' by making your modules weight higher than the others?

Yes, the serviceProviderClasses are discovered in DrupalKernel::discoverServiceProviders(), I've stopped the code there and the list was sorted by module weight and modules with the same weight alphabetically.


How do I run unit tests against datasets? (DrupalWebTestCase and DrupalTestCase) I am testing a module that I am writing against the Unit Testing framework that comes with Drupal 7. All makes sense, and everything asserts as it should.

My question though, is it possible to run test cases against test data?

I can think of a few options/answers:

Trick the unit test into not setting up a test database, and just run against the live data (I don't want to do this, its hackish)
It's also very possible that testing against test data is not the place of a unit test, because technically a unit test should pass if there is data or not - from my understand of unit testing.

Should functionality testing be done in a different place than the SimpleTest framework? Or is there a way to test against data sets?

Drupal 8 contains tests for verifying an upgrade from Drupal 7 would be executed correctly. Those tests basically create Drupal 7 tables, fill them with the required values, and call update.php.

You could need to create a upgrade/update test for your module, or you could test how a function behaves when it reads data from the database that are not in the format it expects.
In the first case, you would need to override the setUp() method, and avoid calling parent::setUp(); in the second case, you would fill the database table used from the test with the test data, call the function, and check what the return value is.

Apart from testing an update, I can think only of a case where a test would need to fill a database table, since:

If the table contains what entered from users, then the test should verify the form validation handler correctly shows error for wrong input
If the table contains data entered from another module, that module should be using a function your module implements, and the test should just check what the function does when it receives wrong/unexpected values

It could be your module is using data from a table that is created from another module, which is not exposing an API to load/save data in that table. In that case, if you know there is another module that enters unexpected data, you could need to verify your module is able to handle that data.


Different roles depending on a user's field I have a problem that I have not a clear idea of how to solve it, the problem is the following: We have a user form registration where there's a mandatory field that is Country. I have also a content type that is called mobility that has a field, incoming country (among others). The thing is that now, I have to make that only users of for example USA, can modify the contents where USA is the incoming country.

I've seen that this could be "done" by just allowing a user from a certain country to view the USA contents but it's not the perfect approach since when I'm in a link like "../content/id/edit" i could try different id's and be able to modify a content that I would not be able theoretically. The only way I see to do it "well" would be to do some approach like having one role for each country but is not scalable.

Any solid approach to solve this problem?

PD: I can't solve it by IP (there's a module) because this user when (s)he registers, choose the country that is from (explaining why would be a bit long but it's a correct approach for what we are looking for)

You should be able to do this with a custom module and without roles. There is plenty of documentation around for creating custom modules, so I will not go into those details.

In your .module file, make use of hook_node_access:

function MODULENAME_node_access($node, $op, $account) {
  $type = is_string($node) ? $node : $node->type;

  // Only work on edits.
  if ($type == 'contry_content_type' && $op == 'edit') {
    // Field get items returns an array.
    $user_countries = field_get_items('user', $account, 'country_field_name');
    $content_countries = field_get_items('node', $node, 'node_country_field_name');

    if ($user_countries[0] == content_countries[0]) {
        return NODE_ACCESS_ALLOW;
    }
  }

  // Returning nothing from this function would have the same effect.
  return NODE_ACCESS_IGNORE;
}


Basic Password Reset steps not working I have reviewed other similar posts, but none matches my problem.

I built a Drupal site based on an old ASP.NET site. I imported the users from the old DB (which had passwords in plain text!). Most users have been able to log in fine, using their old username (email addresses) and passwords.

But a few users are having trouble logging in. In some cases they forgot their password from the old site.

So they request a new password on the login page, get the email with the one-time login link, use it to change their password, but they can't login again using the new password.

What I have done to test / fix

tried resetting password myself in a testing account I set up a couple months ago:

got reset password email link
made sure I was logged out on the site
user emailed link  to get into the account
entered new password
logged out and then couldn't log in again with the password I just entered ("Sorry, unrecognized username or password. Have you forgotten your password?")

tried using a different browser, flushed cookies and cache, all to no avail. I cannot seem to login to this account EXCEPT by requesting a password reset email and using the link in that. But if I log out, I cannot log in again.
installed Password Reset Landing Page (https://www.drupal.org/project/prlp). This moved the password resetting to the page you land on from the email link, but it didn't solve the problem.
I also just tried making a different brand new testing account, asking for a password reset, resetting as before. This time it worked. No idea why it works with this new account but not with the other, older testing account. To be clear, the old testing account still doesn't work following the same steps that worked for the new account.
I monitored the user table in the DB. The password is being changed, but system doesn't recognize the newly entered password.

Is there anything I can post here to get help investigating this?

Tried to reproduce this but wasn't able to make it. Below is my process.

no prlp module

created new user with notify email
used onetime login link
changed password
logged out
logged in using the new password. SUCCESS

with prlp module

request new password
used onetime login link
changed password in the one time login page. SUCCESS
logged out
logged in using the new password

5.1. using username 'asd'. SUCCESS

5.2. using email 'asd@asd.com'. FAIL (not relevant)

enabled logintoboggan (to use email as login)

login using email and new password. SUCCESS
logout
request new password
used one time login link
changed password in the one time login page. SUCCESS
logged out
logged in using the new password

7.1. using username 'asd'. SUCCESS

7.2. using email 'asd@asd.com'. SUCCESS

Anything you'd like to add or to test?


Page editing gives an extra text widget When I try to edit a page that already added am getting an extra text area movable widget as shown in below screenshot.

Is it a bug or an issue with the settings in for the content type page?

You seem to have your field's cardinality set to greater than 1. Change it to 1 and the problem should be fixed.

In case you already have data in the field but you are sure to only have one value stored per entity change the column "cardinality" in the "field_config" table manually to 1.


Change date format in forum Is there a way to change the date format in main forum table? I changed the date format in views for topic list, but the date format wasn't changed on main forum page

What I did to change the date format. In modules/advanced_forum/includes/theme.inc I found the function advanced_forum_preprocess_forum_submitted(&$variables) and changed line 249 to $cutoff = variable_get('advanced_forum_time_ago_cutoff', 0) * 60 * 60; and line 254 - to $variables['date_posted'] = format_date($timestamp, 'custom', 'j M Y,    G:i');


View all nodes of a content type using a filter I have a content type called "Building", which contains a field called "Size". I also have an exposed filter that filters through the size chosen by the user, so the view only displays that size.

What I would like is that the view sorts and displays all the nodes in order of relevancy, i.e. if I choose 5-10 meters, the 5-10 meter buildings show up first, and then the rest of the buildings are also shown.

Thanks, and please feel free to comment critically on this post so I can improve on my questions for the future.

In this case, if you are providing a contextual filter, the view will render the filtered out result. However, as I understand from your question, you need the entire nodes of that content type with the contextual filter values on the top.

For this you can try using hook_views_post_execute() where the pre_render() function is yet not called and sort manually. Or, you can use hook_views_pre_render() function to shuffle the result. At this point, you have all the nodes and you can sort them manually.
Hope this is helpful. Thanks


field slideshow module and image field caption I want to use image field caption and  field slideshow.

How can I set the caption field as caption for my slideshow?

I tried to apply the update but it didn't work.

Did you try this particular patch? Do you use 'Long text' field? I think that this patch doesn't work with standard 'Text' field.