Unique Value validation rule does not show the indicated message I have a Unique Value rule for a field. The rule applies correctly and the offending field gets highlighted in red but it doesn't show any messages !

I have other validation rules on the same field (must be a number, minimum, maximum etc) and they behave correctly i.e field is highlighted in red and the indicated error message appears.

You wouldn't believe this but it was the theme. We had forgotten to include the markup that contains the flash messages sent by core to the user so basically it any flash message (including the validation errors) wouldn't show up.

The reason why other validation errors showed up was the Client-side Validation module that causes some certain form of validation violations to be detected in the client and displays them via it's own device.


Why does the zen theme load javascript in the head element? Most tutorials for jQuery recommend loading javascript before the closing body tag so that the rest of the page can load first. However the Zen theme (im not sure about others) doenst do this. Why is this the case?

Some contrib modules only work correctly if jQuery and other scripts are in <head>.

Check out the Magic module or the AdvAgg module, which gives you greater control over how CSS and JS files are handled in your theme.


Default values not working in multiple select options I have a form with  multiple select options.Other things are working fine. But when I revisit the form I have to select everything again. I have given:

'#default_value' = previously selected array()

But that is not working I guess. Is there any method that the user can add in the selected list without need to select everything again ?
Thank you .

check it out - http://drupal.org/node/73077


Combining Date Start and Date End in Drupal 8 Views Block I am new to Drupal 8 Views - How do you concatenate Event Start Date Sept 1, 2019 with Event end Date ie: Sept 4, 2019? The end result is they just want the Month and Day to show up like this Sept 1-4.

You can create a custom field formatter plugin for the daterange field type and you can use it at other places on the website too.


formBuilder()->getForm() outputs everything except the  tag in a view? When displaying my entity edit form with \Drupal::formBuilder()->getForm($form); (for a flagging attached to a node) in a View that is set to show Content with the Default display, I noticed the <form> tag itself is missing:
<form class="flagging-myflag-edit-form flagging-form" data-drupal-selector="flagging-myflag-edit-form-iq8dn9lwifq" action="/flag/details/edit/MYFLAG/52" method="post" id="myform-myflag-edit-form--iq8dn9lWIfQ" accept-charset="UTF-8">
Everything between the form tags is printed properly.
</form>

The <form> tag appears on the node page correctly, but it does not appear in the view.
So somehow, Views is filtering out the <form> tag, but I need to keep this tag.
This is the code I am using:
function MYMODULE_node_view(array &$build, NodeInterface $node, EntityViewDisplayInterface $display, $view_mode) {
  if ($node->getType() == 'MY_CONTENT_YTPE') {
    if ($display->getComponent('my_flagging_form')) {
      $flag = \Drupal::service('flag')->getFlagById('MY_FLAG');
      $flagging_entity = \Drupal::service('flag')->getFlagging($flag, $node);
      $form = \Drupal::service('entity.manager')
        ->getFormObject('flagging', 'edit')
        ->setEntity($flagging_entity);
      $build['my_flagging_form'] = \Drupal::formBuilder()->getForm($form);
    }
  }
}

According to twig debugging, the custom form is being output through core/modules/system/templates/form.html.twig, but there's no form tag when output by Views (the tag does appear on the node page).
This is form.html.twig:
<form{{ attributes }}>
  {{ children }}
</form>

EDIT: I tried to render it based on the comment of @Ales:
  $form = \Drupal::service('entity.manager')
    ->getFormObject('flagging', 'edit')
    ->setEntity($flagging_entity);
  $form_to_render = \Drupal::formBuilder()->getForm($form);
  $renderer = \Drupal::service('renderer');
  $build['remember_form']['#markup'] = $renderer->render($form_to_render);

This gives me the same output as my original code; the form is there, but the <form> tag is not...
EDIT 2: I also tried using template_node_preprocess() instead of hook_node_view():
function MYTHEME_preprocess_node__MY_CONTENT_TYPE(&$variables) {
  $node = $variables['node'];
  $flag = \Drupal::service('flag')->getFlagById('MY_FLAG');
  $flagging_entity = \Drupal::service('flag')->getFlagging($flag, $node);
  $form = \Drupal::service('entity.manager')
    ->getFormObject('flagging', 'edit')
    ->setEntity($flagging_entity);
  $form_to_render = \Drupal::formBuilder()->getForm($form);
  $variables['MY_FLAG_form'] = $form_to_render;
}

But when I rendered this variable in my theme template, I got the same result-- the <form> tag appears on the node page, but not in the view that shows Content with mode full content.

Looks like views reformats rendering as a form if there are any form elements in a row. See \Drupal\views\Plugin\views\display\DisplayPluginBase::elementPreRender:
    // If form fields were found in the view, reformat the view output as a form.
    if ($view->hasFormElements()) {
      .....
    }

I guess you should see one <form> tag arround the entire view.
In this case a possible solution would be to create a custom views display plugin Forms, that overrides the elementPreRender method and ignores the form elements check.


Edit values of a select list in a view I have a select list in a view that filters the view by the team number.
Each team number will be displayed in the select list like:
2014-2015 - 01, 2014-2015 - 02 and so forth.
All I want are the last two numbers to display on the view's table, so what I did was used a computed field to just grab the last two numbers so then only the team number shows up.
However, I can't use a computed field to automatically fill the contents of a select list, and when I create a team filter, the select list has  2014-2015 - 01 , 2014-2015 - 02, and so forth.
I want to edit the select list so it only shows 01, 02, etc.
I am really good with JS injector and prefer to do most things like this with that, but sadly the page is refreshed so many times it's not a good thing to use.  Any thoughts?

I suggest you create a custom module and in hook_form_alter according to your expose filter module form_id  get your form element,then you can change the value of your expose filter without change the value of them (as what you want)
something like below code can help you

function yourmodule_form_alter(&$form,$form_state,$form_id){
   if ($form_id == "your_views_exposeform") {
            // first try dpm($fom); to see what you have there
            foreach($form['expose_your_field']['und']['#options'] as &$item){
            //  repalce label of select option items with what you want
            }
        }
        }


Is it possible to redirect users when page caching is enabled? I use simple redirect user inside template.php with the following code:

if ( isset($_GET['abc']) && $_GET['abc'] == 1 ) {
  drupal_goto('mypage');
}

Is it possible to redirect to the page even with caching turned on? It seems that if the page that I want to redirect from is already cached, the template.php file does not fire.

Usually no. Not like that.

Caching systems are created to serve content with as minimal as possible PHP execution. If you use varnish, nginx or similar cache, or Boost module, you ay even not have any PHP executed at all. And even if some parts of PHP are executed, theming layer is usually omitted, because logic shouldn't be there - and if logic shouldn't be there, then that's exactly the part that is (or should be) safe to cache.

So first, try to move logic from template to some module, and second - learn about the caching system you are using, and how to add exceptions to it (if just moving the logic does not fix it for you already).


Validate CCK field to not allow links/URLs I want to allow users to input free text, but don't want them including any links or references to URLs. I know how to set up a filter on the CCK field so that 'a' tags cannot be included, but this will not stop the user typing www.google.com etc.

I have tried searching for modules to achieve this, but have not managed to find any. Does anyone know of a module to filter CCK fields to validate for 'www', '.com' etc, or alternatively one for custom CCK validation?

If there aren't any modules I think I would have to follow these instructions to build a custom CCK Validation module. I would appreciate advice on whether this would be the most efficient approach or if this would be reinventing the wheel?

Ok, So I have worked out how to do this.

First install the Field validation module.

Then go to the 'manage fields' page for your content type. To the right of each field is a 'validate' link. Click on validate for the field you wish to add validation for.

Click 'PHP code' and note the 'Be careful, it is powerful and also dangerous.' warning!

Enter a rule name such as 'dont allow URLs'.

In the PHP code box enter the php you wish to validate. I made an array of all the the top level domains etc I didn't want users to use, and checked the input against this in a foreach loop. The code I used to do this is:

$mystring = $this->value;
$arr = array("http", "https", "www", ".com", ".org", ".net", ".info", ".mil", ".mobi", ".edu", ".gov",  ".biz", ".ac", ".ad", ".ae", ".af", ".ai", ".al", ".am", ".ao", ".aq", ".ar", ".as", ".at", ".au", ".aw", ".ax", ".az", ".ba", ".bb", ".bd", ".be", ".bf", ".bg", ".bh", ".bi", ".bj", ".bm", ".bn", ".bo", ".br", ".bs", ".bt", ".bw", ".by", ".bz", ".ca", ".cc", ".cd", ".cf", ".cg", ".ch", ".ci", ".ck", ".cl", ".cm", ".cn", ".co", ".cr", ".cu", ".cv", ".cw", ".cx", ".cy", ".cz", ".de", ".dj", ".dk", ".dm", ".do", ".dz", ".ec", ".ee", ".eg", ".er", ".es", ".et", ".eu", ".fi", ".fj", ".fk", ".fm", ".fo", ".fr", ".ga", ".gd", ".ge", ".gf", ".gg", ".gh", ".gi", ".gl", ".gm", ".gn", ".gp", ".gq", ".gr", ".gs", ".gt", ".gu", ".gw", ".gy", ".hk", ".hm", ".hn", ".hr", ".ht", ".hu", ".id", ".ie", ".il", ".im", ".in", ".io", ".iq", ".ir", ".is", ".it", ".je", ".jm", ".jo", ".jp", ".ke", ".kg", ".kh", ".ki", ".km", ".kn", ".kp", ".kr", ".kw", ".ky", ".kz", ".la", ".lb", ".lc", ".li", ".lk", ".lr", ".ls", ".lt", ".lu", ".lv", ".ly", ".ma", ".mc", ".md", ".me", ".mh", ".mk", ".ml", ".mn", ".mo", ".mp", ".mq", ".mr", ".ms", ".mt", ".mu", ".mv", ".mw", ".mx", ".my", ".mz", ".na", ".nc", ".ne", ".nf", ".ng", ".ni", ".nl", ".no", ".np", ".nr", ".nu", ".nz", ".om", ".pa", ".pe", ".pf", ".pg", ".ph", ".pk", ".pl", ".pm", ".pn", ".pr", ".ps", ".pt", ".pw", ".py", ".qa", ".re", ".ro", ".rs", ".ru", ".rw", ".sa", ".sb", ".sc", ".sd", ".se", ".sg", ".sh", ".si", ".sk", ".sl", ".sm", ".sn", ".sp", ".sr", ".ss", ".st", ".sv", ".su", ".sx", ".sy", ".sz", ".tc", ".td", ".tf", ".tg", ".th", ".tj", ".tk", ".tl", ".tm", ".tn", ".to", ".tr", ".tt", ".tv", ".tw", ".tz", ".ua", ".ug", ".uk", ".us", ".uy", ".uz", ".va", ".vc", ".ve", ".vg", ".vi", ".vn", ".vu", ".wf", ".ws", ".ye", ".za", ".zm", ".zw", ".name", ".pro", ".aero", ".asia", ".cat", ".coop", ".jobs", ".museum", ".tel", ".travel");
    foreach ($arr as &$findme) {
           $value = strpos($mystring, $findme);
           if ($value === false) {
           } else {
               $this->set_error();
           }
    }

Check the tick box that says 'Set errors using field API'

In the last text box you add your custom error message. E.g.

Please remove all links/URLs for example: 'www', '.co.uk'& '.com'. Please check that you have a space after each full stop.

I hope that this helps somebody else.


drupal behat test assert authenticated by role with given fields I am trying to run the following behat step:

@Given I am logged in as a user with the :role role(s) and I have the following fields:

This is defined in DrupalContext.php on lines 68-106.  I have a standard behat install from composer.  When I run this, I get the following error:

  --- FeatureContext has missing steps. Define them with these snippets:

  /**
       * @Given I am logged in as a user with the :arg1 and I have the following fields:
       */
      public function iAmLoggedInAsAUserWithTheAndIHaveTheFollowingFields($arg1, TableNode $table)
      {
          throw new PendingException();
      }

I am still pretty new to OOPHP so when I read this I took it to mean that it couldn't find the original method.  I added a use statement in my feature/bootstrap/FeatureContext.php:

use Drupal\DrupalExtension\Context\assertAuthenticatedByRole;

But I still get the same results.  Here is my implementation of the behat scenario:

@api
Scenario: An administrator should not be able to create a page content
  Given I am logged in as a user with the 'administrator' and I have the
  following fields:
    | field_user_username     | drupaltest  |

You have a typo in your Given condition - you need to have role(s) after administrator.

Given I am logged in as a user with the 'administrator' role(s) and I have the following fields:


Create order in drupal commerce programmically with product cost change in order I have a shop with one product, I want have a feature that user only determine how much he/she want to pay and then pay it.after complement payment manager of site according of amount money he/she paid, create a custom product and sent it.
My idea is create custom porduct with 1$ cost and then create a form and get the  amount value from user,then I want create an order programmically and in order update the price with the value that user entered.
How can Implement this?

I want something like this enter link description here

finally this is my solution for do this job

before I create a product, save it product id,  in my custom function I change it's cost and add to order

global $user;

  // Sanitize just in case
  //862 create by myself as custom porduct
  $product_id = 862;
  $price=  floatval($form_state['values']['field_suggest_your_price']['und'][0]['value'])*100;
  // Load product
  $product = commerce_product_load((int)$product_id);
  $product->commerce_price_usd["und"][0]["amount"]=$price;
  commerce_product_save($product);
  if((empty($product->product_id)) || (!$product->status)){
    drupal_set_message(t('Invalid product id'));
    drupal_goto(); // frontpage
    return FALSE;
  }
//$product->commerce_price["und"][0]["amount"]=$price;
//$product->commerce_price_usd["und"][0]["amount"]=$price;
//dsm($product);

  // Attempt to load existing order for user from session
  $order = commerce_cart_order_load();
  if(!$order){
    $order = commerce_cart_order_new($user->uid);
  }

  // Save new order to get order id
  if(empty($order->order_id)){
    $order->revision = FALSE;
    commerce_order_save($order);
  }
  $order_id = $order->order_id;

  // Wrapper for easy field access and adding line items, order passed by reference
  $order_wrapper = entity_metadata_wrapper('commerce_order', $order);
  // Create new line item based on selected product
  $line_item = commerce_product_line_item_new($product, 1, $order->order_id);
  // Save new line item to get line item id
  commerce_line_item_save($line_item);
  // Add line item to order wrapper
  $order_wrapper->commerce_line_items[] = $line_item;

  // Save order with new order number and line item added
  $order->revision = FALSE;
  $order_wrapper->save();

  if(!empty($order->order_id)){
    drupal_set_message(t('Thank you, your %product is ready for checkout.',
                         array('%product' => $product->title)));
    drupal_goto('checkout/'.$order->order_id);
  }else{
    drupal_set_message(t('Sorry, there was a problem building your order. Please try again later.'), 'error');
    drupal_goto(); // frontpage
  }


Is there a good reason to prefer one method of installing over another? Starting to play around with drupal 8.  My first method of installing was installing drush8 (as mentioned in https://www.drupal.org/documentation/install/download):

Get drush8:

composer require drush/drush:dev-master

and then

drush dl drupal
mv drupal-8.0.1/* .
mv drupal-8.0.1/.* .
rmdir drupal-8.0.1

Then I later read that instead of installing via drush I can install via composer (Using Composer in a Drupal project).  The earlier drupal instructions that I read above had no mention of this installation method.

composer create-project drupal/drupal my_site_name 8.0.*`

I also found a slightly different variation (Composer in relation to Drush Make):

composer create-project drupal-composer/drupal-project:8.x-dev some-dir --stability dev --no-interaction

Which I understand creates a slightly different directory structure (according to this article it also creates a 'web' sub directory).

There's also the Drupal Console method:

drupal site:new my_site_name

Other than personal preference, is there a good or valid technical reason to use one method over another?

First of all, you are describing methods to download drupal, not install. If you use drush dl or drupal site:new my_site_name, this is the same as downloading the tar ball and extracting it. If you want to install drupal, you use drush si or drupal site:install, where you can provide the details for installation like database connection on the command line instead in the standard web installer.

To describe the different download methods, as mentioned drush dl and console site:new are only a shortcut for downloading the tar ball. On the other hand, if you use composer, you don't load the tar ball, but use composer to load each of the components, that are in drupal. If you plan to use only the drupal releases and want to follow the normal upgrade path, you don't need to do this. If you want to use dev versions and want to update without the need to download the whole project, use composer. Probably in combination with git for a complete dev workflow.


How to set permissions to a particular role? I want to create an IT role. Superadmin should only create this IT role and enable or disable the permission for this role anytime (which roles this Superadmin can assign to the users), if this admin wishes to. IT role should not be permitted edit any of the users.

The Superadmin will decide which roles an IT person (IT role) can assign to users. Users with role IT role can not assign the roles above their position, this is a simple funda. For example, such users (with the IT role) cannot assign Admin role.

Superadmin designed the IT role in such a way that he can assign Forum Admin, Writer and Writer Admin. Hence, he can assign these roles he wish to.

Permissions to setup for IT roles:

Such user can create a users.
Such user can block or activate the users.
Such user can assign the existing roles to the users he wants and can revoke it.
Such user cannot delete.

Looks like you should try the Role Delegation module. Some details from its project page:

... allows site administrators to grant specific roles the authority to assign selected roles to users, without them needing the administer permissions permission.
For each role, Role Delegation provides a new assign ROLE role permission to allow the assignment of that role.
The module also adds an assign all roles permission. Enabling this permission for a role is a convenient way to allow the assignment of any other role without having to check all the assign ROLE role permissions on the permissions page.


run a drush command with another user I am using drupalvm to manage my vagrant machines and I want to be able to be able to log into the vagrant machine and run drush to sync with the dev/stage/prod environments. I cannot do this without a bunch of extra setup to pass ssh keys and change usernames.

I would prefer to just pass the ssh username along with the drush command. Does drush have an argument that allows me to do this? I was unable to find it in the docs.

I haven't been using a vagrant setup for a while, but back when I did, I used aliases similar to the one below:

$aliases['ogm'] = array(
  'remote-host' => '127.0.0.1',
  'remote-user' => 'vagrant',
  'ssh-options' => '-p 2222 -i /home/ga/.vagrant.d/private_key',
  'root' => '/srv/www/ogm.postfix.local/drupal',
  'uri' => 'http://ogm.postfix.local',
);

Something like this should still work for your DrupalVM sites.

n.b. remote-user is the ssh username.


Using Feeds to import multiple languages I've already imported a data set of about 1500 articles, all in English. I have another set of the data with matching node ids but in different languages. Can I import a second file into Drupal 7 and have the localized content mesh up with the existing data?

Currently when I try to import the data it overwrites the existing content, I need them to co-exist with the only difference being a language code.

Import from two xml files (on for each language), my empiric solution  :

I created two feed imports.
I forced the language field for each one.
Two separated nodes were created for each content (one in each language) but it didn't links the translations.
So I used a SQL query to finish the job, it's based on the feeds uuid

Note: In order for this to work your GUID must match between the two sources. If you have set that to the node title it is important that you turn off the option to replace content as it will update the previous import :/

UPDATE
    node n,
    feeds_item lng1,
    feeds_item lng2
SET
    n.tnid = lng1.entity_id
WHERE
    (
        n.nid = lng1.entity_id
        OR
        n.nid = lng2.entity_id
    )
    AND lng1.id='feeds_importname_for_lng1'
    AND lng2.guid=lng1.guid
    AND lng2.id='feeds_importname_for_lng2'


How to delete/block a list of users contained in a CSV file? I'm looking for a solution that allows me to delete/block users from a CSV file.

Here is more information of the solution that I'm looking for:

I have a CSV with a list of users that are spam or not responding to emails. I would take that list and give it to a Drupal module and corresponding delete or block or make inactive users.

Ideally, it would work like logintoboggan:

Disable the account and keep its content.
Disable the account and unpublish its content.
Delete the account and make its content belong to the Anonymous user.
Delete the account and its content."

User should be able to set that for the batch.

How can I achieve this? If there is a module that can take me to a similar direction, that would be fine too.

You really don't need a CSV; all you need is the identifying column (e.g. mail or uid). To that end, you have one option  with the Bulk User Delete module.

  This module allows you to bulk delete users through the admin
  interface. You provide a list of email addresses, one per line, and
  the users are deleted using the batch processing API.

With this module, you can grab your mail column to feed into the interface to bulk delete.


Form not receiving a CSS class, it's block wrapper does instead I have a custom form built with Form API that I am trying to add a class to on the form tag.

In the buildForm method, I have:

$form['#attributes']['class'][] = 'hl__single-input-form__form';

But the class doesn't appear on the form tag. Instead, the class appears on the div wrapper for the block that outputs the form.

In the block, the build method has:

  /**
   * {@inheritdoc}
   */
  public function build() {
    return $this->formBuilder->getForm('\Drupal\harlib_newsletter_signup\Form\NewsletterSignup');
  }

The only way I have been able to solve this is with a custom twig file with the following:

<section class="hl__single-input-form">
  <form{{ attributes.addClass('hl__single-input-form__form') }}>
    {{ children }}
  </form>
</section>

But the twig shouldn't be necessary. I also notice that the form id as a css class also goes on the block wrapper, too. What is happening here?

Obviously the block plugin thinks the #attributes key in the returned array is meant for the block wrapper. So I would try to put the form in a subkey, this should prevent that the block plugin can access the attributes of the form:

  return ['form' => $this->formBuilder->getForm(...)];

By the way the core search block is also returning the form array directly like you did in the question and indeed, the resulting form tag in the search block has no classes too. I'm not sure, but this seems to be the same issue.


How to add an attribute to CkEditor 4.x iframe tag Does anyone know of a clean way to add an attribute to an iframe tag, or to add an equivalent parameter to the src attribute? Here is what I am trying to do:

I am using the iframe wysiwyg button in Ckeditor to allow users to paste in a video url from YouTube. The problem is, the mega menu dropdown shows up behind the video. To fix this, the iframe tag for the video either needs to have the attribute wmode="transparent added to it, or the actual src url needs to have the parameter &wmode=transparent appended.

Ideally, this would be enforced and not asked of the user. Has anyone dealt with this and implemented a solution? If so, please let me know what you did. Thanks!

As a quick and dirty work-around, I used jquery to add a parameter to the url (which always has at least one parameter already, thus the ampersand).

$('iframe').each(function() {
      $(this).attr("src", $(this).attr("src") + '&wmode=transparent')
  });

But I want to later refine this to only target urls starting with https://www.youtube.com at the very least and use an attribute instead of a parameter. If anyone can suggest the code for that based on what's above, that would be appreciated. If not, I'll eventually update this post with that code when I have more time to figure it out. Thanks.


How do I load a Media entity from a File entity? I have a File entity loaded programmatically. I want to load a Media entity from it. Is there a way to achieve this?

Example - if your File entity is loaded in a variable named $file, and the field name on the Media entity is field_media_image:

$media_entities = \Drupal::entityTypeManager()->getStorage('media')->loadByProperties([
  'field_media_image' => $file->id(),
]);

$media_entity = is_array($media_entities) ? array_pop($media_entities) : NULL;

Note1 : If the File object belongs to more than a single Media entity, you will need to loop through $media_entities to find the one you want.

Note 2: $media_entity will either contain the Media entity the File entity belongs to, or be NULL if the File entity doesn't belong to a Media entity.


During a Drush pm-uninstall, is there a way to see what sql queries were run? Is there a way to find out what sql queries were run during a drush pm-uninstall module? The reason I want to find out is because I want to see if certain tables were removed during the uninstall. Sometimes modules like ubercart leave orphaned tables even though you uninstall them. I had to find the hard way after installing and testing a few other modules and see my database tables balloon up.

You could try to adapt the devel query log as Letharion suggested, but that would involve some coding.  I have done similar things (for a different purpose) by using the Mysql General Query Log.  This requires restarting mysqld with an additional parameter, but beyond that minor inconvenience, works pretty well and shows you absolutely everything that's going on with the database.


Can't add custom fields to Calendar I've created a new content type event (With title, body and date), but I can't select the type when editing my calendar view (screenshot included).

How come I can only select comments and dates, ..?

edit: it's because I added a view from template (Comments). How do you change the type of this view from comments to content? Is that possible?

You cannot change View types (i.e. Users to Content or Content to Comments etc.).
You will have to start the view from scratch.


Drupal Master/Slave Replication I've setup two MySQL servers with Master/Slave replication for the drupal database and I've confirmed the databases are in sync and replicating.

I am now trying to point drupal to both databases basically for failover/redundancy purposes. That is if I need to reboot our primary database server I don't want our site to go down. (Going read-only is acceptable during failure scenarios)

Based on the following article. I've modified settings.php as follows:

$databases['default']['default'] = array(
  'driver' => 'mysql',
  'database' => 'sdrupal',
  'username' => 'drupal',
  'password' => 'topsecret',
  'host' => 'masterdb.ptp.local',
);
$databases['default']['slave'][] = array(
  'driver' => 'mysql',
  'database' => 'sdrupal',
  'username' => 'drupal',
  'password' => 'topsecret',
  'host' => 'slavedb.ptp.local',
);

The configuration is fine until I shutdown the master (service mysqld stop) - when I do that my site pukes:

  PDOException: SQLSTATE[HY000] [2013] Lost connection to MySQL server
  at 'reading initial communication packet', system error: 111
  in drupal_is_denied() (line 1895 of /www/includes/bootstrap.inc).
  Additional

  PDOException: SQLSTATE[HY000] [2013] Lost connection to MySQL server
  at 'reading initial communication packet', system error: 111
  in dblog_watchdog() (line 141 of /www/modules/dblog/dblog.module).

Whats the trick to make this work?

Regarding Master/Master (High availability) is possible to do load-balancing when no master is down.

The following will make all writes go to master1 and all reads go to master2. If master1 fails, all queries will go to master2. If master2 fails, all queries will go to master1.

'master' => array('master1', 'master2')
'slave' => array('master2', 'master1')

The following will make all queries go to master1. If master1 fails all queries will go to master2:

'master' => array('master1', 'master2')
'slave' => array('master1', 'master2')


How to make a reference on same node without recursion problem Here is the situation.

I have a content type called Product.

Content Type : Product
Title
Body
Color
Product Reference (Entity Reference on content type Product)

Thats mean For a specific product, I could referer this product to more product.

My problem right now is there is a Recursion problem.

Is there any other way to perform my needs.

Thanks a lot

There is no reason you can't have an entity reference field that references the same content type, the problem only comes when you have nodes that reference each other in a loop.

For example if nodes A, B & C have these relations you cause a loop and get the error you describe:

A > B > A
A > C > A
A > B > C > A
A > C > B > C
etc.

If you create your content in a way that avoids loops you avoid the problem, however there is also another work around you can use (which is described at https://www.drupal.org/node/2301499#comment-8973869):

Have a new view mode for your nodes. This could be done in custom code as per the linked example, or by using the Entity View Modes module.
Configure your entity reference field on the product content type to display using your new view mode.
Configure the display settings for your new view mode on the product content type to not display your rendered referenced entity.

This way when you view a product it will display its referenced entity for that field but that referenced entity will not print out its rendered entity, avoiding the recursion.

That linked issue also has a patch that apparently addresses the issue but the maintainer has said it will never be committed so I would use caution if thinking about using that.


Can both my flag as well as unflag text have different background images? I am using the Flag module to flag content and users on my site. In one of the nodes, i have attached a background image to the flag link. On clicking the link, the users also have the ability to unflag it. So on the unflag link i want another background image. Is it possible?

You can use a preprocess function to override the output as a span with classes.

function MYMODULE_preprocess_flag(&$variables) {
  $flag = &$variables['flag'];
  $action = $variables['action'];
  if ($flag->name == 'drupal_like') {
    if ($action == 'flag') {
      $variables['link_text'] = '';
    }
    else{
      $variables['link_text'] = '';
    }
  }
}

Then you can target these classes to write your css as David mentioned.

.flag-heart-dark{
  background: transparent url('images/flag.png') no-repeat;
}

.flag-heart-light{
  background: transparent url('images/unflag.png') no-repeat;
}


How do I stop a node submission programmatically? i'm using Drupal 8. I would like to stop the user to submit a node when he tap save, and show some message. How can I do it programmatically?

Thanks!

You can hide the form submit button using hook_form_alter() and show a link Save and Publish on form. And include a jQuery snippet to show message, which will be triggered when user clicks on a link Save and Publish.


Javascript/jQuery fail after AJAX Referesh I'm using Drupal 7 with Drupal Commerce and the Commerce Product Option module. Design goal is to have a visual product configurator for choosing custom furniture - an area on the Add To Cart Form where product images update as the user selects individual line item options.

So far I've implemented a semi-successful solution that uses jQuery to (A) modify the line item form to modify the product display area, and (B) add handlers to form elements. This javascript is attached to the form via a custom module, hook_form_alter() and $form['#attached']['js'] which references a javascript file with a defined Drupal.behavior.

(function ($) {
 Drupal.behaviors.prod_form = {
   attach: function (context, settings) {...

The problem I'm having is with the Product Display form, which provides the user a SELECT list (ID=edit-product-id) to choose a specific product from a family of related products (4 seat sofa, 3 seat sofa, loveseat, etc.). Upon initial display everything works, however if the user selects another product the javascript form modifications fail.  Looking at the console.log it seems as though the jQuery selectors are failing because they are being called before the form item exists. (no elements are found with selector ...).

I suspect the issue is related to when ajax is called vs. when the elements are being drawn, but stuck on how exactly to resolve. Any pointers or suggestions will be greatly appreciated.

Chris

The CSS id may change on ajax refresh.

E.g edit-product-id, edit-product-id-1

Make sure your js can target the new form markup.


How to get node's title and send list of it to mail I am about to send an email to website admin.

First of all, there will be a function to get list of node's title that city field equal to 'barcelona'.

After that, the list will be send to website admin once every day using e-mail.

Any idea on how to do this with Rules or custom module?

You need to create custom module and implement hook_cron().

See:

https://drupal.org/developing/modules

Also check this post:
 How to create a task which run at cron time and send emails to users?

function get_node_titles() {
    $result = db_query('SELECT n.title FROM {node} n');

    $titles = array();
    foreach($result as $item) {
        $titles[]  = $item->title;
    }

    return $titles;
}


manage multiple sites with a single login My client wants urls site1.com and site2.com that share the same codebase for everything but the theme. They want different node content on each site.

They also want the ability to login to one location site1/user, and be able to update content from both sites there.

Is this possible with a multi-site install or Aegir?

If there are two different databases, it seems that you could not update content from both sites in one Drupal admin panel.

Sounds like you might be looking for the Domain Access module

  The Domain Access project is a suite of modules that provide tools for running a group of affiliated sites from one Drupal installation and a single shared database.


How can I render a menu item as a span (or other elements) instead of a ? I'm using Drupal 7 with the Bootstrap base theme, and I'd like to create a second and third level of drop-down. I tried using the special_menu_links module but nothing happens. I also tried what suggested on https://www.drupal.org/node/143322, but that doesn't work either.

How can I render a menu item as a span (or other elements) instead of a <a>?

You can use Special menu items module.

  User can create a new menu item and place either  or
   to the Path field, without quotes.

Also, you can look at another handy module called Menu attributes which allowed you to have control over menu link attributes.

Both modules use hook_menu_alter to adjust the changes to the menu item, you can take look at the module's code to understand how it works exacitly if you are interested.


Problem in Indexing webform result I have created full text search in webforms using Search Api and its working fine earlier but when i added some new records, the new records are not indexed and not able to displayed them on view. I don't know why new records are not indexed.

You'll need to re-index the site when new records are being added.
You can do it by visiting http://your-site-url/admin/config/search/settings and click "Re-index site".

P.S: This will queue the items for re-indexing. The items will actually be re-indexed when "cron" runs for the next time (manually or scheduled cron job.


Views Search Ignoring Custom Node Access permissions I have a hook_node_access function that denies users view access to a page node if the node has a certain tag and they are not an authenticated user.

This is working fine for viewing the page directly but unregistered users can still see the nodes that they should be denied in a views powered search page. When they click through to the page they are denied access.

I was using the taxonomy access control module to do this before and that hid the result from search, I had to disable it because of a conflict with another module.

Is there anything extra I need to do to make views recognise these permissions?

Here's my hook and helper function:

function mymod_page_perms_node_access($node, $op, $account){
  if ($op === 'view' && in_array($node->type, array('page','publication'))){
    $access_level = field_get_items('node', $node, 'field_access_level');
    if (count($access_level)){
      $access_level = $access_level[0]['tid'];

      $accessIDtoRoleID = array(
        '68' => '7',
        '69' => '2');
      if (isset($accessIDtoRoleID[$access_level])){

        global $user;
        $requiredRole = $accessIDtoRoleID[$access_level];
        if (mymod_page_perms_check_allowed_roles_array(array($requiredRole),$user->roles)){
          return NODE_ACCESS_ALLOW;
        } else {
          return NODE_ACCESS_DENY;
        }
      }
    }
  }

  return  NODE_ACCESS_IGNORE;
}

function mymod_page_perms_check_allowed_roles_array($allowedRolesIds,$roles){
  foreach ($roles as $rid => $role){
    if (in_array($rid, $allowedRolesIds)){
      return true;
    }
  }
  return false;
}

thanks

It seems that a better way to control node access is through hook_node_access_records and hook_node_grants as described here http://drupal.org/node/1260948. This works with views properly.

I wrote this simple module based on the instructions in the link above:

define('MYMOD_REALM', 'mymod');
define('MYMOD_GRANT_ID_PUBLIC', 0);
define('MYMOD_GRANT_ID_MEMBER', 1);
define('MYMOD_GRANT_ID_BOARD', 2);
define('MYMOD_BOARD_MEMBER_RID', 7);
define('MYMOD_MEMBER_TID', 69);
define('MYMOD_BOARD_MEMBER_TID', 68);

/**
  * Implementation of hook_node_grants().
  */
function mymod_node_grants($account, $op) {

  if ($op == 'view') {
    $grants[MYMOD_REALM] = array( MYMOD_GRANT_ID_PUBLIC );
    if (array_key_exists(DRUPAL_AUTHENTICATED_RID, $account->roles)) {
      $grants[MYMOD_REALM][] = array( MYMOD_GRANT_ID_MEMBER );
    }
    if (array_key_exists(MYMOD_BOARD_MEMBER_RID, $account->roles)) {
      $grants[MYMOD_REALM][] = array( MYMOD_GRANT_ID_BOARD );
    }
    return $grants;
  }
}

/**
 * Implementation of hook_node_access_records().
 */
function mymod_node_access_records($node) {

  $grant = array(
      'realm' => MYMOD_REALM,
      'gid' => MYMOD_GRANT_ID_PUBLIC,
      'grant_view' => 1,
      'grant_update' => 0,
      'grant_delete' => 0,
      'priority' => 0,
    );
  if (in_array($node->type, array('page','publication'))){
    $access_level = field_get_items('node', $node, 'field_access_level');
    if (count($access_level)){
      $access_level = (int)$access_level[0]['tid'];

      switch ($access_level) {
        case MYMOD_BOARD_MEMBER_TID:
          $grant['gid'] = MYMOD_GRANT_ID_BOARD;
          break;
        case MYMOD_MEMBER_TID:
          $grant['gid'] = MYMOD_GRANT_ID_MEMBER;
          break;
      }
    }
  }
  $grants[] = $grant;

  return $grants;
}


Drupal 7: Displaying external SQL-table as paginated list The following code works well for displaying a paginated list of Drupal users:

function generate_list() {
  $query = db_select('users', 'u')
    ->extend('PagerDefault')
    ->fields('u', array('name', 'uid'))
    ->orderBy('created', 'DESC')
    ->limit(20);

  $result = $query->execute();

  $list = array();
  foreach ($result as $row) {
    $list[] = sprintf('%s', $row->uid, $row->name);
  }

  $theme_args = array('items' => $list, 'type' => 'ul');
  return theme('item_list', $theme_args) . theme('pager');
}

But when I try fetching from an external SQL-table called pref_users (my site embeds a card game and some users come from outside - through Facebook and other social networks, so I have to maintain some non-Drupal SQL-tables, in the same database where Drupal data is stored) with this code:

function generate_list() {
  $query = db_select('pref_users', 'u')
    ->extend('PagerDefault')
    ->fields('u', array('first_name', 'id'))
    ->orderBy('created', 'DESC')
    ->limit(20);

  $result = $query->execute();

  $list = array();
  foreach ($result as $row) {
    $list[] = sprintf('%s', $row->id, $row->first_name);
  }

  $theme_args = array('items' => $list, 'type' => 'ul');
  return theme('item_list', $theme_args) . theme('pager');
}

then I unfortunately get the error:

PDOException: SQLSTATE[42P01]: Undefined table: 7
ERROR: relation "drupal_pref_users" does not exist at character 67:
SELECT COUNT(*) AS expression FROM (SELECT 1 AS expression
FROM {pref_users} u) subquery; Array ( ) in method
PagerDefault->execute() (line 75 in file includes/pager.inc).

Does anybody please know a way to tell Drupal to fetch data simply from pref_users and not from {pref_users} at it seems to assume above?

the squiggly brackets are used for escaping table names in drupal. For cases where you have multiple sites in one database.

I'm guessing that you have a db prefix set up for all of your Drupal tables to be drupal_

You can set this on a db connection before $result = $query->execute(); using the setprefix method

Something like

 $query->setprefix(array(
     'default'   => 'drupal_',
     'perf_users'     => ''));

untested code

may do it. However you are more likely to want to change your settings.php file and set table prefixs in there


Rule should not fire when user logs in with one-time-link from password recovery I have a rule for user-login that redirects them to their content area and shows a welcome message with some instructions. But when a user uses the password recovery mechanism that rule should not fire. I have tried "path has URL alias" and "user/reset/*" as value. But it did not work. I can't figure out what else i could use.

Reason is: users need their current password, which they don't know, when they are going manually to their user/n/edit page. When the rule wouldn't fire they'd be redirected to the correct password reset page without the current password requirement.

Thanks!

You may want to give this a try:

Rules Event: User has logged in.
Rules Condition: Text Comparison with

Text Data Selector = site:current-page:path
Matching Text = reset
Comparison Operator = contains

Rules Action(s): whatever makes sense.

I'm not 100% sure about the value of the "Matching Text" (if it's not reset, then adapt that value to something that fits for these kinds of one time login URLs).


Form posting before ajax can update content My form is submitting faster than ajax can update my textarea. How can I delay the form from submitting so the ajax can update my textarea?

$form['submit']['#ajax'] = array(
'callback' => 'getCampaignString',
'event' => 'submit',
'wrapper' => 'Comments_replace',
'method' => 'replace',
);
$form['submitted']['Comments']['#prefix'] = '
';
$form['submitted']['Comments']['#suffix'] = '
';

 function getCampaignString(&$form, &$form_state){
    $campaingString = $form_state['values']['submitted']['campaignstring'];
    $comments = $form_state['values']['submitted']['Comments'];
    $comments = $comments."[".$campaingString."]";
    $form['submitted']['Comments'] = $comments;

    $form['submitted']['Comments'] = array(
        '#type' => 'textarea',
        '#title' => t('New Comments'),
        '#name' => 'submitted[Comments]',
        '#value' => $form['submitted']['Comments'],
    );

    return $form['submitted']['Comments'];

}

So basically I have this webform for getting leads. There is a textarea for comments on the form. What I need to do is append a string to the end of the comments text on POST. For example: Say they made a comment like "I want more information" and when they hit submit. I need to add a string to the end of the comments so in the post it will look like this: I want more information - campaignName. The only way I have found to add my campaingname to the post of the comments is to replace the textarea with the new information in it but I cannot seem to replace it fast enought when submitted.

function THEME_form_alter(&$form, &$form_state, $form_id) {
    $form['#validate'][] = 'webform_validate';
}

function webform_validate($form, &$form_state) {
  //Appending comments field with campaignString
  $campaingString = $form_state['values']['submitted']['campaignstring'];
  $comments = $form_state['values']['submitted']['Comments'];
  $comments = "[".$campaingString."]  " . $comments;
  $form_state['values']['submitted']['Comments'] = $comments;
}


How do I send plaintext email? I've been using a combination of drupal_mail() and Mimemail to send out HTML formatted email; it's working fine.  However, in some circumstances, I also need to be able to send out plaintext email, not an empty HTML template, but a completely raw, plaintext message.
I can't figure out how to disable Mimemail for these messages, while leaving Mimemail in place for the others.
How might I be able to do this?

I've spent some time trying to achieve the same goal.
I didn't find a lot of documentation on MimeMail module, I inspected the code and found a solution :
  $message = drupal_mail('my_module', 'my_module_key', 'email@mail.com', $language,
    $params = array(
      'subject' => $subject,
      'plain' => TRUE,
      'plaintext' => $mailBody,
    ));

You just need to use 'plain' => TRUE and put your mail content in 'plaintext' => $mailBody


How to get the Published or Archived revision of a node I'm trying to compare some field values from the edit form of a node to the published/archived field values. However I'm running to an issue where when im trying to load the Node object using
Drupal::entityTypeManager()->getStorage('node')->load($nid)
It's returning the last saved draft revision. How do i get the Node object of the published/archived revision?

P.S. Content Moderation is turned on, and content type is assigned to a workflow.

You can do this with a direct database query in your function, then load the specific revision.

$connection = \Drupal::database();
$query = $connection->query("SELECT vid FROM {node_field_data} WHERE nid = :nid",
    [':nid' => $node_nid,]);
$node_revision_id = $query->fetchField();

$node_revision = \Drupal::entityTypeManager()
  ->getStorage('node')
  ->loadRevision($node_revision_id);

Untested code, but this should put you on the right track.  Might also be worth confirming in your SQL query that "WHERE status = 1" to confirm that the node is still published.


Email Subscriptions with Verification I feel like I'm missing something, because I can't find a module that does this, but it seems like it should be really common.

I would like users to be able to simply enter their email address to subscribe to my site so that I can send them an email whenever I post a new Article. I don't want to require them to create a full drupal account, just a simple email address and then click a verify link.

I've tried Simple Subscription and it provided a simple form block which provides essentially what I'm looking for on the front end:

However, when a user enters their email address this module doesn't provide a verification email. So, I need something more complicated that Simple Subscription.

Any suggestions?

Simple subscription validates email address. It did work for me. I used the latest version of the module.
It also provides a hook hook_simple_subscription which allows modules to do something with the simple subscription form results such as sending email for subscription verification.


How do I instantiate a custom class with dependency injection? I am relatively fresh to the DI party and am struggling to get my head around how exactly to use Dependency Injection.
I understand that I can pass requirements as part of a service, but what about in my own class?

Say I have the below class where I want the language manager service to be injected:

class Foo implements ContainerInjectionInterface {

  protected $languageManager;

  public function __construct(LanguageManagerInterface $languageManager) {
    $this->languageManager = $languageManager;
  }

  public static function create(ContainerInterface $container) {
    return new static(
      $container->get('language_manager')
    );
  }
}

When I call new Foo() I am required to pass an instance of LanguageManagerInterface. That makes sense in terms of a normal constructor method, but that would require me to instantiate the class like the below:

$languageManager = \Drupal::service('language_manager');
$foo = new Foo($languageManager)

That just doesn't feel right to me.

Is there something I am missing, or would this class always have to be a service to take advantage of dependency injection?

A class implementing ContainerInjectionInterface is instantiated by calling the factory method create().

See Drupal\Core\DependencyInjection\ClassResolver

/**
 * Implements the class resolver interface supporting class names and services.
 */
class ClassResolver implements ClassResolverInterface, ContainerAwareInterface {
  use DependencySerializationTrait;
  use ContainerAwareTrait;

  /**
   * {@inheritdoc}
   */
  public function getInstanceFromDefinition($definition) {
    if ($this->container->has($definition)) {
      $instance = $this->container->get($definition);
    }
    else {
      if (!class_exists($definition)) {
        throw new \InvalidArgumentException(sprintf('Class "%s" does not exist.', $definition));
      }

      if (is_subclass_of($definition, 'Drupal\Core\DependencyInjection\ContainerInjectionInterface')) {
        $instance = $definition::create($this->container);
      }
      else {
        $instance = new $definition();
      }
    }

    if ($instance instanceof ContainerAwareInterface) {
      $instance->setContainer($this->container);
    }

    return $instance;
  }

}


What alternatives exist for Autologout in D7 Since the autologout module isn't ready for prime time for D7, what are some alternatives out there?

Is there any snippet out there already that can be used in a sample custom module that will logout users for x minutes of inactivity?

Update 1:
The suggested snippet here keeps D7 from crashing, but does not logout the user.

Thanks!

You can just lower the cookie lifetime in your settings.php file as a temporary solution.

  Set session cookie lifetime (in seconds), i.e. the time from the session is created to the cookie expires, i.e. when the browser is expected to discard the cookie. The value 0 means "until the browser is closed.

ini_set('session.cookie_lifetime', 2000000);


Send base URL for my custom block In my Drupal 8 site, I am developing a custom block in my module custom, with some text and some images. I created a template, and everything works fine. Now I need to add some images for my custom block, and I don't know how to pass the base URL to call those images.

In Drupal 7 I used the following code.

function bloques_block_view($delta = '') {
    $block = array();

    $ruta = $GLOBALS['base_url'] . '/' . drupal_get_path("module", "mymodule");
    $link = $GLOBALS['base_url'] ;

  switch ($delta) {

//footer
    case 'footer':
      $block['subject'] = '';
      $block['content'] = leer_template('footer.tpl', array('%ruta%' => $ruta, '%link%' => $link));
      break;
  }
  return $block;
}

Everything works well, but in Drupal 8 it is a little different. The problem comes with build().

    public function build() {
    $ruta = 'holamundo',
    return array(
        '#theme' => 'mymodule',
        '#title' => 'my title ',
        '#ruta' => '
' . $ruta . '
'
    );

}

Just the title works in the template file; $ruta is not working.

My Custom Block {{ title }}-{{ ruta }}

I don't know if this is the correct way to declare the base URL (just like I did in Drupal 7).

  $ruta = $GLOBALS['base_url'] . '/' . drupal_get_path("module", "bloques");

You can try template_preprocess_block(&$variables). There is a global $base_url variable. Create variable for block template:

function your_module_preprocess_block(&$variables){
  global $base_url;
  $variables['base_url'] = $base_url;

}

Now you can use {{base_url}} in twig template of your block.


How do I interact with Mautic from a custom module? I need to create a new contact in Mautic every time a new user joins my Drupal site.
Drupal.org has the following two modules:

https://www.drupal.org/project/mautic
https://www.drupal.org/project/mautic_api

I can't find documentation from any of these two modules on how to access the Mutic API from a custom Drupal module.
I believe, this could be done from inside a hook like this.
/**
 * Implements hook_ENTITY_TYPE_insert() for user entities.
 */
function custom_mautic_user_insert(Drupal\Core\Entity\EntityInterface $entity){

  // Some code here to access the Mautic API to create the new contact.

}

I have seen the code of https://www.drupal.org/project/commerce_mautic, which uses an event subscriber to do its work, but this seems very complex for such a simple task.

I think you're on the right track. Module https://www.drupal.org/project/mautic_api provides a wrapper around Mautic API - see https://git.drupalcode.org/project/mautic_api/-/blob/8.x-1.x/src/MauticApiService.php#L127
You can use it in you module code via \Drupal::service('mautic_api'). The hook you've mentioned looks correct to me.


Append "node" to tab menu link I have a view that display members for a group. The path for this view is set as node/%/members. When I go to group page, the menu works fine:

I can't find anyway to change these links.

This isn't a problem with the view. The url paths used for your tabs are using relative URLs (e.g. "node/$nid/group-forum") you need use absolute URLs (e.g. "/node/$nid/group-forum").

View

Forum

Members

You need to check the rendering logic in your theme templates to see where the problem lies.


Getting xdebug to work with BrowserTestBase functional tests? I'm having a really difficult time trying to get XDebug working with my functional tests that extend from BrowserTestBase.

Does anyone have a working configuration in place for this?

I'm using PHPStorm (version 2016.2) for debugging and already have a working XDebug setup for standard unit tests. I've been initiating the tests from PHPStorm directly, but would certainly be happy running them from a terminal outside of PHPStorm if it works!

Here's what I've tried for running out outside of PHPStorm in a normal terminal:

export SIMPLETEST_BASE_URL=http://drupal8.dd:8083
export XDEBUG_CONFIG="idekey=PHPSTORM"
vendor/bin/phpunit --configuration core/phpunit.xml.dist /Users/bosborne/Projects/drupal8/modules/cas/tests/src/Functional/CasAdminSettingsTest.php

The tests run but my breakpoints are ignored.

BrowserTestBase and KernelTestBase use phpunit's 'run in separate process' feature which generates a new temporary php file from a template and then executes that. The output is provided as serialized php object which is then read back into the main thread an unserialized to yield the results.

So at present that makes using Xdebug fairly difficult.

We probably should open an issue to look at shipping our own template that support Xdebug.

In the meantime my suggestion would be to use outputting, you can use the standard approaches like var_export, print_r, echo etc or you can use $this->htmlOutput($something_you_need_to_debug); which then shows up amongst the other HTML output.

Then run your tests with -printer="\Drupal\Tests\Listeners\HtmlOutputPrinter"

This requires the BROWSERTEST_OUTPUT_DIRECTORY environment variable to be set, see core's phpunit.xml.dist for info on how to configure that.


Allow only the users with the access code to browse the website I am building my site on Drupal 7.

I want to restrict the usage of my website only to certain people who I have sent the access code to. I don't want to put my website into maintenance mode because I want those users to fully use my site (including registration form etc.).

So how can I build a page with a simple form where users will enter the access code and then get allowed to enter the website? And also whenever somebody types in another URL in the website without actually entering the access code first, they must be redirected to the security page to enter the code; then they will be allowed to proceed to that URL they wanted to go to.

I would prefer to be able to remember their sessions and if the user has a session on the website (such that they have entered the code before) they shouldn't be sent to the security page the second time (until their session time ends maybe?).

How can I achieve this?

create a page, and include the User Login as a block on that page. Theme as desired. You can also set this as a Front page in the system settings if you like.
alternatively, create a customised user login, whereby the password is populated as part of a custom submit function of the form. Then you would use a Code as the user name, and the password would be automatically assigned. The question is too broad to detail how this would be accomplished. Look into the forms API and building forms with customised submit functionality.
get LoginToboggan. It has a setting to redirect users to a specified page on access denied
in permission, for Anonymous Role, uncheck ALL items. This will essentially disallow anonymous user to do anything, or view any content, which should then be redirected to the login page by logintoboggan

Keep in mind that this method is prone to major security breaches by bots. They WILL randomly guess the code and gain access to the site, which is why two fields are required in standard practice (email/user, password)

EDIT FOR OP

I solved it by a custom module. I cant answer my own question due do low reputation so accepting yours as an answer and writing a comment. I created a block, which contains a custom form. This form redirects to home page if the access code is correct and also sets TRUE on $_SESSION['access_code']. And then I created a page and embedded the block In a custom Rule, I redirect user to the access page if $_SESSION['access_code'] is not TRUE and if the user is anonymous whatever the URL it is. So user always redirected to that page, unless they have entered the code before, or a logged in user.


How to add subtitle for menu items in Nice menu in Drupal 7 I'm using nice menu in my durpal-7 site.I need to show a subtitle for each menu item.How can this be done ? I'm new to drupal so it would be great if you could help me.

Try OM Maximenu module

  "Maximize your main navigation by adding text, images, videos,
  slideshow, tabs, menu blocks, user info ..."

  That is now possible by using OM Maximenu which can create menus with
  all other module blocks you want as attachments, modules like views,
  slideshow, menu, user, nice menus, quicktabs, and custom blocks with
  tables, lists, images, videos, etc.

Here a great list of menu 7 Mega Menu modules for Drupal


Contact Us works on local machine, but not on bluehost.com How can I track down why an email is not generated from my new web site when I click Contact on the Contact page?

I turned on maillog and devel. What I get is
    maillog =>
        ... (Array, 6 elements)
 ... (Array, 6 elements)

Subject (String, 23 characters ) [Website feedback] test
From (String, 22 characters ) sam.stamport@gmail.com
To (String, 22 characters ) sam.stamport@gmail.com
Reply-To (NULL)
Header (Array, 7 elements)
Body (String, 128 characters ) admin (http://columbiablooms.org/users/admin) s...
    Krumo version 0.2.1a | http://krumo.sourceforge.net
    [Click to expand. Double-click to show path.] Called from
    /home5/columck5/public_html/sites/all/modules/maillog/includes/maillog.mail.inc
    , line
    90

Your message has been sent.

Error message:

  Unable to send e-mail. Contact the site administrator if the problem persists.

Installing the SMTP module and configuring it correctly was the solution to the problem. Since I am a newbie to Drupal it seems magical that it solved the problem. I don't fully understand the logic flow of SMTP and SimpleNewsletter.

It took three different chats with bluehost before I got SMTP configured correctly.

Following are the SMTP parameters that finally worked. The email address in Home » Administration » Configuration » System - Site Information also was incorrect. I set it to admin@columbiablooms.org and everything finally worked. The admin@columbiablooms.org email address had to first be created via cpanel at bluehost. The password in the screenshots below is the one that I used when I created the email address at bluehost.

I hope all this helps another newbie ...


How to display eck edit form in ctools modal or in other page? I need to display my custom eck edit form in ctools modal. How can I load the form I need in ctools modal or other page?

function edit_education_form_callback($ajax){
  if ($ajax) {
    ctools_include('ajax');
    ctools_include('modal');

    $form_state = array(
      'ajax' => TRUE,
      'title' => t('Education'),
    );

    $output = ctools_modal_form_wrapper('resume_education_edit_form', $form_state);

    if (!empty($form_state['executed'])) {
      // We'll just overwrite the form output if it was successful.
      $output = array();
      ctools_add_js('ajax-responder');
      if (isset($_GET['destination'])) {
        $output[] = ctools_modal_command_dismiss();
      }
      else {
        $output[] = ctools_ajax_command_redirect('my-account');
        drupal_set_message(t('successfully added.'));
        $output[] = ajax_command_after('.modal-title',theme('status_messages'));
      }
    }

    print ajax_render($output);
    drupal_exit();
  }
  else {
    return drupal_get_form('resume_education_edit_form');
  }
}

function resume_education_edit_form($form, &$form_state){
  // How can I call the eck edit form I created?
  // $output = ctools_modal_form_wrapper('eck_edit_form', $form_state)
  // Should I use drupal_get_form('eck__entity__edit')?
}

The right way to load the edit form of a custom entity bundle created with ECK is by using the eck__entity__edit function provided by the ECK module.

Usage example:

$output = eck__entity__edit($entity_type_name, $entity_bundle_name, $entity_id);


Inject new variables in html.tpl.php based on current node content type I would like to add custom classes and id attribute to html.tpl.php (body tag) based on current viewed content type.

I know i can do like:

 function mytheme_preprocess_html(&$variables) {
            $variables['classes_array'][] = 'myClass';
        }

but how to make it conditional like

           $node = $variables['node'];
        if ($node->type == 'lighters') {
//assign value to $variables['classes_array'] somehow
}

Also, how can i define new custom_array to inject variable based on content type to body tag ?
Im on Drupal 7.
Thanks!

If I'm reading it right you've pretty much answered your own question there; only caveat being that I'm not sure if $variables['node'] will be set for that particular theme function.

If it's not you can use menu_get_object() to get it:

function mytheme_preprocess_html(&$variables) {
  if ($node = menu_get_object()) {
    if ($node->type == 'lighters') {
      $variables['classes_array'][] = 'myClass';
    }
  }
}

You can add anything you want to the $variables array and it will be available to you in the template file, as the variable is passed in to the preprocess function by reference. So if you set

$variables['my_var'] = 'something';

you will have access to $my_var, with the value you gave it, in the template file.


User-profile and Profile2 related on my front page the user registers by typing in his username, email, password..once he clicks submit he log ins and is redirected to his profile edit page (not account settings)..i am able to do that using rules..i am using Profile2 and adding new fields..however i also want the old fields such as username, password,and email id to appear there ...
it would be the same password or username and email id that the user entered while registering but i just want to create/display these fields on this edit profile page for completeness.they may have the earlier entered values copied and the user may enter/edit it here again and be able to save (ofcourse he should get an error if he enters a new email id on that page)

what i want is something like this: http://imgur.com/fa31Xt1

Well i think you could do a hook_form_alter and alter the edit page when they go there.  You would need to do a user_load($user) to get the information and then alter the form with those values.  The tricky part is the password is encrypted so that may be an issue.

Example of user load

global $user
$user_info = user_load($user);

Example of hook alter on profile page

function mymodule_form_user_profile_form_alter(&$form, &$form_state)
{
 //Code here
}

http://api.drupal.org/api/drupal/modules%21user%21user.module/function/user_load/7
http://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_alter/7


Return a view's total_rows in Drupal 7 without php filter? Is it possible to list the total number of rows in a view into the header of the view, without enabling the PHP filter? I know I can enable the PHP filter and output $view->total_rows in a header, but I'd like to avoid enabling the PHP filter.

I could use the output $view->total_rows in a template file but is there an existing handler or other trick I'm missing?

On my D7 site with php-filter disabled ...

From a View configuration page:
HEADER section, add, Global Result Summary

pick total row count or whatever, whatever you want:

You may use HTML code in this field. The following tokens are supported:
@start -- the initial record number in the set
@end -- the last record number in the set
@total -- the total records in the set
@name -- the human-readable name of the view
@per_page -- the number of items per page
@current_page -- the current page number
@page_count -- the total page count


Can you tell which page you're on of a DB API pager? I'm doing the usual sort of Drupal 7 DB API pager stuff to work through a bunch of items, e.g (greatly simplified):

$the_nodes = db_select('node', 'n')->extend('PagerDefault');
-- conditions, fields, etc. --
$the_nodes->limit(10);
return $the_nodes->execute()->fetchCol();

and then the appropriate rendering code to make the pager study appear, of course.

What I'd like to be able to do is, from inside the function containing this query, to be able to tell which page of the pager I'm on -- in particular, if I'm on the first page, or not.  The idea is to insert a couple of other records at the beginning of the list, but only on the first page.

So: Does anybody know if this is possible?  Thanks!

Instead of access $_GET directly, you should use pager_find_page().


InvalidArgumentException: Cannot redirect to an empty URL. in Symfony Pages are not shwoing up. They display the follwoing error:

InvalidArgumentException: Cannot redirect to an empty URL. in Symfony\Component\HttpFoundation\RedirectResponse->setTargetUrl() (line 86 of /home/../public_html/domain.com/vendor/symfony/http-foundation/RedirectResponse.php).

On page:
The website encountered an unexpected error. Please try again later.InvalidArgumentException: Cannot redirect to an empty URL. in Symfony\Component\HttpFoundation\RedirectResponse->setTargetUrl() (line 86 of vendor/symfony/http-foundation/RedirectResponse.php).

I also noticed that the LOGO and HOME in the main menu do not redirect to the front page but instead they redirect to the current page, which is not correct.

Any help or insight will be greatly appreciated.

This solution is working  when

Successfully Logout with empty blank page website encounter error.

You need to override the core logout function available in user module
by creating your custom module

that is UserController::logout function

Create a Route subscriber

/module/src/Route/RouteSubcriber.php

<?php

namespace Drupal\modulename\Routing;
use Drupal\Core\Routing\RouteSubscriberBase;
use Symfony\Component\Routing\RouteCollection;
/**
* Listens to the dynamic route events.
*/
 class RouteSubscriber extends RouteSubscriberBase {
 /**
  * {@inheritdoc}
  */
  public function alterRoutes(RouteCollection $collection) {

    if ($route = $collection->get('user.logout')) {
      $route->setDefaults(array(
       '_controller' =>
       '\Drupal\modulename\Controller\RouteController::logout',
      ));
    }
  }
 }

Create Services file

module/modulename.services.yml

services:
 modulename.route_subscriber:
  class: Drupal\modulename\Routing\RouteSubscriber
  tags:
  - { name: event_subscriber }

Create Controller File
module/src/Controller/RouteController.php

<?php
/**
 * @file
 * Contains \Drupal\modulename\Controller\RouteController.
 */
namespace Drupal\modulename\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Url;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;

class RouteController extends ControllerBase
{

  public function logout() {
    //redirecting to home page if you want you can
    // redirect to some other page. by concating path with it.
    $value = \Drupal::request();
    user_logout();
    return new RedirectResponse($value->getBaseUrl());
    //return new RedirectResponse($value->getBaseUrl().'/somepath');
  }

}

that is it.enable the module and try logout will work with out blank page error


How to delete all duplicate node with the same field value in drupal type I need to bulk delete the duplicate nodes based on the same field and keep just one node.

How can I do that ?

I tried that :

$query = \Drupal::entityQuery('node')->condition('type', "diffusion");
$query->groupBy('field_id_diffusion');
//$query->having('COUNT(field_id_diffusion) >= 1');
$duplicate = $query->execute();

If your nodes are not  too many you can achieve it by something like  following   :

$query = \Drupal::entityQuery('node')->condition('type', "diffusion");
$query->groupBy('field_id_diffusion');
$nids = $query->execute();
$nodes = \Drupal::entityTypeManager()->getStorage('node')->loadMultiple($nids);

$diffusion_checklist = [];
foreach ($nodes as $node) {
   $diff_id = $node->get('field_id_diffusion')->value;

   if (!in_array($diff_id ,$diffusion_checklist)) {
     $diffusion_checklist[] = $diff_id;
   }
   else {
     $node->delete();
   }
}

And if you have too many nodes  another solution is implement the same strategy with setup a batch operations


Updating a field value in database via submit handler doesn't update the user profile in UI I've created the field "Attending" that is attached to the user profile.
I have created a form with one checkbox element; when submitted, I've confirmed that the attending_fielddatabase is being updated with the current value (0 or 1), but when I view the user profile through the UI, the updated value isn't being displayed.

The submit handler I am using is the following:

function rsvp_aform_submit($form, &$form_state) {
  global $user;
  db_query("UPDATE {field_data_field_attending} SET field_attending_value = :val WHERE entity_id = :eid", array(':val' => $form_state['values']['rsvp'], ':eid' => $user->uid));
  drupal_set_message(t('Your form has been saved.'));
}

Do you have any idea?

I think that's the caching. First try to clear the cache manually. If that helps you should use cache_clear_all() to clear the corresponding cache tables (e.g. cache_content, cache_views_data) after you update the db.


View: Comparison taxonomy terms I have a content type = news and 5 normal page.
Content type news have 5 taxonomy term that the user can select and chose when write a news.
Each of the 5 normal page have 1 taxonomy term on it.

I want do a view (block) that show only the news that have the same taxonomy term.

My previous solution was to do a view for each taxonomy term but i don't like it because i have 5 block.

Thanks

I believe that Contextual Filters are what you are looking for. The example should be pretty close to your use case from the sound of it.


How to add a submit button in an HTML table? I need to call the gh_cart_prove when the BUTTON is clicked.

function gh_view_categories(){
  $a='
';
  $a.='
';
  $a.=''.'Categoria:'.'	';
  $a.=''.'Soglia minima:'.'	';
  $a.=''.'Tot attuale:'.'	';
  $a.=''.'Crea ordine'.'	';
  $a.='
';
  $query = db_select('uc_product_classes', 'u')
    ->fields('u', array('name','soglia', 'totattuale'));
  $result = $query->execute();
  while ($record = $result->fetchAssoc()) {
    $idUser=gh_get_user_id($record['name']);
    $a.='
';
    $a.=''.$record['name'].'	';
    $a.=''.$record['soglia'].'	';
    $a.=''.$record['totattuale'].'	';
    $a.=''.'<button onClick="gh_cart_prove($idUser)">BUTTON</button>'.'	';
    $a.='
';

  }

  $a.='
';

  return ($a);
}

The button appear but it not works. the function is correctly declared.
How can I resolve this problem?

Assign an id to the button and use Jquery,
set the $idUser in a data attribute example :

 <button id="buddon-id" data-user="<?php echo $idUser;?>" >button</button>
    <script>
    $("#button-id").on("click", function(e){
       userid = $(this).attr("data-user");
    };
    </script>


Best Way to Handle Variables Per Environment I have a custom module. It's FormBase to create a form. And on submit, I post values to an API. All this works. But I want to change the base URL variable (which is used in multiple methods) so that when you on any environment besides live you get a different URL.

I want to figure out the Drupal 8 way of doing this.

class EventSuggestionForm extends FormBase {
  // Needs to be different if not the live site...
  private $baseUrl = 'https://www.example.com';
  private $apiUrl = '/api/v1/';
...

Can I get some advice?

You can create a new setting in your settings.local.php or settings.php file like:

$settings['event_base_url'] = 'https://www.example.com';

or some people are adding switch block based on the server host, e.g.:

switch (@$_SERVER['HTTP_HOST']) {
  default:
  case 'dev.example.com':
     $settings['event_base_url'] = 'http://dev.example.com';
     break;
  case 'stage.example.com':
     $settings['event_base_url'] = 'https://test.example.com';
     break;
  case 'www.example.com':
  case 'preprod.example.com':
     $settings['event_base_url'] = 'https://live.example.com';
     break;
}

Then reference it in the code like:

use Drupal\Core\Site\Settings;
$baseUrl = Settings::get('event_base_url', '');

So your code would look like:

use Drupal\Core\Site\Settings;
class EventSuggestionForm extends FormBase {
  private $baseUrl;
  private $apiUrl = '/api/v1/';

  function __construct() {
    // Read value from the settings file.
    $this->$baseUrl = Settings::get('event_base_url', '');
  }
...

Then change this setting per environment in the settings file, similar as you've different database credentials per different environment. This is the same concept as it's used for the existing $settings['file_public_base_url'] parameter.


Conflict between ajax callback and jQuery UI dialog I have a button that triggers an AJAX callback with the form api like so :

$form['show_modal'] = array(
 '#type' => 'submit',
 '#value' => t('Some crazy text'),
 '#ajax' => array(
     'callback' => 'myCallback',
     'wrapper' => 'myWrapper',
 ),
 '#suffix' => '</div>',
);

I then do some stuff and return my new form and display it (working).

 return $form['myNewForm'];

I want to display it in a custom jQueryUI dialog,
but when I do that my AJAX callback doesn't work anymore ...

 //On click, open modal
 $('#showModale').click(function(){$('#myWrapper').dialog("open");});
 //Modal itself
 $("#myWrapper").dialog({
  autoOpen: false,
  show: {
    effect: "blind",
    duration: 300
  },
  hide: {
    effect: "blind",
    duration: 300
  },
  height: 400,
  width: 1000,
  modal: true,
  resizable: false,
  draggable: false,
});

Any ideas about it ?

a simpler approach might be to include the form in a custom block, and set it's css to match the modal design you want but set the initial block display to none.  Then use an onclick to show the block using whatever transition you want


How to remove default div of views block? My html code:

    &rarr;

<img class="img-responsive" src="<?php print base_path(). path_to_theme();?>/assets/images/img.jpg" alt="">

In views-view-fields--name--name.tpl I'm using this code:

    &rarr;

<?php print $fields['field_fieldName']->content;?>

The generated output is the following.

    →

## I have to remove this div

I have to remove the default
 before the  tag.

Click on field and edit settings
Override style settings for field

Customize field HTML
Customize field and label HTML


form #type => checkboxes with zero / empty option value I am building something which uses a form element with '#type' => 'checkboxes'.

I want this to be reusable, so it should accept anything as option values that works as a PHP array key (integers and non-integer strings).

$form['checkboxes'] = [
  '#type' => 'checkboxes',
  '#options' => [
    0 => 'zero',
    '' => 'empty string',
    ' ' => 'space',
    'other' => 'Other',
  ],
];

However there seems to be a problem with values 0 (zero) and '' (empty string).

Even when the checkboxes for '' or 0 are checked, the values are gone in the $element['#value'] array, e.g. when checking with a custom '#element_validate' callback.

$element['#value'] === [
  # '' and 0 are gone, even if they were checked.
  ' ' => ' ',
  'other' => 'other',
];

Interestingly, the $_POST still contains the values, with an interesting twist, where space and empty string behave like array insertion via []. I suppose this is due to the way POST data is sent.

$_POST['checkboxes'] === [
  0 => '0',
  1 => '',
  2 => ' ',
  'other' => 'other',
];

I can imagine why all of this happens, but is there a workaround or solution?

EDIT: The previous version of the code snippet was misleading, sorry. I had mixed up $_POST and the original '#options' array.

I managed to prevent this problem by adding an '#element_validate' handler on the checkboxes element.

The code below is a simplified version of what I did, up to you to fine-tune.

$element['#element_validate'][] = '_MYMODULE_checkboxes_validate';

function _MYMODULE_checkboxes_validate(array &$element, array &$form_state) {

  // The form value already has the format $[$id] = $id, mostly.
  // However, if trim($id) === '', the array key will be an integer increment.
  $value = $element['#value'];

  // Make sure it has the expected format.
  if (!is_array($value) || [] === $value) {
    $ids = [];
  }
  else {
    // Get rid of integer keys for empty-ish string ids.
    $ids = array_combine($value, $value);
  }

  // Remove dangling * => 0 entries.
  form_set_value($element, $ids, $form_state);
}

Note: If you have the value_is module installed, empty-ish values will always be unset, thanks to _value_is_disabled_options_value_callback().


How can I search in another language? I have 2 languages in my site and a search view for property search
and I am using the Search API module.

When I try to search in English (default language), the search is working.
But when I try to search in the another language the search is not working.

I am searching by tittle.

Any suggestions?

If you are using entity translation for translating the content, you will have to install the Search API Entity Translation module.

  Search API Entity Translation module provides multilingual support for the Search API module through integration with Entity Translation.

This module provides a new index type : "multilingual node index", similar to the "default node index" which is provided by default by Search API.
You can use this to create the views and they will honor the language selected from the language switcher.


Using multiple sort criteria on a view, can't get them to play nicely So, I have a view (D7, Views 3) that provides a list of staff with a thumbnail image based on a location "contextual filter". Some staff members are set as "sticky" and need to appear above all the others. All staff members also need to be sorted by last name, which i'm doing with a custom php sort.

So, first, stickied staff members should be shown sorted by last name. Next, unstickied staff should be shown also sorted by last name.

Last name sort works great, but I can't get the view to group them by sticky.

Here's a screenshot of the view: http://grab.by/h2Gg
Here's a screenshot of the first part of the output: http://grab.by/h2GA (Jeremy Irwin is stickied, so should display at the top)

Here's the php code i'm using for the last name sort:

list($fname1, $lname1) = explode(' ', $row1->title , 2);
list($fname2, $lname2) = explode(' ', $row2->title , 2);
return(strcasecmp($lname1,$lname2));

Any suggestions why this isn't playing nicely with sorting by sticky?

So, first, stickied staff members should be shown sorted by last name. Next, unstickied staff should be shown also sorted by last name.

So you want 2 views (1 being an Attachment) and not 1 View. and you can do all this.

1 View is of all the people fields with only stickied people as a
filter. Sorted by last name.
The Attachment is all non-stickied people sorted by last name. You then
"attach" this View after the 1st view. Get the page to look how you
want using CSS in your theme.

As a final thought I tend to make 2 fields in my content types: first_name and last_name and then join them as a pseudo-field in Views using substitutions or use the Node Automatic Title to hide the title field by using the fname and lname as the title field upon save.

You could change your name column into 2 fields using Views Bulk Operations after creating the "last name" field in your content type ... just saying.

EDIT

The benefits to this approach is that you get rid of the odd custom sorting you've hand made and rely on Core Views utilities on your site. This makes moving your site or upgrading drupal versions easier in the long run ...


Location Module fields are not available under Search api fields I am using Search API's Default Node index. I am using Location module to store Location data. But location module fields are not available under Search API Related fields.

I know this has been an issue but was just wondering if this could ever get fixed? I could have used Geolocation or Geofield modules and used the fields in search api. But unfortunately when i used location module i was not using Search API.

Now I have 10000 Nodes using location module to store location details.

What could be the solution? How to make these fields to be used under Search api so that i can use facets and eventually show them on MAP.?

Please help!

Thanks in advance.

As pointed out here, you can achieve that by means of a combination of modules:

Search API Location + Search API Solr + Location field (creating an aggregated location field).

You will need an extra step by implementing hook_search_api_solr_documents_alter() because the longitude and latitude need to be indexed with the right format.


Problem with session ID and Drupal cookies when trying to establish a connection I tried to established a connection between my app and Drupal services.
When I try to login to remote Drupal site using Mozilla add-on Poster everything is working... POST request return OK 200 and I'm logged into the site.

When I make the POST request from my app, I always get 200 repose OK, but when I visit the site in browser I'm not logged in.
I suppose that Cookie header is not correctly structured in POST request...but I don't know how to fix it.

Does anyone have idea how can I solve this?

I had the same problem in Drupal 8. The AJAX POST isn't retrieving the cookie from user/login as Drupal does a redirect right away to another page (user usually) which is where you get your 200. And there is nothing (nothing) you can do to interrupt that redirect as its wired into the browser. Postman in Chrome (and I presume Poster in Firefox) don't have those restrictions.

In Drupal 7 the Services module provides a login endpoint. After that you can retrieve the session ID and create the cookie by hand. See https://groups.drupal.org/node/358308

In Drupal 8 that endpoint doesn't exist (and there is debate as to whether it should). What I do is:

In the app I create a regular login form with a return destination to my app
<form action="/user/login?destination=/app">
Once that's done I retrieve a CSRF token as by then the cookie is set. In Drupal 8 you get that at rest/session/token. With Drupal 7 and the Services module you retrieve it at a different path based on your end point.
After that every request goes back with the X-CSRF-Token header and the cookie isn't used anymore.


Set a multiple field value on a form I use this field definition in the entity "message" class.

$fields['fichier'] = BaseFieldDefinition::create('file')
  ->setLabel(t('Fichier attaché'))
  ->setSetting('file_directory', 'messagerie/fichier') // dossier d'upload
  ->setSetting('max_filesize', '10MB') // taille max du fichier
  ->setSetting('file_extensions', 'pdf doc txt xls zip rar mp3 mp4 csv jpeg jpg ppt') // extensions autorisées, à séparer par un espace
  ->setSetting('description_field', FALSE) // si on veut activer un champ « description »
  ->setDisplayOptions('form', [
    'label' => 'hidden',
    'type' => 'file_generic',
    'weight' => 0,
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE);

In the associated form I need to set this field a multiple field (I can't find a way to set cardinality in the definition field).
How can I do that ?

You can use BaseFieldDefinition::setCardinality() for that, e.g.:

$fields['fichier'] = BaseFieldDefinition::create('file')
  ->setLabel(t('Fichier attaché'))
  ->setSetting('file_directory', 'messagerie/fichier') // dossier d'upload
  ->setSetting('max_filesize', '10MB') // taille max du fichier
  ->setSetting('file_extensions', 'pdf doc txt xls zip rar mp3 mp4 csv jpeg jpg ppt') // extensions autorisées, à séparer par un espace
  ->setSetting('description_field', FALSE) // si on veut activer un champ « description »
  ->setDisplayOptions('form', [
    'label' => 'hidden',
    'type' => 'file_generic',
    'weight' => 0,
  ])
  ->setDisplayConfigurable('form', TRUE)
  ->setDisplayConfigurable('view', TRUE)
  ->setCardinality(FieldStorageDefinitionInterface::CARDINALITY_UNLIMITED);


How to recalculate the current User Points? I manually deleted a couple of User Point transactions in my database's table userpoints_txn. This results in inaccurate current User Points in the table userpoints_total. Clearing caches or running cron doesn't resolve this problem.

Is there a way to recalculate the current total User Points for all users?

You should have used the Userpoints admin UI or its API (e.g. userpoints_userpointsapi()) to make changes in the records. That way you can make point adjustments without the problem of database integrity that you've introduced. If possible, I'd restore the DB rows and adjust the point records with the UI/APi.

In absence of that being a possibility, you can see that _userpoints_update_cache(), the function used for maintaining updated userpoints/userpoints_total tables, requires those tables to always be consistent, as they are referenced when transactions are added/updated/removed. Thus, the userpoints code won't be much help here.

You'll have to do an aggregate SQL query on the userpoints_txn table for each impacted user to determine their updated score and use that to update the userpoints/userpoints_total tables accordingly.


How to insert records in different table function lawyer_register_form($form,&$form_submit)
{
$form = array();
$form['name'] = array(
    '#title' => 'Username',
    '#description' => 'choose a username',
    '#type' => 'textfield',
    '#required' => TRUE,
);

$form['mail'] = array(
    '#title' => 'email',
    '#description' => 'enter a valid email address',
    '#type' => 'textfield',
    '#required' => TRUE,
);

 $form['fname'] = array(
 '#title' => t('Full Name'),
 '#type' => 'textfield',
 '#size' => 20,
 '#maxlength' => 20,
);

 $form['phone_no'] = array(
 '#title' => t('phone_no'),
 '#type' => 'textfield',
 '#description' => t(''),
 '#size' => 20,
 '#maxlength' => 20,
);

$form['street_address'] = array(
'#title' => t('Street Address'),
'#type' => 'textfield',
'#size' => 50,
'#maxlength' => 100,
);

$form['county'] = array(
'#title' => t('County'),
'#type' => 'textfield',
'#autocomplete_path' => 'lawyer_register-autocomplete-engine',
'#size' => 20,
'#maxlength' => 20,
 );

$form['send_message'] = array(
    '#type' => 'checkbox',
    '#title' => t('Notify user of new account via email.'),
    '#description' => 'If left unchecked, a message will not be sent.',
    '#default_value' => 1,
 );

 $form['submit'] = array(
  '#value' => 'Submit',
 '#type' => 'submit'
 );
 return $form;
 }

 function lawyer_register_form_submit($form, &$form_submit)
 {
 $new_password = user_password();
 $edit = array(
  'name' => $form_submit['values']['name'],
  'pass' => $new_password,
  'mail' => $form_submit['values']['mail'],
  'init' => $form_submit['values']['mail'],
  'status' => 1,
  'access' => REQUEST_TIME,
  ');
   $edita=$edit->uid;
  db_insert('field_data_field_name')
  ->fields(array(
'entity_type' => 'user',
'bundle' => 'user',
'deleted' => 0,
'entity_id' => $edita,
'language' => 'und',
'delta' => 0,
'field_name_value' =>$form_submit['values']['fname'],
))->execute();
   db_insert('field_data_field_county')
->fields(array(
'entity_type' => 'user',
'bundle' => 'user',
'deleted' => 0,
'entity_id' => $edita,
'language' => 'und',
'delta' => 0,
'field_county_value' =>$form_submit['values']['county'],
))
->execute();
    db_insert('field_data_field_address')
->fields(array(
'entity_type' => 'user',
'bundle' => 'user',
'deleted' => 0,
'entity_id' => $edita,
'language' => 'und',
'delta' => 0,
'field_address_value' =>$form_submit['values']['street_address'],
))->execute();
    db_insert('field_data_field_phone_no')
->fields(array(
'entity_type' => 'user',
'bundle' => 'user',
'deleted' => 0,
'entity_id' => $edita,
'language' => 'und',
'delta' => 0,
'field_userphone_value' =>$form_submit['values']['phone_no'],
))->execute();

   user_save(drupal_anonymous_user(), $edit);

I have already created table in database. I want to insert value of

fname, street_address, phone_no & county

In those table. How is it possible?

I have searched lots of time in google but not getting right answer.

if you wants to simple insert the field values in a different table you can write insert query in form submit.

 function lawyer_register_form($form,&$form_state)
{
$form = array();
$form['name'] = array(
    '#title' => 'Username',
    '#description' => 'choose a username',
    '#type' => 'textfield',
    '#required' => TRUE,
);

$form['mail'] = array(
    '#title' => 'email',
    '#description' => 'enter a valid email address',
    '#type' => 'textfield',
    '#required' => TRUE,
);

 $form['fname'] = array(
 '#title' => t('Full Name'),
 '#type' => 'textfield',
 '#size' => 20,
 '#maxlength' => 20,
);

 $form['phone_no'] = array(
 '#title' => t('phone_no'),
 '#type' => 'textfield',
 '#description' => t(''),
 '#size' => 20,
 '#maxlength' => 20,
);

$form['street_address'] = array(
'#title' => t('Street Address'),
'#type' => 'textfield',
'#size' => 50,
'#maxlength' => 100,
);

$form['county'] = array(
'#title' => t('County'),
'#type' => 'textfield',
'#autocomplete_path' => 'lawyer_register-autocomplete-engine',
'#size' => 20,
'#maxlength' => 20,
 );

$form['send_message'] = array(
    '#type' => 'checkbox',
    '#title' => t('Notify user of new account via email.'),
    '#description' => 'If left unchecked, a message will not be sent.',
    '#default_value' => 1,
 );

 $form['submit'] = array(
  '#value' => 'Submit',
 '#type' => 'submit'
 );
 return $form;
 }

    function lawyer_register_form_submit($form, &$form_state)
         {
         $username = $form_state['values']['name'];
         $new_password = user_password();
         $edit = array(
          'name' =>  $form_state['values']['name'],
          'pass' => $new_password,
          'mail' => $form_state['values']['mail'],
          'init' =>  $form_state['values']['mail'],
          'status' => 1,
          'access' => REQUEST_TIME,
          'field_first_fname' => array(LANGUAGE_NONE => array(array('value' =>     $form_state['values']['fname']))),
          'field_first_street_address' => array(LANGUAGE_NONE => array(array('value' =>  $form_state['values']['street_address']))),
          'field_first_phone_no' => array(LANGUAGE_NONE => array(array('value' =>  $form_state['values']['phone_no']))),
          'field_first_county' => array(LANGUAGE_NONE => array(array('value' =>  $form_state['values']['county']))),
          );

    user_save(NULL, $edit);
$user_id = db_query("SELECT uid FROM {users} WHERE name = :username", array(':username' => $username))->fetchField();

        $insert = db_insert('table_name') // in which table you want to insert
                  -> fields(array(
                        'uid' => $user_id,
                        'fname' => $form_state['values']['fname'],
                        'country' => $form_state['values']['country'],
                        'phone_no' => $form_state['values']['phone_no'],
                       //write other fields you want to save
                        ))->execute();
                }


How to make specific custom table data searchable in Drupal 7? I just created custom module with name  example , And it has a form to enter data to it's specific  custom table.
I want to make the data in this custom table searchable with Drupal default search feature.

Please guide me.

Thanks in advance.

Update

I already skimmed through the Drupal api docs and followed the instruction but I couldn't make it working.

The Drupal search interface manages a global search mechanism.

Modules may plug into this system to provide searches of different types of
data. Most of the system is handled by search.module, so this must be enabled
for all of the search features to work.

There are three ways to interact with the search system:

Specifically for searching nodes, you can implement
hook_node_update_index() and hook_node_search_result(). However, note that
the search system already indexes all visible output of a node; i.e.,
everything displayed normally by hook_view() and hook_node_view(). This is
usually sufficient. You should only use this mechanism if you want
additional, non-visible data to be indexed.
Implement hook_search_info(). This will create a search tab for your module
on the /search page with a simple keyword search form. You will also need
to implement hook_search_execute() to perform the search.
Implement hook_update_index(). This allows your module to use Drupal's
HTML indexing mechanism for searching full text efficiently.

If your module needs to provide a more complicated search form, then you need
to implement it yourself without hook_search_info(). In that case, you should
define it as a local task (tab) under the /search page (e.g. /search/mymodule)
so that users can easily find it.

The full documentation can be found  at https://api.drupal.org/api/drupal/modules%21search%21search.module/group/search/7


Template files do not work when in "Templates" directory I have a custom theme that I have created, that contains a .info file, and various .tpl.php files.  The problem is that these templates wont be recognized by Drupal (7).  I've tried clearing all of the caches and re-uploading the files with no avail, as well is restoring the database.

This theme works fine on a local server, but whenever the site is migrated to my staging server, the template is not recognized. The theme will show up in the admin interface under the appearance tab however and is enabled as default.

There are no errors in "recent log messages"

It turns out there were more .tpl.php files in a different directory that was not obvious, thus overriding the templates I intended to use.