Dependent Dropdown based on Database Queries I've been working through the Drupal 7 AJAX form examples in the Examples module, and am trying to set up a dependent dropdown form element with 2 select lists populated from the database.

Basically, I have Select called Specialties, that pulls a list of items, and a second Select called Physicians—which should be populated with Physicians tagged (via Node Reference field) with the chosen specialty. So, for example, the end user selects  "Back" from the Specialties select list, and the second should populate with a list of the 3 physicians containing this Node Reference.

From what I can tell, both queries are returning the right types of nodes, and if i place a condition in the Physicians query to hard-code the specialty field:

->condition('field_specialty_nodereference_nid', '90')

it populates the second list with all doctors tagged with that nodeference.

What I am struggling with is how to make that condition dynamic, so a value from the first select is passed through to the second on change. Thank you in advance for any help you can provide.

Here is my code:

<?php

function docappt_states_form($form, &$form_state) {

// Grab the list of specialties from the DB

  $query = db_select('node', 'n')
  ->fields('n', array('nid','title'))
  ->condition('type', 'specialty')
  ->orderBy('title', 'ASC');
  $results = $query->execute()->fetchALL();

  //define rows
  $specialtylist = array();
  foreach ($results as $result) {
      $specialtylist[$result->nid] = $result->title;
  }

// Let's call some docs by specialty reference
  $query = db_select('node', 'n');
  $query->join('field_data_field_specialty_nodereference', 'specnr', 'n.nid = specnr.entity_id');
  $query
  ->fields('n', array('nid','title'))
  ->fields('specnr', array('field_specialty_nodereference_nid', 'entity_id'))
  ->condition('type', 'physician_profile');
  $docresults = $query->execute()->fetchALL();

  //define rows
  $docfoptions = array();
  foreach ($docresults as $docresult) {
      $docfoptions[$docresult->nid] = $docresult->title;
  }

  $specialties = isset($form_state['values']['specialties']) ? $form_state['values']['specialties'] : key($specialtylist);
  $form['specialties'] = array(
    '#type' => 'select',
    '#title' => 'Specialties',
    '#options' => array(
      0 => t('- Select -')) + $specialtylist,
    '#default_value' => isset($form_state['values']['specialties']) ? $form_state['values']['specialties'] : 0,
    '#ajax' => array(
        'callback' => 'docappt_dependent_dropdown_callback',
        'wrapper' => 'filtered_doc_list',
        'event' => 'change',
        'method' => 'replace',
        ),
    );
  $filtereddoc = isset($form_state['values']['filtereddoc']) ? $form_state['values']['filtereddoc'] : key($docfoptions);
  $form['filtereddoc'] = array(
    '#type' => 'select',
    '#title' => $specialtylist[$specialties] . ' ' . t('Doctors'),
    '#prefix' => '
',
    '#suffix' => '
',
    '#options' => $docfoptions,
    );

  return $form;
}

function docappt_dependent_dropdown_callback($form, $form_state) {
  return $form['filtereddoc'];
}

use FF or Chromes console.log function and be sure your Ajax is being called properly. Or use dd() from the devel module to log whats going on when the change event or other JS actions are called.


How to track an action when user creates a node of a specific content type? I use Drupal 7 and I want to track an action when user creates a node of a specific content type.

I installed the Facebook Pixel and Facebook Tracking Pixel modules, but they don't support my needs. Is there any way to implement this?

I would use the Rules module, which allows for dozens of variations of tracking. As an example, here is a prototype of a rule, in Rules export format, to illustrate the possibilities:

{ "rules_find_links_in_body" : {
    "LABEL" : "Find links in body",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--article" : { "bundle" : "article" } },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "2" : "2" } }
        }
      },
      { "OR" : [
          { "text_matches" : {
              "text" : [ "node:body:value" ],
              "match" : "http(|s):\/\/+",
              "operation" : "regex"
            }
          },
          { "text_matches" : {
              "text" : [ "node:body:value" ],
              "match" : "ANotAllowedTextStringInBody",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "drupal_message" : { "message" : "Node body contains an URL ..." } }
    ]
  }
}

Some more details about the above prototype rule:

Rules Event = After saving new content of type "Article" (adapt the type to fit your needs).
Rules Conditions:

Check if the current user is an authenticated user.
Perform a text comparison, using a Regular Expression as the Comparison operation (which you can perfectly do in Rules, without using the PHP filter for it). For the actual regular expression, this rule uses http(|s)://+, which will discover strings that start with either http:// or https://. Should you have additional / similar requirements to discover variations of this (say some other string like ANotAllowedTextStringInBody), another Rules Condition (with an OR) will take care of that also.

Rules Action = Show a message on the site (adapt the message to fit your needs), and/or add other relevant Rules Actions ... Such as:

use the Message module as illustrated in the answer to "How to log and display all the users that have edited a node (without revisioning)?".
send an eMail, either to a specific user, or all users of a specific role.
use the Flag module to flag the user (for whatever reason).
grant a special role to the user.
... (the possibilities are only limited by your own imagination).

Voilà, easy as that ...


What are "#" properties? While reading the Ajax framework documentation I came across mention of the #ajax property. I know from poking through the code that there are others of these properties with hash signs in front of them. What does the hash sign signify? What are these properties all about?

This is to do with render arrays in general, it's not just specific to AJAX or the form API (although the form API uses render arrays exclusively for building up it's content).

Put simply, array keys in a render array without a # in front of the name are seen as children of the render array, and are subsequently rendered themselves (recursively).

Those with a # in front of them are seen as meta data/variables for the render array to use as necessary, and are not themselves rendered.

The render array docs (linked to above) actually put this nice and succinctly:

  A render array is a classic Drupal structured array that provides data (probably nested) along with hints as to how it should be rendered (properties, like #type).

The # keys are the 'hints' that the above paragraph is talking about, the non-# keys are the nested data.

I'd thoroughly recommend giving that page a read, it does a good job of de-mystifying the whole render array thing, and provides code examples.

There's also another small explanation/code example on the Theming the page docs which might be useful.

Render arrays are used all over the place in Drupal (forms, themes, general markup, etc.) so knowing a good bit about them will help a lot with future Drupal development.


Custom region in theme not on front page? This is probably (hopefully) a simple question, but I can't figure it out: I'm trying to customize a theme to add a div/region for a "banner" that will display the title of the page on each page...except for the front page. The front page will have a similar "banner" but with different content, more like a promotional thing.

I thought the simplest way to include the banner with the title was simply to move the title rendering in the page.tpl.php:

      <?php print render($title_prefix); ?>
      <?php if ($title): ?>

          <?php print $title; ?>

      <?php endif; ?>
      <?php print render($title_suffix); ?>

This works fine, but then I will get it on the front page as well, and there I want it replaced by a similar banner but with custom content, preferably inserted by a custom block I will create.

How do I do this separately for the home/front page?

You can create a page--front.tpl.php file in your theme. This file is the same as page.tpl.php but only for the front.

Remember clear cache after the creation of the file.


Group By Taxonomy term on view but show all articles containing it I am trying to generate a view that groups nodes by a taxonomy attached to them but only shows the Taxonomy term once then all the titles under it.

Term 1
Article
Article
Article
Article

Term 2
Article
Article

Term 3
Article
Article
Article

An example of what im trying to solve.

In my example I have Article with taxonomy term reference field tags and have create following content/terms

2 Tags: test1, test2
4 articles (2 including test1, 2 including test2)

Create a view of content displaying fields and filter to display articles only

add title field
add tag field (can exclude it from display)
format settings > choose grouping field Nr 1. > tags


how to add data to custom content type using node with codeing i have drupal site with custom content type called donation and i have 4 step registration form which contains the data for the custom content type,i want to add forms data in to custom content type node how can i do that i try way like this

$nid = 1;
$node = node_load($nid);
$node->donationname = '.$data1.';
$node->donationitem = '.$data2.';
node_save($node);

The proper method is

  $body_text = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.';

  $node = new stdClass();
  $node->type = 'article';
  node_object_prepare($node);

  $node->title    = 'Node Created Programmatically on ' . date('c');
  $node->language = LANGUAGE_NONE;

  $node->body[$node->language][0]['value']   = $body_text;
  $node->body[$node->language][0]['summary'] = text_summary($body_text);
  $node->body[$node->language][0]['format']  = 'filtered_html';

  $path = 'content/my-lipsum-' . date('YmdHis');
  $node->path = array('alias' => $path);

  node_save($node);

To Add custom fields

// Let's add some CCK/Fields API field. This is pretty similar to the body example
$node->field_custom_name[$node->language][0]['value'] = 'This is a custom field value';
// If your custom field has a format, don't forget to define it here
$node->field_custom_name[$node->language][0]['format'] = 'This is a custom field value';

How to programmatically create/manage node in drupal 7


User tabs for anonymous users The user tabs are:

View

Edit

My content (created with Views with path user/%/track)

Every user can edit his profile with the user tab "Edit".
When registered user enters other profile the two tabs "View" and "My content" are available, without "edit" (that's fine), but what about anonymous users?

When I enter from anonymous user into /user/1/track I see the content but without the tabs(View and My content).

How can I make these tabs displayed from anonymous users?

Do I have to use hook_menu_alter for this core element?

EDIT:
"View user profiles" is already activated for anonymous users in permissions page and user/1 and user/%/track are accessible for anonymous users, but the tabs are missing.

This is a permission issue. Simply enable the permission "View user profiles" for anonymous users.


update hook to delete and bulk update pathauto aliases I have put all of my SEO settings into a feature, in order to migrate the settings from a dev site to a live site. Is there a way to write an update hook that will delete all of my existing content aliases and then bulk update them automatically?

I do it with the following method:

function MYMODULE_update_7100(&$sandbox) {
  module_load_include('inc', 'pathauto');
  module_load_include('inc', 'pathauto.pathauto');

  // Delete the existing node aliases.
  db_delete('url_alias')
    ->condition('source', 'node/%', 'LIKE')
    ->execute();

  // Regenerate the node aliases.
  $nids = db_query("SELECT nid FROM {node}")->fetchCol();
  pathauto_node_update_alias_multiple($nids, 'bulkupdate');

  // Delete the topics taxonomy aliases.
  db_delete('url_alias')
    ->condition('source', 'taxonomy/term/%', 'LIKE')
    ->execute();

  // Regenerate the taxonomy aliases.
  $tids = db_query("SELECT tid FROM {taxonomy_term_data}")->fetchCol();
  pathauto_taxonomy_term_update_alias_multiple($tids, 'bulkupdate');
}


Upload files to create nodes I am trying to create an online catalog of products, that could be filtered, sorted, etc, and I followed these steps:

I have created a content type (product)
I have created a view where I can view and filter/sort these products

Now, the major problem is to manually enter hundreds of products!
I have product descriptions in Excel, and image files with links, but I don't know how to upload everything in bulk.

How could I do this?

Maximum flexibility:

I would use the Migrate module. It has CSV support, and there's even direct spreadsheet support in the works. Migrate documentation.

It will require some coding, yes, and Migrate module is not the easiest module to get a grip on, so if you're new to coding, you may need some help with that, but I think it's by far the best solution.

Easier implementation:

The Feeds module claims that it can

  Import or aggregate CSV files

I haven't used that particular piece of functionality myself, but from previous use of Feeds, I'm under the impression that this could be configured from the UI, and thus wouldn't require any code. Feeds documentation.


If I have added extra fields to a user profile, how can I programmatically check if those fields are empty? I have added some fields to my user entity, (doing this in hook_install(), in .install file). This is in a custom module. If I uninstall this custom module I only want to uninstall those fields if users don't have any values for the field, so I don't end up losing data from my users. How can I check fields of a user?

I would advise against keeping those fields around after an uninstall. It's a module's responsibility to clean up after itself, and a user of your module should be able to assume that if they disable the module, the functionality will be gone, but the data remains in the database.  If the user uninstalls the module, the assumption is that the module will clean up after itself - delete all its data, custom tables, created variables, etc.

If you don't want to lose any data, just disable your module without uninstalling it - then the uninstall hook doesn't run.  But my suggestion is to keep to the community's expectations and properly clean up the custom database tables, fields and variables that your module has created in the uninstall_hook.

I think with open source projects like Drupal, where there are tons and tons of contributing authors and contrib modules, it's even more important for each of us to conform to the expectations of a module's behavior.  Otherwise, if each module does what it wants upon uninstall, we wouldn't know what to expect in terms of our databases.  What if a user has another contrib module that conflicts with your module's fields, for example?  How could they ever get rid of them if your uninstall hook doesn't clean them up?


Prevent Category Pages from Generating I have a website that is generating /category pages and /taxonomy archive type pages, with a list of posts containing a certain taxonomy term.  I do not have a template for this page and they seem unnecessary/duplicate content.  Is there any way to prevent them from being created?

category/region/all/boston?page=2&region=DEFAULT
/taxonomy/term/14/”?page=19&region=DEFAULT

link to one of these pages
http://nyc.thedelimagazine.com/taxonomy/term/14/%E2%80%9D?page=19&region=DEFAULT

If you really want to prevent the URLs from existing at all, you could probably unset the paths using a hook_menu_alter. I would be careful with that though, as it might have unforseen consequences. The creating module may in some way depend on the paths existance.

I don't know where the category paths comes from but I guess the answer will be the same as for the taxonomy ones.

My solution would be to take over the URL with Page manager, and simply pass the user a redirect to the front page. (Or a 404, if you prefer).
Note that I'm talking about "Page manager" in Ctools, not Panels. The two modules are often confused and their names interchanged.


Sort by weight using \Drupal::entityQuery() I want to get all taxonomy term in $lang language, following snippet works correctly and return all terms of $lang code.

    $query = \Drupal::entityQuery('taxonomy_term');
    $query->condition('vid', "news_category");
    $query->condition('langcode', $lang);
    $tids = $query->execute();
    //$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);
    return new JsonResponse($tids);

Then I want get results in order that in the taxonomy list they are, try to sort them with $query->sort('weight','ASC'); but with following snippet the results are  the same before adding sort.

    $query = \Drupal::entityQuery('taxonomy_term');
    $query->condition('vid', "news_category");
    $query->condition('langcode', $lang);
    $query->sort('weight','ASC');
    $tids = $query->execute();
    //$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);
    return new JsonResponse($tids);

Does anybody know where the problem is? How can I get terms in order they are in  taxonomy list?

Taxonomy overview list uses something like:

  ->sort('weight', 'ASC')
  ->sort('name', 'ASC')

If that doesn't work for you, take a look at \Drupal\taxonomy\TermStorage::loadTree


SCORM (v 1.2) integration for Quiz module We are looking for SCORM integration with Drupal's Quiz module.

Essentially we should be able to Import/Export quizzes and questions as SCORM package(s). Ideal if SCORM player can be used for quiz taking and Results/Feedback displaying.

I couldn't find any library or API to ease up the integration work. Wondering if I have to write my own Importer and Exporter to handle this requirements.

Have a look at the Opigno LMS distribution, which is fully compliant with SCORM 2004 v3. Here is a quote from its project page:

Opigno LMS is a full-fledged Learning Management System based on Drupal.
It allows to:

Manage training paths organized in courses and lessons.
Assess students thanks to varied quizzes.
Award certificates to successful students.
Sell your trainings online.
Facilitate interactions thanks to live meetings, forums and chats.
...

Maybe not to start "using" this distribution, but by reviewing it to get an idea about it's SCORM compliance, and then copy-an-paste whatever fits / makes sense to also include in your own site.
Contributed module SCO Node somehow relates to SCORM and might potentially be of some help to get you going (quote is from its project page):

The SCO Node module allows nodes to be created that contain SCORM content. The SCO content can then be played and scored on a Drupal 7 site.
The module currently supports SCORM 1.2 and some of SCORM 2004


Performance effect on field length When we are adding a text field to a content type the default length is 255. I am curious to know the performance effect of the field types and the length have for it.

Is there a preferred order of fields and length based on performance? so that we can chose our fields accordingly.

Going over 255 means that field can not easily be indexed and thus if you filter on it in views or in a query it will be slow. As long as you stay below this limit all is well.


changing the process of registration I need to make a different process for user registration in drupal.
1] set username, email and password.
2] send a verification email to user's email address.
3] by clicking on the link in the email direct to the site as a logged in user.

I mean I need to set password in the first step, not after clicking on the link in the email. although It's a bit illogical but users would be less confused in this way.

if there is a module for this please let me know otherwise I need to change it programmatically.

User registration password.
This is the first result when searching "drupal user registration password" on google.


How do I update the body of a node using a query? Let us consider I have a node called "DrupalTest" for which I need to update the body content using AJAX.

Shall I execute a query, or is there any other way to update the body content?

Load the node using node_load().
Set the body property of the node; examine the node object to determine which one the body property is. If you have the Devel module installed, kpr() will help you there.
Save the node using node_save().

This ensures that the hooks associated with updating a node get executed, and that the cache is properly cleared.


How do I convert special characters into html in twig I have some list items in drupal 8 which created by item_list template.I am sending some  tagged data to the item_list template. My idea was to get the output as This is new page.

But it returns the output as
&lt;a href="/this-is-new.html"&gt;This is new page&lt;/a&gt;
.

I need to print this in a twig template. But with the output I had it renders as a string in the template not as a html anchor tag. I needed to view a link to another page in template. But all I am getting is a string with the This is new page. What should I do?

NOTE: this should be avoided as it is considered bad practice as mentioned in the comments, leaving here as an example to avoided
Inside your twig template try this
  {{ var|raw }}

where var is the variable being printed.
For more information here


Display multi-value entity reference field in node edit form as draggable? Is there a way to display a multi-value entity reference field as a draggable widget in a node edit form? I'm looking for the exact same behavior that a multi-value image field has by default. I would like a way for the content editor to easily reorder the referenced entities after they have been added via an autocomplete field. I really thought this was core functionality.

Thanks for your help.

I have found this module, but the UI is pretty bad and I really want the same UI that an image field has. https://www.drupal.org/project/entityreference_dragdrop

You can get the multiple values input in a table format with the draggable option if you choose Autocomplete widget for that field under Manage form display for that Content type (not the Autocomplete (Tags style)).

If your field accepts an unlimited number of values the widget will present as one autocomplete input field with a button to Add another item. As you add more items you will be able to drag and drop to rearrange the values order.

You can also get that reordering widget with Inline entity form widget (with the additional module Inline entity form).


EntityFieldQuery for getting the count of a user blog EntityFieldQuery for getting the count of a user blog. Blog is a content type.

Try this

global $user;

$query = new EntityFieldQuery;

$count = $query->entityCondition('entity_type', 'node')
 ->entityCondition('bundle', 'blog')
 ->propertyCondition('status', 1) // Getting published nodes only.
 ->propertyCondition('uid', $uid)
 ->count()
 ->execute();

print $count . ' blogs from ' . $user->name;


Commerce cart form alter to do an availability check I have some nodes I use as rentable objects, and I want to check availability on the Commerce Cart page (made by Views, the one you see at /cart). I also need to check it a last time before the user is sent off to payment, but as for the views Cart form, what function actually handles the quantity updates? I can see that the edit quantity field has my pre-update value as default_value and the new value as value, but which function actually sets that on submit?

I'm not sure what you're asking about quantity for, so I'm going to set that question aside and answer the broader question of confirming availability before purchase. In Drupal Commerce, the product pricing system serves a two-fold purpose:

Determine the price of a product for the current user.
Determine if the product is no longer purchasable.

While #1 is the most common use case, #2 even has some core representation: if you add a product to your cart and then disable that product as an administrator, the product will be removed from your cart thanks to a default product pricing rule that unsets the price of disabled products. We'll make this process more explicit in the next version of Drupal Commerce, but right now you should understand that if the unit price of a product line item is "unset" or set to a NULL (empty) value, the product will not be considered purchasable.

This will result in one of two behaviors:

For a product in the cart, it will be removed.
For an Add to Cart form, the Add to cart button will be changed to Product not available.

So, in your case, I'd just add a product pricing rule that performed the availability check. If the product is not available, the Add to Cart form will not allow the product to be purchased. If it was already in the cart, it would be removed, so you might use a separate rule to remove unavailable products from the cart and display a message informing the customer what happened. If they were on a checkout page, it would be user friendly to also send them back to the cart page.

Since I don't know how you're checking availability, I'll just add that if you can't do what you need through Rules directly, you can just whip up a simple custom condition to perform the check for ya. There should be plenty of examples in our code and elsewhere.


Advanced forum: How to modify template of forum list page? Here's the normal template for Advanced Forum:

I'd like to modify the template of advanced forum so that I can

Remove the elements in red
Rearrange the elements in blue
Edit the elements in green
Display the topic starter's profile2 picture

so that I can achieve the result below:

So far, I've tried editing advanced-forum.naked.topic-list.tpl.php but it doesn't change anything. I've managed to remove some of the content with Panels but I cannot modify what's left over here.

When I had to do this I found there are lots of template files and it's not obvious what controls what. I ended up putting die() in each one to find out which template file was used for each view, and then a case of trial and error to make the changes I wanted.

When you have worked out which files need editing then you should copy them from:

/sites/all/modules/advanced_forum/styles/naked/advanced-forum.naked.TEMPLATE_NAME.tpl.php

to your theme at:

/sites/all/themes/YOUR_THEME/templates/advanced-forum.naked.TEMPLATE_NAME.tpl.php

Any files here will override the ones in the advanced forum themes folder.


What is the best way to allow user Edit one Form? I want to make a dynamic website using Drupal 7 that allow user to edit any part of the site

this site has more than 10 pages each page has a different content and structure

should I make a content type to each page and add one node to each cck and give permission to site admin to edit this node

Or there is another way (I don't want to make a lot of cck because it make a lot of tables in database) also I need to edit only

I want the best way to make it

Thanks

If your question is primarily about how to allow the user to edit a form (as the title suggests), then I think the way to go is

Create a new role at /admin/people/permissions/roles and call is something like 'editor'.
Then go into the permissions page at /admin/people/permissions and give the new role 'Edit any content' permissions under the 'Node' section for each of the content types you have.

If you're simply wondering whether all those content types are OK, I'd say that having 10 content types for a Drupal site is not that crazy or unusual.  Of course, if you're just trying to distinguish the pages from each other in some way, sometimes tagging/taxonomy is better than putting them in different content types, but that depends on what you're trying to achieve.  If they legitimately have different fields/structure, than you're OK to have 10 content types.

Does that answer your questions or were you getting at something else?


How to make SASS/SCSS Module works with Drupal 7? I've installed SASS/SCSS module within drupal seven... There is no configuration page apart from activating debug, and development mode. So, I thought there will be no other configuration needed. I've created my .sass files in the css directory... but nothing happens...

Could anyone helps?

You didn't mention whether you installed the PHamlP library or not and from your question description, it sounds like that is the problem -- it needs this to actually render your .sass files. From the readme:

1. Create a folder inside the SASS module (sites/all/modules/sass) and name it phamlp
2. Download PHamlP_3.2.zip from http://code.google.com/p/phamlp/downloads/list
3. Extract its contents to the phamlp folder you just created
4. Once you have installed/enabled the module you can visit admin/settings/sass where you can
configure various settings surrounding the behavior of this module.


Theming custom block type have multiple paragraph field I've created a custom block type includes a paragraph type field and make it multiple. I've configured this block to display it only on the front page. I have a page--front.html.twig template in my custom theme. What I want to do in my front page template is looping through the paragraph field to get each field item and theming it in custom HMTL. So what is the correct way to do this? I've tried block--BLOCKID.html.twig and try this code.

{% for item in content.field_home_page_carousel %}
{{ kint(item.field_home_slide_image) }}
{% endfor %}

but I got nothing.

I Agree with Kevin's comment. Focus on theming the block.
Activate your theme's debug mode and view the template suggestions for your block. Add a new template and name it as one of the template suggestions, e.g. block--views-block--more-by-this-author-block-1.html.

It may help to duplicate the original block's code and paste into your new twig file, then find a good place to add your for loop.
Now you can loop through the paragraphs:

{% for item in content.field_home_page_carousel %}
    <p>{{ item.field_home_slide_image }}</p>
{% endfor %}


theme_preprocess_node function not getting executed from template file I am trying to print action "tabs" in my node.tpl.php file. I added the preprocess function as below-

function MYTHEME_preprocess_node(&$variables, $hook) {

 $variables['page_tabs'] = menu_local_tabs();

}

Then trying to print in my tpl like below.

print $page_tabs;

But it is not getting executed at all. Infect the control is not going inside preprocess function when I am trying to exit like below-

function MYTHEME_preprocess_node(&$variables, $hook) {

 echo "good bye";
 exit;

}

Any help is greatly appreciated. Thanks

For using this hook, u will have to replace MYTHEME with your theme name, like if your theme name is bartik, then your function will be

bartik_preprocess_node(&$variables, $hook)

After that clear your cache, by going to Configuration >> Development >> Performance

or just write in url admin/config/development/perfromance


Show entries in view only if other nodes with same term reference exist I have a view of several fields from one content type (content type is called "summary"). A required field in the content type is a term reference, called "connector". "connector" is also a required field in a different content type ("details"). I only want to include the content of a node summary in the view if a node details exists with the same "connector" reference.

Is this possible when using views? Using the interface would be ideal, but since I am already doing some post-rendering for that view, it might be easiest to remove the unwanted entries there?

From what it sounds like, it should be possible to do this using the relation module. However, I can't wrap my head about how to configure it.

Any help highly appreciated!

After sifting through several modules, I decided that it's easiest to achieve this with theme pre-processing. Here is what I did:

I used the drupal 7 schema that I created years ago (http://upsitesweb.com/blog/2011/06/drupal-7-database-schema), to figure out which tables to join. The vocabulary I am using has the vid 14. I pre-processed the view and checked for each line, whether the corresponding node in the details content type exists, rewrite the view entries to only contain matched entries.

It must be possible to also achieve the same with contributed modules. However, it was faster and more efficient to use views pre-rendering instead, especially, since other aspects of this view are getting pre-rendered anyway.

function theme_views_pre_render(&$view) {
   if ($view->name == "summary_details") { //filtering summary entries without detail
      $nids = array(); // array of nodes
      $nodeswithdetails = array(); // manipulated results
      foreach($view->result as $key => $result) // check each node of the result array on it's nid
      {
        $nid = $result->nid;
        $return = theme_ensure_details($nid);
        if ($return == 1) {
           $nodeswithdetails[] = $view->result[$key];
        }
      }
      $view->result = $nodeswithdetails;
   }
}

function theme_ensure_details($nid) {

   $results = db_query('SELECT s.nid AS sum_nid FROM {node} n, {node} s, '
                      .' {taxonomy_index} t, {taxonomy_index} t1, '
                      .' {taxonomy_term_data} td WHERE t.tid=t1.tid '
                      .' AND t.tid=td.tid AND td.vid=14 AND n.type=:dettype '
                      .' AND n.nid=t.nid and s.type=:sumtype AND s.nid=t1.nid '
                      .' AND s.nid= :nid',
         array(':nid' => $nid,':revtype' => 'details', ':reptype' => 'summary'));

    $found = 0;
    foreach ($results as $row) {
       if ($row->sum_nid == $nid) {
       $found= 1;
    }
  }
  return $found;
}


Views 3 List Style CSS Usually, when I make a views block list, and I want it horizontal, I would just add CSS styles to the block itself.

#block-views-something li
{
  display: inline;
  list-style-type: none;
  padding-right: 20px;
}

Having to do this for each block is a pain. I know Views 3 lets me add a class to the view to style the list, but I have never been able to do it. I have tried HTML List, and adding classes to Page: Style options Row class, and Wrapper class or even List class. I have tried it with a dot like .mystyle and without the dot 'mystyle'.

In fact, I just get myself into a right old mess. Could anyone advise me the simplest route to take to add the class to whatever box I should add it to?

The only good way is to use the 'add a class'-option in views. That allows for maximum flexibility and should not break if something in the view changes. (block-view-id-something can break when numbers or names change).

One you have added a css class to the field, something like horizontal. Then you can define it in your theme file css with .horizontal {...}.

But since themes can update their css, overwriting your changes, you are even better off using an extra stylesheet in your themes folder. Give it any name you want, add the .horizontal {...} lines. Then open the *.info file in your theme and add stylesheets[all][] = <stylename>.css.

If it might break after a style update, all you have to do is add this line again.


Setting a header for checkmark in tableselect I am interesting in adding text next to the checkmark in the table #header.

As you can see from the photo there isn't any text there.

My code for the table:

$header = array(
    'campground' => t('Campground'),
    'name' => t('Name'),
    'phone' => t('Phone Number'),
    'message' => t('Message'),
  );

$form['table'] = array(
    '#type' => 'tableselect',
    '#header' => $header,
    '#options' => $options,
    '#default_value' => $values,
    '#empty' => t('No campground to claim'),
  );

Is it possible to add a title next to the checkmark?

I ended up needing to keep the label actually in the correct column, and so went a different route.  I have jQuery available to me as well.

I added an #after_build to my form that would insert some JavaScript:

$form['#after_build'][] = 'mymodule_config_form_after_build';

Then in that function, added:

function mymodule_config_form_after_build($form, &$form_state) {
$data = <<< EOT
  jQuery(document).ready(function(){
        var liveTable = jQuery("#edit-variables table").filter(function() {return !(jQuery(this).css('visibility') == 'hidden' || jQuery(this).css('display') == 'none');}); // Get the right table
        var cb = jQuery("th.select-all input[type='checkbox']", liveTable); // get the right checkbox
        if (cb.length == 1) { // attempt at being smart
            var th = jQuery("th.select-all", liveTable); // Need the table head next
            th.css('width', '15%'); // I found the auto width logic was messing up the table, so I put in this hack to cover my label width
            cb.attr('name', 'form-select-all');
            cb.attr('id', 'form-select-all');
            var label = jQuery("<label for='form-select-all' style='padding: 0px;'>Active Replacement?</label>");
            cb.before(label).detach().prependTo(label); // put the label in and move the checkbox before it

        }
    });

EOT;
drupal_add_js($data, 'inline');
return $form;

The first jQuery filtering is needed because Drupal seems to add a hidden table to help facilitate header handling (???).  I was coming up with too many tables and check boxes.


Field settings are not being exported with Features I have a product content type that has a product reference field. Under the Product types that can be referenced section there is a list of product types that can be referenced. I have selected one of these.
When exporting/importing this content type, the field settings (eg. the selected referenced product) are not exported. How could i export this without selecting the referenced product manually.

The setting got exported but could not be set, because it was referencing an nonexistent product type.

On the old site i had a Recurring Product type w. a "recurring_product" machine name. I wanted to export the display for this. On the new site only a "recurring" product type existed and therefore could not match the setting.


Which search method should I use? I want to add search option to my site but I can't decide what I should use.

I am building a news site. It has a simple structure but in time there will be lot of indexed page. When somebody use the search box, they can search inside news, the categories of the news, and the authors of the news.
The search result page should show all of them like 3 blocks as in this screenshot.

I tried the Search API, but it doesn't provide these.

What should I use? Can you please give me some links for tutorials/documentations. How can I do that?

To make it cleaar, when I type "Marvel" in the search box, the result should include all nodes containing marvel and all tags including marvel (e.g. marvel's movies, marvel's show). I try to show two different blocks per node and tags in the search result page.

To restrict the search you can use the Custom Search module, this module adds options to select:

which content type(s) to search,
which specific module search to use (node, help, user or any module that implements search),
which input type to use (with Elements),
advanced criteria

And if you want modify the search result page you can modify the tpl file search-result.tpl.php


Webform module issue - content type not displaying By accident I deleted the Webform content type in my Drupal 7 installation. It was a complete accident and thought that I was deleting a different content type. I tried going through a couple of tutorials that I saw online but was unable to get the content type back. Does anyone have any ideas on how to do this?

I stumbled across this: http://www.drupalgardens.com/documentation/feature/webforms/recreate which was a small step forward, but it still doesnt work. Has this happened to anyone before? I have tried uninstalling the and re-installing the module, clearing my cashe, and running cron. Still nothing.

Can anyone provide any suggestions? I can't be the only one that this has happened to before and there has to be so sort of fix to this... Also, please note that I am a relatively new Drupal developer.

Drupal can act funny when you start deleting things and then trying to reinstall them. Do you have access to your database?

If so uninstall webform and delete it - then head into your database and delete any webform tables that might still be hanging around.

Dont even try this without backing up your database first though incase you happen to delete anything important.

Then re-install webform.

This is a pretty drastic step and you will lose all data surrounding your webforms.

I have had to do this with other modules that have left tables behind when uninstalled and then they mess when reinstalling said modules.

Once again though if you take this route be careful what you delete.


Add Extra fields in User Form I want to add extra fields during user registration. I don't Understand Where I can access to user form and user twig, because I want to validate and reformat the Form.

My background is symfony, and I expect The model if I want to add some properties ( in drupal maybe is entity ) and the twig ( the view Parts ), Instead here I don't know where is the user form.

I'm trying to create the module and use some hook, but I don't know if the right way to customize the form

You can go to configuration -> account settings -> manage fields and add your field. then in the settings check it to show in registration form

admin/config/people/accounts/fields


Module not found via Composer I recently switched to drupal_composer to manage my dependencies and updates. And so far I can really see the benefit of this work method, and highly encourage everyone to switch.

However, I tried installing the module Simple Oauth, but composer can't find it.

$ composer require "drupal/simple_oauth:^2.0-alpha4"
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package drupal/simple_oauth could not be found in any version, there may be a typo in the package name.

Potential causes:
 - A typo in the package name
 - The package is not available in a stable-enough version according to your minimum-stability setting
   see <https://getcomposer.org/doc/04-schema.md#minimum-stability> for more details.

Read <https://getcomposer.org/doc/articles/troubleshooting.md> for further common problems.

Installation failed, reverting ./composer.json to its original content.

When browsing composer, nothing is found either.

$ composer browse drupal/simple_oauth
Package drupal/simple_oauth not found
Invalid or missing repository URL for drupal/simple_oauth

Is this due to the alpha release not being published or something?

It doesn't say the module was not found, it says there is no compatible version.

My composer version gives a much better error:

$ composer require "drupal/simple_oauth:^2.0-alpha4"
./composer.json has been updated
> DrupalProject\composer\ScriptHandler::checkComposerVersion
Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - Conclusion: remove drupal/core 8.2.3
    - Conclusion: don't install drupal/core 8.2.3
    - drupal/simple_oauth 2.x-dev requires drupal/core ^8.3 -> satisfiable by drupal/core[8.3.x-dev, 8.4.x-dev].
    - drupal/simple_oauth 2.0.0-alpha4 requires drupal/core ^8.3 -> satisfiable by drupal/core[8.3.x-dev, 8.4.x-dev].
    - Can only install one of: drupal/core[8.3.x-dev, 8.2.3].
    - Can only install one of: drupal/core[8.4.x-dev, 8.2.3].
    - Installation request for drupal/core (locked at 8.2.3, required as ~8.2.0) -> satisfiable by drupal/core[8.2.3].
    - Installation request for drupal/simple_oauth ^2.0-alpha4 -> satisfiable by drupal/simple_oauth[2.x-dev, 2.0.0-alpha4].

2.0-alpha4 requires Drupal 8.3. Leaving out the version specifier installs it as "1.0.0-beta5", which is however not listed anymore on the project page and therefore probably not really supported anymore.

8.3.0 will be released pretty soon, so if this is a new project, you could already switch to the recently released 8.3.0-rc1, there will likely only be very few changes until 8.3.0. See https://www.drupal.org/core/release-cycle-overview


What is a "Variant" in Drupal? I tried to read a bit about what is actually a Variant in Drupal (and especially in Ctools).

But the 2-3 explanations I read were not clear enough for me. It was a wired experience for me since I've already learnt some "similar" Drupal unique terms such as Drupal argument, Contexual filter, Page (Drupal), Entity, Node, etc.

So what is a Variant and why do we need them? Please use the simplest explanation you can.

"Variants" are typically used / related to "Page Manager", which is part of the CTools module. The "simplest explanation***" is ... not "simple" to provide. However there is an interesting (amazing?) video intro about it: refer to Learn Page manager! Part 3: Variants and selection rules.
While you're at it, you may want to look at the entire (impressive) video series around there, i.e. Learn Page manager!. Here is a summary of the entire set of videos about this topic:

Page manager allows you to collect and manage contextual information in a flexible and consistent way. It is an important part of building infrastructure on Drupal websites, and you should know how to use this module.
The screencast series is targeted at experienced Drupal developers.
Episodes 1, 2 and 3 introduces the most basic concepts, such as custom pages, variants, selection rules and (to some extent) contextual objects.
Episodes 4, 5, 6 and 7 talk about Panels, with emphasis on Views integration but also some words on efficient caching.
Episodes 8 and 9 about access control, menu items, and not least the little-known but very useful Contextual Administration module.
Episodes 10 and 11 talks more about using contextual objects in Page manager, including using Views as context. This is, imho, where the real power in Page manager is.
Episodes 12 and 13 collects various bits and pieces, such as how to use Panels to easily rearrange the node edit form, import/export settings, and some extra modules that can be used with Page manager.

Some more recommended (free) tutorials that you may want to consider, and which will help a lot to understand the typical Drupal terminology in your question:

The 32 (!!!) great video tutorials Learn the Rules framework, organized in 7 chapters, about the Rules module.
A similar set of 8 video tutorials about the Flag module.
The set of 30 video tutorials about the Views module.

In Drupal 8, Page Manager has become a separated module, while formerly (up to Drupal 7), it was part of the CTools module. Here are some more quotes from the (D8 related) project page:

It supports the creation of new pages, and allows placing blocks within that page.
Like Drupal 7's Page Manager, it provides a concept of "page variants", each with their own selection conditions.
Additionally, it can be used to take over an existing page, like overriding /node/% to change what is displayed when viewing a node.
It utilizes the core Conditions, Context, and Blocks APIs to accomplish this.

So that's part of the changes coming up in the CTools module in D8.


Drupal path prefix based node content I'm new to Drupal and have a basic question which I cannot find a good answer to. I have already posted this at Stack Overflow but still am hopeless. I am trying to dynamicly determine the contents of my website based on a selection made by the user and keep the selection displayed in the routing for SEO purposes.

In other words I want to a path prefix which I can use as a variable to display nodes specifically for that franchise. My content types have multiple CCK references to content types Franchise and I want to base my selection on the location inside my content type franchise.

It's a website for a Restaurant with multiple franchises.

What i'm trying to do is the following:

The user visits my website and gets a splash screen presented with the available franchises or a textbox to enter his postalcode
Upon selecting he enters the main website with the navigational structure adapted to that particular franchise only. The selected Franchise city should remain inside of the url structure. Nodes should not be made available without the city inside of the url. For example: domain.com/city/, domain.com/city/menu, domain.com/city/menu/dishes, domain.com/city/contact, ...
The contents of all nodes are based upon the city the user selected. Some franchises have extra nodes which should be displayed in the main navigation aswell. The contents of the views and panels should automaticly be adjusted to that particular Franchise aswell.
Users can change the selected franchise by clicking on a main link which links back to the splash page.

What I have found so far which might be part of the solution is:

Purl
Context
Spaces

Parts of the nodes will be the same for all franchises other parts will be different. Menu item prices will also be different.

This is the first website i'm building using Drupal so any advice is welcome.

Thanks!

What you want, is not (simple) with only views and CCK. That is because both lack a system for persistence in filters and arguments.

I can advise you to add a new module to your stack: Domain Access. This is a large module, which is not simple to configure right, but it sounds like it is the exact solution to your problem. It will allow you filter content, based on the domain (franchise) it is posted into.

The mayor concern with this module is its complexity. The second concern would be its use of Drupal's content access hooks and system. Modules like Domain Access, i18n, Organic Groups all use this system, which has very severe penalties for performance. IOW: Domain Access, or any access-module, will make your site notably slower and less performant.


Using Contextual Filters to Filter "Content: Published" Is there any solution to filter "Content: Published" with Contextual Filters?

Out of the box I don't believe this is available. I have a similar use case however I am also using Workbench Moderation. I'm using the moderation state as the contextual filter and using setting a standard filter of current revision as true. This allows you to target a specific moderation state in your view, published being one of them. It could get irritating if you end up with a lot of moderation states and have to target each of them specifically but my use case requires me to get either just published, or all content regardless of published or not.


What permission restricts access to run updates in Drupal 7? I have a role in my Drupal site that I don't want to access the Drupal database updates.  I can't seem to find the permission for "Run updates".  What permission restricts access to this page (update.php)?

The permission is Administer software updates


Views JSON entity reference fields I have a page content type with fields Title, Body and Blocks field collection with fields Title and URL.

It might be field collection, paragraphs or entity reference, it doesn't matter because all of these types require relationship in views in order to get its fields.

I need to generate a JSON output with views that look like this:

{
  'title': 'This is my title',
  'body': '
lorem ipsum dolor sit amet.
',
  'blocks': [
    {
      'block_title': 'Block one',
      'block_url': 'www.example.com'
    },
    {
      'block_title': 'Block two',
      'block_url': 'www.site.com'
    },
  ]
}

What I managed to achieve so far, is this:

[
  {
    'title': 'This is my title',
    'body': '
lorem ipsum dolor sit amet.
',
    'block_title': 'Block one',
    'block_url': 'www.example.com'
  },
  {
    'title': 'This is my title',
    'body': '
lorem ipsum dolor sit amet.
',
    'block_title': 'Block two',
    'block_url': 'www.site.com'
  }
]

This is Drupal 8. Any suggestions?

The data structure you want does not fit with what Views is supposed to provide. Views is intended only for generating lists. 'title' and 'body' are assumed to not be part of a list, so views has no configuration for defining single hardcoded values, and goes against how views works.

Your other option is to create a custom route with a node parameter (example) that returns a JsonResponse object with populated blocks property. So your code may look something like this (based on route parameter example above):

use Drupal\node\NodeInterface;
use Symfony\Component\HttpFoundation\JsonResponse;

class ExampleController {
  function foo(NodeInterface $node) {
    $response = [
      'title' => $node->label(),
      'body' => $node->get('body')->first()->getValue(),
    ];

    $blocks = [];
    $block1 = $node->get('block')->get(0)->get('entity');

    $blocks[] = [
      'block_title' => $block1->label(),
      'block_url' => $block1->toUrl()->toString(),
    ];

    /* ... add the rest of the blocks ... */

    $response['blocks'] = $blocks;

    return new JsonResponse($response);
  }
}

The code will need to be adjusted according to your entity field setup.


file_save_data doesn't save image I'm using Drupal 7.56..
I want to upload images from other urls..
I use:

$image_original_path = '.. here my original path..';
$my_destination = 'sites/default/files/images/';
$my_new_name = 'my_image.jpg';
$filename = $my_destination.$my_new_name;
$image_object = file_get_contents($image_original_path);
$file = file_save_data($image_object,  $base_url.'/'.$filename, FILE_EXISTS_RENAME);

But the image is not uploaded..
Any idea please?
Thank you..

Updated:
Try with this code:

$image_original_path = '.. here my original path..';
$image_object = file_get_contents($image_original_path);
$file = file_save_data($image_object, file_default_scheme().'://'.basename($image_original_path),FILE_EXISTS_RENAME);
// Add this code also
if (is_object($file)) { // if you get back a Drupal $file object, everything went as expected so make the status permenant
  $file->status = 1;
  $file = file_save($file);
}


Import URL Alias with Node I'm using ne-impot and ne-export with drush for importing and exporting nodes. When exporting, as part of the uuid module, the URL alias is included with the export. However, when importing a node, the alias is not kept. I have tried using another custom module (https://github.com/kapasoft-config-scripts/designssquare_alias_path) that I found from this site: http://margotskapacs.com/2014/04/solving-menu-import-issue-when-featuring-sample-data-in-drupal, but that doesn't seem to be working either. Does anyone know of a way to import and export a URL alias along with the node from the command line? Thanks!

Try the Pathauto module to do this. I found it helpful for auto-aliasing URLs in bulk, and you can also customize it by using

function MyModule_pathauto_alias_alter(&$alias, array &$context) {

}

it works pretty well.


Modules/Methods for Faster Data Entry I have an unlimited-cardinality text field on a node that users need to enter 50-100 values on.  Right now, the user has to type in one value, click "add another item", and then click inside the text field to start the process again.

Is there a module or a way to enable them to simply hit "Enter" after entering the first item, that will automatically open the next text entry area and move the cursor inside it?

This particular solution was a custom form, where I had fine control over the CSS classes applied to the different elements, but it might also work for node-edit et al.

You would use hook_form_alter() to target whichever form you want.  Then, you would add a custom CSS class and an '#attached' property to that form element, containing a 'js' element which would point to a custom javascript file within your module.  The code in this file would watch elements of that CSS class for when a user hit 'tab', and then automatically click the 'Add More' button for you.  JS added below for reference:

(function ($) {
  Drupal.behaviors.formAutoTab = {
    attach: function (context, settings) {
      $('.othercustomclass').focus();
      $('.customclass').keydown(function (event) {
        if (event.keyCode == '9') {
          $('input[type=submit][id^=addbuttonidgoeshere]').mousedown();
          event.preventDefault();
        }
      });
    }
  }

})(jQuery);

The trick is .othercustomclass which you will need to refocus on the new element after it's added.  I think core Drupal does apply some sort of 'ajax-processed' class or something else to the fields added by the 'Add More' button, which you might be able to use as the jquery selector.


Default File Display is Using Incorrect Image Style I'm using Media-7.x-2.0-beta1. When adding an image with the default file display (default file display is identical to Original), it uses the "Medium" thumbnail display. I've checked to make sure the default is not configured to this display.

Where would these settings be saved that I could double check to make sure they were actually changed when I altered them? Is there any other reason for the Default display to be displaying the image in the wrong image style?

After some search, I got your issue and from where you can set that. So I delete my previous answer and following is the updated one.

As in my setting, I have four Image settings,

Default
Teaser
Preview
Wysiwig

Now, by default it is taking some height and width.

Now those all four setting you can change at Admin/Structure/File types/Images/Manage file Display and you can find all four image file set on right hand top corner in following images. Now, you can see as I have selected Default and at bottom of the page it is showing None(original image).

Note: Now, image uploaded in the body field area before save/post of the body content may not show what you have selected, but if you post it it will show what you image style you had selected. As stated in following image.


Move views pager to top of node instead of bottom Is there a simple way to move views' pager to a different place than the default bottom?

Go to the View UI. Click Theme: information. The top list item will say Display output. There are several file names to go from the least specific to the most specific. These are the choices to override the default View template for Display output. If you want every view pager to be at the top choose views-view.tpl.php otherwise choose something more specific.

Create a file in your theme folder titled with one of these title options. Click the blue Display output link and copy the code into the file you just created. Save. Clear cache. Congratulations you have now overridden the View theme template.

Find the code

  <?php if ($pager): ?>
    <?php print $pager; ?>
  <?php endif; ?>

and move it to the top of the code where you want the pager to be. Save.


How to place the language switch in the main menu bar? The language switch appears on the bottom of the page.
How can I move it to the main menu?

Check your page.tpl file and check where it is, OR, you can check the list of blocks in your site to see where it is placed and move it to your desire position


Image style settings for scaling an image What settings can I use for the image style module that will make all thumbnails in a gallery  of a consistent width and height? Thus, if an image's width is smaller than the thumbnail width when scaled, the width of the thumbnail remains consistent.

Have you tried the Scale and crop option ? Go to admin/config/media/image-styles/add add a new style and then select Scale and crop with, for example, 100px width and height. This will produce some square thumbnail with 100px sides.


How add CVV's custom validation before order review in Ubercart I'm developing a Gateway Payment module for Ubercart. It is necessary to validate that the User does not digit three ceros -000- (bank policy) before the order review form. I've seen that Ubercart does the CCV's validation in the uc_credit.module

      if (variable_get('uc_credit_cvv_enabled', TRUE) && !_valid_cvv($cc_data['cc_cvv'])) {
        if (!$silent) {
          drupal_set_message(t('You have entered an invalid CVV number.'), 'error');
        }
      $return = FALSE;
      }

How could I add my validation without hacking Ubercart modules.

Thanks in advance.

You can create a custom validation function in your module and name it whatever you like for example 'custom_validation_function'. and in the same module add this validation function to the form's validation list by using form_alter.

function <module_name>_form_alter(&$form, &$form_state, $form_id) {

  if ($form_id == '<ubercart_form_id>') {
    $form['#validate'][] = 'custom_validation_function';
  }
}


Pass Preprocess Values From Custom Module to Custom Form My use case:

I would like to create a unique textfield per region in a custom form.

MYMODULE/MYMODULE.module:

function MYMODULE_preprocess_region(&$variables) {

    foreach (array($variables['elements']['#region']) as $key) {
        drupal_set_message($key);
    }

}

MYMODULE/src/form/MyModuleForm.php:

protected function getEditableConfigNames() {
    return [
        'module_config.module_config_settings',
    ];
}

public function buildForm(array $form, FormStateInterface $form_state) {

    $config = $this->config('module_config.module_config_settings');

    //build this...
    $form['region_name'] = array(
        '#type' => 'textfield',
        '#title' => t('Form Item Title),
    );

    return parent::buildForm($form, $form_state);

}

What is the appropriate way to pass variables/info from the .module file to the .form?

*Note: I have a fully functioning form, hopefully I am showing enough of it to illustrate my focus.

It seems that you can get the list of blocks from this answer: How do i get the all the regions available in the current theme programatically?

MYMODULE/src/form/MyModuleForm.php:

protected function getEditableConfigNames() {
    return [
        'module_config.module_config_settings',
    ];
}

public function buildForm(array $form, FormStateInterface $form_state) {

  // Get the block list based on previous Q/A
  $theme = \Drupal::theme()->getActiveTheme()->getName();
  $system_region = system_region_list($theme, REGIONS_ALL);

  foreach ($system_region as $region) {
    $form[$region . '_title'] = [
      '#type' => 'textfield',
      '#title' => t('Form ' . $region . ' Title'),
    ];
  }

  return parent::buildForm($form, $form_state);
}


How to let the user enter the price for particular product in Commerce Kickstart? I have installed Commerce Kickstart (version 7.x-2.25).

I have to set the price as 100 Rs. At the same time user will enter an amount above 100rs.

Is there any option for the user to enter the price and go to cart and checkout page?

I guess you're looking for Auction

  An auction is a process of buying and selling goods or services by
  offering them up for bid, taking bids, and then selling the item to
  the highest bidder.

Check Commerce Auction module

  This module lets you create auction/reverse auction websites using
  drupal commerce.


How to use access callback and access arguments to restrict access by role? I'm creating website for a hostel, in this there are two roles (guest and property owner).

if i give 'access callback' => TRUE the page can be accessed by both of the property owner and guest, but i don't need it, the page should be accessed by only property owners.

The callback is, well the callback; the function that will be run to determine access for the path.

The arguments are the arguments provided to that function for context. They can be static, or come from parts of the URL (not query params).

What you need to do is instead of TRUE, provide the name of a function which determines whether the current user is a "property owner", and return TRUE or FALSE from that function to allow/deny access respectively.

The common way to achieve that for role-based access is to use hook_permission to provide your own permission to the system, call it "access top secret area" or whatever, grant the new permission to the property owner role through the UI, and change the access arguments to an array containing that new role.

The default access callback is user_access, so it will have the effect of running

$access = user_access('access top secret data');

Obviously if you need more advanced logic, e.g. to determine that a property owner is accessing only data on a property they actually own, a custom callback will make more sense.


How do you print the view name on a "view page"? I have set up a custom template for my new view and need to print the views title at the top of the page. What is the best way to do this?

This should normally just work. What do you mean by "custom template", did you make a .tpl.php file? What .tpl.php did you use?


how to make multiple ajax callbacks from a drop-down field? I have a select field in my custom module (Drupal 7), which needs to refresh the values of 2 different field types when a value is selected, firstly a checkbox field, which currently is refreshed correctly when am changing the dropdown value, and a text field, which is not changing, as it keeps the value from the first dropdown option by default.

Samples of my codes:

$form['webform_name'] = array(
'#type' => 'select',
...
#ajax' => array(
  'event' => 'change',
  'callback' => 'ajax_checkbox_callback',
  'method' => 'replace',
  'wrapper' => array('checkboxField','txtField'),
)

$form['checkboxField'] = array(
'#type' => 'checkboxes',
...
'#prefix' => '
',
'#suffix' => '
',

$form['txtField']=array(
'#type' => 'textfield',
...
'#prefix' => '
',
'#suffix' => '
',

function ajax_checkbox_callback($form, &$form_state) {
    return array(
    '#type' => 'ajax',
    '#commands' => array(
    ajax_command_replace("#checkboxField", render($form['checkboxField'])),
    ajax_command_replace("#txtField", render($form['txtField']))
    )
  );
}

How can I make the txtField field to clear and load the corresponding value every time I change my drop-down values?

In your ajax_command_replace where the form is rendered, do this: ajax_command_replace("#checkboxField", render($form['checkboxField']['values']=$text)), where $text is the value from the checkboxes, as shown below:

function ajax_checkbox_callback($form, &$form_state) {
    return array(
    '#type' => 'ajax',
    '#commands' => array(
    ajax_command_replace("#checkboxField", render($form['checkboxField']['values'] = $value_text_form_text_field_1)),
    ajax_command_replace("#txtField", render($form['txtField']['values'] = $value_text_form_text_field_2))
    )
  );
}


How to display tabbed menu, created via hook_menu? I am fairly new to Drupal and still figuring out its inner workings.
Currently, I am playing around with creating own modules. I want to create a tabbed menu via hook_menu and display it. Unfortunately, I seem to fail here. I lack the understanding how to activate the coded menu in the hook on one of my pages. Since I do not define a block (and with such have no hook block_info or block_view in my module), I am not able to place my module via the structure menu anywhere. And by itself, the tabbed menu does not show up anywhere. My module is available in the modules' list and I can activate and deactivate it. I also cleared all caches, but I can't seem to find it anywhere.
Hence, my question is: how do I activate and place the menu on my site?

My module has the two files dummy_module.module and dummy_module.info.

dummy_module.module:

/**
 * Implements hook_menu().
 */
function dummy_module_menu() {
  $items = array();
  $items['dummy'] = array(
    'title' => 'dummy_module',
    'page callback' => 'temp_output',
    'access callback' => TRUE,
    'weight' => 1
  );
  $items['dummy/new_tab1'] = array(
    'title' => 'Current 1',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'page callback' => 'temp_output1',
    'weight' => 2
  );
  $items['dummy/new_tab2'] = array(
    'title' => 'Current 2',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'temp_output2',
    'weight' => 3
  );

  return $items;
}

function temp_output() {
  return 'Hello world!';
}

function temp_output1() {
  return 'Hello world 1!';
}

function temp_output2() {
  return 'Hello world 2!';
}

dummy_module.info:

name = Dummy Module
description = This is a dummy module and hence the basis for all further module development.
core = 7.x
files[] = dummy_module.module

Alright, I found the problem: my tabs definitions were lacking the extra line

'access callback' => TRUE,

With this line in each tab definition, the tabs show up as extected.
Here is my final code for dummy_module.module:

<?php

/**
 * Implements hook_menu().
 */
function dummy_module_menu() {
  $items = array();
  $items['dummy_module'] = array(
    'title' => 'dummy_module',
    'page callback' => 'temp_output',
    'access callback' => TRUE,
    'weight' => 30
  );
  $items['dummy_module/new_tab1'] = array(
    'title' => 'Current 1',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'page callback' => 'temp_output1',
    'access callback' => TRUE,
    'weight' => 1
  );
  $items['dummy_module/new_tab2'] = array(
    'title' => 'Current 2',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'temp_output2',
    'access callback' => TRUE,
    'weight' => 2
  );

  return $items;
}

function temp_output() {
  return 'Hello world!';
}

function temp_output1() {
  return 'Hello world 1!';
}

function temp_output2() {
  return 'Hello world 2!';
}


SEARCH API + VIEW to search members I have a website in Drupal version 7.28. I have page where i want to search members by using Search option created from VIEW. It goes like this after submission:

https://domain.com/search-members?search_api_views_fulltext=anything

This page and functionalty was working fine few days back but not now. Page is blank without any error. There is result in database.

I can understand above info might not be sufficient to help but my only question is:

What can cause a blank page without an error? Possible problems?

Here is the updated ERROR MSG:

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'aeeee01_drpl21.search_api_db_user_index_field_business_phone' doesn't exist: SELECT COUNT() AS expression FROM (SELECT 1 AS expression FROM (SELECT t. FROM {search_api_db_user_index_field_business_phone} t WHERE (word = :db_condition_placeholder_0) UNION ALL SELECT t.* FROM {search_api_db_user_index_field_city} t WHERE (word = :db_condition_placeholder_1) UNION ALL SELECT t.* FROM {search_api_db_user_index_field_country} t WHERE (word = :db_condition_placeholder_2) UNION ALL SELECT t.* FROM {search_api_db_user_index_field_department} t WHERE (word = :db_condition_placeholder_3) UNION ALL SELECT t.* FROM {search_api_db_user_index_field_first_name_} t WHERE (word = :db_condition_placeholder_4) UNION ALL SELECT t.* FROM {search_api_db_user_index_field_job_institution} t WHERE (word = :db_condition_placeholder_5) UNION ALL SELECT t.* FROM {search_api_db_user_index_field_job_title} t WHERE (word = :db_condition_placeholder_6) UNION ALL SELECT t.* FROM {search_api_db_user_index_field_last_name} t WHERE (word = :db_condition_placeholder_7) UNION ALL SELECT t.* FROM {search_api_db_user_index_field_member_advisor} t WHERE (word = :db_condition_placeholder_8) UNION ALL SELECT t.* FROM {search_api_db_user_index_field_specialization} t WHERE (word = :db_condition_placeholder_9) UNION ALL SELECT t.* FROM {search_api_db_user_index_field_state} t WHERE (word = :db_condition_placeholder_10) UNION ALL SELECT t.* FROM {search_api_db_user_index_field_zip_code} t WHERE (word = :db_condition_placeholder_11) UNION ALL SELECT t.* FROM {search_api_db_user_index_name} t WHERE (word = :db_condition_placeholder_12) ) t GROUP BY t.item_id) subquery; Array ( [:db_condition_placeholder_0] => mlang [:db_condition_placeholder_1] => mlang [:db_condition_placeholder_2] => mlang [:db_condition_placeholder_3] => mlang [:db_condition_placeholder_4] => mlang [:db_condition_placeholder_5] => mlang [:db_condition_placeholder_6] => mlang [:db_condition_placeholder_7] => mlang [:db_condition_placeholder_8] => mlang [:db_condition_placeholder_9] => mlang [:db_condition_placeholder_10] => mlang [:db_condition_placeholder_11] => mlang [:db_condition_placeholder_12] => mlang ) in SearchApiDbService->search() (line 928 of /home1/aeeee01/public_html/sites/all/modules/search_api_db/service.inc).

You can look into this :
https://api.drupal.org/api/drupal/includes!database!database.inc/function/db_query/7#comment-7019

https://api.drupal.org/comment/51338#comment-51338

https://api.drupal.org/comment/16974#comment-16974

And check if you made change in your taxonomy vocabulary, deleting any fields that the search would index in the views.

You can also re-index your user.


Is there an accordion-style menu module? I have been searching high and low for a module that integrates an accordion-style menu system in D7, similar to http://drupal.org/project/accordion_menu. Anybody know of one?

DHTML Menu is great and it should work for what you need. I haven't used the 7.x version yet but they have a stable release. Here is an excerpt about it from the module's project page:

... uses Javascript to reduce the number of page loads when using nested menus; this is particularly useful with Drupal's administration system.
Ordinarily in Drupal, in order to see the sub-items in a menu, you need to click the link of this item and wait for a full page load. After enabling DHTML Menu, clicking a menu link once will expand it to reveal its sub-items without reloading the page. A double-click on the item will load the page normally. Additionally, a cookie stores which menus are open and which are closed, so that the state of the menus remain consistent as you navigate around the site.


cck delta values: delta with leading space = "historical change," no leading space = "multiple selection?" One of our sites began exhibiting a periodic bug where users would try to save their profiles and get an error about an illegal value in one of the fields (a cck field for "industry," fwiw, that we disabled by removing edit permissions for it a month ago). The field has a number of possible values as checkboxes, so users were able to pick more than one when the field was available to them for editing, prior to us disabling it.

We noted that admin users could save the profiles, and that they would then begin to be savable by users with normal privileges.

We zeroed in on the content_field_industry table, and began running through cases with assorted users before we finally figured out that field records with multiple deltas sometimes suffered from the issue, but other times didn't. After more digging around, we finally observed that:

if the record had more than one delta and values in the field_industry_value column had a leading space, the record would fail to save for normal users
if an admin user saved the user profile, any delta records with a leading space in the field_industry_value column would be destroyed and the profile would become editable by a normal user
if the record had more than one delta and the values in the field_industry_value column had no leading spaces, normal users could edit their profiles with no error

We don't want to lose the data, but we don't want it to be edited by normal users anymore, either, and we don't mind the thought of losing meaningless deltas (the ones that serve a historic purpose rather than a "this is a multiple selection" purpose).

Is there a safe way to clean up this issue, perhaps by simply deleting leading-space deltas?

Use a custom module and unset the field items using hook_form_alter(), or do it in your themes template.php.

/**
* Implements hook_form_alter().
*/
function YOUR_THEME_form_alter(&$form, &$form_state) {
  if ( $form_id= 'YOUR_FORM_ID' ) {
    unset($form['YOUR_FORM_FIELD']);
    // ... ADD MORE
  }
}


how to put permission to only paid users can print something in my drupal site I have a Drupal site which I plan on putting a print pdf function to its contents. How do I manage this so that only paid users can print the pdf?

If you mean controlling who can view/download (i.e. be 'served') the PDF then you need to read up on the private file system (Working with files contains a pretty good introduction).

If you mean showing the PDF to anyone who requests it, but only allowing paid users to print from it, you can't. That would be controlling a user's browser, which you can't do for obvious security reasons. It's the nature of the web; if you want to distribute content, you have to face the fact that it can be copied unless you go down the DRM route.

The only DRM solution I know of for PDFs is Adobe Content Server; it's written in Java and is a real pain in the proverbial but it does work. You can control the number of times a person can print or even copy/paste data from the PDF.

It does introduce a really annoying workflow, though, that you'll need to explain in detail to your users; and it ain't cheap.


Getting image URL and rewrite results for Views Module I have a Content Type of only an Image field and I am using Views module to create a view for it as in follows

Using Image URL Formatter module I was able to get the image absolute URL, but using the following "rewrite rule" in Views

It outputs the URL wrapped in a

or

tags, how can I possibly get the pure text URL for this image?

Views does reject having style attributes to any of the html elements even though the style attribute is explicitly included in rewrite results of any field in the view.

The reason and workaround maybe found here: Rewrite results strips some html attribute

My recommendation is, you can write tpl for that particular field and use the output text (which will be the url in your case) to build the div or any html element around it.


Output xml feed data into view I have an xml feed and i want to display it with a view.
I have created a content type with the fields that are in the feed but how can i tell the view to get the data from this feed. I don't want to insert my feed data into the database. How can this be done programmatically? Maybe from the theme section in views? Maybe with some hooks like hook_views_data_alter?
Any help would be much appreciated.

Thanks

So i solved it. In hook_views_pre_render i added something like:

if($view->name=='property_list'){
// ..got the xml , processed it
// and in the folowing array I added; of course field_address is an item in a content type
$view->result[$i]->field_field_address[0]['rendered']['#markup'] = $child->address;
// if i wanted the field to be a link, then altered this array item
$view->result[$i]->field_field_address[0]['rendered']['#path']['path'] = 'property-detail?id='.$child->ID;
}

The link pointed to another view where the detailed property was shown;


DDEV php/twig error "Unknown "link_attributes" filter." So I'm trying to setup a local environment with ddev for the first time. I got it running, cloned my live files with git and imported my DB.
Site ain't working and got this in the log : "PHP message: Uncaught PHP Exception Twig\Error\SyntaxError: "Unknown "link_attributes" filter." at /var/www/html/web/themes/customs/myTheme/templates/menu--main.html.twig
Any pointer how to fix that ? I did :

ddev exec drush en link_attributes
-> [notice] Already enabled: link_attributes

This site with the same file/db is working on 2 VPS. What's going on ?

It was an module identification problem. I thought it was the link_attributes modules but the error is from twig_link_attributes. That one didn't download cause it's a git submodule or something... Anyway that folder is empty.


Embed a View into a render array In Drupal 7, I used the following code implementing views_embed_view in a render array.

  $view_output = views_embed_view($view_name, $display_id, $uid);

  $page['profile']['bio_mobile'] = array(
    '#type' => 'markup',
    '#markup' => $view_output,
    '#prefix' => '
',
    '#suffix' => '
',
  );

How do I do that using Drupal 8?  Although the function is still documented, it return nothing more than just the array I passed in.

Indeed, #markup only allows string, but you can by using a block type

$view_output = views_embed_view($view_name, $display_id, $uid);

$page['profile']['bio_mobile'] = array(
  '#type' => 'block',
  'content' => [
    'system_main' => $view_output,
   ],
  '#prefix' => '
',
  '#suffix' => '
',
);


how to change the widget of view's exposed filter form? I have an exposed filter form, and its default widgets are textfields. I'd like to change them to selects based on values from database.
I have tried hook_form_alter and hook_form_views_exposed_form_alter, but get an error:

An illegal choice has been detected. Please contact the site administrator.

The code I used to change the widget is like this and I've tried #validate option.

$form['field_address_province'] = array(
        '#type' => 'select',
        '#options' => $province_options,
        '#validate' => true,
        '#description' => 'Select address',
    );

Edit:

Sorry for the lack of infomation.
The $province_options is an array like

Array
(
    [0] => Please Select
    [6] => Area1
    [7] => Area2
    [2] => Area3
)

i tested this kind of thing and found that when you try to switch a exposed widget field you need to provide an array with the empty first key, if it is checkboxes or radios; if new widget will be a select then you need to provide an array with the 'All' first key. E.g.:

//Suppose that you have a default input widget which you want to change to select widget.
//We will get the values which we want our new select widget will get as options:
$opts = array(
  'first_key' => 'First value',
  'sec_key' => 'Second value',
);

// Then we will add required 'All' first key:
$options = array('All' => 'Choose a value') + $opts;

// Then we will create our new select widget
$form['YOUR_FIELD_NAME'] = array(
     '#type' => 'select',
     '#title' => t('MY TITLE'),
     '#options' => $options,
   );


How do i disable price, shipping and payment in ubercart I need to set up a "shopping cart" to allow users to collect URLs from my local database. All my products are free. Based on which URLs are in the users "basket" I fetch files and pack them in a tar file and send the user a URL where the tar file can be downloaded.

How can I turn off or hide price, payment and shipping in ubercart?

You can use UC Price Visibility Module.

  Often, you want to advertise your products without revealing the prices, and show something
  like, "contact us for pricing." This Ubercart module allows you to show or hide product pricing per role, on a product-by-product basis. You can configure what message should be shown when the price is hidden, and which field should be replaced with this message (either the display price, sell price, or add to cart button).


how to display all content for the people table How does one display all the data in the people table in a SQL or other statement? I would like to get a complete listing of the table(s).

There is no table {people} in the database.  However, the way I understand this question, you want to display everything that is recorded about all user entities (i.e. you want the list of user entities that is shown under People in the admin interface expanded to include all the fields attached to such entities).

In that case, you can install the Views project and enable the Views and Views UI modules (both part of the Views project). The recipe below assumes you're using Views 3 on Drupal 7. Older versions are different.

Navigate to Home » Administration » Structure » Views and click Add a new view. Give the view the name "Users", and select "Users" from the Show pull down menu.  Click Save & Exit.  This will give you a page view showing all users, but no fields.

Now, return to Home » Administration » Structure » Views, locate the view named "Users", and click Edit.

Next, locate the "Fields" widget, and click Add.  Filter on "User".  This will show all fields defined for the user entity (except pass), with a checkbox for each.  Check all boxes and click Apply (all displays).  Now you've get to configure how to show each of the fields.  You can of course do a lot of fine tuning here, but I find it better to do that later, after the view is fully populated with fields. So just click Apply (all displays) to each of these.  AFAIK, this gives you access to all the fields in the user entity except pass (which holds the user's hashed password, and is excluded for security purposes).

After you've added all, there will be a preview at the bottom of the page.  At this stage, the listing will not be pretty, but you can fine-tune how this appears later, by editing the format of the view.

When done editing, remember to click Save (near top of screen) to save the view.

If your objective is to export this data, there are deveral modules let you export lists produced by Views. One of these is Views Data Export.


page which display only $content (no header,footer,sidebars) I wanted to show a page which displays only $content. I successfully got the output when I used this code in template.php inside my theme.
function THEMENAME_preprocess_page(&$vars) {
  if (isset($_GET['ajax']) && $_GET['ajax'] == '1') {
    $vars['template_file'] = 'page-ajax';
  }
}

In page-ajax.tpl.php, I used the following code.
<?php
  echo $content
?>

Is there anyway to achieve the same thing using a custom module?
update
I think you all misunderstood my question, i want to override page.tpl with only $content, Not how to create a tpl using hook_theme!
Currently i have used the same code in my module, but the problem is i have to manually copy page-ajax.tpl to my active theme directory. You can refer the module i created http://drupal.org/project/ajax_links_api

Drupal works its way down a function call stack to find and use hooks defined in other places. So, in much the same way that THEMENAME_preprocess_page() works, so does MODULENAME_preprocess_page - See http://drupal.org/node/223430 for the specific order that these preprocess functions are called.

Now, as for setting up the template. You define it using http://api.drupal.org/api/function/hook_theme - As an example from the block module:

function block_theme() {
return array(
'block' => array(
      'render element' => 'elements',
      'template' => 'block',
    ), // Omitted remainder.

Notice the 'template' attribute. That maps to block.tpl.php. So assume the following:

function myModuleName_theme() {
return array(
    'my_themehook_special' => array(
        //notice I am setting this up to look for the file in a subdirectory of the module
        'template' => 'moduleSubdirectory/filenameOfTemplate',
        'arguments' => array('yourArgumentObject' => null),
    )
);
}

That would register your template. Check out this blog post for more: http://www.trevorsimonton.com/blog/tplphp-hooktheme-drupal-variable-template-module


Admin toolbar default left / vertical On page load I need to

show the toolbar on the left / in vertical mode when in admin theme
collapse/minimize the toolbar when in frontend theme

I'm looking for the event and the function to trigger those actions programmatically, e.g. something like

$(document).on('toolbar.loaded', Drupal.toolbar.setOrientationLeft);

and

$(document).on('toolbar.loaded', Drupal.toolbar.closeToolbar);

(I'm using the Admin Toolbar plugin)

Please note that I'm looking a solution that does not check CSS classes or triggers DOM clicks, in order to avoid timing problems due to asynchronous loading or exisiting toolbar settings.

If you go through its possible to make it as horizontal. Try this code wherever needed:

jQuery('#toolbar-bar button').each(function(){
  if(jQuery(this).html() === 'Vertical orientation'){
    jQuery(this).click();
  }
  if(jQuery(this).find('span.label').text() === 'Tools'){
    var open = jQuery(".toolbar-box").find('.open').length;
    if (open > 0) {
      jQuery(this).find('span.label').click();
    }
  }
});

For checking try this in the console first and add snippet to your JS file.


Advice on using Organic Groups for course management in an academic context I am thinking about using Organic Groups for course management in an academic context.

Initially I was going to create an OG group per course e.g. Physics 101.
However if the users change per semester this could become tricky to manage...

There are 2 options I can think of:

Create a new group each semester e.g “Physics 101 – Semester 1, 2013”

But would soon end up with 1000’s of groups.

Somehow archive the data, clear down the group and re-enrol the next class each semester

I'm unsure how we could effectively do the archival while keeping the data available, and it seems like it would become a convoluted process

I would love to know how other users of OG handle this type of problem?

Is there any online material that would help me learn how to use OG in this way?

Thanks for your help in advance!

Joe

I currently run a site where every 6-12 months users Groups (OG) will change. To help me, I use the Profile2 module, it makes dynamically changing user info such as OG memberships simple. If you're not already using it, have a read of the handbook.

The way I have solved the issue you have addressed is to have a spreadsheet of all the users who have changed groups, run a simple code on my spreadsheet to edit the "groups" column of the users to what they will now be, (you can simply cross reference another sheet, say the enrollment sheet for that class, and if the username or student ID appears there, put that class ID into the group column in the sheet), and when the spreadsheet is complete, simply export as a csv and then run an import through the Feeds module. This gives you the option to update the existing user information, and you have all of the old spreadsheets as an "archive". Alternatively, you could take a snapshot of the tables database, keep this in an archive, and run simple SQL Queries to update the groups of a user.

Let me know if you need more information, if you choose to approach it this way!


Clean URLs not working I just have Drupal 7 and 8 installed in my localhost on Opensuse Leap. With Drupal 7 I cannot pass the clean urls test, however the site is completely functional. By clicking the links on the menu I can access localhost/drupal7/?q=admin/dashboard or localhost/drupal7/?q=admin/people (for example).

In Drupal 8 I can access the front page localhost/drupal8 but when I click some link, for example "Log in", I'm redirected to localhost/htdocs/drupal8/user/login. And I get an Apache 404 error. I don't understand why the server redirects to another directory when both installations are using the same configuration file.

I already tried all drupal.org apache-related tutorials without success.

Does anybody know how to solve this issue?

I ran into this issue as well moving to opensuse leap from another distribution.  There was more than one problem.

Even if rewrite_module is listed in loadmodule.conf, this file is not not read without a change to httpd.conf.  You can check if the module is loaded with
apache2ctl -M

As is posted elsewhere Options and AllowOverride arguments need to be placed within the relevant Directory tags.

If there is a subdirectory of the webserver, there needs to be a RewriteBase argument given in the .htaccess file.

Try this to get things working:
In file /etc/apache2/default-server.conf
Within the <Directory> tags add or edit the Options and AllowOverride lines to
Options All
AllowOverride All

In file /etc/apache2/loadmodule.conf add
LoadModule rewrite_module    /usr/lib64/apache2-prefork/mod_rewrite.so

In file /etc/apache2/httpd.conf uncomment the IfDefine tags
#<IfDefine !SYSCONFIG>
  Include /etc/apache2/loadmodule.conf
#</IfDefine>

In file /srv/www/htdocs/NAMEOFYOURSUBDIRECTORYHERE/.htaccess add a line
RewriteBase /NAMEOFYOURSUBDIRECTORYHERE

Check if the configuration file "Syntax is OK."
It will probably complain that some modules have already been loaded, but that's alright.
 apache2ctl configtest

Restart Apache
systemctl stop apache2; sleep 5; systemctl start apache2


Secure Login in Drupal I'm designing a sensitive site and I want that login/passwd is not sent as plain text. I don't want to provide https connection or maintain a SSL certificate as it can easily be compromised on shared hosting.

For non-admin users login using openid will solve this issue but how do I do it for Admin(uid=1) ?

For admin login one way is to use a secured VPN of another country to login and once session cookie is placed I can close VPN and use my normal internet connection.

Any ideas?

Although this question isn't version specific but I need it for D6 site.

If you're already using OpenID, then that should work, but if you dont want to add yet another module and you have access to a server over ssh, you can temporarily route all traffic in a tunnel through the server, which will effectively secure all internet traffic, and allow you to connect to the site and send the password "in the clear" as it were over HTTP, but the SSH tunnel would encrypt it before it left your machine.

If you happen to be on a mac, i highly recommend using Sidestep.app to facilitate quickly connecting/disconnecting from the tunnel.

http://chetansurpur.com/projects/sidestep/

For this to really work for you and not be a complete annoyance, I repeat, you need to have SSH access to a server already set up, ideally, with public key access configured.


Re-importing photo from facebook At the moment, the module fboauth imports the photo of the person from facebook and adds it as his/her profile picture, when configured to do so. Later on, when the person changes his/her profile picture, the photo will not be updated at the site because subsequent logins only imports fbuid.

How can the user re-import the photo (or any profile data for that matter) at a later point of time, and update it at the profile here?

Please consider guiding me in the right direction and I will try to come up with some code. Will the hook fboauth_user_update() work for this? Or should I do the trouble of fetching, saving to server, and editing the db, etc? Please help.

its better to use Facebook realtime update https://developers.facebook.com/docs/graph-api/real-time-updates/v2.2

create your callback to handle this and register it with real time updates

do the following in your callback

1- load user from facebook ID you get it in the posted from facebook

2- get the new image from facebook

3- replace it with the current image

4- save user

or you can forget about real time update and replace the image whenever user login

here the code you can use

1- Make your action by Implementing hook_fboauth_actions().

2- use hook_user_login to call the action you create which grab the photo and update it

Thats all


How to display only the status message to anonymous users in page.tpl.php I want to display the status messages to all of the users but the error and warnings to the administrator.I am using this code

<?php if($is_admin): ?>
      <?php print $messages; ?>
<?php endif; ?>

But I have no idea how to distinguish the message type.

This seems like a similar question to yours regarding printing messages. Additionally, this indicates that the message type is stored within the message object. You should just be able to iterate through a message object to get it. Something like

foreach (drupal_get_messages($messagesVariable) as $type => $messages) {
    if (($status_heading[$type] != 'error') || ($status_heading[$type] != 'warning')) {
        *perform your given action here*
    }
}


drush archive-dump and archive-restore remotely I know how to backup and restore a whole site using drush archive-dump and archive-restore which is explined in this link:
Backup and restore Drupal sites with Drush

my question: is it possible to do the archive-dump and the archive-restore using aliases from a different server of the site.?

I have tried putting in the aliases file remote-host and root but it doesn't work.

After multiple tests using the command drush archive-dump and archive-restore, I came to the conclusion that it is necessary to install drush in the final servers.
I wasn't able to run the command archive-dump from a server which has drush installed to make a backup of the other server which doesn't have drush installed  because using the aliases file the drush cmd in the source server raises the following error:

bash: drush: command not found

That means that drush is needed in the destiny server. The way I concluded this was making a debug from the source server using the option --verbose and I realized that when you use the aliases file in drush command at the end this command makes a call with ssh like this:
executing

ssh -o PasswordAuthentication=no user@server 'drush --verbose --uri=urlserver.com --root=/var/www/html archive-dump --destination=/home/user/backup/example.com.tar.gz --overwrite 2>&1'

If you notice the drush command is simply being passed to the destination server.


How can we assign points to users in the site? I want to give points to users in the site, like if a user creates an account then he should be awarded some points even if I want to award points for the  activities like if user visits a page, if a user posts a comment etc.

There is a module for that, userpoints

Also using Rules to assign them for certain actions is common with that module.