Modifying views exposed filter query string I'm looking for a way to modify views' resulting query string (URL) after applying a filter, but have been unsuccessful so far.

I have a view with exposed filters, taxonomy lists to be specific. Hitting apply generates something like:  www.mysite.com/myview?foo=123
My goal is to have it instead generate:  www.mysite.com/myview?foo=bar

I know views' exposed filters depends on tid for the filter to work when visiting a page (e.g. pasting a link and visiting the page), and I have some hook_views_pre_buildcode to handle that. My issue is going the other direction. What hook, function, or other approach can I use to modify that?

For reference I've tried replacing view object contents in hook_views_pre_build, hook_views_post_build, hook_views_pre_execute, hook_views_post_execute, and hook_views_query_alter, but nothing seems to have the desired effect. I do not want contextual filters due to the need for order independence.

Came up with a solution using hook_views_pre_render combined with a JS history.replacestate. More of a workaround, but it does the job. Would still like to find a way to modify the view object or a PHP hook though.

Here's a stripped down version of the php hook implementation:

function mymodule_views_pre_render(&$view) {
  if ($view->name == "myviewname") {
    $path_settings = array("mymodule" => array('query_params' => array()));
    foreach ($_GET as $key => $val){
      if (array_key_exists($key, $view->exposed_input)) {
        $path_settings['mymodule']['query_params'][$key] = $view->exposed_input[$key];
      }
    }
    drupal_add_js($path_settings, 'setting');
  }
}

Then in the module's js attached behaviors:

function tidyViewsQueryString() {
  currentLocation = window.location.href;
  for (var key in Drupal.settings.mymodule.query_params) {
    if (Drupal.settings.mymodule.query_params.hasOwnProperty(key)) {
      currentLocation = updateUrlParameter(currentLocation, key, Drupal.settings.mymodule.query_params[key])
    }
  }
  if (currentLocation != window.location.href){
    window.history.replaceState(null, document.title, currentLocation);
  }
}

//From https://gist.github.com/niyazpk/f8ac616f181f6042d1e0
function updateUrlParameter(uri, key, value) {
    // remove the hash part before operating on the uri
    var i = uri.indexOf('#');
    var hash = i === -1 ? ''  : uri.substr(i);
         uri = i === -1 ? uri : uri.substr(0, i);

    var re = new RegExp("([?&])" + key + "=.*?(&|$)", "i");
    var separator = uri.indexOf('?') !== -1 ? "&" : "?";
    if (uri.match(re)) {
        if (value.length > 0)
          uri = uri.replace(re, '$1' + key + "=" + value + '$2');
        else
          uri = uri.replace(re, '$1' + '$2')
    } else {
        uri = uri + separator + key + "=" + value;
    }
    return uri + hash;  // finally append the hash as well
}


Select translation: where? In Drupal 7 (i18n) there is a possibility to select an existing node as a translation of another node.

In Drupal 8, is there also that possibility?

No, that was the old form of multilangual sites. This was removed in Drupal 8 in favor of entity translations.

Now every field had its own language instead of the node. This means the common properties of the node (nid, author, etc) can remain untranslated, while the values of the individual fields can be translated. (it prevents duplicate content)

So there is no way to select one node as a translation of another.


Turning on verbose logging Is the "Verbose logging" in Drupal actually the PHP errors that can be activated in various ways (.htaccess, php.ini, settings.php) to be seen on screen?

Is it drush ws --full ?

From the material I've seen I can't say for sure if there is a unique definition for this concept in Drupal.

I would thank an experienced Drupal programmer to give the final word on this.

Navigate to admin/config/development/logging and set "All messages, with backtrace information".


View is duplicating content added by entity reference I have two content types, Project and Resource,

I have a view displaying fields from Project, and also fields from Resources via an entity reference field.

The problem is, if I add more than one linked resource to a project via my entity reference field, the view duplicates that Project node, instead of adding another linked resource to that project.

Any help much appreciated!

I assume that you have a view, that shows content of type Project.
In project you have a nested reference to a Resource.
Basically you are asking views to show you all the Projects, and related to them Resources, so for every Resource that you are adding, views is showing you projects that are related to new Resource, but, since you have only one node of type Project - views showing you Project for every Resource that you added, so you have what was implied to happen.

If you want to have list of Resources on a Project page - I would suggest you to create small view blocks, using node id of a resource as a context filter to the view,  (So in this case view would be showing you list of the Resources to the given Project on each project page.)
For that you need to create another entity_reference field on a content type of Project and filter it through the view that you created.

If this is what you were looking for. It was hard to understand you tbh


Views - No results behavior with Exposed filter criteria I have a views setup with one title field, exposed filter criteria and No results behavior (Simple Text). Problem is No results behavior shows before user applied any filter criteria. I need No results behavior to show up only if filter criteria didn't find any content. Help please and thank you!

I think you selected the Autosubmit option in the exposed form settings.

    Autosubmit
    Automatically submit the form once an element is changed


How to get nid of a managed file? in hook_file_download there is just a parameter named uri. How can I get nid of the node that contains the file in uri?

For exmpale I have a file field in my content type.I create a node and add some files to file field. Now when this file is going to be downloaded, in hook_file_download I want to get nid of the file.How?

If this is an file attached through a file or image field, you can instead implement hook_file_download_access(), which gives you the $field, $entity_type and $entity to which the file belongs.


Is it possible to alter nodes on export with Node Export I want to write my own module which changes a few things upon exporting of nodes with Node Export.
I saw that there are some API's. But I haven't seen any working examples. Is there some documentation on the API of Node Export? And if not can someone provide me with some examples of changing data for export and changing it again upon import?

Thanks,
Jaap

You can manipulate the nodes in hook_node_export_node_alter() and hook_node_export_node_import_alter()
See node_export.api.php for more information.


What is the correct order of disabling the default contact form on Drupal? Drupal comes with a default contact form on each site we install. And while we already have the webforms and recaptcha module installed, some of our site owners still use the default contact form found in
/admin/structure/contact.
I need to remove them because when they are enabled, the site is prone to spam attacks. I've had a few instances where some of the sites had form submissions with PDF file uploads of inappropriate content. So you see how this is a security risk for our organization.
I removed that contact form in my local site by disabling the following modules in this order:

contact form
contact storage
contact

But I need to do this for all our sites now, so I wrote the following in my hook_update_n() function:
function my_profile_update_8011() {
    $config = \Drupal::configFactory();
    $moduleHandler = \Drupal::service('module_handler');

    if($moduleHandler->moduleExists('lightning_contact_form')) {
        Drupal::service('module_installer')->uninstall(['lightning_contact_form']);
    }
    if($moduleHandler->moduleExists('contact_storage')) {
        Drupal::service('module_installer')->uninstall(['contact_storage']);
    }
    if($moduleHandler->moduleExists('contact')) {
        Drupal::service('module_installer')->uninstall(['contact']);
    }

}

When I deployed this update to our dev environment, it would work on most of the sites, but fail on the rest. They all have this same error message:
The error output from the server was: >  [notice] Update started: my_profile_update_8011
>  [error]  SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause': SELECT 1 AS expression
> FROM
> {contact_message} t
> WHERE id IS NOT NULL
> LIMIT 1 OFFSET 0; Array
> (
> )
>
>  [error]  Update failed: my_profile_update_8011
 [error]  Update aborted by: my_profile_update_8011
 [error]  Finished performing updates.

All our sites share the same codebase, so I don't know where my update hook went wrong.
Is there a better way of disabling these modules?
thanks,
Kevin

You may be able to use this (untested) approach in your hook_update_N() implementation:
function my_profile_update_8011() {
  $config = \Drupal::configFactory();
  $moduleHandler = \Drupal::service('module_handler');

  $mods_removable = [
    'lightning_contact_form',
    'contact_storage',
    'contact',
  ];

  // Read the configuration.
  $module_data = $config->getEditable('core.extension')->get('module');

  foreach ($mods_removable as $module) {
    if($moduleHandler->moduleExists($module)) {
      // Unset the modules you do not need.
      unset($module_data[$module]);
    }

  // Write the configuration.
  $config->getEditable('core.extension')->set('module', $module_data)->save();
  }

See this answer for additional info.


Multiple forms and required fields affecting hook_form_FORM_ID_alter() When creating a new content type, the $form_id is correctly picked up in my module.  Let's say in my example, my form is called the 'foo_form'.  The below hook_form_FORM_ID_alter function works fine when I go to add/content/foo-form

function MyModule_form_foo_form_alter(&$form,&$form_state,$form_id) {
  echo 'It works!';
}

The problem is that my content type has some required fields.  If the user does not fill them in all out and submits, then the submission fails as expected.

The problem is that now on the error page telling the user that he or she needs to fill out the required fields, the $form_id is no longer 'foo_form', but instead named 'search_block_form' because on all my pages I have a search block on the left side bar.  Now my hook_form_FORM_ID_alter() does not get invoked because my module is getting 'search_block_form' as its $form_id instead of 'foo_form'.

I tried using hook_form_alter(), which works globally, but because there are 2 $form_id's on this required fields error message page, my MyModule_form_foo_form_alter() gets called twice (once for 'search_block_form' and 'foo_form')!

How do I resolve this issue, other than exclude displaying the search form block when adding new content?  How do I make 'foo_form' the primary $form_id???? I find this odd since if I go to add a new content, Drupal is "smart" enough to ignore the 'search_block_form' $form_id.

EDIT: My code to test visibility about what $form_id's are present before submitting and after submitted without filling in all the required fields.

function MyModule_form_alter(&$form,&$form_state,$form_id) {
  case 'search_block_form':
    //this one always shows up
    echo $form_id . "
";
  break;
  case 'foo_form':
    //does *not* show up when submitting form
    //with missing required field values
    echo $form_id . "
";
  break;
}

To do form validation use the form API validation capabilities:

http://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#validation

http://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#validate


Deciding between (CCK) Fields and Taxonomy for a list of options. Pros and cons? Sometimes I wonder why to choose Term reference or a regular List (float/integer/text) over the other, when I would like to "force" my users to select one or multiple values from a list.

Taxonomy vocabulary and a Term reference field pros:

new terms can be added right in the textbox (see "Autocomplete term widget (tagging)")
separate sites are created automatically for the different terms where referenced nodes are listed (no separate view has to be added, but can be if necessary)
views can easily be created
terms hierarchy
terms can be reordered easily
list of terms can be extended easily
terms are easily fieldable, which means more display possibilities when viewing a given node
?

Term reference field cons:

?

List (float/integer/text) field pros:

views can easily be created
the field is closely related to the given content type, no separate vocabularies have to be added
?

List (float/integer/text) field cons:

after adding some nodes with the given field, and going to "Field settings" for changing them, I get the message: "There is data for this field in the database. The field settings can no longer be changed." (example screenshot)
?

I would appreciate if you could tell me some other pros/cons over the other when having to force the user to select some values from a list.

This is my personal opinion:

Use taxonomy terms is you might need to change them later, re-arrange them, add or remove (yes remove, bad, but ok), share them between content types and have a page per each listing all the content that have it and also provide an RSS feed of the same.

Use options list or CKK option list is you know for sure the options will never change, if you need to have a key-value configuration if you want to share them between content types, but don't want to have listing pages of the content that have it. Also fields can have grain level permissions and don't generate RSS feeds.


The update manager module makes admin pages very slow, what might be the causes and how could I solve this problem? All of a sudden, my admin navigation started being slow, very slow. It takes between one and two minutes to load a single page (with very little content). When I unable the update manager module, the problem vanishes. Any hint on what causes this malfunction and how I could solve it? Thanks!

Update module is slow when site is behind a router or firewall:

https://drupal.org/node/369145

  The Update Status module attempts to get update information using the
  internet. Many servers have firewalls that block this.

That means that Drupal tries to access the Internet, but if the site is behind a router or a proxy the petition probably is ignored, so Drupal is 'stalled' waiting for response. When Drupal is tired of waiting (the petition timeouts), usually several seconds after, the page request continues and finllay Drupal delivers the page. You feel that the site is slow, but in fact Drupal has been waiting same as you.

The solution is to disable Update module in dev environments, or allow the site to connect to Internet to get the update information.


Adding action to textarea I am hoping that this enquiry will be a easy one for someone to help shed some light on... I know that in order to create a textarea in Drupal 8 the following code can be used (e.g. render array)

$the_textarea=array(
        '#type' => 'textarea',
        '#required' => FALSE,
        '#ajax' => array (
            // Function to call when event on form element triggered.
            'callback' => array($this->componentCallbackObject,$this->componentCallbackFunction),
            'event' => $this->componentEvent,
        ),
    );

In the above code, a callback is defined using ajax ... this has the result of the code requiring the client to communicate with the server, which then sends back instructions to the client side using ajax... Is there away to get a component to execute some javascript (where the javascript would be loaded when the page in question, first loads) and when either the upkey, downkey or onchange event is triggered for the textarea the javascript, which would already be available to the client would be executed.

The main point here is that the client wouldn't need to communicate with the server, just with the javascript which is loaded when the page first loads e.g. without having to callback to the server and then wait for the server to send back the information.

The technique you need is easy, the full details can be complicated (depending on exactly what you want the JS to do). You can attach a custom JavaScript file from without your module in three steps:

Create the JS file.
Define a library.
Attach the library to the form element.

The JavaScript should typically live in a folder named js at the root of your module: js/my-great-jscode.js.

To create your library add a [module_name].libraries.yml file to the root of your custom module.  In there define the library:

my-library:
  version: 1.x
  js:
    js/my-great-jscode.js: {}

Then to attach the code to your form element you add #attached => library to the render array.

$the_textarea=array(
  '#type' => 'textarea',
  '#required' => FALSE,
  '#ajax' => array (
  // Function to call when event on form element triggered.
  'callback' => array($this->componentCallbackObject,$this->componentCallbackFunction),
  'event' => $this->componentEvent,
  ),
  '#attached' => [
    'library' => [
      'my-module/my-library',
    ],
  ],
);

There is more detail in Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module on Drupal.org


Where to find Drush for Drupal 6? I am trying to install and work with Drush for my Drupal 6.22 site. However, on the modele's page I can only find the module's tar.gz package for Drupal 7. nor can I find D6 package elsewhere. So appreciate your help.

Drush is version agnostic.  From the same page:

  It is valid to use the latest '7.x' (or master) no matter what your version of Drupal is. Drush is independent of Drupal version :)


How can I add a field to a view description I'm running into a quite simple problem : I would add fields to a view description, in order to list my views by this field.

Example : add a taxonomy field to the views, let's say "View color". Then, I would create a view of views, only for the views having a color, ordered by their colors and letting me see a XML containing the color and a link to the view's page :

<...>
    <view>
        <color>red</color>
        <link>http://example.com/path-to-red-view</link>
        <color>blue</color>
        <link>http://example.com/path-to-blue-view</link>
    <....>
</...>

I don't want to generate the links by rewriting (I know how to do that), but really add a field to the views.

The question is a bit wobbly, but I don't figure out how to write it. I found nothing on the web describing what I want to do, maybe due to that.

Thereby, all help is welcome !

Thanks

I don't know that it will provide all the functionality you are looking for, but you could look into Views Field View:

  This module allows you to embed a view as a field in a view. A new
  field handler is made available, so this can also be used in area
  (header/footer/empty) handlers as well as rows.

  This view handler can accept arguments from fields of the parent view
  using tokens and pass them into the child view for each row. Raw or
  rendered token values can be used, as well as static values.


Make content type available for anonymous to edit and use front end theme I have a content type that I have made available for anonymous users to edit. I want that content type when it is in edit mode to use the front end theme. How would I achieve this?
Thanks

Just make sure your anonymous user role (and any other relevant roles) don't have the 'View the administration theme' permission...then they'll get the default front-end theme when accessing any page that's deemed to be an 'admin' page.


Styling a Calendar View Page I can't seem to get any templates to work with my Calendar View Page.

In the view settings, clicking Theme Information reveals some possibles but I've tried them all.

I'm not sure what to name my file to allow it to work as a theme template.

I'm not sure how to theme this Calendar! I only want to add a custom drop down menu above it!

You need to clear the cache before any templates you add will be recognized.


How can I modify the advanced search form when my hook runs too early? I'm using hook_form_FORM_ID_alter to modify the content of the form on the search page — I want to remove the "phrase" and "not" fields, and restrict the "only of the types" checkboxes to a hand selected list of types.

I have the following code, which is being called and which I think should work:

function MYMODULE_form_search_form_alter(&$form, &$form_state, $form_id) {
    unset($form['basic']);
    unset($form['advanced']['keywords']['phrase']);
    unset($form['advanced']['keywords']['negative']);
    unset($form['advanced']['type']);
    $form['advanced']['type'] = array(
        '#type' => 'checkboxes',
        '#title' => t('Only of the type(s)'),
        '#options' => array(
            'blog' => 'Blog entry',
            'event' => 'Event',
            'news' => 'News article'
        )
    );
    // print_r($form);
    // die;
}

Except node_form_search_form_alter gets to the search form after my form alter hook runs, so I don't get a chance to modify any of the form elements that it's adding.

I'm running Drupal 7.22.

How can I modify the advanced search form when my module hook runs before the hook that defines the advanced search form?

Changing the module weight will work, but sometimes that can cause problems with the order in which other hooks in your module are invoked.
Drupal provides hook_module_implements_alter() for exactly this sort of situation, so that you can target the order a specific hook is run in:

Alter the registry of modules implementing a hook.
This hook is invoked during module_implements(). A module may implement this hook in order to reorder the implementing modules, which are otherwise ordered by the module's system weight.

The code might look something like
function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'form_alter') {
    // Move MYMODULE to the end of the list.
    $group = $implementations['MYMODULE'];
    unset($implementations['MYMODULE']);
    $implementations['MYMODULE'] = $group;
  }
}

Once you clear the cache your module's implementation of hook_form_alter() will be invoked last (unless of course another module is implementing hook_module_implements_alter() and altering the order again. But that's a different story).
I personally prefer this method as it's just a simple code change, no need to maintain any changes to the system table in the database.
I'm not sure how well that works with a form_FORM_ID_alter hook (never tried it), but with this method you can at least make sure that only the weight for hook_form_alter() need be updated.
Actually looking at the code for drupal_alter(), changing the conditional to if ($hook == 'form_search_form_alter') would probably work.


How to upload multiple files at once? We need to upload multiple files of different types, is there a module that will check for valid mime types and upload only the valid files, (based on site settings, eg: png, doc, jpg, txt) ?

clientside_validation (drupal-6 and drupal-7) performs some additional client-side checks, including checks on uploaded file extensions (but not MIME Types).  (And, as @tim.plunkett mentioned in the comments, mimedetect is useful for server-side MIME Type validation, but the file must be uploaded to the server in order to be validated.)

For uploading multiple files, consider the following:

swfupload (drupal-6; Flash)
plupload (drupal-6 and drupal-7; Flash and several other technologies supported; new/under development)

For uploading multiple images, additionally consider these:

image_fupload (drupal-6; uses swfupload above)
jifupload (drupal-5 and drupal-6; free; uses Java applet)
aurigma (drupal-6; software purchase / service subscription required)


Create an admin menu in a MENU_LOCAL_TASK I have added a MENU_LOCAL_TASK to a node. Within that local task I want to display an admin menu block using system_admin_menu_block_page() however I always get You do not have any administrative items. I have no trouble getting admin menu pages to work as MENU_NORMAL_ITEMS. Any ideas what I am doing wrong? Code below.

function my_module_menu() {
  $items = array();
  $items['node/%node/settings'] = array(
    'title' => 'Account settings',
    'description' => 'Manage your account settings.',
    'page callback' => 'system_admin_menu_block_page',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'access callback' => 'my_module_access_account_settings',
    'type' => MENU_LOCAL_TASK,
    'file path' => drupal_get_path('module', 'system'),
    'file' => 'system.admin.inc',
    'weight' => 1000,
  );
  $items['node/%node/settings/upgrade'] = array(
    'title' => 'Upgrade your account',
    'description' => 'Use this form to upgrade your account.',
    'page callback' => 'my_module_upgrade_account',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'access callback' => 'my_module_access_account_settings',
    'type' => MENU_NORMAL_ITEM,
  );
  $items['node/%node/settings/cancel'] = array(
    'title' => 'Cancel your account',
    'description' => 'Click here to cancel your account and remove all your data.',
    'page callback' => 'my_module_cancel_account',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'access callback' => 'my_module_access_account_settings',
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function my_module_access_account_settings($node) {
  if ($node->type == 'my_node_type') {
    return TRUE;
  }
  return FALSE;
}

After further investigation reading the code here, it appears that this can be done.

For example, admin/tasks has admin menu children in a MENU_LOCAL_TASK however, it appears that it looks at the current local task's parent item and then looks for MENU_NORMAL_ITEM children.

Unfortunately, this doesn't work in my case since I use wildcard urls (%node) and my local task is not the default one. (like the admin/tasks one is).

So I came up with a workaround function that achieves what I need.

The function my_module_account_settings($node) basically queries the DB for the current MENU_LOCAL_TASK's mlid, then queries the database for ALL menu links that have the current MENU_LOCAL_TASK's mlid as their parent.

I then call the theme function for admin_block_content and boom.

Let me know if anyone comes up with either a better, or more correct way of doing this.

function my_module_menu() {
  $items = array();
  $items['node/%node/settings'] = array(
    'title' => 'Account settings',
    'description' => 'Manage your account settings.',
    'page callback' => 'my_module_account_settings',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'access callback' => 'my_module_access_account_settings',
    'type' => MENU_LOCAL_TASK,
    'weight' => 1000,
  );
  $items['node/%node/settings/upgrade'] = array(
    'title' => 'Upgrade your account',
    'description' => 'Use this form to upgrade your account.',
    'page callback' => 'my_module_upgrade_account',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'access callback' => 'my_module_access_account_settings',
    'type' => MENU_NORMAL_ITEM,
  );
  $items['node/%node/settings/cancel'] = array(
    'title' => 'Cancel your account',
    'description' => 'Click here to cancel your account and remove all your data.',
    'page callback' => 'my_module_cancel_account',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'access callback' => 'my_module_access_account_settings',
    'type' => MENU_NORMAL_ITEM,
  );
  return $items;
}

function my_module_account_settings($node) {
  $current =  menu_get_item();

  // get current MENU_LOCAL_TASK mlid
  $current_mlid = db_select('menu_links' , 'ml')
    ->condition('ml.link_path' , $current['path'])
    ->fields('ml' , array('mlid'))
    ->execute()->fetchField();

  // get all menu_links where the parent link id is the current
  // MENU_LOCAL_TASK
  $rows = db_select('menu_links' , 'ml')
    ->condition('ml.plid' , $current_mlid)
    ->fields('ml' , array('mlid', 'link_path'))
    ->execute()->fetchAllKeyed();

  foreach ($rows as $mlid => $path) {
    // load each of the admin menu items within this local task
    // in my case i replace the placeholder/wildcard with the node nid
    $item = menu_get_item(str_replace('%', $node->nid, $path));
    if ($item['access']) {
      $items[] = $item;
    }
  }

  // return the themed block
  return theme('admin_block_content', array('content' => $items));
}

function my_module_access_account_settings($node) {
  if ($node->type == 'organisation') {
    if (user_access('edit org account settings')) {
      return TRUE;
    }
  }
  return FALSE;
}


Drupal Views in Glossary mode removing pager I am adding alphabetical page to the view using glossary mode. I am able to create the alpha pager but the issue is, when I click on the alphabet the alpha pager doesn't appear again. I have to go back to view the alpha pager.

From what I remember, you have to create the Glossary display of the view, and then you set the results page as an Attachment of that view display (attachment being the view display type).

Views ships with a default Glossary view, it's just disabled.  I would suggest enabling that and take a look to see how that does it.


Can Drupal be configured to find modules in other locations? I put my modules in sites/all/modules. Is there a way to configure Drupal to find more modules in other locations as well?

Edited

I use Virtual Hosts often but not in the way you described. The format I'm familiar with looks like this, and it helps me put the entire work project somewhere else not inside www.

<VirtualHost *:80>
    ServerName testdrupal.com
    DocumentRoot "C:/proj/testdrupal"
    ServerAlias testdrupal.com

   <Directory "C:/proj/testdrupal/">
       Options Indexes MultiViews FollowSymLinks
       AllowOverride All
       Order allow,deny
       Allow from all
   </Directory>
</VirtualHost>

I think what you're describing is something different, right? I'm trying to leave the drupal folder inside www as usual, but move only the sites/all/modules to another location, but I still can't figure out how the VHost entry will look like in this case. Let's say I want to move it to C:/proj/testdrupal. I hope I didn't completely misunderstand you.

Before answering, it's helpful to have a little background about how Drupal finds modules. Drupal uses a list of suggestions from the Drupal root to figure out where to find modules. In order of priority:

sites/$SITENAME/modules
sites/all/modules
profiles/$INSTALLPROFILE/modules
modules

If Drupal doesn't find a module in (1), it checks (2). If it's not there, it checks (3), and so on.

For (1), if you're just using a basic, single-site install of Drupal, $SITENAME is default. Otherwise:

In Drupal 6, $SITENAME is the host name of the site. If your site is located at example.com, $SITENAME would be example.com.
In Drupal 7, $SITENAME is defined in sites/sites.php. If you look at example.sites.php, you can see how to define it. It's also important to note that any module listed there will only be usable for that specific sites, not all sites.

In (2), any module found there will be usable on any site in the Drupal installation. It will also be left untouched when you upgrade the core installation. This is, of course, the recommended place to put modules and likely all documentation you've read have told you to put your modules here.

(3) is used for installation profiles that require a specific module. Installation profiles are essentially a way to define a custom initial state for a Drupal site. For example, Drupal comes with two installation profiles built in: Standard, which includes most-used features, and Minimal, which only includes the bare minimum needed for a Drupal site to function.

(4) is used by Drupal core. While you can technically add modules here and they will be available for all sites, you shouldn't. Seriously. The modules folder is touched when Drupal core is updated, and will cause problems down the line if you're sticking modules you need for your site to function there.

Now that the background is out of the way, you can use file system tricks to have your modules housed outside of where Drupal looks.

For example, you could set up a symbolic link from sites/all/modules to another directory outside of the Drupal installation:

In Unix/Linux/BSD-based systems: ln -s /path/to/modules/folder /path/to/drupal/sites/all/modules
On Windows Vista/Server 2008/7 and higher: mklink C:\path\to\drupal\sites\all\modules C:\path\to\custom\modules\folder

As far as I'm aware, there's not much you can do in earlier versions of Windows that don't have mklink.


How to use settings.local.php with Drupal 7? I couldn't find answer from previous questions nor drupal.org/pantheon.io.

I don't know that how to get local Drupal to use settings.local.php?

There isn't a settings.php if I clone the repo from pantheon.io nor a settings.local.php.

If i create settings.local.php file it still thinks that it as a fresh install and redirects to install.php. So it doesn't recognize that file.

Naturally, all works if I create a settings.php. Can't I just create settings.php for local development and add it into gitignore so  it won't get pushed to remote repo?

When u install drupal u need to copy example.settings.php into settings.php, after drupal installation u need to include following code in settings.php:

if (file_exists(DRUPAL_ROOT . '/' . conf_path() . '/settings.local.php')) { include DRUPAL_ROOT . '/' . conf_path() . '/settings.local.php'; }


Hook_enable vs hook_install [granting permissions to user role] I'm trying to grant a permission to a user role using hook_install and it doesn't work(drupal 7.54). But it works with hook_enable. Do you know how to make it work with hook_install as well?

function porta_batch_editor_install() {
  $permissions = array('access porta batch editor');
  //grant 'access porta batch editor' permission to pb role
  foreach(array('pb role') as $role_name) {
    $role = user_role_load_by_name($role_name);
    user_role_grant_permissions($role->rid, $permissions);
  }
}

It works with the following approach:

function porta_batch_editor_enable() {
  $permissions = array('access porta batch editor');
  //grant 'access porta batch editor' permission to pb role
  foreach(array('pb role') as $role_name) {
    $role = user_role_load_by_name($role_name);
    user_role_grant_permissions($role->rid, $permissions);
  }
}

It should work on install. Are you actually uninstalling the module? Disabling and uninstalling is not the same thing in Drupal 7. Uninstall at admin/modules/uninstall, once the module is disabled. You can use drush pm-disable/pm-uninstall module_name.

test.module

function test_permission() {
  return array(
    'test permission' => array(
      'title' => t('Test permission title'),
    ),
  );
}

test.install

function test_install() {
  $test_perm = array('test permission');

  $perms = module_invoke_all('permission');
  // We can find the 'test permission' in $perms.

  $role = user_role_load_by_name('administrator');
  user_role_grant_permissions($role->rid, $test_perm);
}

The above gives administrators the test permission on module install.


How do I make a $node object properties available in my views--template? I have a node--type and view--type templates. In view--type I cannot access $node, for example with $node->nid.

How can I inject $node inside view type templates?

I have a views-view-field--mypage--page--body.tpl.php file; this is a field template of the body of teasers where I inserted a Read more link. I need the URL for that link.

Views doesn't load the complete $node object for performance reason. Instead, it build, or attempt to build, an optimized query to only load the fields configured in the Views.

When editing the views, you should have a Fields block. In this block, use its Add fields links to add the additional fields you want to use in your template. If you don't want to display these fields using Views itself, be sure to configure them to be excluded from display.


How do you store webform submits to a different database? I have a client requirement where "user generated content", in specific, webform submissions from the public, need to be stored in a different database from the normal 'one' database approach.

How do I configure the site to store webform submissions in a different database?

General the most secure way is to push a webform submission into a different 'external' database is to create a webservice to populate the external database. Then you can use the 'Remote post' handler to push the submission data via the webservice into the external database.

@see https://www.drupal.org/docs/8/modules/webform/webform-videos#handlers

To disable the saving of submissions…

Goto /admin/structure/webform/manage/WEBFORM_ID/settings
Check 'Disable saving of submissions'


Views pagination based on taxonomy terms I have an archive Views page in Drupal 7 that is paginated after 10 items, themselves grouped and sorted by a taxonomy term ("issue date").

I've been asked whether it's at all possible to make the pager more descriptive based on the taxonomy vocab — i.e., instead of it just being "Go to Page 2", it's "Go to issues 2012-07-06 to 2012-06-29".

Any idea how I'd do that? Thanks!

I can't really understand why dates are stored as taxonomy terms, but yes, you can solve your task with powerful plugin system of Views. You should create custom views pager, which adds specific conditions to Views query.
The best example is an article by Views author Earl Miles: Creating a Date Pager Plugin for node "created" field (wow! dates, too).

  As an example, we’re going to create a pager plugin that is somewhat useful, and completely non-traditional for Drupal. You have, however, very likely interacted with a pager of this nature before. Instead of relying on the number of results, we’re going to rely on the post date of the content...

The code is avalible in Views plugin examples module.
Your task is more complex and, of course, requires professional skills.


Get a views result using PHP code, and iterate the proper way I have a view called all_projects_list. This view fetches Fields (not nodes), and i'd like to get it by code, and iterate on it. I managed to do this by using:

$view = views_get_view_result('all_projects_list', 'default');
foreach($view as $project){
    print_r($project->_field_data['nid']['entity']->field_project_code['und'][0]['value']);
}

Which as you can see is very, very dirty.
Is there a Drupal way of doing this ?
Thanks in advance.

It's not very different from what you do, but here's example code from a project of mine, showing how I usually do it

$view = views_get_view('a_view');
$view->preview('panel_pane_1', array($node->nid));
foreach ($view->result as $tid) {
  print $tid->taxonomy_term_data_taxonomy_term_hierarchy_tid;
}

Based on the function documentation

  To be called externally, probably by an AJAX handler of some flavor. Can also be called when views are embedded, as this guarantees normalized output.

I've always assumed that preview() is the proper way to do it, and it has served me well on a number of occasions.


How to copy content type? How to copy content type in Drupal 7 ?

I can't find a button to duplicate content type.

Maybe too late you can use the Bundle Copy module:

  Bundle copy is a replacement for the Content copy module which lives in the CCK project for Drupal 6.  Has export/import support for: Node types, Taxonomy, User, Field API fields, Field groups

UPDATE 7.x-2.x-dev notes

The following features have been added:

Export/import of Field Collection
Cloning of Content types
Export/Import of Commerce Entity bundles

Drupal 8: Bundle Copy is in Drupal 8 Core CMI.


How to inject a product field to product display? I have added a field on a product.I want the same field to appear on the product display that is being referenced.I need to do this with code.
How can I do this?
thanks

I would personally be using views to either override the product page, or I would hide the fields on the manage display page of the product, and show all the fields using a view in a block with a contextual filter to get the content by ID.

However, you can override the product using a template like node--product.tpl.php and use something like...

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

To print your chosen field.


Exclude domain in robots.txt Is it possible to exclude a domain name in robots.txt?

I have a single Drupal site with multiple domains pointing on it. For example our dev and staging server are being crawled by Google when our .htaccess password protection is disabled.

I don't intent to block any access in our development server but to tell search engine bots to stop indexing all the contents when the domain is/are dev or staging.

Basically I am seeing some of the links pointing in dev servers when I search some of my content in Google.

Is there any way or any module that could handle this?

EDIT:

Here's how I ended. Inside theme_preprocess_html().

// Avoid search engines to index dev and stage domains.
  $restricted_domains = array('dev.mydomain.com', 'stage.mydomain.com', 'editorial.mydomain.com');
  if (in_array($_SERVER['HTTP_HOST'], $restricted_domains)) {
    $meta_robot = array(
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'robots',
        'content' => 'noindex, nofollow'
      ),
    );
    drupal_add_html_head($meta_robot);
  }

Robots.txt will not help your site being crawled (technically) by anything. They're just guidelines which Bots should follow. You should limit dev and test server access by Firewall rules, or as you've mentioned by httpauth.


hook_services_resource is not working EXAMPLE : this is my sample for service resource hook, i'm using drupal 7. I have enabled the services module and ctools module. the end point is working fine, but when i browse the endpoint/commerce_rest/retrieve url is not working

It returns the following exception, exception 'ServicesException' with message 'Could not find resource retrieve.' as following:

/var/www/webui/drupal/sites/all/modules/services/includes/services.runtime.inc:359\nStack trace:\n#0
/var/www/webui/drupal/sites/all/modules/services/servers/rest_server/includes/RESTServer.inc(83): services_error('Could not find ...', 404)\n#1
/var/www/webui/drupal/sites/all/modules/services/servers/rest_server/includes/RESTServer.inc(36): RESTServer->getController()\n#2
/var/www/webui/drupal/sites/all/modules/services/servers/rest_server/rest_server.module(40): RESTServer->handle()\n#3 [internal function]: rest_server_server()\n#4
/var/www/webui/drupal/sites/all/modules/services/services.module(218):
 all_user_func('rest_server_ser...')\n#5
[internal function]: services_endpoint_callback('commerce_rest', 'retrieve')\n#6
/var/www/webui/drupal/includes/menu.inc(516): call_user_func_array('services_endpoi...', Array)\n#7
/var/www/webui/drupal/index.php(33): menu_execute_active_handler()\n#8 {main}

And the source code is:

function test_module_services_resources() {

   $resource = array(
      'commerce_rest' => array(
      'retrieve' => array(
        'file' => array('type' => 'inc', 'module' => 'search_service'),
        'callback' => 'test_module_search_service_results',
        'access callback' => 'search_access_callback',
        'access arguments' => array('view'),
        'access arguments append' => TRUE,
        ),
    )
 )
);
    return $resource;
}

this hook is not invoked, when I browse the url.

You can try:

/**
 * Implements hook_services_resources
 */
function test_module_services_resources() {

  $resources = array();

  $resources['search_results'] = array(
    'index' => array(
    'callback' => 'test_module_search_service_results_index',
    'file' => array(
      'type' => 'inc',
      'module' => 'test_module',
      'name' => 'resources/search_results.resource'
    ),
    'access arguments' => array('access content'),
    'args' => array(),
    ),
  );

  return $resources;

}

Ensure the resource callback test_module_search_service_results_index is located in your module subfolder

test_module/resources/search_results.resource.inc

Then try hitting http://www.example.com/api/search_results (using your site services endpoint)


db_select only ever returns one result I am constructing a query that has to fetch the field collection line item, and it's associated field collection field to get the node id that the field collection field is being used on. The problem is it's only ever returning one single result when I know for sure there are at least two to return. Perhaps a fresh set of eyes can help.

Run list field table

"entity_type","bundle","deleted","entity_id","revision_id","language","delta","field_run_list_item_value","field_run_list_item_revision_id"
"node","run_list",0,100000018,48,"und",0,4,12
"node","run_list",0,100000017,47,"und",1,3,11
"node","run_list",0,100000017,47,"und",0,2,10

Run List field's line item table:

"entity_type","bundle","deleted","entity_id","revision_id","language","delta","field_story_target_id"
"field_collection_item","field_run_list_item",0,2,10,"und",0,100000004
"field_collection_item","field_run_list_item",0,3,11,"und",0,100000009
"field_collection_item","field_run_list_item",0,4,12,"und",0,100000004

This is my query:

$rl_query = db_select('field_data_field_story', 'fci');
$rl_query->fields('fci', array('field_story_target_id', 'bundle', 'entity_id'));
$rl_query->leftJoin('field_revision_field_run_list_item', 'rl', 'rl.field_run_list_item_value = fci.entity_id');
$rl_query->fields('rl', array('entity_id', 'field_run_list_item_value'));
$rl_query->condition('fci.field_story_target_id', $node->nid);
$rl_results = $rl_query->execute()->fetchAll;

When I dpm($rl_results); it ends up looking like:

... (Array, 1 element)
    0 (Object) stdClass
       field_story_target_id (String, 9 characters ) 100000004
       bundle (String, 19 characters ) field_run_list_item
       entity_id (String, 1 characters ) 2
       rl_entity_id (String, 9 characters ) 100000017
       field_run_list_item_value (String, 1 characters ) 2

I should expect to see more than one result returned. In this example, there should be two.

You also put another condition in your query

"$rl_query->condition('fci.field_story_target_id', $node->nid);"

You can check by commenting this line.


Protect previous migrated field values on system of record migration I have a successful migration of content type A, B and C. In the migration of C, I have entity reference fields that get populated with the correct values coming from migration A and B.

My reference fields is a multi value node entity reference field. To prevent the values being over ridden from my previous migrations, I use the system of record method.

https://www.drupal.org/node/1117454
https://www.drupal.org/node/2550939

The example is very specific to a commerce migration.

// If "updating" a product, protect these fields.
        // We know its updating if the product exists in the database with the sku.
        // Migrate updates by deleting an entire entity and replacing with
        // the new one. We circumvent the removal of the values of these
        // fields by pulling them and overriding the defaults provided
        // in the mapping.
        // You could do the same with a nid id found with a title, or something similar.
        // $row->migrate_map_sourceid1 is usually the entity id you're looking for,
        // our example here uses a commerce_product and loads it with the provided sku
        if ($product = commerce_product_load_by_sku($row->sku)) {
            // Use the metatdata wrapper to pull values
            $product_wrapper = entity_metadata_wrapper('commerce_product', $product);

            // field_stock
            // Some products have a NULL stock, lets keep the zero default if NULL
            if ($product_wrapper->field_stock->value() !== NULL) {
                $row->stock = $product_wrapper->field_stock->value();
            } else { $row->stock = 0; }

            // field_max
            $row->max = $product_wrapper->field_max->value();
        }

I am not sure how I would use my prepare row, current content types, their ids etc to remove the current values, update the new values, and then add the previous ones again? Or am I misunderstanding how this is suppose to work? Thanks in advance!

My solution was to use the prepare($node, stdClass $row). This basically takes the current values and joins them to the new ones.

https://www.drupal.org/node/1222668#comment-4795190


Drupal 8 - Alter page attachments AFTER form submit How do you add a library to page attachments (or perform any other alteration) only AFTER form submission?

Long explanation:

I have a very simple contact form which redirects to the frontpage after submission and displays a "Thank you" message.

I need to trigger custom JS events for Google AdWords integration after form submission. In theory this is very simple, just implement hook_page_bottom and attach library with custom JS code.

However, this library should only be attached after form submission and I can't figure out how to detect whether a page load comes from a form submission. My first attempt was to implement hook_form_alter and add a custom submit handler. However, this submit handler is only fired right after form submission, but not in the next page load, which means that my library doesn't get attached.

What is the Drupal way of this?

I see two ways of doing this.

Options 1: Make the form Ajax. Either by using Form API in Drupal or Jquery. Then in success function call your custom js event. Or else you could also do something like this:

 $('#some-form-123').submit(function() {
    _gaq.push(['_trackEvent', 'Contactform', 'Form submitted']);
  });

The above code is an example, you need to use it for your event.

Option 2: In Drupal set a cookie when the form is submitted. Then in page load, check if the particular cookie exists. If it does exist invoke your custom event and unset the cookie. Then, the cookie is only present if the form is again submitted.

See the following:

https://www.drupal.org/docs/8/api/javascript-api/ajax-forms
https://github.com/jquery-form/form
https://github.com/js-cookie/js-cookie


How to force a redirect (override the destination query string in the URL) I have a custom form submit callback to redirect users to a specific page:

function MYMODULE_authfrontpageredirect_callback(array &$form, FormStateInterface &$form_state) {
  $url = \Drupal::service('path.validator')->getUrlIfValid('node/16');
  $form_state->setRedirect($url->getRouteName(), $url->getRouteParameters());
}

This works correctly unless the url has a destination query string, such as
/node/add/mynode?destination=/user

In this case, the user will be redirected based on the query string (to /user) instead of my submit handler destination (node/16).

How do I forcibly override the destination query string content for this submit handler?

This question is similar to this D7 question but since Drupal 8 has the Symfony routing system the answers there did not help me.

To force a redirect remove the destination query string from the request:

\Drupal::request()->query->remove('destination');

After this you can also reset the RedirectDestination service, although this seems not to be necessary for a form:

\Drupal::destination()->set(NULL);

When you have already a URL object set it directly in $form_state:

$form_state->setRedirectUrl($url);


Single quote in in filter return exception querySelectorAll I face a problem when filter with single quote in field.
Anyone know why? And how to disable this exception?

I found a solution for this by using patch.
https://www.drupal.org/project/drupal/issues/2902769
Because this is a core funtion patch, I marked it as can-solve but not plan to use it myself, because the filter works still only some annoying console log.


Redirect from one URL to another based on user role I have two pages on my site (created using views) that I would like to hide from anonymous users by redirecting them to a custom access denied page. i.e. If an anonymous user tries to go to the page "wolfdogs/deceased" they are redirected to "access-denied". I found this bit of php that looks promising:

if (in_array('anonymous user', array_values($user->roles))) {
  $dest = $_SERVER['REQUEST_URI'];
  $dest = substr($dest,1); //this removes preceding slash from string
  $path[]='vote'; //example paths to hide from anonymous users...
  $path[]='volunteer';
  $path[]='papers-list';
  $path[]='event-register';
  $path[]='replays-list';
  $path[]='how-to-upgrade';
  $path[]='membership-renewal';

  if (in_array($dest, $path)) {
    return drupal_goto('members-only'); //this line re-directs to custom access denied page.
  }
}

Ideally I would like put this into a block, and then put the block on the "hidden" pages. However, it was written for Drupal 6; I don't if it works with Drupal 7, and I am unsure how to implement it into a block.

You should be able to restrict the access to the view right from the view edit page. When you are editing the view, change the "Access" setting under the Page Options to allow access based on the Role Authenticated User, which will display an Access Denied page for any anonymous users.


render array with images I have this array in PHP

$link = array(
    '#type'    => 'link',
    '#title'   => 'link1',
    '#href'    => 'http://www.link1.example',
    '#suffix'  => '
',
  );

when i call the render() functions i get the correct html

link1

How i can change the above render array in order to include an image as a link?

In other words i want this as output from the render() function

I have tried to use the theme('image',$array) function but when the result of theme() is passed to the render() i don't see the image to my page but the actual html code.

The pre-render function for a 'link' element type is drupal_pre_render_link()...looking at the docs, you can pass these parameters:

#title: The link text to pass as argument to l().
#href: The URL path component to pass as argument to l().
#options: (optional) An array of options to pass to l().

You can force a link prepared through l() to display HTML by passing 'html' => TRUE as an option, so you should be able to do the same through the render array:

$image = theme('image', array('path' => 'images/link1img.png'));

$link = array(
  '#type'    => 'link',
  '#title'   => $image,
  '#href'    => 'http://www.link1.example',
  '#options' => array('html' => TRUE, 'title' => 'link1'),
  '#suffix'  => '<br />',
);


How can I get all the taxonomy term objects from the database regardless of vocabulary? I can see in the Drupal taxonomy api taxonomy_get_tree() which returns an array of term objects, however, the vocabulary ID is a required object.  I thought also about taxonomy_term_load_multiple, but an array of IDs is necessary to populate it.

How can I get all the objects regardless of vocabulary affiliation? More or less what I am looking for is taxonomy_get_tree('all').

Each term object contains the [vid] it's associated with. I need to be able to loop through each object and determine the vocabulary it's associated with rather than the other way around.

You can use the entity_load() function. The second argument, $ids, is defined as such:

  An array of entity IDs, or FALSE to load all entities.

So you can get all taxonomy terms in the database with this simple call:

$all_terms = entity_load('taxonomy_term', FALSE);


I want to add more fields to be indexed by solr. How can I do that I am now using search_api and search_api_solr. I want more custom fields, to be specific, like the weight for a term referred by a node content type, to be indexed together the out-of-the-box filed(like content type, created, language, etc.). How can I achieve that? what is the hook or api to do that?

Go to admin/config/search/search_api and click "Edit" next to your Index and select "Fields".

Check the checkbox next to the fields you want indexed under the column "Indexed" and click "Save Changes" when you're done.


Set dropdown list programmatically in exposed view filters I have programmatically set a text CCK to a select and given a few choices:

function mymodule_form_alter(&$form, $form_state, $form_id) {
  if ($form_id == 'views_exposed_form' && $form_state['view']->name == 'myview') {
    // Add our custom All buttons.
    $form['field_1hour_currency']['#type'] = 'select';
    $form['field_1hour_currency']['#options'] = array(
      '' => t('<Any>'),
      'USD' => 'USD',
      'EUR' => 'Euro'
    );
  }
}

But this display defaults to a Multiple Choice box, and I want it to be a dropdown list. How can I set programmatically a select to force single so it displays a dropdown list?

Thank you

Add the following to your form_alter implementation:

$form['field_1hour_currency']['#multiple'] = FALSE;
$form['field_1hour_currency']['#size'] = 0;


Scheduler module not working even after cron run Installed 'Scheduler module' and try to publish a content on specific time. But it seems like it is not working.

I tried with  'Run cron manually' also, But it doesn't ,While trying with Scheduler light weight cron it is working.

Why is it not working?

Step: 1. First of all u have to uncheck the published node content types..

Then u have to set the schedular time for particular node

Then U can use Rules module to publish.


Anonymous users email subscriptions to node updates How can I achieve the following:

I want to be able to notify the anonymous user by email when I update a node.

Example: I have `mysite.com/cool-page. I want to have a block with an email field so users can subscribe basically to that page. And every time I update the content from that page, I want the subscribed users to be notified by email.

With Rules I managed to set something up so every time my node is updated it will send an email to users of a role. The problem is that I want to send an email to a list from the database (that I previously collected in a subscription block).

I use Drupal 7.

You could try the MailChimp Subscriptions module. It won't let you subscribe to individual pages, but instead to node authors. (Never tested that)

Another way, might be to use the Simple Subscriptions module and to write some custom code to achieve exactly what you want.


create a page view to have only one specific content type show I'm using D7 and I am working on a blog page. I have created a content type called News, I created a view called News as well.

I want to firstly create a page, all the content that the type is News will be shown on this page, but not other content type.

I can't find where to specify content type in the view settings. Both CONTEXTUAL FILTERS and FILTER CRITERIA seem only have all the content, but how do I specify content type?

Thank you!

Under filter criteria, click on add, select content: Type, and then check the type you want filtered


Downloaded Drupal 8 with composer, now what? I'm a complete Drupal newbie trying to install Drupal 8 for the first time on a new server.  I downloaded the software following the instructions in section 3.5 of the User Guide, but there doesn't seem to be a next step.  Section 3.6 seems to be an alternate method of downloading, and nothing in 3.7 seems to be a continuation of 3.5.  How do I get back on track?

Further information:  In 3.7, it says to go to the URL I set up for the site.  When I do this, I get an index of the directory with these files and directories in it:

LICENSE
README.md
composer.json
composer.lock
[DIR] drush/
load.environment.php
[DIR]   logs/
phpunit.xml.dist
[DIR]   scripts/
[DIR]   vendor/
[DIR]   web/

I'm installing on Ubuntu 18.04 with Apache 2.4, MariaDB 10.1 and php 7.2.

Composer installs all dependencies for you

Next steps

setup a database with user and pass
setup so that your apache/nginx see /web as the webroot (revisit/fix this step so you can get on next step)
visiting the URL should bring up the installation procedure which should ask for DB/user/pass, follow the instructions to complete the installation


how to get the submitted value of tableselect function test($form, &$form_state){
   $form = array();

   $header = array(.............);

   $values = array(.............);

   $form['table'] = array(
      '#type' => 'tableselect',
      '#header' => $header,
      '#options' => $rows,
      '#multiple' => $IsCheckbox,
      '#empty' => t('No users found'),
    );
    $form['submit'] = array(
      '#type' => 'submit',
      '#value' => t('Submit'),
    );
  return $form;
} // end of function test()

function test_submit($form, &$form_state){

$selected = $form_state['values']['table'];

drupal_set_message($selected)  // displays array index (0,1,2 etc)

return;
}

How to get the selected table row values in Drupal form. Need assistance on the issue. Any help would be appreciated.

You can exclude unselected options with array_filter, e.g.

$selected = array_filter($form_state['values']['table']);


How to add a custom icon or symbol to a flag link? I'm working on a 'sample request' implementation for a commerce site using Flag, Views, sessions and a little custom code.

I'd like to add an icon or a symbol to let people know that an item they are viewing has been flagged.

I'm not sure exactly how to approach this, I can imagine perhaps adding a conditional field that displays an image or check box that is then changed by Rules or ajax, or perhaps something more complicated in JavaScript?

It could really be as simple as adding a checkbox that is checked or unchecked as the flag link is clicked or maybe even changing the css/html on click to be identified as marked.

Anyway, grateful for any advice here.

Option 1: Show an image beside the Flag text

You can use CSS to add padding to the left of the text and in it show a background image, as shown also in the community documentation about How to show an image beside the text. Here is an excerpt from it (replace "bookmarks" with the machine-name of your flag):

.flag-bookmarks a {
  padding-left: 20px;
}
.flag-bookmarks a.flag-action {
  background: url(images/i-dont-like-it.png) no-repeat left center;
}

.flag-bookmarks a.unflag-action {
  background: url(images/i-like-it.png) no-repeat left center;
}

Refer to the Flag Theming guide for (way) more details, i.e.:

Theming flag links using CSS, which provides a "map" of the HTML that makes a flag link.
Theming flag links using Templates, which explains how to use the flag.tpl.php file in the 'theme' folder that is located inside Flag's own folder, and which is used to generate the HTML for the Flag links. It also explains how you can theme different flags differently, using a flag specific flag--FLAGNAME.tpl.php file (whereas FLAGNAME is the flag's machine-name).
Theming examples, which contains solutions to some common theming tasks.

Option 2: Transform Flag link into a button

You can transform the Flag link into a button, by adding this CSS (quote from that link):

.flag-wrapper.{flag-name} a.flag-action {
  background-image: url('path to the button image');
  display:block;
  text-indent:-9999em;
}
.flag-wrapper.{flag-name} a.unflag-action {
  background-image: url('path to the button image');
  display:block;
  text-indent:-9999em;
}

Notes:

text-indent:-9999em hides the element (by placing it off the screen).
Replace .{flag-name} with your flag's machine-name.


Form Load and Unload What are the functions  in Form API that perform the task just like form load and unload
I want to perform few checks when the form loads and delete those checks when the form is unloaded.

           function form_example_form($form, &$form_state) {
                 $form['search'] = array(
                '#type' => 'textfield',
                '#title' => t('Search for Members'),
                '#size' => 60,
                '#maxlength' => 128
                );
                $form['submit'] = array(
                '#type' => 'submit',
                '#value' => t('Search'),
                '#submit' => array('myform_newform_submit'),
                );
                 $header = array(
                    array('data' => t('ID'), 'field' => 't.id'),
                    array('data' => t('First Name'), 'field' => 't.fname'),
                    array('data' => t('Last Name'), 'field' => 't.lname'),
                    'operations' => array('data' => t('Operations'), 'colspan' => 2),
                  );
                if((variable_get('results'))!="") {

               $query = db_select('myform', 't')
              ->extend('TableSort')        //Sorting Extender
              ->orderByHeader($header)
              ->extend('PagerDefault')
              ->condition('lname',variable_get('results'),'=')
              ->limit(2)
              ->fields('t', array('id', 'fname', 'lname'));
              $results = $query->execute();
              foreach($results as $node)
              {
               $rows[]=array(
                    'id' => $node->id,
                    'first_name' =>$node->fname,
                    'last_name' => $node->lname,
                   'modify' => l('Modify', 'myform/modify/'.$node->id),
                    'delete' => l('Delete', 'myform/delete/' . $node->id));
               }
               }
               else
               {
               $rows = array();
               }
            $form['pager_table'] = array(
              '#theme' => 'table',
              '#header' => $header,
              '#rows' => $rows,
              '#empty' => t('Empty Rows')
              );
              // attach the pager theme
              $form['pager_pager'] = array('#theme' => 'pager');
                return $form;
                                     }

                             function form_example_form_submit($form,&$form_state)
               {
        variable_set('results',$form_state['values']['search']);
                   }

Now when I change the link how do I free the variable at form unload

Lets try this method

on your form

function form_example_form($form, &$form_state) {
  $name = 'myname';
  $value = 'nikhil';
  variable_set($name, $value);
  // Your form elements goes here ...
}

function form_example_form_submit($form, &$form_state) {
  $name = 'myname';
  $myname = variable_get($name, $default = NULL);
  echo $myname; // will print nikhil
  variable_del($name);

}

As i dont know any Form Unload event i will do

drupal_add_js("jQuery(document).unload(function() {
//make an AJAX call to clear the value });", 'inline');

in javascript

Good luck.


How does a Rule access a variable defined in the event info? I'm looking at the Drupal Commerce module in Drupal 7, and it has a Rule to send an email notification that the order was completed after checkout.  Perusing the code in commerce_checkout.rules.inc, the hook_rules_event_info() has a variable of type commerce_order().

How does Rules retrieve the tokens and the $order object?  Or how does the Commerce Order module define a variable type to use with Rules?

I was looking in the wrong place and thought about how Rules work the wrong way.  The event for when an Order entity is part of the Rule is triggered by the Commerce module on checkout.

rules_invoke_all('commerce_checkout_complete', $order);

And for the other entities, Rules already takes care of most by invoking events from its events.inc.


Update field value after save a node My content type has a field call tracking code, I have granted permission for users are able to create content. When they create content, they cannot see tracking code field but after they submit the content, they will see a tracking code string in message area.

In that node I also have reference field with other content type, so the string that I expect to show must include the id of reference node and id of the node being created.

EX: P1C2 (1 is id of reference node, 2 is id of node being created)

Does drupal have any modules support to do that or I must do it programmatically and how can I build the coding for that? Thank you all!

You could use the computed field module.

  Computed Field is a very powerful field module that lets you add a
  custom "computed fields" to your content types. These computed fields
  are populated with values that you define via PHP code. You may draw
  on anything available to Drupal, including other fields, the current
  user, database tables, you name it. (Feeling the power yet? :) ) You
  can also choose whether to store your computed field values in the
  database with other content fields, or have them "calculated" on the
  fly during node views. (Although you should note that Views use
  requires database stored values.) This field is literally the Swiss
  Army knife of fields. So start cooking up your PHP based values!

You can get all the information that you add in other fields with in the computed field. Since you have not yet saved the node you might want to add the following code at the beginning to make the nid available.

https://drupal.org/node/149225


Broken Admin Menu, How Can I Repair It? A while back I upgraded from D6 to D7 using the Drupal upgrade script. A bug that's lingered in my system is broken menus.

For example, on /admin I have a link for both "People" (/admin/people) and "User management" (/admin/user). The link for "User management" is dead, it goes to /admin, and I believe it is a carryover from the D6 install. I can give many more examples if necessary.

Is there a way to remove the broken menu items without affecting my working D7 menu items?

Thanks in advance to anyone that helps!

Unfortunately—and this is not an ideal solution, but seems to be what everyone is using successfully—I have had to use the following brute-force SQL statement in the past.

First, backup your entire Drupal database!

Then, execute this in your favorite SQL manager:

DELETE FROM menu_links WHERE module = 'system';

Then visit /admin/config/development/performance and clear the cache.

taken from https://drupal.org/node/865702#comment-4015758


User can self-register unless email is on a blacklist I want users to be able to register unless their email address is on a blacklist (including wildcards), in which case an administrator has to approve the registration. How do I go about this?

No need to add any custom code as your requirement is just to allow visitors to register by themselves but you want to block them for log in till the administer won't approve them, if this the scenario then just go to the following URL:

/admin/config/people/accounts

or you can navigate through Admin Menu:

configuration >> People >> Account Settings

Here you can find section "Registration and Cancellation" under which you can find:

Who can register accounts?
Select:
Visitors, but administrator approval is required

Note: You can also set "Require e-mail verification when a visitor creates an account", if you required e-mail verification too.

For validation whether the email is in your blocked List or not you can validate it by writing your own custom validation function using:

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

if($form_id == 'user_register_form'){

  $form['#validate'][] = 'your_validate_func_handler';

}

}

function your_validate_func_handler(&$form, &$form_state){

// here is your code to compare

}

Note: "hook" will be replaced from your custom module name.

Hope this will help you.


Image files aren't recognized when changing a html file to page.tpl.php I want to create a drupal theme base on a static web template. after googleing I've found out that I should set up a .info file and also put my header in the html.tpl.php and body in page.tpl.php and so on.
I change index.html file into page.tpl.php, but the image in the site aren't recognized by drupal(although the index.html worked correctly).
It seem to me that drupal should show the page exactly same as static version because I have't added any code into the page ( in order to change the static version into the dynamic one ).
if so, how can I find the problem.
Thanks

HTML:

    <script type="text/javascript" src="js/modernizr.js"></script>
    <script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
    <script type="text/javascript" src="js/rgpars-custom.js"></script>

=====>

.info file:

    scripts[] = js/modernizr.js
    scripts[] = js/jquery-1.8.2.min.js
    scripts[] = js/rgpars-custom.js

html.tpl.php file :

    <head profile="<?php print $grddl_profile; ?>">
      <?php print $head; ?>
      <title><?php print $head_title; ?></title>
      <?php print $styles; ?>
      <?php print $scripts; ?>
    </head>

If your images (ie. your img directory) are in your theme directory, use something like <img src="<?php print base_path() . path_to_theme(); ?>/img/works/works-full8.jpg" /> to include them.

If they are in your sites/default/files directory, use .

If they are in your site root, use


Access values from multiple field forms as elements of one form I'm trying to create entities from my custom form. To do that, I created "Add more" button, where I'm dynamically adding new elements that I'm attaching fields to by using:

field_attach_form('myentity', $entity, $form['wrapper']['myentities'][$key]['fields'], $form_state);

I would like to create entities in submit callback with field values from those elements.

The problem is, that when I have a multiple elements, inputs for the same type of fields of different entities have the same "name" attribute (eg. field_myfield[und][0][value]), which means that I can access only the value from the field of the last entity in the submit callback, which means that I cannot fill my entity with proper values before saving. I tried to put '#tree' => TRUE up the form tree, and unset this value on field level, but it didn't change an input name, and "values" structure.

How can I have in my submit callback access to all of the field values, so I could use them for creating entities?

You need to use the #parents variable as documented in the field_attach_form page.
See field_attach_form


How to make select option works like a button? I have created a contact form by using webform module, in that I have added one component as reset and the type is select options.

My requirement is when I choose this reset option from that dropdown and submitted the form, I want to reset my form. I have no idea how can I achieve this. I tried following but not worked, please help me regarding this.

function test_form_alter(&$form, &$form_state, $form_id) {
   if ($form_id == 'webform_client_form_111') {
    $form['submitted']['reset']['#option'] = 'test_reset';
  }
}
function test_reset(&$form, &$form_state){
  $form_state['rebuild'] = FALSE;
}

You can write a simple jQuery script for achieving this.

$('select').on('change', function() {     // you can refine this with your field id.
  if( this.value == 'reset' ) {           // Replace value for your 'reset' option.
    $('#yourid').find('form')[0].reset(); // Replace id here
  }
})


What to replace entity_uri() with in Drupal 8? So I have the following code in my Drupal 7 module:

$uri = entity_uri('node', $node);
$breadcrumb[] = l($node->title, $uri['path'], $uri['options']);

Anyone know how to convert the above code to Drupal 8?

Since l() is depreciated, I believe the second line should be replaced as follows:

$breadcrumb = array(Link::createFromRoute($node->title, $uri['path'], $uri['options']));

I'm struggling with what to do with entity_uri() since the change records don't really indicate how that function is to be replaced.

Note: this is being used within the BreadcrumbBuilderInterface class.

Try with this code:

$link = $node->toLink($node->getTitle(), 'canonical', $options);

Get more information about Node object here: "Node Object"


Memory error when creating image styles I am getting the following error when image styles are being created on my Drupal 7.24 site:

  mod_fcgid: stderr: PHP Fatal error:  Allowed memory size of 134217728
  bytes exhausted (tried to allocate 73834563 bytes) in
  modules/system/image.gd.inc on line 237"

My style is doing a scale and crop down to 300x200.

I know this could be a problem with my memory limit, which is currently 128M.  As this is high, this doesn't seem like an issue.

Could it be from the use of the File (Field) Paths" module for my image names?

What's the size of your image? For scale you may need roughly:

X * Y * 4 (bytes per pixel) * 2 (for source and destination image) * 2 ( to make sure there is enough RAM for computation).

Now, core can require up to 32 MB, and modules can easily double or even quadruple this. So, let's optimistically assume your core + modules only use 64MB. That leaves other 64MB. It means you can safely scale images up to 4194304px. It seems you have enough memory for 4Mpx input images. Anything larger can cause this error and it will not be anything surprising.


Only show the amount of views in Advanced Forum I am using the 'Advanced Forum' module in Drupal 7 and I want to have a 'Views' column in the topic list. I have managed to do this using the Statistics module, but now at the bottom of every node it says '## reads', much to my dislike. Therefore, I would like to remove every visible view count; only leaving the views column in the 'Advanced Forum'.

Is this possible? If it is possible, how can I do it?

Also, the view count on nodes is permission based, so you can deny the view permission to everyone and then it will only show for UID 1.


How can I create a view showing count of users by birth year? I want to create a table showing a count of number of users by birth year. Right now I've done the following:

Create a view of profiles rendered as a table (no grouping fields, though I've tried grouping to no avail)
Create two fields:

Birth date, rendered as four digit year, aggregated as "Group results together"
Profile ID, aggregated as COUNT DISTINCT

Sorted these by descending birth date

The problem is that this does not group the dates by year - it still groups the dates by day. Right now, rather than one line in my table for each year, I'm getting something like this:

2017 | 1
2017 | 2
2017 | 1
2017 | 1
2017 | 3
2017 | 1

...the left column being the four digit year and the right column being the number of users born on a particular day in 2017. The above should have rendered as:

2017 | 9

How can I get my table to show a count of users by birth year?

You could try out the following module which enables aggregation on your chosen granularity: https://www.drupal.org/project/views_date_format_sql

After enabling, a checkbox will appear in the Date field setting of the view, called 'Use SQL to format date'.


How can I add a new module to existing Examples Module? I have created a New Drupal 8 Module that could be added to existing Examples Module. So, How I can proceed?

Thank you so much on starting on this! Examples module have helped many developers overcome the Google fail!

And contributing to it is pretty easy. Personally, to add the module to the main module, I would follow the steps below:

Create a sandbox project with the name foo_example (foo being the nature of your module.
Check if the module satisfies the checklist : https://www.drupal.org/node/2209627
Create an issue in the issue queue with

Title : Add foo_example to the D8 repo.
Category : Plan
Version : 8.x-1.x-dev
Component : Other
Status : Needs Review

Inside the body give a description of what your module does, link it to the sandbox project.

Next, you wait for the reviews :) You might get it reviewed by your peers or friends/IRC so that some obvious issues are spotted on early. And the maintainers of the examples module should be able to review it. And you should also get credits for your work!


How do I access the database from a stand-alone PHP script? I have problems to define the right path to the root and bootstrap data in php.

My structure (Windows) looks like the following.

C:\xmapp\

htdocs\

testdrupal\

test.php

includes\

bootstrap.inc

sites\

default\

settings.php

The content of the test.php file is the following.

<?php

  chdir('C:\xampp\htdocs\testdrupal\');
  // Bootstrap Drupal up through the database phase.
  include_once('./includes/bootstrap.inc');
  drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
?>

When I run it, I get the following error.

  Parse error: syntax error, unexpected '/' in C:\xampp\htdocs\testdrupal\test.php

What am I doing wrong?

Check the first line (where you have ..testdrupal\');

The \ before the ' is escaping the ' so it's as if it's not there (sorry, it's tricky to explain without my morning coffee).

With the character escaped, the line is being read as follows:

chdir('C:\xampp\htdocs\testdrupal'./includes/bootstrap.inc');

Which is where your error is most likely coming from.

Try changing the first line to the following:

chdir('C:\xampp\htdocs\testdrupal\\');

The extra \ means that you are escaping the following character so the line will be read the way you want it to be.

There's a quick explanation of escape characters here.


services userpoints with xmlrpc server can't be linked by external device? I had searched the article, and i still can't figure out how to use services userpoints with xmlrpc.(My Environment drupal 7,Service 3.x, userpoints )

i read the readme in the userpoints module.

$result = xmlrpc($server_url, 'userpoints.points', $key, $uid, $points, $tid, $event, $description);

i wrote this code in the other sites,and tried to add/subtract the points.It doesn't work.

I tried function xmlrpc() in drupal API and follow the api rules, it doesn't work either.
drupal api function: xmlrpc($url, $args, $options = array())

the code i wrote:

$key='1234';// casually set
$uid=1;
$points=1;
$tid=18;
$event='event testing';
$description='description testing';
$result = xmlrpc('http://my.domain/userpoints-api/', array(
  'userpoints.points' => array($key, $uid,$points,$tid,$event,$description),
));
dpm($result);

$result is nothing.
Does anybody have the experience on this?
Thank you guys.
Please help me.

i check the access.log
i got the message belowed

210.65.11.209 - - [23/Aug/2013:15:49:50 +0800] "POST /userpoints-api/add HTTP/1.0" 200 767 "-" "Drupal (+drupal.org/)

I didn't test xmlrpc($server_url, 'userpoints.points', $key, $uid, $points, $tid, $event, $description) is worked or not.

Instead, I use POSTMAN extension from chrome store to post data to the userpoints service api endpoints path.

The userpoints alias must be filled, the data here is "pointss".
url:http:userdomain/userpoints_api/pointss method:POST
header: Content-type | application/xml
raw/xml

<?xml version="1.0"?>
<methodCall>
   <methodName>pointss.add</methodName>
   <params>
     <param>
           <name>uid</name>
           <value><int>1</int></value>
           <name>points</name>
           <value><int>170</int></value>
           <name>tid</name>
           <value><int>18</int></value>
           <name>operation</name>
           <value><string>test for operation</string></value>
           <name>description</name>
           <value><string>test for description</string></value>
           <name>entity_type</name>
           <value><string>node</string></value>
           <name>entity_id</name>
           <value><int>1</int></value>
     </param>
   </params>
</methodCall>

Done.


Node Access permission for anonymous users The website is set Only login users can access. but There are times a node maybe allow an anonymous user to access by sending the user the URL for the node.

I try to use the Content_Access module to make it but it failed to make it.

How can achieve it??

Content Access controls access by content type. The module you want is the Nodeaccess module.


Prevent Development modules from being added to configuration management We have modules that are only used for local development like Stage File Proxy. How would I prevent these modules from being added to the configuration management?

From Dave Reid on Twitter

Ignoring Development Modules

If you have a certain list of modules that should only be enabled on the development or staging server, then this may be done with the built-in --skip-modules option in the config-export and config-import commands.

For example, if you want to enable the 'devel' module on development systems, but not on production server, you could define the following configuration settings in your drushrc.php file:

# $command_specific['config-export']['skip-modules'] = array('devel');
# $command_specific['config-import']['skip-modules'] = array('devel');

You may then use drush pm-enable to enable the devel module on the development machine, and subsequent imports of the configuration data will not cause it to be disabled again. Similarly, if you make changes to configuration on the development environment and export them, then the devel module will not be listed in the exports.

http://www.drush.org/en/master/config-exporting/#ignoring-development-modules


How to list all managed files? I need to get Drupal to list all its files and their management status for debugging purposes. It seems like there must be a simple way to print the list of managed files, right? How is this done?

There is at least 1 issue queue item looking to add "reporting" to the Media module, such as show me where this file is used on the site.

If you're using Drush. Look at drush sql-cli and a query such as select fid, filename from file_managed where status = 1


How do you migrate a site with Drupal 7 Image Styles and make sure the adjusted images migrate? I am moving a D7 site from local to staging for the first time. I pushed my codebase through deployment, and I did drush sql-dump to get the database moved over. Then I copied the files directory as-is.

The new server site works perfectly -- except that images that are supposed to be generated by the image styles show up as broken. They're not being dynamically generated like they should, even though the styles themselves are there.

Any thoughts on why this would happen or how to debug it?

Turns out I was trying to run deployment with my files directory outside of the Drupal root, and even though I was relatively pointing to the right path, it just didn't like that. So I symlinked sites/default/files to the folder outside of the Drupal root and it works fine now.


How to add Javascript in Drupal 7 with jQuery? I am trying to provide the option that users be able to put comment under each paragraph. So at the end of the article, I have something like this:

Comments for paragraph 1

  /* here I show the comment for paragraph 1 */

Comments for paragraph 2

  /* here I show the comment for paragraph 2 */

Comments for paragraph 3

  /* here I show the comment for paragraph 3 */

so  I have added the following to node.tpl.php:

    for($b=1;$b<$number;$b++)
   {
         echo "Commentsfor Paragraph $b:" ."
" . "
" ;

        foreach($cid_numbers as $no)
          {

             $e=($content['comments']['comments'][$no]['#comment']->paragraph_id);
             if($e==$b)
             print render($content['comments']['comments'][$no]);

           }
        }

and it works. But now I want to hide the comments and only when users clicks on a link like:  Comments for paragraph 1, then he be able to see the comments.

In order to do that I have added the following to node.tpl.php file:

and also changed the first code to this:

    for($b=1;$b<$number;$b++)
   {  ?>

<?php echo "Commentsfor Paragraph $b:" ."
" . "
" ; ?>

 <?php
   foreach($cid_numbers as $no)
    {

  $e=($content['comments']['comments'][$no]['#comment']->paragraph_id);
   if($e==$b)
    print render($content['comments']['comments'][$no]);

   }   ?>
 <?php

   }

This is the website that gave me the idea that how to do the hide/show: http://renaudjoubert.com/en/article/how-add-javascript-drupal-7-jquery?utm_source=twitterfeed

But the output looks like this:

comments for paragraph 1

 here it show comments for paragraph 3

comments for paragraph 4

and then when I click on the link "comments for paragraph 1" then  it displays the comments for paragraph 1 and also the link " comments for paragraph 2".
So what is my mistake? Have I put  tag in the right place? Or do you have any suggestion that how can I hide comments and show them when click on the link?

I may be wrong but I would remove your inner foreach and just use your $b variable instead of $no.

Alternatively here is another way to do it:

http://jqueryui.com/accordion/


How to embed and choose entityform in custom content type? I have a D7 Website, and I am using entityforms module.
I want to include those entityforms which I created in my custom content type so that users can submit their details. For example: a node with multi-field comments box.
To achieve this, I added a field in custom content type of type "Entity reference" -> List.
As an admin, I get to choose all available entity forms but not as a custom user role for which it shows "access restricted" while choosing entity form type.

Please guide.

OK, so I gather the problem you are trying to solve is the fact that a non-administrator cannot pick an entityform from the list? The solution: go to /admin/structure/entityform_types, choose "Edit" for each Entityform and be sure to check the boxes in "Roles" for "authenticated user". That way anyone logged in should be able to see and use the form.


Panels selection rule node author I was wondering, I have a panels using the "Node template", is there a way to have "node author" as a selection rule, now I only have "node type".

I'm using Drupal 7.9.

Under the "Contexts" tab for your page variant, add a relationship to Node:author.  This will expose the available fields from the author for your use.

However, What are you trying to do?  You might be better off to define what you want in Views and then set up a node page variant to display the view for you.


Form Submit without module Is a module required to submit a form ?
I get a standard form from our designer and try to send it as follow:

<form action="/kontakt" class="sky-form" method="POST" name="kontakt">
  ...
  <input type="submit" class="btn btn-u btn-u-lg" value="Nachricht absenden">
</form>

I have tried different function calls without success

MYTHEME_form_submit(array &$form, FormStateInterface $form_state)
contact_form(array &$form, FormStateInterface $form_state)
contact_form_submit(array &$form, FormStateInterface $form_state)
MYTHEME_contact_form_submit(array &$form, FormStateInterface $form_state)
...

i have to say, that i am a beginner in Drupal 8, so help is very appreciated.

thank you.

Two ways to approach this.

One way is to use the Webform module. If this is just a simple contact form, you can get this done with Webform in five minutes.

The second way is create a custom module that implements a route, Form class and related methods. Wouldn't take an intermediate long, but a beginner should try Webform first.

You cannot simply paste form HTML into a twig file and expect it do anything. Drupal is ignorant to its existence and therefore no hooks will work, as you already saw.

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


Drupal 7 get user by Profile2 field value I have Profile2 field name uid_intranet which is unique.
And in one of my module, I want to get $user object by uid_intranet. The API is kinda like:

$users = profile2_get_users('uid_intranet', 100)

But no such API. So any solutions?

Thanks!

UPDATE 01, my complete code:

// Helper
function _mymodule_get_profiles_by_profile2field($field_name, $field_value) {
  $table = "field_data_{$field_name}";
  $column = "{$field_name}_value";

  // Profile IDs
  $pids = db_select($table, 'ui')
    ->fields('ui', array('entity_id'))
    ->condition($column, $field_value, '=')
    ->execute()
    ->fetchAllKeyed(0,0);
  if (is_array($pids) && count($pids) > 0) {
    $profiles = profile2_load_multiple($pids);
  }
  return $profiles;
}

Why not adding your helper function to query the database, something like below

function mydmoulename_get_user_by_prfoile2field($field_value) {
    $user = new stdClass();
    $user_id = db_select('field_data_field_uid_intranet', 'ui')
        ->fields('ui', array('entity_id'))
        ->condition('field_uid_intranet_value', $field_value, '=')
        ->execute()
        ->fetchAllKeyed(0,0);
    if (is_array($user_id) && count($user_id) > 0) {
        $user = user_load_multiple($user_id);
    }
    return $user;
}

NOTE:

When you add a field to profile, a custom table is created in database,so check your database and get the table name, in above example I am using table name as "field_data_field_uid_intranet". When you browse the table you will find column where it wil be storing the field value against the user who added the fied, you need to check the column name which is holding the field value in above exampe I am using "field_uid_intranet_value" as column name change it according to your requirement.

Once done, now you have your own function simply call it passing the field value as argument like

$user = mymodulename_get_user_by_prfoile2field(100);

you will get the complete user object as return value.


Disable blocks for certain pages How can I disable blocks (e.g., the menu block or the search block) from a custom module?

Concretely I have an access to my clients managed by a custom module, and I don't want anything appears on their access page except my company's logo.

If you want to change the visibility of many blocks at the same time, this module would be perfect:

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

  Block Visibility Groups allows the site administrator to easily manage
  complex visibility settings that apply to any block placed in a
  visibility group. The visibility settings for all blocks in the group
  can be edited on one administration form.

  This modules works in conjunction with the Drupal 8 core's block
  administration system. It is a simpler alternative to modules like
  Panels.

Even you want to code this yourself, you can use this module as a starting point. The author of this module has a 2 hour video how this code was built.


Drupal Commerce : Shopping Cart Checkout for Orders What I'd like to do is have an order page where the user see's a list of all products.

They'll then fill out the quantities they want and click on 'checkout'  .

So it'd look like how the Cart looks once you've added products

Has anyone done this or anything similar.   I'm currently looking at using Drupal commerce on Drupal 7.

Much Appreciated.

My initial thought is for you to check out the commerce_add_to_cart_extras module.  Granted, it's still in its dev version, but you can create a view with products, specify quantity, and bulk-ly add to cart.

To go straight to checkout, you may need to add a little redirect in the submit handler for that button.


Workbench module without taxonomy vocab Is there a way to use a workbench module for workflowing purposes without having any taxonomy vocabularies defined?

Your question is too vague. Workbench is a Suite of modules: Moderation, Access, Files, Media ...

Workbench Access can work with Taxonomies or Menu hierarchies.

Currently Workbench only works with data whose base type is a Node it does not work with custom Entities you may use on your site.


Using webform-form-[nid].tpl.php to change default template On drupal 7, using webform 7.x-4.11, I am trying to modify the template of a specific webform.

So, in /web/themes/bartik/templates (I am using bartik theme) I created a file named webform-form-23.tpl.php

As "23" is the nid of my webform. But the template is not applying at all...

If a create a file webform-form.tpl.php it is well applying to all my webforms...

This is not a matter of caches as it is well applying when using a file named "webform-form.tpl.php" (with no ID) and despite of that the cache has been cleared at every changes.

Can someone help me on this one?

Have you made a clear cache in admin/config/development/performance?

Or have you looked if in the template there is a error in the code? To verify this you can try to copy all code of "webform-form.tpl.php" in your "webform-form-23.tpl.php" and at the top of the code, before the first TEST!!! , refresh the cache and look if TEST!!! is displayed. If you display TEST!!! in your previous code there is an error.


Send email with attachment I want to send an attachment with drupal_mail() using hook_mail_alter(). Do you have any ideas about which parameter should I use?

Does the variable $param help, in some way?

The default mail implementation in Drupal does not support attachments.

You will need one of the contrib mail modules which support attachments, for example http://drupal.org/project/mailmime. I wasn't able to find any useful docs and it seems that the maintainer is aware of it and hopefully working on something.