How to add auto taxonomy to node fields? How to add auto categorization(Taxonomy Term) to node based on node body/description.

Node Body/Description: Retro is back in style, so flaunt the same when wearing this T-shirt from PUMA. Fashioned for men, this piece can be easily worn when heading out for a crazy day ahead with friends. Live in the moment by wearing this T-shirt with casual trousers and flip-flops when you hit the street with your best buddies
Here i have : ->T-Shirts, flip-flops, MEN etc,
By reading this content i want to assign auto taxonomy term reference in node field as T-Shirts to node.
Is it possible to do this?
Anyone help me ASAP.
Thanks in advance.

If I understand you, there is a few modules which can handle it:

Word Link (I recommend it)

  The Word Link module allows you to automatically convert specific
  words into links. It works as text filter. This can be useful for
  crossposting your site's pages, or for the contextual advertising of
  your partners (SEO).

Active Taxonomy Links

  Active Taxonomy Links module processes nodes of selected content types
  replacing words in the nodes with links to taxonomy terms.

Glossify (this one supports Drupal 6 also)

  The Glossify module provides filters that scan and parse content and
  replace terms in the text with links to their pages. The d7 version is
  a complete rewrite of the module to be as simple and performant as
  possible.


Where is my stylesheet located? I would like to make small css changes such as h1 and various font, background colors and divs etc. I am using Newsflash theme on Drupal 7 and I have searched and searched my folders thus: sites> all> themes> newsflash> css> local.css

I can probably override things here but I would prefer to go to the source stylesheet if it exists.  Does it exist?  If not, is local.css the right place to write my changes?

Go to /admin/config/development/performance

Uncheck Aggregate and compress css files

Now with your browser right click and inspect element, hover mouse over the .css file and it will tell you where it is at.

If it's coming from a contrib module, you should add your css on your theme's CSS file (in your case being local.css), as when you update that contrib module, it will lose the changes.

As you can see in my screenshot, that is coming from my theme's homepage.css file.

PS: After you're done, remember to turn back on (check-mark) Aggregate and compress css files in Performance.


custom node type that save to a custom table I’m trying to convert one of my sites into a Drupal site. The site is a travel site and has a lot of data on there, so I’m trying to convert my database tables to custom node types, but my tables are large,  I have about 30 different tables with a total of about 200+ fields.

If I would just convert all the fields to CCK fields I would end up with a database with 400 to 500 tables, I don’t like that, so I’m trying to create custom node types that save to custom tables.

Does anybody know how to do this, and if you know of an example somewhere that would be great

Thanks
Rob

You're probably best off if you use the Feeds module to import your data into Drupal. Messing with the database configuration yourself just because you "don't like that" a lot of tables would be generated seems like a lot of work for not much potential benefit.

If you're worried about filling up the Drupal database, it is possible to use one database for Drupal's content and configuration, and another for data that you're using Drupal to expose to users. D7 boasts master/slave database configuration support. It is also possible to integrate with databases that Drupal does not support for its main configuration database, e.g. Mongo.


Module to separate the links of menus by language? A few days ago I found a module to separate the links of menus by language. Given a localized menu then you get the links separated by languages. Very useful I think.

But now I can't remember its name. Does anyone know it?

I found it, it's a sandbox project though: http://drupal.org/sandbox/TimBrandin/1835360


Importing large amount of data slow process with cron and queue I am currently importing large amount of data into Drupal and I am using the hook_cron with the queue API and so far everything is working. Data is been imported as nodes and the relationship between them is created and the views are displaying the data properly.

The problem I am having is how long it is the process taking to do the import of the data. I tried using the "Ultimate Cron" to see if a parallel processing of the cron job will speed things up, but I had no luck.

I have my queue full of pending data to be process and I can think of a way to speed it up. I read about creating multiple queues, but I haven't try that.

The server is a pretty decent server and the server load is less than 2% all the time, swap is empty and I am only using 800MB of 16 GB of RAM.

I think it will be good to use multiple queues and separate php non blocking (shell_exec) process to read each queue, the idea is to call a php script to run in background which will pick a queue data and create nodes or whatever.


How do I delete a vote (e.g.rate module)? Is there a module with a functionality to delete votes using the voting api? If not, how do I implement a button that erases all votes? Or is it easier if I just empty the MYSQL table?

The voting api defines some drush commands:

drush generate-votes <entity_type> <vote_type>
drush votingapi-recalculate <entity_type>
drush votingapi-flush <entity_type>

if you don't use drush, you can run the code from the function that the module uses on devel php or similar

<?php
$entity_type = "name_of_the_entity";
$cache = db_delete('votingapi_cache');
$votes = db_delete('votingapi_vote');

if (!empty($entity_type)) {
  $cache->condition('entity_type', $entity_type);
  $votes->condition('entity_type', $entity_type);
}
if (!empty($entity_id)) {
  $cache->condition('entity_id', $entity_id);
  $votes->condition('entity_id', $entity_id);
}

$cache->execute();
$votes->execute();


How to place a specific comment on top of list PLease help me with this requirement in D6.

I need to mark one comment as best, so this comment should stick on top of all comments posted irrespective of sort order.

How can this be achieved, any ideas?

Found Best Reply module.

  Best reply module allows node authors to mark a particular comment as the best reply. It aims to encourage quality comments and to give some recognition to people posting quality responses.


View / Edit tabs no longer functional I seem to have done something to mess up the View / Edit tabs which appear above page content when you are logged in with appropriate rights. The tabs appear but they are no longer clickable. If I access the "edit" link via the dashboard, I can edit the page contents no problems - it's just the handy short-cut that has stopped working.

Anybody know how to fix this?

Use chrome/firefox's inspector and click on the edit link that will highlight the element that's sitting over the top of it and you can sort your CSS out for that element


Product reference add to cart form shows only add to cart button I've created a content type with a product reference field, but when I create a content with the reference to the product, it shows add to cart form with only add to cart button. I wanted to display Price, quantity, and product attributes on the add to cart form. I've searched a lot to find out any configuration for this, but no luck. Can anyone please help me regarding this?. It works fine in Drupal 7, but in Drupal 8 there is no way I can set up the form.

First be aware that Commerce is still in Alpha, so behavior might change between versions!

I suppose you are looking for something like this from the Drupal Commerce Blog.

I have no idea how to get there as I am awaiting a more stable version of Drupal Commerce, but I suppose the breadcrumb in the image should give you some directions on where to find these settings.


How do I wrap a div around specific fields in a view? I have to make a small website using drupal 8 for a school project but I keep getting stuck with the twig templating. I'm trying to wrap a div around certain fields in drupal 8 with twig.
The layout at the moment is as follows(this is an example);

Content type image

Content type Title
Content type Category

Is there any way to accomplish this using a twig template for the certain view?

The bottom two items have to go in a div.

To add CSS classes you don't need to use Twig, you can do it using the Views UI

Click on your field. Then under style settings, checkmark customize field HTMl and select DIV as your element. Checkmark create css class and type your class name.


Retrieve File Url from Upload Form When Form is submitted I have the following code in my form.

function video_subtitles_menu() {
    //print "video_subtitles_menu 1";exit;
  $items = array();
  $items['video_subtitles_test/upload'] = array( //this creates a URL that will call this form at "examples/form-example"
    'title' => 'Upload Subtitle', //page title
    'description' => 'Uploading subtitle for videos',
    'page callback' => 'drupal_get_form', //this is the function that will be called when the page is accessed.  for a form, use drupal_get_form
    'page arguments' => array('video_upload_subtitles_form'), //put the name of the form here
    'access callback' => TRUE
  );
      //print "video_subtitles_menu 2";exit;
  return $items;
}

function video_upload_subtitles_form($form, &$form_state) {
 $form = array('#attributes' => array('enctype' => 'multipart/form-data'));
 $form['video_name'] = array(
    '#title' => t('Name Of the video'),
    '#type' => 'textfield',
 );

 $form['sub_file'] = array(
        '#type' => 'file',
        '#title' => t('Upload video'),
        '#size' => 48,
        '#description' => t('Pick a video file to upload.'),
    );
 $form['submit_button'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),

    );
 return $form;

}

function video_upload_subtitles_form_validate() {
  if(!file_check_upload('upload')) {
    // If you want to require it, you'll want to do it here... something like this:
    form_set_error('upload', 'File missing for upload.');
  }
}

function video_upload_subtitles_form_submit($form, &$form_state) {
 $video_name = $form_state['values']['video_name'];//I am able to get this
 $file = file_save_upload('sub_file', array());
print "<pre>";print_r($file);// no response here
drupal_set_message(t('The form has been submitted.'));//this also not printing
}

On the submission handler, it only returns the text field, I don`t get anything from file upload field, when I use file_save_upload.

This is the response which i get in firebug, I have tried uploading text and excel file.

What I am trying to do is create a block where you can upload a file than I need to get the url to upload it to CDN but how to get the link of file at form submission.

I am using Drupal 7 by the way.

found the solution here.I am not sure what is the core issue but below is the solution

This was the comment in the above link where I found solution.

  More than likely eveyone who is having a problem here has been
  developing on their local computer, then are tryng to migrate their
  system to a remote server. When you do this, you are probably moving
  your setting for directory paths along as well.

  For example the temp path for your images is probably different than
  the image temp path on your host system.

  I recommend this test in Drupal 6.14. goto /admin/settings/file-system

  and look at your temporary directory... if its glaring red, then try
  renaming it to something like: /tmp. if that does not work, try
  renaming to just tmp ( no forward slash)

  Next step to test this will be to upload an image or file. I tested it
  by uploading a new logo. But remember, that if you do a FULL DB dump
  from phpmyadmin from your local computer to the new host, you will
  probably see this problem again.

For Drupal 7 guys I just went to admin/config/media/file-system , so basically find out where the file system is in your config area and I change the '/tmp' to 'tmp'.

After changing it was able to print the file object :)

stdClass Object ( [uid] => 1 [status] => 0 [filename] => 3-26-2014 12-15-54 PM.png [uri] => temporary://3-26-2014 12-15-54 PM.png [filemime] => image/png [filesize] => 30536 [source] => private_file [destination] => temporary://3-26-2014 12-15-54 PM.png [timestamp] => 1395828492 [type] => image [field_replacement] => stdClass Object ( [uid] => 1 [status] => 0 [filename] => 3-26-2014 12-15-54 PM.png [uri] => temporary://3-26-2014 12-15-54 PM.png [filemime] => image/png [filesize] => 30536 [source] => private_file [destination] => temporary://3-26-2014 12-15-54 PM.png [timestamp] => 1395828492 [type] => image ) [fid] => 3102 )

Hope it help someone.


I can't set a default value on hook_form_alter() I have form alter for the user_register_form which is called.
In this hook, I try to set a default value for a textfield but it doesn't work.
I've tried all the syntax possible #default_value, #value, value, default_value, event in the attributes array.

This is my code.

function pre_registration_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
  $form['field_code_postal']['#cache']['max-age'] = 0;
  $form['field_code_postal']['#default_value'] = 'COUCOU';
  $form['field_code_postal']['#value'] = 'COUCOU';
  $form['field_code_postal']['value'] = 'COUCOU';
  $form['field_code_postal']['value']['#value'] = 'COUCOU';
  $form['field_code_postal']['value']['#default_value'] = 'COUCOU';
  $form['field_code_postal']['value']['value'] = 'COUCOU';
  $form['field_code_postal']['value']['default_value'] = 'COUCOU';
  $form['field_code_postal']['default_value'] = 'COUCOU';

  $form['field_code_postal']['#attributes']['value'] = 'COUCOU1';
  $form['field_code_postal']['#attributes']['#value'] = 'COUCOU2';
  $form['field_code_postal']['#attributes']['default_value'] = 'COUCOU3';
  $form['field_code_postal']['#attributes']['#default_value'] = 'COUCOU4';
}

How can I set a default value?

According to this Documentation you can do something like

 $form['field_code_postal']['widget'][0]['value']['#default_value'] ='COUCOU1';

and for another guys help if you want to fill entity referenced field( also files are entity in drupal 8) use

 $form['field_image']['widget'][0]['target_id']['#default_value']= $file; //


Drupal 7 form_state[redirect] does not work I am new to Drupal development and I stuck on a problem.
I have got a form which I append to a node. The custom submit method is called correctly, but my redirect does not work. When I press the button I got redirected to the form.
Thank you very much in advance

    function ticketGenerator_node_view($node, $view_mode) {
    $nodetype = node_type_get_type($node);
    $nodetype = $nodetype->type;
    if ($view_mode == 'full' && node_is_page($node) && $nodetype=='event') {
    $node->content['buttonKaufentest'] = drupal_get_form('ticketGenerator_generateform',$node);
    }
    return $node;

}

    function ticketGenerator_generateform($form, &$form_state,$node){
    $form = array();
    $form['name'] = array(
    '#type' => 'textfield',
    '#title' => t('Name'),
);
    $form['submit'] = array(
    '#type' => 'submit' ,
    '#value' => 'buttonalter',
    '#submit' => array('ticketGenerator_list_submit')
 );
 return $form;

}

   function ticketGenerator_list_submit($form,$form_state){
   drupal_set_message('custom submit has been invoked');
   $form_state['redirect'] = 'www.google.de';
   }

You need to pass $form_state in by reference, or the change won't be persisted outside of the function scope:

function ticketGenerator_list_submit($form, &$form_state) {


Drupal 7 - Output taxonomy terms on a node? Currently I want to output the taxonomy term of the current node I'm viewing. I have an Article content type and I created a view block placed it in the footer. Now in this view I'm using PHP Field and I want to output the taxonomy terms on the current page. Right now I know menu_get_object() can get you the node ID of the page, but I'm not sure how would one get the taxonomy terms of the current page?

I was thinking of doing a node_load() on the nid of the page and then parse the taxonomy array then fetch the TID then do another function to grab the Taxonomy name. Any other easier way of doing this?

You don't need php field for this.

On the right side click on Advanced, under RELATIONSHIPS add "Content: Taxonomy terms on node".

On the left side add a new field. Search for taxonomy and you should see a Taxonomy term name field that is now available thanks to the relationship.


Drupal Commerce order total amount not update after I programmatically changed line item's price I am using Drupal Commerce. Now I have to alter the product price programmatically. After search on google and here, I found some people did it:
Alter cart unit price and total amount

Then I made a test by using hook_commerce_cart_order_refresh(). Here is my code:

function mymodule_commerce_cart_order_refresh($order_wrapper){
    foreach ($order_wrapper->commerce_line_items as $delta => $line_item_wrapper) {
        $line_item = $line_item_wrapper->value();
        $qty = $line_item->quantity;
        $line_item->commerce_unit_price['und']['0']['amount']=100;
        $line_item->commerce_total['und']['0']['amount']=$qty*100;
        commerce_line_item_save($line_item);
    }
}

It changed the cart and order line item unit price and line item totoal amont. But the order total will not changed. Still calculated on the old price.

I also notice somebody have the same question:Order Total not updating after I change the line item price , but I don't know that answer how it works. It said using following code:

The solution was to use commerce_price_add_component()

$line_item_wrapper = entity_metadata_wrapper("commerce_line_item", $commerce_line_item);
$line_item_wrapper->commerce_unit_price->data = commerce_price_component_add(
    $line_item_wrapper->commerce_unit_price->value(),
    'base_price',
    array(
            'amount' => $booking_price,
            'currency_code' => 'AUD',
            'data' => array(),
    ),
    TRUE
);

But I don't know where to use the above code, put in a hook?

Is some one can give me a idea?

I'v found the way. Put answer here:

function mymodule_commerce_cart_line_item_refresh($line_item, $order_wrapper){
    $line_item->commerce_unit_price['und']['0']['amount']=110;
    $line_item->commerce_unit_price['und']['0']['data']['components']['0']['price']        ['amount']=110;
}

Because the commerce_order_calculate_total() is based on components, so if you only changed the commerce_unit_price amount is not enough. Must change data also.


Multiple forms on the same page: hook_forms only works after cache_clear_all In a User Tab there are multiple node forms of the same type.

To do this I implemented hook_forms. Multiple forms are shown and they work (sometimes).
But if the user adds some (or delete) nodes and calls his page again he gets the following error:

(Lets say the user owns node 1 and 2)

  Notice: Undefined index: mymodule_a_form_1 in drupal_retrieve_form() (Zeile 738 von /htdocs/includes/form.inc).

  Warning: call_user_func_array() [function.call-user-func-array]: First argument is expected to be a valid callback, 'mymodule_a_form_1' was given in drupal_retrieve_form()
  (Zeile 773 von /htdocs/includes/form.inc).

  Notice: Undefined index: mymodule_a_form_2 in drupal_retrieve_form() (Zeile 738 von /htdocs/includes/form.inc).
  Warning: call_user_func_array() [function.call-user-func-array]: First argument is expected to be a valid callback, 'mymodule_a_form_2' was given in drupal_retrieve_form()
  (Zeile 773 von /htdocs/includes/form.inc).

The forms work again if I clear all caches.

So what is wrong with this (sample) code?:

<?php

function mymodule_user_profile_tab_content($uid) {
  $out = array();
  $users_node_ids = _get_user_node_ids();
  foreach($users_node_ids as $nid) {
    $node = node_load($nid);
    $out[] = drupal_get_form('mymodule_a_form_'.$nid, array('node' => $node));
  }
  return $out;
}

/**
 * Implementation of hook_forms()
 */
function mymodule_forms($form_id, $args) {
  $forms = array();
  if (strpos($form_id, 'mymodule_a_form_') === 0) {
    $forms[$form_id] = array(
      'callback' => 'mymodule_a_form',
    );
  }
  return $forms;
}

I had the same problem and it seemed to be resolved after correcting an issue with the function definition. Make sure that $form_state is a reference.

function mymodule_a_form($form_id, &$form_state, $args) {
...
}

One of the other things that I noticed is that the cached module_implements no longer had a reference to my module, so when Drupal was looping through the implements and looking for a function called mymodule_forms(), it couldn't find it.  You can check to see if this is the issue by comparing the cached implements to the static version.

    $cache_implements = cache_get('module_implements', 'cache_bootstrap')->data['forms'];
    ksort($cache_implements);
    dpm($cache_implements, 'CACHED FORM IMPLEMENTS');

    $static_implements = drupal_static('module_implements');
    ksort($static_implements);
    dpm($static_implements['forms'], 'STATIC FORM IMPLEMENTS');

If that is the issue and your form declaration is correct then maybe try doing an include on the page that references your dynamic forms.

module_load_include('admin', 'mymodule', 'inc');


Change site name programmatically We have a requirement that when we save a node that nodes title should be the site name. We used to do it in Drupal 7. But I was not able to find the proper method for it in Drupal 8.

This is what we tried:

$config = \Drupal::service('config.factory')->getEditable('system.site');
$config->set('system.site.name', "Demo Site");
$config->save();

Got it from here: https://www.drupal.org/docs/8/api/configuration-api/simple-configuration-api

Any suggestions?

Nearly :

$config = \Drupal::service('config.factory')->getEditable('system.site');
$config->set('name', "XXXXXXX");
$config->save();

Just have to implement hook_node_update to fit your needs.


Denying access to node form edit I need to make some checks on node access form based on user/role attributes that cannot be handled by Drupal core modules, so i think to do them in _form_alter hooks.

Which is the best thing to do when the user has not access to the form edit ? I can do a drupal_goto(...) but i would like to stay in the same form, showing an access denied command. How can i do it?

I think the standard way to handle this would be to implement hook_node_access(), make your checks there, and deny access if any of your conditions aren't met.

This will result in the standard 403 page when a user without the correct permissions tries to access the page, which semantically speaking would probably be the best result.

The code might look something like:

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

  if ($type == 'my_type' && ($op == 'create' || $op == 'update')) {
    if ($account->something == 'something') { // allow access
      return NODE_ACCESS_ALLOW;
    }
    else {
      return NODE_ACCESS_DENY;
    }
  }

  // Return the default ignore value if your module doesn't need to get involved in this decision
  return NODE_ACCESS_IGNORE;
}


How to Post JSON data to Cart service in Drupal Commerce Services I'm uses Drupal commerce services for mobile commerce. But I don't know how to Post jSON to REST service Cart or Order. With Comment services I"m post JSON successful as below:

URL: [http://myserver.com/services/comment/][1]
METHOD: POST
JSON BODY:
{
    "comment":{
      "comment_body":{
        "und":[
          {"value":"Good job"}
        ]
      },
      "nid":"23",
      "subject":"Drupal Services Comment"
    }
}

I don't know what is JSON Body to POST to Cart or Order Service like that? Anyone Please help me? Thanks

I found JSON structure for Cart or Order Services. It's something as below:

{
   "type":"commerce_order",
   "commerce_customer_billing":"10",
   "commerce_line_items":
       [
           "11",
           "13",
           "14",
           "15",
           "16"
       ]
}


db_query not returning anything (or empty) - drupal 7 I am trying to perform a db_query but am unable to do so.

The query I am trying to perform is very simple, but to make things even simpler, the following query does not even work for me:

$result = db_query('SELECT name FROM users WHERE uid = 1');

and if I do:

echo (string)$result->name;

nothing is displayed.

Does anyone know what could be causing this?

Edit - Updated with new code:

define('DRUPAL_ROOT', getcwd());
$_SERVER['REMOTE_ADDR'] = "localhost";
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$result = db_query('SELECT OFFICE_ID FROM {OFFICE}');
$counter = 0;
foreach($result as $record) {
  $counter = $counter + 1;
  print $record->office_id;
}
print $counter;

Nothing will be printed, but at the end of the loop, the number of loops performed is the same as the number of rows returned from a direct query on the DB itself.

The return from db_query() is a resource that you can iterate over, it's never a single value.

The way to get a single field from a query is with the fetchField() method:

$result = db_query('SELECT name FROM {users} WHERE uid = 1')->fetchField();

If you've got more than one result then you can iterate over it like so:

foreach ($result as $row) {
  // Do something with $row...
}

or, you can make use of one of the helper methods to get data directly from the query into a local variable. These include:

fetchObject()

  Fetches the next row and returns it as an object.

fetchAllAssoc()

  Returns the result set as an associative array keyed by the given field.

fetchAllKeyed()

  Returns the entire result set as a single associative array.

fetchAssoc()

  Fetches the next row and returns it as an associative array.

fetchCol()

  Returns an entire single column of a result set as an indexed array.

fetchField()

  Returns a single field from the next record of a result set.


How do I hide a view's field based on role? In /admin/people, I want to hide the display name (i.e. the Display name must not appear in the user list), but only for a specific role.

In my .module file, I have tried following hooks:

function hook_views_data_alter(array &$data) {
  kint($data['users']);die;
}

function hook_views_pre_render(\Drupal\views\ViewExecutable $view) {
  if($view->id() == 'myview'){
    print_r($view->result);die;
      // kint($value->_entity->get('title')->value);
  }
}

function hook_views_post_render(\Drupal\views\ViewExecutable $view) {
   if ($view->id() == 'viewid') {
    // Set the view title.
    $field_name = $view->getFields();
  }
}

function hook_field_views_data_views_data_alter(array &$data, \Drupal\field\FieldStorageConfigInterface $field) {
  $field_name = $field->getName();
  echo 'hjsjhwd';
  print_r($field_name);die;
  }

None of them helped me. I thought of getting fields of the view "user" and after that I will unset it for particular role. But in views listing, Name field is still appearing. How can I hide it for a particular role?

Is there any way to achieve this?

The most efficient way would be using hook_views_pre_view(), which allows you to alter a View at the very beginning of the process i.e. before any query is built/run and before any rendering takes place. You can remove the 'name' field handler from the View based on the desired logic.

/**
 * Implements hook_views_pre_view().
 */
function MY_MODULE_views_pre_view($view, $display_id, array &$args) {
  if ($view->id() !== 'user_admin_people') {
    return;
  }

  $user_roles = \Drupal::currentUser()->getRoles();
  if (!in_array('my-special-role', $user_roles)) {
    $view->removeHandler($display_id, 'field', 'name');
  }
}

This solution assumes that you are only interested to serve this very specific use case - remove the field only from this specific View. Users might still be able to see the Display Names of users in other areas of the website.


How to input search terms via a separate form on a content page to a Views Exposed Filter on a different page? When visiting a content page (node), I want users to be able to input search terms into a form from there which will be fed into a View via its Views Exposed Filter.

The View I have is contained within Panels in a Panels-based page and it's Views Exposed Filter is made available as an external block. This approach allows me to layout this View and Views Exposed Filter with other separate items in other Panels.

Given that the Views Exposed Filter is made available as an external block, I can display it on other pages such as content. However, entering search into this form on these content pages results in the just the View being displayed - I need it to display the Panels-based page as mentioned above with the View results.

So I would somehow need to feed the input supplied by the user into the form on the content page, as a parameter into the Panels-based page.

My initial thoughts and questions on implementaton

Is it a case of using something like dpm() (which I have found useful in the past) to understand the form data being input so that input from the form can be fed to the Panels-based page and 'routed' to the Views Exposed Filter? I think the form data needed by the Views Exposed Filter is understood but how would I know where to submit the data i.e. can I give the URL for the Panels-based page as the form action URL and is there anything else I need to do so that the Panels-based page will convey the form input data to the Views Exposed Filter in the panel?

It is possible to use dpm() to understand the form data. In a custom module, you can use hook_form_alter() to act on the exposed filter form.

It would look something like this:

function example_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    dpm($form);
  }
}

You can then set the action.

function example_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    $form['#action'] = '/path-to-panel';
  }
}

Just beware that this will alter all the exposed filters on the site. You can create a different if statement to target them more specifically if you have more than one.


How to get the front page title in page.html.twig? I'm trying to use the page title in my theme's page.html.twig. On normal pages, {{ node.label }} does the job, but that doesn't work on the front page. There, node is NULL, presumably because the font page is a view rather than a "real" page.

I have tried to dump all the available variables on page.html.twig using kint, but it seems that none of them contains the page title. Other questions discuss a similar matter, but either only for normal pages or for getting the title from PHP (and not from within a TWIG template).

I'm looking for an approach that works in any template, although page.html.twig is most important for me right now. It should also take a global title override into account. The ideal solution would also work on normal pages (i.e. not the front page).

TL;DR: I'm looking for a template variable/function X so that {{ X }} is the current page title, no matter whether I'm on the front page or on any other page.

You should really try using the blocks for this, but here's how to do what you asked:

function YOUR_THEME_preprocess_page(&$variables) {
  $request = \Drupal::request();
  $route_match = \Drupal::routeMatch();
  $page_title = \Drupal::service('title_resolver')->getTitle($request, $route_match->getRouteObject());
  $variables['current_page_title'] = $page_title;
}

This code should go in YOUR_THEME.theme file. You can use it then in page.html.twig this way:

{{ current_page_title }}

See this for more information.


Drupal Commerce - Line Item 'display path' from views How is the 'display path' is built when the Cart view is rendered?
Why would it not be rendering some display path URLs?

I'm using a modified version commerce_add_to_cart_extras module whereby I'm trying to link the line item to the product display node by customizing the display path. I can see it being added correctly when I inspect the $line_item object in save function of CommerceLineItemEntityController. But the line items in my cart still aren't linked and when I output the display path as a field in the view, it's empty.

If it would help, I can add the debug print I captured via devel's dd() function of the $line_item or my code but they will make the post rather long so I've left them out for now.

Edit the view, click the "Quantity input field", are you sure the "Link products added to the cart from this View to this View's path if displayed as a page." checkbox is checked? That's what makes it populate the display path.


How can I achieve this functionality to allow url prefixes without hacking the core? Lets say I have a site example.com with the following urls:

example.com
example.com/page1
example.com/about

This is an American site, but I also want an Australian version.

The urls for the Australian site will be:

example.com/au
example.com/au/page1
example.com/au/about

The homepage and page1 are identical on both sites so the same content is served. However there is an Australian specific version of about so different content is served.

How can I map all of the /au pages to the ones without /au and somehow pass the fact that it is an AU page so I can determine what content to serve?

Update:

To clarify I want every single page that exists to be accessible via it's normal path alias, or the normal path alias prefixed with "au/".

I have managed to achieve this by editing bootstrap.inc in the following way:

A. Alter request_path(). After the line:

$path = substr(urldecode($request_path), $base_path_len + 1);

I added:

if(substr($path, 0, 3) == 'au/') {
  $path = substr($path, 3);
  $_SESSION['au'] = TRUE;
} else {
  $_SESSION['au'] = FALSE;
}

B. Alter drupal_settings_initialize(). After the $base_path has been set add:

if(isset($_SESSION['au']) && $_SESSION['au']) {
  $base_path = '/au/';
}

This means both /page and /au/page are treated in exactly the same way and I can use $_SESSION['au'] in a node preprocessor hook to determine which content to serve.

Now my question is how can I achieve this behaviour without hacking the core?

Use i18n. It does this for you.

You have the possibility to choose how the content is served (from the module configuration page), between a subdomain for ex. "au.mysite.com/post-name" and prefixes like "mysite.com/au/post-name".

You will have a language field for your content-type, and you can easily set different content for different languages.


Create two views this the same url and different permissions I would like to build a set of views, all of which use the same url.  I also want to set up role based permissions for each one so each users get routed to a different view when they visit the url (the url which all the views share.)  Is it possible to build this view system?

My final goal is to have a single navbar link which sends normal users to a view that filters content based on the users NID.  Admin users will be sent sent to a view that shows everything.

Make the views as blocks and configure each one to display according to the permissions you're interested in, then place all blocks on a single page and link to it. The system will try to load all blocks, but will not show the ones the user doesn't have access to.

One caveat is a privileged user (such as admin) seeing their AND "lower permission" views, but that can be worked around, too.


Oracle database connection in drupal 7 I want to retrieve a list of products from an external oracle database and show it in my drupal site as a catalog.
But the problem is that, how can I make the connection to oracle db from a drupal 7 site.
Please any suggestion on how to perform this operation is highly welcome.
Thanks!

I recommend separate this from Drupal. I mean if you just want a list of products so write an external application to prepare a xml format of this list and feed it to Drupal.

You need install PHP PDO_OCI to make connection from PHP application into Oracle.

Drupal has an Oracle Driver but I recommend external application instead


How to unit test hook_form_alter implementation code in custom module How to unit test hook_form_alter implementation code in custom module?

Don't, that doesn't make sense. Unit tests make sense for APIs and classes, things with clear interfaces and definitions what's the input/output.

A form alter means you're altering more or less internal structures from another module that might change over time. Especially backend forms are explicitly excluded from Drupal Core BC for example, which means that they can be changed over time. You want to do a full browser test to make sure that your logic/changes actually work in the resulting form that is displayed in the browser.

See https://www.drupal.org/docs/8/testing/types-of-tests-in-drupal-8 for documentation of different types of tests in Drupal 8 and when they should be used. There are 4 different types of test classes for a reason.


Reaction after click on custom link inside views I have a views which select all not validate "event". And the purpose is to add a button to validate the "event".
My hope is when I click on the button a popup ask you to confirm the validation. if yes i want to use rule to make this action.
My issue  is that i don't know how to begin it

Have a look at the Rules Link module. Some details from its project page:

  This module lets you create links which trigger arbitrary functionality with the help of Rules.

  Features:

  Attach the link to any entities.
  Show the link only for certain bundles.
  Narrow the entities on which the link will be shown using the visibility conditions.
  The links are usually displayed using Views.
  For entities that can be displayed, the links can be shown on node view.
  Supports an arbitrary number of additional Rules parameters for passing context via Views.
  3 types of links: Javascript, Normal and Confirmation form links.
  Use individual permissions for each link.

Some more details (from its README.txt):

  To create a new link go to admin/config/workflow/rules_links and click on "Add rules link". Enter the title of your link and set all the settings. After clicking on the "Save Rules Link" button, the module will generate a new And- and Rules-Set and their forms will be embedded into the rules link editing form.

  The And-Sets are called Visibility Conditions and will define when to render the links. The Rules set is the rule, that will be triggered on clicking the rule. Additionally Rules Links also generates access permission for each link, which you'll have to set in admin/people/permissions.

  The best way to display the links is currently using views. Rules Links link will create a Views field for each link, using the title of the link as title for the field. So if you have link for nodes with the delete 'Delete node', you'll find the Views field under name 'Content: Delete node'.

  Alternatively you can use render the links directly in the entities that can be displayed, using the option 'Show link in entity' in the Rules Links settings.

  Note that this will not work for links were the parameters have multiple
  paramaters.

  If you would like to render a link yourself in a theme or in a module, than use the function rules_link_render_link().

PS: I'm assuming this question is about D7.


Commerce Kickstart: How do I fix a SQL error on string length after using Features Override to save customizations? After reading the update instructions on Commerce Kickstart (Installing & Upgrading), I attempted to use the Features Override module to save my customizations/configuration prior to updating to the most current version of Commerce Kickstart. I have changed menus, user profiles, etc. and would like to keep those updates intact.

I followed the instructions posted on the project and generated a "Feature.tar" file.

Attempt #1:

Selected all items shown in Features Override dropdown (179 items)
Downloaded the file
Enabled the new feature through "Modules" UI
Received this set of error msgs [truncated for demo purposes]:

PDOException: SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'info' at row 1: INSERT INTO {system} (filename, name, type, owner, info) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2, :db_insert_placeholder_3, :db_insert_placeholder_4); Array ( [:db_insert_placeholder_0] => sites/all/modules/features_override_0916/features_override_0916.module [:db_insert_placeholder_1] => features_override_0916 [:db_insert_placeholder_2] => module [:db_insert_placeholder_3] => [:db_insert_placeholder_4] => a:12:{s:4:"name";s:25:"Features Override 09-2016";s:4:"core";s:3:"7.x";s:7:"package";s:8:"Features";s:12:"dependencies";a:2:{i:0;s:18:"commerce_kickstart";i:1;s:4:"node";}s:8:"features";a:2:{s:12:"features_api";a:1:{i:0;s:5:"api:2";}s:23:"features_override_items";a:153:{i:0;s:61:"facetapi.search_api@product_display:block:field_blog_category";i:1;s:58:"facetapi.search_api@product_display:block:field_brake_type";i:2;s:56:"facetapi.search_api@product_display:block:field_hub_type";i:3;s:64:"facetapi.search_api@product_display:block:field_intended_use_alt";i:4;s:59:"facetapi.search_api@product_display:block:field_primary_use";i:5;s:85:"facetapi.search_api@product_display:block:field_product:commerce_price:amount_decimal";i:6;s:71:"facetapi.search_api@product_display:block:field_product:field_axle_size";i:7;s:71:"facetapi.search_api@product_display:block:field_product:field_build_kit";i:8;s:67:"facetapi.search_api@product_display:block:field_product:field_color";i:9;s:72:"facetapi.search_api@product_display:block:field_product:field_frame_size";i:10;s:86:"facetapi.search_api@product_display:block:field_product:field_product_specific_options";i:11;s:73:"facetapi.search_api@product_display:block:field_product:field_wheel_sizes";i:12;s:64:"facetapi.search_api@product_display:block:field_topic_related_to";i:13;s:25:"field_base.commerce_price";i:14;s:30:"field_base.field_blog_category";i:15;s:23:"field_base.field_images";i:16;s:54:"field_instance.commerce_product-product-

Attempt #2

Same as above
Generated the file & saved it directly to the server under "Advanced Options"
On refresh, received same error msg as above.

I watched an Acquia tutorial on Features that seemed to show the creation of "Features" as something very straightforward, but I can't seem to get through the process.

It looks like I have a string length issue. Where do I set the max length of a column input? (System >> Info).

Any tips? Any tutorials or videos that you recommend?

Great news! Kind of.

After looking at the database more (using the Database Admin module), I found that the "info" column is a BLOB. A BLOB has a max char length of 65,000.

Given the number of changes I made to the default settings, my Feature Override complete set of Feature Overrides well exceeded the 65,000 characters allotted. I opted to split the Feature Overrides into individual packets, grouped by type (variable / facetapi / user). This appears to have done the job. Fairly straightforward after better understanding the db setup and limitations there.

In terms of avoiding extensive overrides, I suspect that I created this snag by starting out with the demo store implemented in Commerce Kickstart. That option seemed like a good plan for me at the time because it provided some basic features already setup. I adapted those for what I need, but it may not be a particularly good foundation from which to grow the site. Any feedback there?


Registration form to be submitted via ajax I want to submit drupal'S registration form to be submitted via ajax .How can I acomplish this???

You need the Ajax submit for any form module, here:

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


How to alter views exposed form and add ajax to filters I have a views with 2 exposed filters - both taxonomy reference, select.
I want to limit options in second filter based on user selection from the first. Tested with enabled/disabled ajax in views - no difference. Tested with exposed form in block - no difference.

Error message replace target filter: "An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (60 MB) that this server supports."

Using standard form alteration and ajax in form exposed filters, the filtering produce error. This work fine in custom form, but not in views exposed filter.

<?php

use Drupal\Core\Form\FormStateInterface;

function mymodule_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  if ($form_id == 'views_exposed_form') {
    if ($form['#id'] == 'views-exposed-form-articles-page-1') {
      //kint($form);
      //kint($form_state);
      //
      $form['field_tags2_target_id']['#prefix'] = '
';
      $form['field_tags2_target_id']['#suffix'] = '
';

      $form['field_tags_target_id']['#ajax'] = [
        'callback' => 'tags_ajax_callback',
        'wrapper' => 'tags2-replace'
      ];
    }
  }
}

function tags_ajax_callback($form, FormStateInterface $form_state) {
  // remove test2 1 (tid 3) from Tags2 options
  unset($form['field_tags2_target_id']['#options'][3]);

  $response = new AjaxResponse();
  $response->addCommand(new ReplaceCommand(
    '#tags2-replace',
    $form['field_tags2_target_id']
  ));
  return $response;

  //return $form['field_tags2_target_id'];
}

How to make this work?

This patch is related to this issue https://www.drupal.org/files/issues/2019-08-01/2842525-56.patch. See the section core/modules/views/src/ViewExecutable.php especially, the FormBuilder part is already committed but the rest is waiting.


Identify form control id in Drupal 7 Forms API does form controls in Forms API have id's? Below is my sample code:

function myid_user_page_form(){
    $form = array();
    $form['id'] = array(
        '#type' => 'fieldset',
        '#title' => t('ID Information'),
        '#collapsible' => TRUE,
        '#collapsed' => FALSE,
    );
    $form['id']['myphoto_button'] = array(
        '#type' => 'button',
        '#value' => '...',
        '#attributes' => array(
        'onclick' => "myphoto_options();",),
    );
    return $form;
}

Sorry for this very simple beginner's question but how to identify my button's id in the sample above?

You can add id to your form like this,

$form['#attributes'] = array('id' => 'myid');

Also if you want to add class,

$form['#attributes']['class'][] = 'myclass';


Drupal 7 update.php Notice: Array to string conversion in update_results_page() when running custom module update Notice: Array to string conversion in update_results_page() (line 212 of /Users/timdaff/Sites/local-quest-skills-for-life/update.php).

I'm getting the above notice after running update.php on the update function for my module.  It is a simple update to disable some modules I no longer require.  I'm not a PHP guru and it appears to me I have everything correct.

/**
 * Disabling modules. Implements hook_update_N().
 */
function features_controller_update_6009() {
    $return = array();
    $modules = array('views_cache_bully');
    $modules[] = 'gauth';
    $modules[] = 'oauth_common';
    $modules[] = 'oauth2_common';
    module_disable($modules,TRUE);
    $return[] = array('success' => TRUE, 'query' => 'Disabling views_cache_bully, oauth, gauth, gauth_login');
    return $return;
}

Per the docs, the return value should be a string (the message to show to the user after the update) or null.

Currently you're returning an array, hence the notice.


what is the importance of delimter in a feeds module Guys what is the importance of the delimiter in feeds module. cause i only leave it as is. i dont change it so maybe its the one causing the instability of my import process.

By the way im trying to import large files from database which i converted in to chunks of csv files, which i have no luck in accomplishing. So can someone enlighten me the role of delimiters in csv and in feeds module

The delimiter in csv (comma separated values) files is a comma, usually. It may be changed. The delimiter expected by Feeds must match the delimiter used in the csv files, or feeds cannot detect where one value ends and the next begins.


Can we create a core PHP file inside the files folder? As per Drupal's folder structure, custom code is always in sites/modules or in the theme folder. One of my colleagues created a custom PHP file in the files folder. Is this OK or are there any security issues?

Files under that folder are writable by the web server. You could argue that makes it a security risk, but your server would already have to have been compromised in one way or another for it to become so. If your server is configured properly it will only execute PHP files, not serve them for plain-text download.

From the point of view of convention, though, you shouldn't do this. Putting code files all over the file structure makes maintainability infinitely harder.


Security concerns with cache_get() and cache_set() are there any security concerns with Drupal's cache_set() and cache_get() functions?
I mean, I receive some values through an Ajax-GET-request. Can I pass them to the two functions with the following validation?

Javascript:

//token was passed through drupal_add_js() to Drupal.settings.my_module
var url = path + token + '/' + var1 + '/' + var2;
$.get(url);

Page callback:

function my_module_ajax_callback($token, $var1, $var2) {
  if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
      && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
      && is_numeric($var1)
      && drupal_valid_token($token, $var1)) {

    if (is_numeric($var2) && $var2 >= 0 && $var2 < 3600) {
      //can I pass $var1 and $var2 to cache_get() and cache_set() at this point? e.g.:
      cache_set(var1, var2);
      //Are there still security risks?
    }
  }
}

I would welcome every advise.

Thanks!

Daniel

currently there are no known  bugs which would cause any security issue using cache_set and cache_get. You can put any values there
both key and value are escaped.
for example you can try this key '; drop table abr;--'
and it will be saved without any issues


Get non-standard user attributes in layout I want to show the amount of credits the user has. I know the $user object has the following properties:

uid - name - pass - mail - theme - signature - signature_format - created - access - login - status - timezone - language - picture - init - data - sid - ssid - hostname - timestamp - cache - session - roles

But I have also extended user properties like address street, address city, user credits, ... . But how can I print those properties in my layout theme? They are also not in my users table in my database.

First, to access the additional user fields you will need to load the full user object using an available user id with the user_load() function.

global $user; //This contains the basic information for your current user.

$account = user_load($user->uid); //$account now includes all of your custom account fields.

Now that you have the fully loaded user object you will need to choose a template to modify.

Depending on where the values need to be, this could be one of many templates.  I highly recommend checking out the Theme Developer module to help find preprocessing functions and available templates to override.

There is some fantastic information on setting up variables for use in a template here.

Example snip:

<?php
function drop_preprocess_foo(&$variables) {
  // Do not do this unless you mean to:
  $variables['foo_list'] = array('list item 4');
  // Instead do this:
  $variables['foo_list'][] = 'list item 4';
}
?>


Leave Month (Date) Field blank (Optional) I was wondering if it's possible to have Drupal (7), leave the Month field NULL (empty).

When someone sets a Date, sometimes they don't need to enter a Month along with it. When I try this by Default, Drupal says a Month is needed.

Thanks

You can use Number field and do the validation if you just want to store only DD(Day).

Date picker is using to collect Day Month Year


Run Drush command with Gulp I would to know how I can run a drush command like drush @alias cc all with a gulp workflow ?

This is my starting code:

var plugins = require('gulp-load-plugins')();
    gulp.task('drush:cc', function () {

      return gulp.src(source)
        .pipe(plugins.shell([
          'drush @vmdevd6mg cc all'
        ]))
        .pipe(plugins.notify({
          title: "Caches cleared",
          message: "Drush Drupal CSS/JS caches cleared.",
          onLast: true
        }));
    });

Thanks
EDIt: another way to run drush but seem not to work too,no error message given.

// Run drush to clear the theme registry.
gulp.task('drush', plugins.shell.task([
   'drush @vmdevd6mg cc all'
]));

both tasks give:

gulp drush
Error: spawn drush @vmdevd6mg cc all ENOENT

EDIT1: New test

My new task and the result:

//Vidage de cache Drupal avec Drush
gulp.task('drush', function() {
  return gulp.src(basePaths.drushscript, {
      read: false
    })

    .pipe(plugins.shell([
      'drush @vmdevd6pf cron && drush @vmdevd6pf cc all'

    ]))
    .pipe(plugins.notify({
      title: "Vidage de Cache",
      message: "Cache Drupal vidé complètement.",
      onLast: true
    }));
});

Part of the global launch task:

gulp.watch(folderPaths.js.jsd68, ['drush']);

Give:

 /bin/sh: 1: drush: Permission denied

    events.js:160
          throw er; // Unhandled 'error' event
          ^
    Error: Command `drush @vmdevd6pf cron && drush @vmdevd6pf cc all` failed with exit code 127

EDIT: final gulp task work like
//Vidage de cache Drupal avec child_process - 2020-06

gulp.task('drush-cp', function(done) {
  return cp.spawn('drush', ['cache-rebuild'], {stdio: 'inherit'})
  .on('close', done)
   /*  .pipe(plugins.notify({
    title: "Vidage de Cache avec Drush",
    message: "Cache Drupal vidé complètement.",
    onLast: true
  })); */
  ;
});

Try:
The first thing you’ll need is to import the dependency for “child process.” Next, you’ll want to set up an array variable containing all the paths to files you want auto-cache clearing setup for. This will basically be any Drupal template file. I would start with the main template directories you know you need it set up for and then add the additional paths along the way. Once we have our variables set, we then build our “clearcache” task using the “child_process” dependency that is shown below. Once we have all the pieces setup, we combine them in a watch task and let the magic happen! Using this task in your workflow will save you so much time, and even more importantly, save you the headache of clearing your cache every 2 minutes.
If you do run into some issues having your task running, make sure your Drush is setup and working in your command line as these Gulp task relies on Drush to complete its work.
code:

var cp = require('child_process');
var drupal_files = "paths/to/your/drupal/files/you/want/auto-cache-clearing";

// Clearcache Task
gulp.task('clearcache', function(done) {
  return cp.spawn('drush', ['cache-rebuild'], {stdio: 'inherit'})
  .on('close', done);
});

gulp.watch(drupal_files, ['clearcache']);

Source: http://serversideguy.com/2018/02/05/how-can-i-automatically-clear-cache-for-drupal-using-gulp/


Custom Field Type only shows -hidden- Widget I want to create a Field Type with text_textfield as default widget.
But all I get is -hidden-

Here is my FieldType Class

<?php

namespace Drupal\gettweet\Plugin\Field\FieldType;

use Drupal\Component\Utility\Random;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemBase;
use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\DataDefinition;

/**
 * Plugin implementation of the 'get_tweet_field_type' field type.
 *
 * @FieldType(
 *   id = "get_tweet_field_type",
 *   label = @Translation("Get tweet"),
 *   description = @Translation("Reference a tweet token"),
 *   default_widget = "text_textfield",
 *   default_formatter = "text_default"
 * )
 */
class GetTweetFieldType extends FieldItemBase {

  /**
   * {@inheritdoc}
   */
  public static function defaultStorageSettings() {
    return [
      'max_length' => 255,
      'is_ascii' => FALSE,
      'case_sensitive' => FALSE,
    ] + parent::defaultStorageSettings();
  }

  /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    // Prevent early t() calls by using the TranslatableMarkup.
    $properties['value'] = DataDefinition::create('string')
      ->setLabel(new TranslatableMarkup('Text value'))
      ->setSetting('case_sensitive', $field_definition->getSetting('case_sensitive'))
      ->setRequired(TRUE);

    return $properties;
  }

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    $schema = [
      'columns' => [
        'value' => [
          'type' => $field_definition->getSetting('is_ascii') === TRUE ? 'varchar_ascii' : 'varchar',
          'length' => (int) $field_definition->getSetting('max_length'),
          'binary' => $field_definition->getSetting('case_sensitive'),
        ],
      ],
    ];

    return $schema;
  }

  /**
   * {@inheritdoc}
   */
  public function getConstraints() {
    $constraints = parent::getConstraints();

    if ($max_length = $this->getSetting('max_length')) {
      $constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
      $constraints[] = $constraint_manager->create('ComplexData', [
        'value' => [
          'Length' => [
            'max' => $max_length,
            'maxMessage' => t('%name: may not be longer than @max characters.', [
              '%name' => $this->getFieldDefinition()->getLabel(),
              '@max' => $max_length
            ]),
          ],
        ],
      ]);
    }

    return $constraints;
  }

  /**
   * {@inheritdoc}
   */
  public static function generateSampleValue(FieldDefinitionInterface $field_definition) {
    $random = new Random();
    $values['value'] = $random->word(mt_rand(1, $field_definition->getSetting('max_length')));
    return $values;
  }

  /**
   * {@inheritdoc}
   */
  public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
    $elements = [];

    $elements['max_length'] = [
      '#type' => 'number',
      '#title' => t('Maximum length'),
      '#default_value' => $this->getSetting('max_length'),
      '#required' => TRUE,
      '#description' => t('The maximum length of the field in characters.'),
      '#min' => 1,
      '#disabled' => $has_data,
    ];

    return $elements;
  }

  /**
   * {@inheritdoc}
   */
  public function isEmpty() {
    $value = $this->get('value')->getValue();
    return $value === NULL || $value === '';
  }

}

If you are absolutely sure your field type is compatible with some existing widgets and formatters you can reuse them by implementing hook_field_widget_info_alter and hook_field_formatter_info_alter.

/**
 * Implements hook_field_widget_info_alter().
 */
function gettweet_field_widget_info_alter(array &$info) {
  $info['text_textfield']['field_types'][] = 'get_tweet_field_type';
}

/**
 * Implements hook_field_formatter_info_alter().
 */
function gettweet_field_formatter_info_alter(array &$info) {
  $info['text_default']['field_types'][] = 'get_tweet_field_type';
}


Proper debugging of REST Resource due to cache I'm creating some REST routes for my custom resources and I'm having some trouble with the debugging aspect of development.

Every time I change the resource's code, should I need to XDebug it, I need to clear Drupal's cache (drush cr) for the debug to work.

I have successfully disabled the ResourceResponse cache mechanism, so that when the data has changed in Drupal, it is reflected on the response.

Although, I think that maybe due to the annotation mechanism, it's caching the function of my REST Resource, and, subsequently, when I change it, those changes don't propagate and Xdebug doesn't pick them up.

I also noticed that git signals that the resource plugin file has changed every time I clear the cache, which I think might be related.

Does anyone have some pointers they can share to overcome this?

As per @4k4 's suggestion, I'll try to put into and answer what he helped me figure out (though some details are still a bit murky).

When developing in a local environment, we can override the settings.php file with a settings.local.php file. In this local file, we can setup several settings regarding disabling Drupal's cache functionality.

At the time of writing, the instructions in this link were pretty straightforward and sufficient, but I would like to point out a few aspects that I felt weren't very explicit:

In my specific case, while developing custom REST Resources, both the response and the function of my resource were being cached. This is something I want to work like this in production. Although, for development, caching the function of my REST Resource meant that everytime I changed it, I had to clear the cache to allow for XDebug to see the changes in my Resource file. I overcame this by following the instructions in the Find cache bins section of the above link. Regarding my use case, I think the relevant cache bins should be the discovery and rest.
I think (though not sure), that having these bins not cached results in having to clear the cache if you add new discoverable code to your installation, ie, modules, REST resources, maybe themes. As these operations aren't as frequent in my case as the debugging procedure, it's a tradeoff I'm willing to make, but YMMV.
If you are using gitto version your code base, be sure to .gitignore the sites/default/settings.local.php file, otherwise it might end up in your production server, making it substantially slower.
I also tried following the procedure using Drupal Console as the link above suggested, but apparently since version 1.0.0-rc12 the drupal site:mode dev command isn't supported because it proved unstable. Maybe that will change soon.


hook_field_formatter_view doesn't get called I'm kind of new to this formatter, widget system, so i hope you can help me out.
I'm trying to add a new widget to field type list_text, so i have added a info hook like this

function market_field_widget_info() {
  return array(
    'product_list' => array(
    'label' => t('Product List'),
    'field types' => array('list_text'),
    'settings' => array('size' => 40),
    'behaviors' => array(
      'multiple values' => FIELD_BEHAVIOR_DEFAULT,
    ),
  ),
);

And to my widget i have added a widget form hook like this

function market_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

  if ($instance['widget']['type'] == 'product_list' && arg(0) == 'node' ) {

  $node = node_load(arg(1));

  $options = array();
  foreach($node->field_products['und'] as $item ) {
    $entity = entity_load('field_collection_item', array($item['value']));
    $options[$item['value']] = $entity[$item['value']]->field_title['und'][0]['value'];
  }

  $element['product'] = array(
    '#type' => 'select',
    '#title' => t('Vare'),
    '#options' => $options,
  );
return $element;
}

And this works great, i get the information into the selector that i want, but when it is posted nothing is displayed, so i added a view to it

function market_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
  $element = array();

  switch ($display['type']) {
    // This formatter simply outputs the field as text and with a color.
    case 'default_list':
      foreach ($items as $delta => $item) {
        $element[$delta]['#markup'] = "TEST";
      }
      break;
  }

  return $element;
}

But still nothing, am i missing something here? I have tried putting in a die, but its like the view hook is never called, hope you can help.

Best regards

In order for hook_field_formatter_view() to be called you also need to implement hook_field_formatter_info, to let the field system know about your custom formatter.

There's a good article called Creating new field formatters in Drupal 7 that has a step by step guide.


How to modify a field value at theme/Views level? My content type has a Link field which stores a website URL (e.g. 'site.com'). I use this field in various views and node templates.

My site is multi-language, and I know how to check the current language using the global $language.

Now I need to modify the link field value depending on the selected language. So output 'site-en.com' if visitor is viewing the site in English, 'site-de.com' if viewing in German etc.

I can't use manual field translation (Entity Translation) because the field values are imported from XML using Feeds, and there are hundreds of values.

So I wonder if there is a hook to programatically modify a field value before it is used by templates and Views module?

Or maybe there is a better way..?

copy /modules/field/theme/field.tpl.php to your theme folder and rename it to field--field-site-link.tpl.php (if field key of your field is field_site_link), edit template, see comment in file for avalable variables, or just override existings


How can I add extra data to a file field? I am using Drupal 7's core module, file.

The file field array looks like this:

[field_game] => Array
    (
        [und] => Array
            (
                [0] => Array
                    (
                        [fid] => 57
                        [display] => 1
                        [description] => the-pyro-guy.swf
                        [uid] => 0
                        [filename] => the-pyro-guy.swf
                        [uri] => public://swf/the-pyro-guy_2.swf
                        [filemime] => application/x-shockwave-flash
                        [filesize] => 5506729
                        [status] => 1
                        [timestamp] => 1346017444
                        [rdf_mapping] => Array
                            (
                            )
                    )
            )
    )

In addition to the above data, I want to store keys containing the game's height and width in this same file field. Can I do this, preferably in code?

You can't by default, but check out the File Entity module.

  This module extends the core file entity, making it a full fledged
  entity, allowing for fields, display formatters, and more.

This allows you to add fields (such as a height/width field) to files in the same way that you add fields any other fieldable entity (nodes, terms etc...).


Commerce Order Total Tax line via EntityMetadataWrapper I need the final tax amount for an order found on the commerce order total. when using dpm and entity metadata wrapper i can't seem to break it out in order to grab the value.

$order = entity_metadata_wrapper('commerce_order', 3);
dpm($order->commerce_order_total->getPropertyInfo());

the most thorough insight on getting access to the tax line and individual subtotals. found via: https://gist.github.com/BBGuy/3e1f624eaee2088d8eee

// order total object
$order_total_obj = $order_wrapper->commerce_order_total->value();
// Order total (cents).
$order_total = $order_total_obj['amount'];
// order currency code
$currency_code = $order_wrapper->commerce_order_total->currency_code->value();
// subtotal without vat
$total_ex_vat = commerce_price_component_total($order_total , 'base_price');
// total tax (in this case vat 20%)
$total_vat = commerce_price_component_total($order_total , 'tax|vat_20');
// subtotal with vat
$sub_total = $total_ex_vat['amount'] + $total_vat['amount'];
// formatted price string with currency sign
$sub_total = commerce_currency_format($sub_total, $currency_code);


load paragraph in graphql i have a content type with "artist" and i have a paragraph type with "album" name. in album i have two field 1. name 2. release date.
i create a field with "field_album" name in "artist" content type that this field reference to paragraph. now i want write a query that show artist name and all albums with name and release date.
I create this query to load artist but i cant load paragraph.

    query{
  nodeQuery(filter: {conditions:[{field:"title",value: ["artistname"], operator: EQUAL}]}){
    count
    entities {
      ...on NodeArtist{
        nid
        title
      }
    }
  }
}

for load paragraph query must like this

query{
  nodeQuery(filter: {conditions:[{field:"title",value: ["artistname"], operator: EQUAL}]}){
    count
    entities {
      ...on NodeArtist{
        nid
        title
        fieldAlbum {
          entity{
            ... on ParagraphAlbum {
              fieldName
              fieldReleaseDate
            }
          }
        }
      }
    }
  }
}

https://github.com/drupal-graphql/graphql/issues/676#issuecomment-423912937


How can I render a field based on the value of another field I set up a boolean field and an image field. I want to display the logo when the page is viewed only when the boolean field is checked.
Below is the code that I am working with in a node template file.

<?php
      // We hide the comments and links now so that we can render them later.
      hide($content['comments']);
      hide($content['links']);
      hide($content['field_boolean']);
      hide($content['field_logo']);
      print render($content);
    ?>
  <?php if ($content['field_boolean']['und'][0]['value'] == '1'): ?>
    <?php print render($content['field_logo']); ?>
  <?php endif; ?>

Try this:

$logo = render($content['field_logo']);
hide($content['field_logo']);
// ...
<?php if ($content['field_boolean']['und'][0]['value'] == '1'): ?>
  <?php print $logo; ?>
<?php endif; ?>

At the moment you're hiding the logo field, which will probably prevent it from being rendered at all, even the second time you call render(). Taking a copy of the rendered logo field and outputting it later should work instead.

You could also do it this way:

<?php if ($content['field_boolean']['und'][0]['value'] == '1'): ?>
  <?php
  show($content['field_logo']);
  print render($content['field_logo']);
  ?>
<?php endif; ?>


using same addressfield for profile2 and commerce module I have a site with two different profiles (with different fields) where one of these are able to buy a product. In this context I want to use the same addressfield for one type in the billing information making automatic filling of a company's address.

I've tried Commerce Customer Profiles module however it seems that I am unable to merge these fields. Does anyone have some suggestions on how to use profile2 information in commerce module?

Profile2 and Commerce Customer Profiles are different entities.

Even if the address field is the same, the data will need to be copied over somehow.

One way to do it would be with

hook_field_attach_load

and load in the relevant address field data there, when the field is loaded.

Keep in mind:

That hook can be passed multiple entities
Ensure the user id for both entities is identical prior to merging the data.

More info on the Field Attach API


Add Custom Line item API or Method Drupal Commerce I have some products in a Drupal Website using Drupal Commerce. Those products are listed via a custom modules to the front end. If the user clicks on any of the products then it goes to the product display page. There I have 2 checkbox and the Add to Cart Button. Such as

Gift Packaging ($10.99)
Custom Messages ($4.99)
These are 2 checkboxes coming from a drupal form created on my custom module.
I want to add these as line items to the Selected Product. Such as,

If user choses Product A and Gift Packaging then,
Product A ($10.00)
Gift Packaging ($10.99)
Total : $20.99

So how can I add the chosen line item to that product once the user clicks on the Add to Cart Button. I have a function that is fired once the button is clicked. The function is "my_module_add_to_cart()".
How can I show the updated Price as $20.99 to the /cart page table?

Why not use Commerce Product Options which provides this functionality out of the box, directly in the default Add to Cart form?

To adjust the price based on the chosen options, you can use the Commerce Pricing module, which comes as part of the Commerce project. It basically provides a number of rules conditions and actions which allow you to adjust the price of a line item and e.g. add a fixed amount or multiply it by a certain value.


What is the template name for www.mysite.com/user/login I have literally tried every combination possible, what am I missing?

page--user--login.tpl.php
page--user.tpl.php
page--login.tpl.php
user--login.tpl.php
page-user-login.tpl.php

page--user--login.tpl.php   ... if you create one, make sure you flush your cache!

Also, check out this module:
https://drupal.org/project/devel_themer

It'll help you determine these sorts of things, just don't leave it running after you're done development!


Views switches to another view on apply or any change When I'm working on a block display in Views on Drupal 7, and hit the "Apply" button, I'm taken to the master (or first view), instead of staying on the block display that I'm working on.

How do I fix this behaviour and remain on the correct display when applying settings?

I finally tracked it down to a setting in Views (where it shows all of the views) and the Settings tab. Under the Advanced Option here, I was able to turn off a "Disable Javascript on Views" setting that had somehow gotten turned on. The Ajax function was not firing and the main URL was resetting for every update of any kind. This meant jumping between views for every change of any field whatsoever.

That setting fixed everything though, so I'm posting in case anyone else has the issue and can't find a reason.


Why would enabling a new module result in the majority of modules disabling? On my Drupal Commerce site, I was attempting to add a Commerce Discount-related module that would allow me to specify a discount based on taxonomy term/product category. When I enabled the module however, my site showed that my enabled module count dropped by ~50 modules. Yikes! This included key features of the site, including payment methods (Paypal, FirstData), as well as XML sitemap-related modules. I also received some exception errors related to existing Rules on the site that were related to shipping rules.

I was able to revive through a backup, but had never seen this type of response before. Any ideas?

It appears you're being affected by a known issue that has been resolved in Drupal 8 but still needs to be back ported to Drupal 7. The PHP extension Suhosin causes modules with parentheses in the package name to be disabled. You can edit your Suhosin configuration to remove parentheses from the array index blacklist or, if you're unable to do that in a pinch, you can edit the relevant module files to remove the parentheses from their package names.

More info in the core issue: https://www.drupal.org/node/2665152


Hierarchical Select Doesn't allow multiple vocabularies in drupal7 Hierarchical Select I have taxonomy vocabularies:

For example

Products, systems and Support

Each vocabulary has 2 terms:

Products -> product1, product2

systems -> systems 1, systems 2

Support -> support1, support2

I am using Hierarchical Select as a field to select this vocabularies.

But with Hierarchical Select ,it is defaulting to only one vocabulary.

Please let me know how to select terms from multiple vocabularies while creating nodes and alternate to Hierarchical Select.

You can't I'm afraid; it's actually a limitation of the taxonomy term field type, not of Hierarchical Select.

You can only ever choose one vocabulary per term reference field, regardless of the widget you're using. For example, this is what the field settings page looks like when adding a bog standard term ref field on a Drupal install that doesn't even have HS installed:

As you can see you only have the option to choose one vocabulary.


Multilingual comments form missing I have a website in 2 languages. The site uses panels. The nodes Comments form & comments only shows in English and not in Greek.

Has anyone encountered a similar problem? Thnx in advance.

The i18n comments can be used for this.  From the project page:

  A very simple module which would allow you to show all/any comments
  attached to all node translations. Just a great way to communicate in
  truly multi-lingual environments.

  For example I have node in English and Spanish. Drupal natural way
  would be to show comments for en/es translation separately (attached
  to en/es content). But i18n_comments will aggregate all English and
  Spanish comments for any translations. It doesn't matter if user will
  leave a comment to any node translation.


Some links are still visible after logging out in drupal8 The question is clear from the title itself , after logging out i can see some view links , one on the side navigation menu and two on the main navigation . I checked the view permission , but its same as the other view which are not visible . Any idea ??

I would suggest, you check the permission at two places

(1) Views permission, which you can find at views UI, under page setting, so from there you can apply the Role restriction.

(2) Permission of Entire that Navigation block under blocks layout, Which allows the display of entire block.


How to add variables in *.libraries.yml in drupal 8 I need to convert the below code added in hook_page_attachments()
 and
 add the external js in *.libraries.yml but not sure how to add variables like
$token and $user->mail in the *.libraries.yml so I can just attach library

   drupal_add_js('http://js.acobot.com/' . check_plain($token) . '.js', 'external');
    $script = 'var _aco = _aco || [];';
    drupal_add_js($script, array('type' => 'inline', 'scope' => 'footer'));
    if ($user->uid) {
      $user_info = "_aco.push(['email', '" . check_plain($user->mail) . "']);";
      drupal_add_js($user_info, array('type' => 'inline', 'scope' => 'footer'));
    }

Add Your Script to a file
In *.libraries.yml, I have added

acobot-initialise:
  version: 1.x
  js:
    js/acobot.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

Added that file to the library under

  $attachments['#attached']['library'][] =
  'acobot/acobot-initialise';

Use drupalSettings to pass data from php to js

  $attachments['#attached']['drupalSettings']['acobot']['email'] = check_plain($account->getEmail());

Added script acobot.js as follows

  (function ($, Drupal, drupalSettings) {

  'use strict';

  Drupal.behaviors.acobot = {
      attach: function (context, settings) {
            var _aco = _aco || [];
            _aco.push(['email', drupalSettings.acobot.email]);
      }   };

  })(jQuery, Drupal, drupalSettings);

First add your acobot script inline:

function mymodule_page_attachments(array &$attachments) {
  $attachments['#attached']['html_head'][] = [
    // The data.
    [
      '#type' => 'html_tag',
      // The HTML tag to add, in this case a  tag.
      '#tag' => 'script',
      // The value of the HTML tag, here we want to end up with
      // alert("Hello world!");.
      '#value' => 'alert("Hello world!");',
      // Set attributes like src to load a file.
      '#attributes' => array('src' => 'http://js.acobot.com/' . check_plain($token) . '.js'),

    ],
    // A key, to make it possible to recognize this HTML  element when altering.
    'hello-world',
  ];
}

next add your library with *.js file where you can call push method

cuddly-slider:
  version: 1.x
  js:
    js/cuddly-slider.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings

and pass user mail to  drupalSettings.

$build['#attached']['drupalSettings']['fluffiness']['cuddlySlider']['foo'] = 'user mail here';

All examples are available here https://www.drupal.org/docs/8/creating-custom-modules/adding-stylesheets-css-and-javascript-js-to-a-drupal-8-module


Show entity reference content with a field other than the title I want to add a field to a custom content type that allows users to select other content from the site to display as a list on the given node.

I can do this by creating an entity reference field to content type. This works, but I can only seem to have it show the link in reference to the Title field of the corresponding node. I want to set a different field as the link. How do I do this?

If I could show the fields in a view, I could select the field to show more easily, however, I have not found a way to have a view show the contents of a field from the current page.

Originally, I had implemented this via a system of taxonomy terms and a view but my users want the ability to go in and manually set the relationships so I have had to fall back to this. If someone has a better suggestion for this problem I would love to hear it.

I've done this before:

You can override the Autocomplete field widget, so instead of title, it will give you back something else! You need to inheritance the existing one and after 2-3 of other inheritance you will be able to reach the autocomplete ajax functionality and rewrite it. It's pretty complex, but not impossible!


Search form escaping characters and spaces? Drupal 7.

I'm thinking it must be in the htaccess file, as I just went live, and suddenly if I search for something like "two words" it ends up searching for "two%20words" and obviously I get no results.

Same goes for quotes, etc.  Any ideas?

That wasn't entirely it - it was escaping with a %25 and passing it to the search form, causing no results.  It was an issue with my htaccess, it's fixed.


Invalid CSRF token using flag.link_builder service (Flag module) I have a REST route that returns a list of user accounts. I have a flag setup called 'following' as you can follow and unfollow other members. In my REST route, I use:

$flag_link = \Drupal::service('flag.link_builder')->build('user', $member->id(), 'following');

which generates the link correctly as far as I can tell. In my javascript object I can see the link that was created. This is an example of the JS object of a user that I use on the front end:

0:
  flag_link:
    #access: true
    #action: "flag"
    #attached: {placeholders: {…}, library: Array(1)}
    #attributes: {title: "", href: "/flag/unflag/following/3?destination&token=LEfyLe9PPaQfgNNRSXUA82k4SVHQGRmBEI0adgBva9g", class: Array(1)}
    #cache: {contexts: Array(1), tags: Array(0), max-age: -1}
    #flag: {id: "following", label: "Following"}
    #flaggable: {}
    #theme: "flag"
    #title: {#markup: "Follow this person"}
  id: "3"
  name: "ronnie"
  url: "/user/3"

When I go to click the link it 403 forbiddens with the message message: "'csrf_token' URL query argument is invalid."

The HTML I am outputting is:

  Unfollow this person

Any idea what I am doing wrong?

Here is a screen shot of my request when I click the anchor

I created an example. You can check it and find the solution there.
https://github.com/Mykola-Veryha/ajax-flag-link


Dynamic route's controller method not firing I'm trying to use the Background Image module, but there seems to be a problem with the dynamic route it registers for generating CSS. I've been debugging it, but I have run into a wall. It's basically a duplicate of the core Image module's routing setup, so I'm not sure what's wrong, but the controller method never fires; the controller isn't even instantiated. Here's the config file:

route_callbacks:
  - '\Drupal\background_image\Routing\BackgroundImageRoutes::routes'

Here's the routes method:

  public function routes() {
    error_log('Router::routes');
    $routes = [];
    // Generate background image CSS files. If clean URLs are disabled the
    // files will always be served through the menu system. If clean URLs are
    // enabled and the file already exists, PHP will be bypassed.
    $directory_path = $this->streamWrapperManager->getViaScheme('public')->getDirectoryPath();

    $routes['background_image.css'] = new Route(
      '/' . $directory_path . '/background_image/css/{background_image}/{scheme}/{file}',
      [
        '_controller' => '\Drupal\background_image\Controller\BackgroundImageCssController::deliver',
      ],
      [
        '_access' => 'TRUE',
      ]
    );
    error_log(print_r($routes, true));
    return $routes;
  }

Here's the $routes object:

Array
(
    [background_image.css] => Symfony\Component\Routing\Route Object
        (
            [path:Symfony\Component\Routing\Route:private] => /sites/default/files/background_image/css/{background_image}/{scheme}/{file}
            [host:Symfony\Component\Routing\Route:private] =>
            [schemes:Symfony\Component\Routing\Route:private] => Array
                (
                )
            [methods:Symfony\Component\Routing\Route:private] => Array
                (
                )
            [defaults:Symfony\Component\Routing\Route:private] => Array
                (
                    [_controller] => \Drupal\background_image\Controller\BackgroundImageCssController::deliver
                )
            [requirements:Symfony\Component\Routing\Route:private] => Array
                (
                    [_access] => TRUE
                )
            [options:Symfony\Component\Routing\Route:private] => Array
                (
                    [compiler_class] => Symfony\Component\Routing\RouteCompiler
                )
            [compiled:Symfony\Component\Routing\Route:private] =>
            [condition:Symfony\Component\Routing\Route:private] =>
        )
)

If I try to hit a URL such as /sites/default/files/background_image/css/3/public/dq5DbF1hqHxkHXGiHSl9yuXubPox08bOX6nE12gX2h0.css?p2aptq (which the module correctly generates when I've got a background image set up on the site) I get a 404 error and nothing in the error log.

I'm using docker4drupal and have checked the nginx config and am 99% sure that's not the issue (there are no rules for /sites/default/files/ and I do see the 404 in the nginx log.)

Why doesn't the dynamic route work as it should, and as it doesn't for the Image module?

Well, I'm an idiot. The problem was nginx after all. There actually was a block to handle CSS/JS assets that was preventing the dynamic route from executing because of a lack of physical files. I had to place the following above that rule:

location ~ ^/sites/.*/files/background_image/ {
    try_files $uri @drupal;
}

Here's the offending rule:

location ~* ^.+\.(?:css|cur|js|jpe?g|gif|htc|ico|png|xml|otf|ttf|eot|woff|woff2|svg|svgz)$ {
    expires 30d;
    tcp_nodelay off;
    open_file_cache off;
    open_file_cache_valid 45s;
    open_file_cache_min_uses 2;
    open_file_cache_errors off;

    location ~* ^.+\.svgz$ {
        gzip off;
        add_header Content-Encoding gzip;
    }
}

I found the solution after searching for relevant issues on other modules that generate dynamic files, such as imagecache, which led me to the official nginx Drupal guide. Definitely a learning exercise.


Unable to uninstall the Field Collection module I want to remove field collection module in Drupal 8 as the module has been deprecated. When I try to uninstall after removing the fields from content type the option to uninstall is greyed out.

I get an error

  field_collection: There is content for the entity type: Field
  Collection Item. Remove
  field collection item entities.

I guess you solved this already, but if somebody else stumbels over this, here my 5 cent on how to get rid of field collection. I encountered the same issue as @nitnac23 and was only able to get it out via direct data base manipulation:

definitely make a DB backup this time (might save your website)
Remove all field collection fields from your entities
run the cron potentially multiple times (this cleanes up the entities - fingers_crossed)
it is important, that you no longer have fields pending deletion as a reason for not beeing able to dissable fields collection (under /admin/modules/uninstall/) - if you still have it, try running the cron again (more infos here)
clear the contents of the database tables field_collection_item and field_collection_item_revision directly in the database
uninstall field collections now via /admin/modules/uninstall/
if you have still field_deleted_* tables in your DB, drop them (I had 12 before runing the cron and still 2 after unsintsalling the module)

That should do it hopefully :)


How can I log the flags users put, then auto unflag them? I used this link to set up a UserPoints Store:

Drupal 7 - How to Set up a Simple UserPoints Store.

I need help finishing one thing:

When user flags item
some code starts working and logs the fact that this specific user just flagged this specific page(content)
Once this information is logged somewhere.
the page(content) that the user see's as [Already Flagged] needs to automatically unflag.
So that user can flag it again if he/she wishes.

If you look in the link above it can be understood that flagging a item(page/content) deducts points from the UserPoints system. As soon as the user presses flag this they get the option to type in the quantity they would like to "purchase" or flag. I need this quantity logged too.

In short, this is an example of how it should log:

User | Time/Date | Quantity |  Page
-----+-----------+----------+--------
id2  | 8/18/2016 |     3    | /node/9
id7  | 2/13/2016 |     1    | /node/5
id4  | 4/28/2016 |     1    | /node/1

I hope it makes sense. It would make more sense if you take a look at the info in the link.

The Log

Userpoints transactions are automatically "logged" in that Views can display them with all required data. So if I understand the question correctly, flags is irrelevant here in terms of logging as you just want the userpoints transactions.

Create a "userpoints transactions" view.. Not "content" or "user".

Add a relationship for Userpoints Transactions: User
Add fields for
(Users) User: Uid (Uid),
Userpoints Transactions: Timestamp (Timestamp),
Userpoints Transactions: Points (Points) and
Userpoints Transactions: Entity ID (Entity ID) (according to your link, this should be the node id)
If you have more than one category of userpoints, you can add a filter for Userpoints Transactions: Category

Automatic Unflag

It sounds like in your link, Business Rule 2: Unflag an item is unneeded in your case? I'd just change this to a rule where the the flag is unflagged and then redirect to the node / page if needed. I'm not really sure what the requirements are here.


How do I check radio buttons in Twig template? In a form, I have this field:

$form['payment'] = [
  '#type' => 'radios',
  '#title' => $this->t('Payment Mode'),
  '#options' => [
    'chk' => $this->t('by check'),
    'tfr' => $this->t('by bank transfer'),
    'crd' => $this->t('by card'),
  ],
  '#required' => TRUE,
];

In the Twig template associated to the form, I'd like to show the field and some html stuff depending on the selected option. I tried this:

<form{{ attributes }}> {{ form.form_build_id }} {{ form.form_token }} {{ form.form_id }}
  <div>
    {{ form.payment }}
    {% if form.payment ==  'chk' %}
      You chose 'Check'
    {% elseif form.payment ==  'tfr' %}
      You chose 'Bank Transfer'
    {% elseif form.payment ==  'crd' %}
      You chose 'Card'
    {% endif %}
  </div>

But it is nor working!
Any idea?

That's a task for #states not for Twig. I think this also could be ajaxified a little bit more elegantly but using #states on some items does the job as well.

$form['payment'] = [
  '#type' => 'radios',
  '#title' => $this->t('Payment Mode'),
  '#options' => [
    'chk' => $this->t('by check'),
    'tfr' => $this->t('by bank transfer'),
    'crd' => $this->t('by card'),
  ],
  '#required' => TRUE,
];

$form['chk'] = [
  '#type' => 'item',
  '#markup' => $this->t("You chose 'Check'"),
  '#states' => [
    'visible' => [
      ':input[name="payment"]' => ['value' => 'chk'],
    ],
  ],
];

$form['tfr'] = [
  '#type' => 'item',
  '#markup' => $this->t("You chose 'Bank Transfer'"),
  '#states' => [
    'visible' => [
      ':input[name="payment"]' => ['value' => 'tfr'],
    ],
  ],
];

$form['crd'] = [
  '#type' => 'item',
  '#markup' => $this->t("You chose 'Card'"),
  '#states' => [
    'visible' => [
      ':input[name="payment"]' => ['value' => 'crd'],
    ],
  ],
];


Drupal 7: LDAP: How to fetch user information on a webform 0 down vote favorite

I have a drupal 7 webform and I want to pull the user information of the logged in user using LDAP. This information is stored on another form of my site. and so when a user opens the current form, I want to display something like this -

Hello, USER_NAME, your current status is STATUS and so on...

USER_NAME and STATUS and many other fields are stored on another form so how can I pull this using LDAP? I have already installed LDAP on my website. I searched a lot on web but could not find a working example.

Can someone help me here pls?

Figure out the raw ldap queries you need. Outside of php or drupal.
Write them down.
Use ldap views module to make reusable drupal ldap queries. ldap views can use tokens and I think parameters in queries ... parameterize as needed.

Then wherever you want your custom message embed the view results onto the page using Context, Panels, hook_page_build .... whatever.


Ordering Table by column I try to add the possibility to order by column in the header of my table element.

I started to use Drupal 8 and I can't find any clear documentation about table on the API site to do what i want...

Thanks in advance.

You have to do this while defining the header array like

$header = array(
     array(
       'data'  => t('Url'),
       'field' => 'd.path',
       'sort'  => 'asc',
     ),
     array(
       'data'  => t('Text'),
       'field' => 'd.text',
     ),
    );

So, this table will have two columns, Url & Text. And it will be sorted in ascending order by column Url.


How to know "keys" for Entity::create() The document says Entity::create() takes

  "$values (optional) An array of values to set, keyed by property name"

as an arguement.

I also found snippets like

$term = Term::create([
    'name' => $term_name,
    'vid' => $vocabulary_name,
  ]);

and they worked.

But how exactly do you know what kind of values can be set in the array?
In the case above, where did people take the keys 'name' and 'vid' from?

If you look at the of baseFieldDefinitions method in class Term:

Here is a list of fields you can set in create Term:

tid : Term ID
uuid : The term UUID.
vid: The vocabulary to which the term is assigned.
langcode : The term language code.
name : Name of term.
description : description of term
weight : weight of term.
parent : Term parent.

Example:

$term = Term::create([
    'name' => 'term name',
    'vid' => 'tags',
    'status' => 1,
    'tid' => 13,
    'uuid' => 1,
    'langcode' => 'en',
    'description' => 'tags description',
    'weight' => -12,
    //'parent' => parent tid
  ]);
  $term->save();