array value within Rule's PHP action always gives 0 instead of related uid I want to fetch the latest Ubercart order's associated uid and if it is NOT the same as the newest user's ID then my Rule should validate and send an email to a selected address.

In the Rule I created, I've written the following PHP action in order to first check what $uids[0] is giving me. When this works as require, I'll put the same code as a PHP condition, replacing the watchdogs with return FALSE & TRUE.

The problem I'm facing is that $uids[0] always gives 0 instead of the last order's user ID.

$query = db_query("SELECT uid, created FROM {uc_orders} order by created desc");
$uids = array();
while ($records = db_fetch_array($query)) {
    $uids[] = $records['uid'];
}
$latestaccountuid = $account->uid;
$latestorderuid = $uids[0];

$message = "Latest account id:".$latestaccountuid." .Latest order uid:".$latestorderuid;

if ($latestaccountuid == $latestorderuid) {
watchdog('FALSE', $message);
//return FALSE;
}
else {
watchdog('TRUE', $message);
//return TRUE;
}

I think the problem is with your $account variable. I don't see where it's instanciated in your code. It's probably related to the current logged in user, so you've to find a way to access this information from Rules. Try to use dsm($account); if you're using the devel module and check if the variable is empty.


Commerce Product is not visible for anonymous user in search result I am using apachesolr, apachesolr_commerce, apachesolr_autocomplete for search functionality in drupal 7.
Commerce Product is not visible for anonymous user in search result but when loggedin Commerce Product results are including into search results.
Any suggestions?

Got solutions to Disable Apache Solr Access module and than search works fine for other users as well.
Thank you.


How can I recover from a backup but include many changes from a dynamic site? After the Drupageddon disaster, I've discovered that my backup plan is not sufficient. I have daily, weekly, monthly and yearly DB and file backups thanks to backup_migrate and backup_migrate_prune, but my site is a dynamic one with many users making posts daily. So I was able to easily find a DB backup from pre-Oct 15th to restore to, but I had no easy way to incorporate the thousands of legitimate changes that had occurred on the site since then.

I recognize that it's probably too late for this time, but I'm thinking about how to make sure I'm not screwed in the future. Is there any good method to accomplish this sort of thing? A module that logs all database transactions so they can be individually inspected and reapplied if they're deemed legitimate? Or anything at all better than either loosing weeks of user data or doing a manual diff of the current and known-good databases and praying that I didn't miss something?

A module that logs all database transactions so they can be individually inspected and reapplied if they're deemed legitimate?

Where it would log to? Database? Impossible, it would kill your server. Filesystem? It's slow. And it's big. Another thing worth noting is that if you would want to manually approve / disapprove each query, you can either:

Inspect them carefully, and you already told us there is a lot of them, so it could take you up to hours per one edit, if your content types are complicated enough - not nice on dynamic site.
Inspect them fast, probably making your data inconsistent.

Last but not least, if you will add that as a module, anyone with proper permissions will be able to disable that module, making your efforts void.

Modules that should be able to help some are:

Drupal Tiny-IDS
PHPIDS

Sadly, as far as I understand, neither would help in this particular case.

What I would do is:

Hourly backup. If possible, done as a snapshot of virtual machine, because that's fast and unobtrusive.
Mail about each new user, new role assignment, and password change. Sadly, if no one monitors that mail, no one can help.


How reset $form_state on ajax call for get real value in submit? I have see some post about that,but i still have no real answer.

In my form, user can select a register address in a select field.
When he select an address, the ajax set value on some other fields :

  The code :

  if($form_state->getTriggeringElement()['#name']=="mes_adresses")
  {
      $listAdresse = $this->adresse_service->getUserAdresseById($form_state->getValue('mes_adresses'));

  }

  $form['containerGeneral']['livraison']['adresseComplete']['nom_livraison'] = array(
      '#title' => 'Nom de livraison',
      '#type' => 'textfield',
      '#value' => $listAdresse['nom'],
  );

  $form['containerGeneral']['livraison']['adresseComplete']['prenom_livraison'] = array(
      '#title' => 'Prénom de livraison',
      '#type' => 'textfield',
      '#value' => $listAdresse['prenom'],
  );

  $form['containerGeneral']['livraison']['adresseComplete']['pays_livraison'] = array(
      '#title' => 'Pays de livraison',
      '#type' => 'select',
      '#required'=>true,
      '#options'=>$this->taxonomy_service->getTermsByVid('pays_livraison'),
      '#value' => $listAdresse['pays'],
  );

  $form['containerGeneral']['livraison']['adresseComplete']['adresse_livraison'] = array(
      '#title' => 'Adresse de livraison',
      '#type' => 'textfield',
      '#value' =>  $listAdresse['adresse'],
  );

  $form['containerGeneral']['livraison']['adresseComplete']['adresse2_livraison'] = array(
      '#title' => 'Adresse de livraison',
      '#type' => 'textfield',
      '#value' =>$listAdresse['adresse2'],
  );

  $form['containerGeneral']['livraison']['adresseComplete']['cp_livraison'] = array(
      '#title' => 'Code postal de livraison',
      '#maxlength'=>5,
      '#type' => 'textfield',
      '#value' => $listAdresse['code_postal'],
  );

  $form['containerGeneral']['livraison']['adresseComplete']['ville_livraison'] = array(
      '#title' => 'Ville de livraison',
      '#type' => 'textfield',
      '#value' =>$listAdresse['ville'],
  );

  And the callback :

public function ajaxChangeAdresseCallback(array &$form, FormStateInterface $form_state)
{

    $form_state->setRebuild(TRUE);
    return  $form['containerGeneral']['livraison']['adresseComplete'];

}

So there are 2 things :

  #value

If you set value like that, user can never change the value because

$form_state->getValue()

ll keep the value set by the ajax.

  #default_value

If you set the value like that, that doesn't work because the #default_value parameter if use just the first time the form is loaded.

  The main problem is with $form_state.

If you kint when you submit your form $form_state->getValue() and $_POST, $_POST is good but not the $form_state.

But the issue are in the validate function too, if user select the option new address, ajax reload the form, set empty everywhere, and when you submit, the validate function ll tell you you have empty value.

I know on D7 some people unset the $form_state['values];

But on D8 ?

So how reset the $form_state value ?

Thank to @4k4 for the solution posted here :

How do I change the default value of a field with AJAX?

For my problem, this is how i add this feature :

$form['containerGeneral']['livraison']['adresseComplete'] = array(
          '#type' => 'container',
          '#prefix'=>'
',
          '#suffix'=>'
'
      );

      $form['containerGeneral']['livraison']['adresseComplete']['nom_livraison']['#tree']=true;
      $form['containerGeneral']['livraison']['adresseComplete']['prenom_livraison']['#tree']=true;
      $form['containerGeneral']['livraison']['adresseComplete']['pays_livraison']['#tree']=true;
      $form['containerGeneral']['livraison']['adresseComplete']['adresse_livraison']['#tree']=true;
      $form['containerGeneral']['livraison']['adresseComplete']['adresse2_livraison']['#tree']=true;
      $form['containerGeneral']['livraison']['adresseComplete']['cp_livraison']['#tree']=true;
      $form['containerGeneral']['livraison']['adresseComplete']['ville_livraison']['#tree']=true;

      if($form_state->getTriggeringElement()['#name']=="mes_adresses")
      {

          $_SESSION['compteur']++;

          $listAdresse = $this->adresse_service->getUserAdresseById($form_state->getValue('mes_adresses'));

          $key = $_SESSION['compteur'];

      }

      $form['containerGeneral']['livraison']['adresseComplete']['nom_livraison'][$key] = array(
          '#title' => 'Nom de livraison',
          '#type' => 'textfield',
          '#required'=>true,
          '#placeholder' => 'Nom',
          '#default_value' => $listAdresse['nom'],
      );

      $form['containerGeneral']['livraison']['adresseComplete']['prenom_livraison'][$key] = array(
          '#title' => 'Prénom de livraison',
          '#type' => 'textfield',
          '#required'=>true,
          '#default_value' => $listAdresse['prenom'],
      );

      $form['containerGeneral']['livraison']['adresseComplete']['pays_livraison'][$key] = array(
          '#title' => 'Pays de livraison',
          '#type' => 'select',
          '#options'=>$this->taxonomy_service->getTermsByVid('pays_livraison'),
          '#default_value' =>  $listAdresse['pays_livraison'],
      );

      $form['containerGeneral']['livraison']['adresseComplete']['adresse_livraison'][$key] = array(
          '#title' => 'Adresse de livraison',
          '#type' => 'textfield',
          '#required'=>true,
          '#placeholder' => 'Adresse de livraison',
          '#default_value' =>  $listAdresse['adresse'],
      );

      $form['containerGeneral']['livraison']['adresseComplete']['adresse2_livraison'][$key] = array(
          '#title' => 'Adresse de livraison',
          '#type' => 'textfield',
          '#default_value' =>$listAdresse['adresse2'],
      );

      $form['containerGeneral']['livraison']['adresseComplete']['cp_livraison'][$key] = array(
          '#title' => 'Code postal de livraison',
          '#maxlength'=>5,
          '#type' => 'textfield',
          '#placeholder' => 'Code postal de livraison',
          '#default_value' => $listAdresse['code_postal'],

      );

      $form['containerGeneral']['livraison']['adresseComplete']['ville_livraison'][$key] = array(
          '#title' => 'Ville de livraison',
          '#type' => 'textfield',
          '#placeholder' => 'Ville de livraison',
          '#default_value' =>$listAdresse['ville'],
      );

Don't forget to set $_SESSION['compteur'] to 0 on submit and to set it to 0 on form load.


Turning a query string into an array after using parse_url Okay, I am afraid this might be a 'duh!' question, but I am just having one of those days!   Well, the problem is, I am getting the following error every time I have a query string in my url (https://www.google.com/?q=hello):

Recoverable fatal error: Argument 1 passed to drupal_http_build_query() must be an array, string given

I am modifying a custom module that someone else wrote and this is the code that is problematic.

$pieces = parse_url($href);
$pieces['html'] = TRUE;
$pieces['path'] = isset($pieces['path']) ? $pieces['path'] : '';
if (isset($pieces['scheme'])) {
  $pieces['path'] = $pieces['scheme'] . '://' . $pieces['host'] . $pieces['path'];
}

return l($image, $pieces['path'], $pieces);

This is what $pieces looks like:

scheme (String, 5 characters ) https
host (String, 13 characters ) www.google.com
path (String, 22 characters ) https://www.google.com/
query (String, 6 characters ) q=hello
html (Boolean) TRUE

Obviously, the problem is due to $query not being an array.  I am wondering how best to rewrite the above code so that I can properly call the l() function with the query string and any other attributes that a user might put in there.  Any and all help would be greatly appreciated.  Thanks.

You need to use an associative array, e.g.

$pieces['query'] = array('q' => 'hello');

The arguments for l() are in no way related to, or compatible with, the return from parse_url(). To avoid confusion it'd be better to build up a separate options array to pass as the 3rd argument to l().


Delete content in a user registration field after X number of days I am looking for a way to delete the data in a custom registration field (field:transaction_code) after 30 days. How can this be achieved?

Let me explain better. I want users to get the registration code from me. When they have that registration code, their accounts will be valid for 30 days. Once those 30 days are over, the user will then be required to enter a new transaction code. Thus they will need to revisit the registration page

Are you sure this is the right way to proceed?
I think it would be better if you use a custom field with 2 properties: the registration code and a timestamp which holds the time until the value is valid.

And every time when you want to use the value, you check the timestamp. Also with this version you could easily set up a cron or advancedqueue job to delete old values.


Composer: Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring When i remove drupal/pathauto or another module contrib composer print:
Dependency "drupal/core" is also a root requirement, but is not explicitly whitelisted. Ignoring.

Why ?

Composer remove removes the selected package and its dependancies. However there are, some dependencies like drupal/core that shouldn't be removed. For example, if we try to remove drupal/pathauto this message would pop up, as Drupal/pathauto depends on drupal/path core module, and should/can not remove anything from core or any dependencies shared with other packages. You can see in pathauto.info.yml file what it depends on.


Apply only database updates for a single module update.php and drush up --no-core both list several database updates pending across several modules. I'm being asked to only apply the database updates for a few specific modules because it is desired to do just these modules and test things in relation to that before running any of the other updates.

drush seems to only give me the option to apply all of the pending updates as does the update.php script. Is there a way to apply only the pending database updates for a particular module when there are pending updates for multiple?

Drush allows you to just update a module you specify:

drush up module_machine_name

If you just want to apply pending database updates, for the modules that have already been updated:

drush updatedb

This case is relevant when updating the code base through git, or for multisite installations.
In your specific case, this might be what you were looking for - just apply database updates (using this command: for all modules that require database updates), but don't update any additional codebase.

If you want to just apply the updates for a certain module, you can do this also manually. The updates can be found in the module.install file:

function modulename_update_prioritynumber
(e.g. devel_update_7000)

The priority number determines the order of the updates to be applied.
You can manually execute the code for the updates using drush:

drush eval "the update code"

for example:

drush eval "variable_del('dev_query');
drush @yoursite eval "variable_del('dev_query');

(@yoursite added if bootstrapping is needed for multisite installations)

This example will delete the variable dev_query from the variable database table (from the function devel_update_7002).

For more discussion on this, see: drush updatedb for a single module - especially the answer from moshe weitzman, the drush maintainer, about applying individual updates. I'd recommend applying the updates of the module you are concerned about over uncommenting the updatedb statements in other modules - as the other answer suggests.


Can Drush be assigned as a ssh users default shell? Problem:
I need to allow ssh access to my web server to dev team in order to use Drush. I am reluctant to give them full SSH access due to lack of trust in their SSH skills and knowledge.

Attempted Solution:
I tried creating users on my server and only allow them access to Drush using the following command.

useradd -s /usr/bin/drush drushuser

On logging in with drushuser, a list of commands displays and logs out immediately.

I do something similar with git and git-shell, I set the /usr/bin/git-shell as their default shell and it does allow them to push and pull content remotely.

Is there any way I can get the same results for drush?

Drush has some sort of interactive shell - try drush php:cli. (You would created a script /usr/local/bin/drush-shell similar to git-shell.) However, I just tested and it doesn't seem to work for Drush 9. If you are still using Drush 8, it seems to work just fine (as drush core-cli). Disclaimer: I haven't actually tested this as a login shell.

The other more standard approach is to use lshell and set it up so Drush and needed tools can be used. I haven't tested this either - sorry.


Hide Group audience/content visibility in node When displaying a node belonging to some OG, the group audience and the group content visibility is displayed at the end of the node just after the content of the node.

Is it possible to disable that ?
I would avoid code editing if possible.

In the OG content type, you will see a field for group audience. You can simply hide it in the Manage Field tab. Or, you could use CSS. In both cases, you are not hacking the core code.


How to make Localization update believe that the translation of a local .po-file is not up to date? I use a local development branch of a contributed project on several sites. The strings that need translation does not exist on https://localize.drupal.org/ (yet), so I cannot use it to translate the project.

Checking l10n update status produces:

$ drush l10n-update-status
…
my_project (7.x-1.x)   Up to date
…

Now, how do I convince Localization update that the translation of this file is not up to date?

So far I've tried:

Editing and saving (i.e. changing the last updated timestamp).
Editing the embedded timestamps POT-Creation-Date and PO-Revision-Date.
Clearing the cache.

But no joy. Localization update keeps insisting that translations from this file is up to date.

Figured it out!

After changing the last updated timestamp for, you need to refresh the information.  The following sequence of commands works:

$ touch my_project.7.x-1.x.nb.po
$ drush l10n-update-refresh
$ drush l10n-update-status
…
my_project (7.x-1.x)   Local update available
…

Editing the embedded timestamps POT-Creation-Date and PO-Revision-Date is not required and have no effect.


Check if the site allows new user registration In Drupal 7, on my frontpage custom template, i want to show a text if the site is allowing new users to register.
Any clues?
Thanks

In a preprocess function for your template, add code something like:

$variables['is_registration_open'] = variable_get('user_register') == USER_REGISTER_VISITORS;

Then in your template:

<?php if ($is_registration_open) : ?>

Registration is open!

<?php endif; ?>


Date range display in views using PHP How do I display date ranges for Value1 and Value2 in the following format where value2 is display as the difference between Value1 and Value2 expressed in days. I'd like to rewrite the results of a view field using PHP code.

Value1=1-Jan-2013

Value2=6-Jan-2013

i.e. result expected:

1-Jan-2013 +5d

<?php
$datetime1 = date('d-M-Y', strtotime(value1));
$datetime2 = date('d-M-Y', strtotime(Value2));
$interval = date_diff($datetime1, $datetime2);
$result = $datetime1 . ' ' . $interval;

result will be
1-Jan-2013 +5d


Control Visibility of Paragraph Without Fields I'm preprocessing a paragraph to add a custom form but I'm having trouble with the visibility. I don't need any fields on this paragraph.

If I just add the form to the paragraph the whole paragraph is hidden for anonymous users.

function my_module_preprocess_paragraph__my_paragraph(&$variables) {
  $paragraph = $variables['paragraph'];
  $form = \Drupal::formBuilder()->getForm('Drupal\my_module\Form\MyCustomForm');
  $variables['content']['form'] = $form;
}

However, if I add a title field to that paragraph everything shows up fine. Is there a way I can get the form to show without having to add fields?

Implement hook_field_widget_alter

It will give control of paragraph fields.

function hook_field_widget_entity_reference_paragraphs_form_alter(&$element, &$form_state, $context) {
  if ($element['#paragraph_type'] == 'xyz') {
    $element['subform']['field_name']['#access'] = FALSE;
  }
}


How to get live data from a service? In the UK our weather office provides a live weather data feed. I would like my Drupal site to retrieve data from this service.

I've read up on the XML-RPC API that is in Drupal 7 core. I've successfully built a Hello World! module that acts as a client, makes a call to a service, and successfully gets a response.

However, Drupal 7 is old and I'm wondering if I should be looking into a more 'modern' approach. I've read up on the Services module.

Can anyone advise me on what are currently the recommended ways to get data from a service into a Drupal 7 site.

I'm not looking for a weather module. This is an API learning exercise.

Thanks.

Thanks for the advice. The solution:

For example, to get a three-hourly five-day forecast for Dunkeswell Aerodrome:

  $base = 'http://datapoint.metoffice.gov.uk/public/data/';
  $resource = 'val/wxfcs/all/json/3840?res=3hourly';
  $api_key = '&key=abcde12345abcde12345';
  $url = $base . $resource . $api_key;
  $response = drupal_http_request($url);
  $data = json_decode($response->data, TRUE);


Drupal views_get_view in custom service I created a custom service with mymodule_services_resources and I'm calling a function to return some items. This function inside is calling a view with views_get_view. The problem is always return an empty array.

If tested the same code somewhere else it shows the right results, but it does not work with services. I have something like this:

$view = views_get_view('the_view');
$view->set_display('default');
$args = array("my_param");
$view->set_arguments($args);
$view->pre_execute();
$view->execute();
$view->result; //empty array in the WS

I tried loading the admin user ($user = user_load(1); ) before calling the view but I had the same results.

Is there something I should add, change or remove in order I can get the results of a view calling service endpoint?

Thanks!

the module services_views will help you expose the view as a resource in two different ways

It has currently two features:

Create view based resource creating Services display in a view
Execute any view of the system via views resource call


How to access remote index in search_api? I have two drupal installations, one instance contains data like entities. The other one access this entities with service-calls and display the website.

I would like to make the entities searchable for users with search_api(_solr) and created an index in the data server which contains the entities.

Now.. How can I access this index from the other drupal installation? I found the services_search_api module, but there is only a DEV Version :-(

Thank you in advance for your help.

Using the services_search_api Module is the right way, but you have to apply patches from the following Issues:

Support keys: provide Key Field for searching Solr Indexes. See Comment #1
Undefined functions: add required functions from previous Services Module. See Comment #4


Clean URLs not working, I can't log in to Admin Panel I just moved my drupal website to another host. But I am unable to login as mysite.com/user. It gives me a 404 not found error which means clean urls are not working afaik.

So, I checked PHP configuration with phpinfo(); and there is "mod_rewrite" visible in "loaded modules" section.

Anyway, I wanted to disable clean urls, however if I try to login as mysite.com/?q=user, it redirects to mysite.com/user and it is giving 404 not found error again.

So I kinda have no way to login to my website to update URL aliases. I have renamed my .htaccess file to disable it, result did not change.

I have updated this line:

  RewriteRule ^ index.php [L]

to this line:

  # RewriteRule ^ index.php [L]
  RewriteRule ^(.*)$ index.php?q=$1 [L,QSA]

Still, nothing changes. Since I can't control the web server, all I have is FTP and MySQL. Any ideas?

You can add this line to your settings.php file and it would allow you to login

$conf = array( 'clean_url' => 0,);

Another method is to find the .htaccess file in D7 root, and open it,
find the "# RewriteBase /drupal" in codes, delete the "#", change the "drupal" to your file's name: my file is "blog",
"RewriteBase /blog" - the end change to this.


Hierarchical grouping in Views? Drupal 7, Views 3, etc.

I'd like to use Views' grouping feature to group results hierarchically. I added the two fields I want to group with to the grouping list. I'd like to group by year, then by term. Here's the output I get now:

2011

Term 1

Result 1
Result 2

2011

Term 2

Result 3
Result 4

2012

Term 3

Result 5
Result 6

2012

Term 4

Result 7
Result 8

... and so on.

Here's what I want to see:

2011

Term 1

Result 1
Result 2

Term 2

Result 3
Result 4

2012

Term 3

Result 5
Result 6

Term 4

Result 7
Result 8

I thought that by using the "Use rendered output to group rows" checkbox, it would cause Views to ignore differences in the contents of the actual date field (which is more granular than just the displayed year) and only sort by year. Am I misunderstanding this checkbox, or is there something preventing it from working properly?

I found the answer to my question by tinkering. Like most solutions to my aggravating questions, it's stupidly simple.

I checked "remove tags from rendered output".

Upon inspection of the HTML page source, I found that the attribute content="[long, granular-to-the-millisecond datetime]" (e.g. content="2011-08-01T00:00-04:00") was plopped inside a  tag that was wrapped around the rendered output. So even though it looked like it was being grouped only by the 4-digit year value, it was actually being grouped by this whole, long value:

[Year]

Since each of these contained a totally unique datetime value, it appeared not to be grouping by year at all.


One click download button for webform submissions I have webform submissions and want to download all its data with one click download button. Right now it show other options like below:

But I want only a single download button for this. Is there any way to achieve this?

I have added a "Quick Download" button with my custom module.

Create a custom module.
Add this in the hook_menu in your .module file.

$items['node/%webform_menu/webform-results/quick-download'] = array(
    'title' => 'Quick Download',
    'page callback' => 'generic_webform_results_quick_download',
    'access callback' => 'webform_results_access',
    'page arguments' => array(1),
    'access arguments' => array(1),
    'file' => 'includes/webform.report.inc',
    'weight' => 7,
    'type' => MENU_LOCAL_TASK,
);

Create a file includes/webform.report.inc in your module folder and add the below function.

function generic_webform_results_quick_download ($node) {
    module_load_include('inc', 'webform', 'includes/webform.report');
    module_load_include('inc', 'webform', 'includes/webform.export');
    $export_info = webform_results_export($node, 'delimited', array('delimiter' => ','));
    $export_info['exporter'] = webform_export_create_handler($export_info['format'], $export_info['options']);
    webform_results_download($node, $export_info);
}

Clear CMS cache, go to the "Results" tab of the webform, you will see the "Quick Download" option. This downloads the data in CSV format.


File field not getting updated i tried to update file cck field of a content type as below from another node as below.

<form action="" method="post" id="tfrm" enctype="multipart/form-data">
    <input id="tf" name="tf" type="file" />
    <input id="btn" type="submit" value="Submit" name="btn" />
</form>
<?php
if($_POST['btn']){
$node=node_load(32);

$filename = basename($_FILES['tf']['name']);
$image = file_get_contents($_FILES['tf']['tmp_name']);
$file = file_save_data($image, 'public://' . $filename, FILE_EXISTS_RENAME);
$filesinfo = (object) array(
          'uid' => 1,
          'uri' => $file->uri,
          'filemime' => file_get_mimetype($file->uri),
          'status' => 1,
 );
$node->field_ftest[LANGUAGE_NONE][0]=(array)$filesinfo;
print_r($filesinfo);
  node_save($node);

}
?>

file gets uploaded but results error in updating file field .

localhost
Error
The website encountered an unexpected error. Please try again later.
Error message

    Notice: Undefined index: fid in file_field_presave() (line 219 of C:\xampp\htdocs\drupal\modules\file\file.field.inc).
    Warning: array_flip(): Can only flip STRING and INTEGER values! in DrupalDefaultEntityController->load() (line 173 of C:\xampp\htdocs\drupal\includes\entity.inc).
    Notice: Trying to get property of non-object in file_field_presave() (line 220 of C:\xampp\htdocs\drupal\modules\file\file.field.inc).
    Warning: Creating default object from empty value in file_field_presave() (line 221 of C:\xampp\htdocs\drupal\modules\file\file.field.inc).
    Notice: Undefined property: stdClass::$uri in file_save() (line 601 of C:\xampp\htdocs\drupal\includes\file.inc).
    Notice: Undefined index: fid in file_field_update() (line 261 of C:\xampp\htdocs\drupal\modules\file\file.field.inc).
    Notice: Undefined index: fid in file_field_update() (line 287 of C:\xampp\htdocs\drupal\modules\file\file.field.inc).
    Notice: Undefined property: stdClass::$fid in file_usage_add() (line 685 of C:\xampp\htdocs\drupal\includes\file.inc).
    PDOException: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'fid' cannot be null: INSERT INTO {file_usage} (fid, module, type, id, count) 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] => [:db_insert_placeholder_1] => file [:db_insert_placeholder_2] => node [:db_insert_placeholder_3] => 32 [:db_insert_placeholder_4] => 1 ) in file_usage_add() (line 692 of C:\xampp\htdocs\drupal\includes\file.inc).

You should use Form API to create and manage file uploads and their management. You can do something like this instead:

...
$form['file'] = array(
    '#title' => t('File'),
    '#type' => 'managed_file',
    '#description' => t('File formats: %format. Maximum: %max_size. Resolution %resolution', array('%format' => 'Jpg, Jpeg, Png, Gif', '%max_size' => '800 Kb', '%resolution' => '80x100')),
    '#upload_location' => 'public://',
);
...

and submit function:

...
$node = node_load(32);
$file_d = $form_state['values']['file'];
$file = file_load($file_d);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
file_usage_add($file, 'node', 'TYPE', $file->fid);
$file_info = image_get_info($file->uri);

$file_arr = array(
  'fid' => $file->fid,
  'alt' => '',
  'title' => '',
  'width' => $file_info['width'],
  'height' => $file_info['height'],
  'uid' => $file->uid,
  'filename' => $file->filename,
  'uri' => $file->uri,
  'filemime' => $file->filemime,
  'filesize' => $file->filesize,
  'status' => 1,
  'timestamp' => $file->timestamp,
  'rdf_mapping' => array(),
);

$node->field_ftest[LANGUAGE_NONE][0] = $file_arr;
node_save($node);
...


How to give a path to a link with filter? I am trying to give a path to a submenu with Filter(field) as

my-view&field_subject=C

but it shows error like 'path is either invalid or you do not have access to it.'

when i give 'my-view' it works perfectly.

But i want to show the view with 'Subject' column with Value C only.

'&' is used to divide query parameters, to split the page and parameters, use '?'

e.g.
my-view?field_subject=C


Creating a dynamic URL in node--resource.tpl.php I'm trying to create a URL in my node--resource.tpl.php file that contains fields from the resource in question in the URL. The following code is what I've been playing with, but when the user clicks the link it just shows as follows:

http://pf.dev/content/specific-resource-feedback?nid=&title=

Ie. The nid and title are not being filled out correctly. So here's the code I'm using (incorrectly) to create the URL:

    <a href="/content/specific-resource-feedback?nid=
<?php $content['nid']) ?>&title= <?php $content['title']) ?>">
Trouble with this resource? Let us know.

Any ideas why this might not be working as intended?

The title is defined for a node.tpl.php file as $title, and the node id can be retrieved with: <?php print $node->nid; ?>  therefore, it should read something like this:

  <a href="/content/specific-resource-feedback?nid=<?php print $node->nid; ?>&title= <?php print $title; ?>">
  Trouble with this resource? Let us know.


Embedding views in tpl files I need an advice. Is there any downsides when embedding views in the page/node tpl files like the following:

<?php print views_embed_view('course_videos', 'block_1'); ?> and this <?php $key =  views_get_view_result('course_videos', 'block_2');  ?> in the node.tpl files

I am little bit concerned cause I've read several articles saying you must not query the db or use a complex php logic in the tpl files. Everything's working like a charm now. The site is still not in production though...

Thank you in advance!

Including views in tpl is going backwards. Drupal allows you to use views as pages and as blocks. You can apply templates to that pages and blocks, and you can put blocks in regions. By calling views from template, you are messing with theme registry and cache logic. It might be not an issue if site is small, and both read and write volumes are low, but it will result in pages being out of sync on heavy loaded site.

Instead of outputting view directly, make a region, output it in template file, and put a views block inside.

Using views_embed_view in a preprocess function in template.php might be OK. Opinions and experience with it can vary, and I would try to avoid it, but certainly it does not mess with cache or theme registry like using it in tpl would.


How to Import features back to database I have lots of feature modules in my site. I want to import it back to database for upgrade purposes. Any idea how can I do that?

I used this patch from here - http://drupal.org/node/1014522#comment-5719202

After you patched it you can then use drush features-import-all --yes or drush fia -y to import features to database.


How to set a phone number via entity_metadata_wrapper? I am trying to update a user programmatically in Drupal 7.

User records have multiple custom fields, configured via admin interface #overlay=admin/config/people/accounts/fields

My code sets text and datetime fields fine, but fails to update a phone number field.

Error message:

EntityMetadataWrapperException: Unknown data property field_mobilephone.
in EntityStructureWrapper->getPropertyInfo()
(line 335 of /Applications/MAMP/htdocs/sites/all/modules/entity/includes/entity.wrapper.inc)

Code:

  $new_user = user_save(null, $fields);

  $obj = entity_metadata_wrapper('user', $new_user);
  $obj->field_firstname->set($_REQUEST['firstname']);
  $obj->field_lastname->set($_REQUEST['lastname']);
  $obj->field_mobilephone->set($_REQUEST['mobilephone']);

When I do var_dump($obj) I can see all configured text fields in the output, but not the phone number fields.

Field type is 'phone number', provided by the cck_phone-7.x-1.x-dev module (I couldn't find any other place where it could come from).

So question is how do I set phone number field via entity_metadata_wrapper?

I got around this problem by using the following snippet just before the user_save(..) call:

$fields['field_mobilephone'][LANGUAGE_NONE][0]['number'] = $_REQUEST['mobilephone'];
$fields['field_mobilephone'][LANGUAGE_NONE][0]['country_codes'] = 'au';

This approach bypasses the entity_metadata_wrapper altogether.
Pretty sure there's a cleaner way, but I'm not yet aware of it.


How do I get all the referenced taxonomy terms without the field name? I have been looking into entityQuery but haven't seen what I am trying to do yet.

If I have a node object, is it possible to get all taxonomy terms referenced by the node object, regardless of the field they are in?

Most of what I have seen would be getting the terms from a specific field, but I won't have access to the field name. I just need to find all terms in a specific vocabulary that are referenced by the node. Thanks!

You can iterate through all the fields on the node and add conditions to check that the field is an entity reference field, and that the target type is taxonomy_term:

// Iterate through each field on the node entity to get all the tagged
// taxonomy terms on the node.
foreach ($entity->getFields() as $field) {
  // Only look for fields that are entity reference fields.
  if ($field instanceof EntityReferenceFieldItemList) {
    // Get the field settings.
    $field_definition = $field->getFieldDefinition();
    $target_type = $field_definition->getSetting('target_type');
    // Check that the field targets are taxonomy terms.
    if ($target_type == 'taxonomy_term') {

      // Do stuff..

    }
  }
}


How do i create a breadcrumb based on Main Navigation Menu in programatically? I want to display the breadcrumb according to the main navigation menu.

If i've a menu structure like
a->b
  ->c
  ->d
e->f
  ->g
Now if i go to menu a->c, now the breadcrumb shows Home > c but i want it as like a >bHow to do it programatically ?

Menu breadcrumb module create breadcrumb based on a menu. Maybe this could help.


How to send auto login email using Email Auto Login drupal module? I have enabled Email Auto login Module on drupal 7. How can I send an auto login email using the above module. I have enabled the module and then saved the settings from the link
http://www.example.com/admin/config/system/email_auto_login. I have even checked the README file but could not find a way to send a auto login email using token
How can I send the auto login email using this module?

First of all to send out an email automatically you will need a triggering event – and probably also some condition, under which the action of 'sending' should be fired. Otherwise drupal will not know when to send out an email – and to whom.

I suppose you have a look at the Rules Module (https://www.drupal.org/project/rules). It might first look quite complex, but basically it consists of these three main elements you have to configure to add a new Rule to your webpage: Event, Condition and Action. With that you can automate almost everything, especially sending reminder-emails etc. – and most probably you can also trigger Email Auto login.


How to implement Node Access based on a Term in the user's profile? Some info about what I'm working on:

Nodes:
I have a content type that contains user_reference.
Taxonomy:
I have a vocabulary called cities, which is enabled for all users and contains terms like London, Paris, ...
Users:
All users are tagged with terms from the cities vocabulary, through the use of a taxonomy reference field added to their profiles.

What I am trying to achieve:

I want to give access to an administrative role to view/edit/delete nodes where the users referenced in these nodes are tagged with a certain term.

Example: I want to add a role called "London Supervisor".

Users who have this role can view/edit/delete any node where the referenced users have the terms London. So I want to give access to an administrative role to view/edit/delete nodes where the users referenced in these nodes are tagged with a certain term.

My question:

Anybody any suggestion about how to implement this?

Haven't tried it myself yet, but Taxonomy Access Control looks promissing:

Automatically controls access to nodes (based on their taxonomy terms).

Configuration page for each user role.

Three node access permission types: View, Update, Delete.


Views won't handle my pathauto pattern for taxonomy pages I have two taxonomies on my site that need to be browsable independently using different Views. Therefor I decided to prepend the term paths with the vocabulary name. In PathAuto patter section I have defined:

[term:vocabulary:name]/[term:url:path]

and the paths look the way I want:

vocabname/taxonomy/term/tid

however the Views don't work. The pages that are generated for the path

vocabname/taxonomy/term/%

somehow won't jump in. I see the error that no content has been tagged with this term, whereas the view should display teasers of the children terms.

So, do you think there is a wrong assumption on my side as per the url aliasing process (what occurs first)? Should that work?

Yes - you're very close on this, but you're right that the pathauto path is not being recognized by views here. To overcome this, you're going to need to add a 'default argument' in your views argument handling code and use PHP code to pass the term id from the end of your string.

It looks like from the version of tokens you are using that you're on Drupal 7 / Views 3, correct? If so, you're going to want to add this under

Contextual Filters -->
Content: Has taxonomy term ID -->
Provide Default Argument -->
PHP Code

and then in the php code section add this code:

$path = isset($_GET['q']) ? $_GET['q'] : '';
$path = explode('/', $path);
return $path[3];

This gets the current path as an array and returns the 3rd element, or the TID and passes it to your view.


Display Auto Generated Youtube Thumbnails with 'Video Embed Field' Module in Views I added some videos to my site and I'm using views to display them. I followed a tutorial and i used the rewrite the output option of the view with allowed replacement patterns to display videos in lightbox in this way.

Here when i clicked on the a image, the video will played in the lightbox and that was great.
In the above link added a custom the image field as thumbnail but that doesn't work well, because when i add more than one video all will have the same thumbnail.

But then i also came to know, that the Video Embed Module when used to add videos, auto generates the thumbails of the added youtube videos in a public directory. So again i worked on the replacement patterns and got the raw thumbnail field generated by the Video Embed Module.

Again i rewrote the output with the raw thumbnail as image

But the thumbnail image is broken and the image path is shown as
public://video_embed_field_thumbnails/youtube/RQieoqCLWDo.jpg which i guess is not recognized by drupal.

So my point here is, Is there a way to access the raw thumbnail in the rewrite patterns so that every youtube video gets its own thumbnail without manually adding image as thumbnail.

I only use the video embed field in views and have set the formatter to colorbox. I get the auto-generated thumbnails by default and on click of it, the video opens in a colorbox. You don't need to do anything else then this.


I have issue with commerce_order_load_multiple function The way i am using this function is

foreach ($mms as $mm) {
    $orders_of_user += commerce_order_load_multiple(array(), array('uid' => $mm->uid, 'status' => 'cart'));
  }

But i am not getting anything output from this and when i use static value of integer in place of uid i am getting result..

 $orders_of_user += commerce_order_load_multiple(array(), array('uid' => 421, 'status' => 'cart'));

I don't understand what causing the problem in foreach

when i use static value of integer in place of uid i am getting result

Logically speaking, that can only mean that $mm->uid doesn't contain what you think it does.

Install the devel module and use the dpm function to inspect the var:

foreach ($mms as $mm) {
  dpm($mm);
}

That should tell you what's going wrong.


Create a new user programmatically and mimic the registration flow? I notice we already have an example for programmatically creating a new user in Create a user programmatically and give they a role. However, this example uses user_save(), which does not mimic the registration process, (e.g. no email is sent to the user).

Could I use user_register_submit()?

I'm not clear on what your overall goals are here. However, you might check out the Form Clerk module. You can use it to create users, as well as many other things.

  Form Clerk is an administrative utility that provides a semi-automated way to input data into a Drupal form. Multiple instances of form data can be entered with one command. For example, multiple users with varying permissions can be created, or multiple articles with arbitrary content can be added.


Using the t() function in Drupal 6 So I have used the t function correctly e.g. t('hello world')
But I am not sure what else to do to get these strings translated. I tried looking at the hook_locale documentation, but I wasn't sure what a group was. Could someone help me find some documentation that would help me understand what I need to do after adding the t function?

Thanks.

function my_module_block($op = 'list', $delta = 0, $edit = array()) {
    ...
    if ($op === 'view') {
    $content .= '
' . t('my holiday') . '
';
    ...
    $content .= drupal_get_form('cool_form');
    $block['content'] = $content;
    return $block
}
}

EDIT: added some code. Is this enough code?

All you have to do is to Enable your proper language (using locale module) and then use translate interface (site building -> translate interface) , and you can translate your string.

after that whenever t('hello world') is called , drupal checks for proper language , then checks if there is a translation for 'hello world' in that language , if true , then it will print translated string.


Cannot manage footer menu I want to manage my footer menu, but I get this error:

The website encountered an unexpected error. Please try again later.

Symfony\Component\Routing\Exception\RouteNotFoundException: Route "contact.site_page" does not exist. in Drupal\Core\Routing\RouteProvider->getRouteByName() (line 190 of core/lib/Drupal/Core/Routing/RouteProvider.php).
Drupal\Core\Routing\UrlGenerator->getRoute('contact.site_page') (Line: 269)
Drupal\Core\Routing\UrlGenerator->generateFromRoute('contact.site_page', Array, Array, 1) (Line: 105)
Drupal\Core\Render\MetadataBubblingUrlGenerator->generateFromRoute('contact.site_page', Array, Array, 1) (Line: 753)
Drupal\Core\Url->toString(1) (Line: 167)
Drupal\Core\Utility\LinkGenerator->generate('Contact', Object) (Line: 94)
Drupal\Core\Render\Element\Link::preRenderLink(Array)
call_user_func(Array, Array) (Line: 376)
Drupal\Core\Render\Renderer->doRender(Array) (Line: 448)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array) (Line: 490)
Drupal\Core\Template\TwigExtension->escapeFilter(Object, Array, 'html', NULL, 1) (Line: 183)
__TwigTemplate_c1bdd8f86c8cc62844cbb93f33c11d8a2e27610acf3c1abe4f7e3e1886bfcf45->doDisplay(Array, Array) (Line: 379)
Twig_Template->displayWithErrorHandling(Array, Array) (Line: 347)
Twig_Template->display(Array) (Line: 358)
Twig_Template->render(Array) (Line: 64)
twig_render_template('core/themes/classy/templates/dataset/table.html.twig', Array) (Line: 384)
Drupal\Core\Theme\ThemeManager->render('table', Array) (Line: 435)
Drupal\Core\Render\Renderer->doRender(Array) (Line: 448)
Drupal\Core\Render\Renderer->doRender(Array) (Line: 448)
Drupal\Core\Render\Renderer->doRender(Array, ) (Line: 195)
Drupal\Core\Render\Renderer->render(Array, ) (Line: 226)
Drupal\Core\Render\MainContent\HtmlRenderer->Drupal\Core\Render\MainContent\{closure}() (Line: 574)
Drupal\Core\Render\Renderer->executeInRenderContext(Object, Object) (Line: 227)
Drupal\Core\Render\MainContent\HtmlRenderer->prepare(Array, Object, Object) (Line: 117)
Drupal\Core\Render\MainContent\HtmlRenderer->renderResponse(Array, Object, Object) (Line: 90)
Drupal\Core\EventSubscriber\MainContentViewSubscriber->onViewRenderArray(Object, 'kernel.view', Object) (Line: 111)
Drupal\Component\EventDispatcher\ContainerAwareEventDispatcher->dispatch('kernel.view', Object) (Line: 149)
Symfony\Component\HttpKernel\HttpKernel->handleRaw(Object, 1) (Line: 64)
Symfony\Component\HttpKernel\HttpKernel->handle(Object, 1, 1) (Line: 57)
Drupal\Core\StackMiddleware\Session->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\KernelPreHandle->handle(Object, 1, 1) (Line: 99)
Drupal\page_cache\StackMiddleware\PageCache->pass(Object, 1, 1) (Line: 78)
Drupal\page_cache\StackMiddleware\PageCache->handle(Object, 1, 1) (Line: 47)
Drupal\Core\StackMiddleware\ReverseProxyMiddleware->handle(Object, 1, 1) (Line: 50)
Drupal\Core\StackMiddleware\NegotiationMiddleware->handle(Object, 1, 1) (Line: 23)
Stack\StackedHttpKernel->handle(Object, 1, 1) (Line: 656)
Drupal\Core\DrupalKernel->handle(Object) (Line: 19)

Maybe it's caused by contact module, but I hav uninstalled it.

Yes it is because you uninstalled the contact module.  Try to install it again, then reset/delete that menu link from it and then uninstall it again.


How do i use pathauto to create a url alias for nodes' menu local tasks? The nodes are aliased automatically using the Pathauto module.  E.g., node/448 is displayed as aliased/path.

Is it possible to alias node/448/edit to aliased/path/edit?

The Sub-path URL Aliases module will do this.


Create a node programmatically then reference an existing node to that node? I'm using Drupal 7 and trying to create a node programmatically. Once the node has been created I would like to reference it to an existing node

I'm creating a node programmatically like below

$node = new stdClass();
$node->type = $type;
$node->title = $title;
$node->uid = $user->uid;
node_object_prepare($node);
//set field values
node_save($node);

Which works.

I would then like to update an existing node to reference the newly-created node.
I basically load the existing node, get the node id from the newly created node and update the reference field, like below

$node2 = node_load($node2);

$node2->field_reference['und'][0] = array(
  'target_id' => $node,
  'target_type' => 'node',
);

node_save($node2);

drupal_goto("node/$node->nid");

I get two errors when I add the second part to the code
Notice: Undefined property: stdClass::$nid in node_tokens()
Recoverable fatal error: Object of class stdClass could not be converted to string in DatabaseStatementBase->execute()

The first part works, the second does not. I'm getting the id of $node2 through tokens.

How can I make this work?

As for the second part, you need to pass node ID or array of node IDs to node_load function first argument.

Your code should look like the following:

$node2 = node_load($nid); // pass integer node ID or array of integers

$node2->field_reference['und'][0] = array(
  'target_id' => $node->nid, // pass integer node ID not node object
);

node_save($node2);

drupal_goto("node/{$node->nid}");


Drupal automatic "antihack" behaviour I experience some difficulties with formalizing a question for Google, so I'm going to post it here and request real human help=)

Are there any systems (modules or smth similar) in Drupal that monitor user activity and detect possible malicious actions? And react automatically?

For example, in some form, a dummy user tries a certain kind of SQL injection. Typing something like " or 1=1 -- or similar. This is obvious that this sort of data cannot be entered be accident. Drupal then detects this:"Ahah, this is going to be something like an SQL injection", then blocks the user IP for a month, for example, and logs all information about this event. Or sends an email to admin: "User @@ possibly tried to carry SQL injection while entering @@ form while doing @@ (situation description goes there) and was blocked for a month. See log at @@"

As I understand Drupal is pretty secure but it's secure in a passive way. I want to get it not only waiting for an attack and process it but also response to this attack. Or at least notify administrator of something anusual and therefore dangerous.

I hope you will understand what I want to get (not necessarily exactly what I mentioned) and extend the scope from my possibly idiotic imaginations to what is really used today.

I believe you're looking for the Drupal Tiny-IDS module:

  Minimalist, but performant intrusion detection system that monitors Drupal for malicious activities and targets to be simple to understand and easy to use.

It attempts to detect:

XSS (Cross Site Scripting)
SQLi (SQL Injection)
Code execution (Local/Remote file inclusion, etc.)

And can 'react' in a bunch of different ways:

Log entry
Warning message (to the malicious user)
Mail alert
Rules integration (which you could use to disable the user account)

I think that ticks all the boxes :)


Create a menu block with images in Drupal 8 & keep menu order On the 1st level pages from our main menu I would like to list all the 2nd level child page titles from that page and corresponding images from those children  pages' content fields. I would like them ordered the same as they are in the menu. I am using the path-auto pattern of [parent-url]/[page-title]. I'm open to any suggestions on how to do this.

I've looked into trying to create this with a view block or even a view REST feed but it appears I cannot get attributes from a menu in views in Drupal 8 to use to sort or filter the items. I tried to do this with a menu block but it appears I cannot add fields such as an image to show.

I finally had time to come back to this, so I'll answer my own question as I believe the following solves it. This code could for sure use some refactoring & cleaning up. I'm very new to Drupal 8 & I'm fairly new to Drupal in general. Feel free to suggest improvements.

<?php
/**
 * @file
 * Displays children pages as a block
 */

namespace Drupal\child_pages_display\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Url;
use Drupal\Core\Path;
use Drupal\Core\Menu;
/**
 * Provides a 'Next Previous' block.
 *
 * @Block(
 *   id = "child_page_block",
 *   admin_label = @Translation("Child Page Block"),
 *   category = @Translation("Blocks")
 * )
 */
class ChildPageBlock extends BlockBase {
  public function build(){
    $menu_tree = \Drupal::menuTree();
    $menu_name = 'main';

    // Build the typical default set of menu tree parameters.
    $parameters = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
    $expandedParents = $parameters->expandedParents;
    reset($expandedParents);
    $root = current($expandedParents);
    $parameters = new \Drupal\Core\Menu\MenuTreeParameters();
    $parameters->setRoot($root);
    $parameters->setMaxDepth(3);
    $parameters->setMinDepth(1);

    // Load the tree based on this set of parameters.
    $tree = $menu_tree->load($menu_name, $parameters);

    //Set Cache for block
    $cache['max-age'] = 3600;
    $cache['contexts'][] = 'url.path';
    $cache['tags'][] = $root;

    //Get node IDs from menu
    $nids = array();
    foreach($tree as $item){
      $nids[] = $item->link->getUrlObject()->getRouteParameters()['node'];
    }

    //Load nodes & generate content from nodes
    $nodes = (!empty($nids)) ? entity_load_multiple('node', $nids) : array();
    if (!empty($nodes) && is_array($nodes)){
      foreach($nodes as $key=>$val) {
        $nodeContent = array(
          '#prefix' => '
',
          '#suffix' => '
'
        );
        $url = \Drupal::service('path.alias_manager')->getAliasByPath('/node/'.$key);

        //Get image thumbnail from content & use specified image style
        if(null !== $val->get('field_thumbnail')->entity){
          $imgPath = ($val->get('field_thumbnail')->entity->uri->value);
          $imgCroppedPath = \Drupal\image\Entity\ImageStyle::load('basic_page_thumbnail')->buildUrl($imgPath);
          $img = ($imgPath != '') ? '' : '';
        }else{
          $img = "";
        }
        $nodeContent['#markup'] = '' .
            '
' . $val->getTitle() . '
' .
            $img .
          '';
        $content[] = $nodeContent;
      }
    }else{
      //Menu has no nodes
      $content['#markup'] = '';
    }
    //Add cache & css library to block
    $content['#cache'] = $cache;
    $content["#attached"] = array('library' => array('child_pages_display/child_pages_display_css'));
    return $content;
  }
}


IMCE directory per user I'm working on a scenario where users should not be able to access others' files. So, I wrote a custom module that creates a folder names user's name, then I went on to /admin/config/media/imce to set permissions and I typed php: return 'users/'.$user->name as instructed on the same page. However, that gives me Parse error: syntax error, unexpected end of file in DRUPAL_ROOT/sites/all/modules/imce/inc/imce.page.inc(789) : eval()'d code on line 1 and There is no valid directory specified for the file browser!. What to do? Any suggestions?

Its a syntax error, generated because you're missing some parenthesis or other required syntax. Do you have a semicolon at the end of return 'users/'.$user->name?
Should be:
'users/'.$user->name;


Inline Entity Form - start with first new node open My install is using Inline Entity Forms and I would like it so that when a user visits the create node page, the inline entity form starts already visible but with all fields empty and ready to be created (no need to click "Add Node").

I would like to implement either a module or tpl  file in my theme to achieve this. Please can you advise on how to go about it.

I've used this patch https://www.drupal.org/node/2225675 but it only works when editing existing content.

I read the codes in the inline_entity_form.module, and found the inline_entity_form_single is always displaying a form, so i copied its code to my module and it works:

function YOURMODULE_field_widget_form_alter(&$element, &$form_state, $context) {
  $field = $context['field'];
  if (isset($field['field_name']) && ('FIELD_NAME' == $field['field_name'])) {
    if (empty($element['form']) && empty($element['entities'][0])) {
      $element['actions'] = array();
      $instance = $context['instance'];
      $settings = inline_entity_form_settings($field, $instance);
      $controller = inline_entity_form_get_controller($instance);

      $parents = array_merge($element['#field_parents'], array($element['#field_name'], $element['#language']));
      $parent_langcode = entity_language($element['#entity_type'], $element['#entity']);

      $ief_id = $element['#ief_id'];

      $element['form'] = array (
        '#type' => 'container',
        '#op' => 'add',
        '#parents' => array_merge($parents, array ('form')),
        '#entity_type' => $settings['entity_type'],
        '#parent_language' => $parent_langcode,
        '#ief_id' => $ief_id,
      );
      $bundle = reset($settings['bundles']);

      $form_state['inline_entity_form'][$ief_id]['form settings'] = array (
        'bundle' => $bundle,
      );

      $element['form'] = inline_entity_form_entity_form($controller, $element['form'], $form_state);
    }
  }
}


How to send new content notifications based on taxonomy selection in user profiles? I am building a website in Drupal 7 where the requirement is for users to sign up, create profile2 where they must select from a list of checkboxes pulled in from my interests taxonomy terms.  For example: jobs, research collaboration, media interviews.

Once another user posts an opportunity (content type) I need to send all users a notification based on the interest categories selected when creating the opportunity (compared to each user's interest selections in profile2).

Probably the Rules module? Has anyone done anything like this before? I can't seem to wrap my head around the problem.

You may want to give it a try to process the results of a VBO enabled view via Rules, as detailed below.

Step 1 - make it work for a single (1st) term

Remark: this is an intermediate step to prepare a prototype for Step 2 (if you have enough Rules experience, just start straight from Step 2).

Create a rule like so:

Rules Event: After saving a node of type "Opportunity"
Rules Condition: Check if the node was tagged with your 1st term, using "List contains item" (and the list to be checked being the field of the node that contains the interest categories).
Rules Actions:

Load the VBO list of users that you want to be processed.
Add a loop to perform a Rules Action, for each row contained in your Views results. Within this Rules Action, you then send a notification to the user being processed.

Some more details about the VBO-view you'd have to create for this:

The view should list all users who have some specific term selected (which corresponds to the 1st term).
It should include an appropriate filter for the term ID to be processed.
It should have exactly 1 result (row) for each user to be notified.
One of the columns should be the eMail Id (I don't see other columns needed for this to work).

For more details, have a look at the tutorial "How to process the results of a VBO enabled view via Rules?".

Step 2 - make it work for all terms (not just the 1st term)

Since the Opportunity may have been tagged with multiple terms, you need to improve the solution from Step 1 to handle all the terms (not just the 1st one). To do so, these are the steps to improve the rule from Step 1:

Add a "Rules Loop" as your very first Rules Action, to iterate over each term that the Opportunity was tagged with.
For each term in this iteration, perform these sub-items:

check which term you're actually processing. This check is similar to the Rules Condition from Step 1, but you should use the Conditional Rules module to be able to include such Rules Condition as part of a Rules Action. BTW you can either use IF/THEN constructs, or CASE/WHEN constructs.
If the check succeeds, then perform a Rules Action similar to the Rules Action from Step 1.

Remove the Rules Condition from Step 1 (it is now included via the previous check using Conditional Rules).


How to validate file is selected or not on ajax processed jquery validation I am trying to do jquery validation on file upload for file is select or not. I want when user click on upload before submit check file is selected or not. if not stop ajax request. Any Idea to validate it?

$videoForm['profile_photos']['images']['field_photo'] = array(
    '#parents' => array('video', 'field_photo'),
    '#id' => 'field_photo',
    '#type' => 'managed_file',
    '#title' => 'Photo <em>(optional)</em>',
    '#field_name' => 'field_photo',
    '#process' => array(
    'm_customer_profile_image_remove',
    'm_customer_profile_image_upload',
    'file_managed_file_process',
        'customer_profile_image_preview',
    ),
    '#upload_location' => 'public://' . $user->uid,
    '#limit_validation_errors' => array(array('video', 'field_photo')),
    '#upload_validators' => array(
        'file_validate_size' => array(64*1024*1024),
        'file_validate_extensions' => array('gif jpeg jpg png')
    )
);

What are you using for the file upload element? Is this in a form, webform etc.? With the Form API managed_file should do what you want.


drush make and drupalcode patches I would like to download the stable version of a project and apply a patch. This patch was not submitted but applied directly to the project. I have the following drush make file (just a test snippet)

; Drush make script for the level platform install profile and features
core = 6.20
api = 2
projects[drupal][type] = core

projects[flot][dir] = "contrib"
projects[flot][version] = "1.2"
projects[flot][patch][] = "http://drupalcode.org/project/flot.git/patch/0b9d38d28e9f66cee239e7f92ccd2a368ce377c7"

This tells me that the patch has failed. If I download the file and use patch -p0 it will patch correctly.

Anyone have an idea why this is not working, and how to fix it?

This looks like a git based patch, I believe that you with drush need to use generic patched, which with git can be created like this:

git diff --no-prefix > file.patch


Views: Sort items using contextual filter arguments Im trying to create a block of "Related products", I have 3 criterias for show the related products: Color, Texture and size. These are taxonomy vocabularies.

In the view I can use contextual filters for get the matching products while viewing another product. These results are sorted alphabeticaly by default in the view.

Im trying to show first the items that match the Color of the product, then the ones that match the Texture and then those that match the size.

Can someone tell me if this is possible? and how would you do it?

This is the screenshoot of the view

Yes. I would first get my contextual filters working so that my view was returning results for matching color, texture and size. Then I would use my Sort Criteria to add sorting filters to sort first by Color, then by texture, then by size. Order is important in the Sort Criteria.


Cache problem in Drupal 6  when updating node When I update a node programmatically the node is updated successfully, but it doesn't display updated content. It only display the previous content.

How can I make the node display the updated content?

Assuming D6, You have to use the reset flag (third argument) in your node_load.


Using Panels and Views to Display Information from Entity Reference I'm currently work on a site that manages retail stores and visits made by salespeople to those stores.

I have the following two content types:

Store:

    contains basic store information: address, phone number, etc

Sales Survey:

date of sales call
salesperson
general info gathered on call
Entity Reference to the Store

I'm currently working with panels to create a custom display for the store content type and I would like to include a section showing the 5 most recent sales calls made to that store and the information about that call.

I've been trying to create a content pane in views to include in the panel for the store node display, but I can't figure out how to access all Sales Surveys that reference the store that is currently being displayed.

Any thoughts?

I'm using:
Drupal 7
Panels3
Views 3
Entity Reference

Let me know if I can provide further clarification, I think part of my problem is just in wrapping my mind around all the things I'm trying to bring together and I'm still very new to Drupal.  Maybe I'm going at this in the wrong way?

Any help is appreciated!

First, you need to create a view (probably block display) of the sales surveys, with a contextual filter. Create a new view of Sales surveys, with a block display. Add whatever fields you want to the display. Then, open the "advanced" tab, and add a contextual filter:

choose the field that you've named as the entity reference to the store
provide a default value -> "content ID from URL"

Once you save that view, go into panels, and add that view to the page you are creating for the stores.


add base url before field text content I have a text field used to enter a code (like 1111). This code is linked to a file (image) hosted in another server.

When a user displays this content type, I want to automatically display 3 things :

*the field content with the code (1111 for exemple) (I know how to do it)

a picture whose url will always be : www.url.com/FIELD_CONTENT.jpg (www.url.com/1111.jpg)
a link to the picture

Is it possible to do that ?

D8 but i can create a D7 website if needed.

You can render your image with a render array like this:

$a = array('#theme' => 'image',
        '#uri' => 'http://www.url.com/'.FIELD_CONTENT.'.jpg',
        '#alt' => 'Whatever',
    );

If you want that to be the content of an A tag (the link to press), render the link like this:

Link::createFromRoute($a, routename)->toString()

Is this what you need?


Connecting Commerce module with registered users I have a site that forces users to register before they can make any purchase, But I can't figure out a way to get the information from the registered users on my site and use it in my commerce module customer profile, so people don't have to enter their information again while making a purchase.

Using:
Drupal 7 Commerce Module

Commerce Addressbook could be useful for you.


Add an input field to the product view How do I add input fields to the commerce products (in Drupal 8) in order to save the information of those fields when the user purchases the product?

For example, if I want to sell t-shirts I would like an extra field to add some text and print it in the t-shirt.

Instead of adding the field to the product, consider adding the field to order items.

Then make it available in 'manage form display' -> 'add to cart'.

in Drupal 7 this functionality was provided by Commerce customizable Products module, now it has been moved into Commerce 2.x itself.


Blocks as Fields in Content Type I really like the ability to edit a block in Drupal on whatever page it's on--without having to drill down through menus.  However, a block doesn't seem to be a valid field for a content type.  If something is promoted to the front page, I can edit the item in a similar fashion to a block.

A work-around is to create a page, and put the block on the page.  However this creates additional maintenance.  For instance if the page is deleted, someone has to remember to delete the block too.

Is there any way of creating a field type which would be a block?  Or even better, is there any way in which a text field can be edited on the fly if it's not on the home page?

Any thoughts would be appreciated.

The display suite module has a "region to block" in its extras. This lets you put any of the fields displayed into its own block which can then be put where you want but I believe that editing will still take you to the full node edit page anyway.

For editing on the fly you should look into the jeditable module and/or editablefields module.


What is the nature of list variables provided by "Fetch content flagged by user"? On my site (Drupal 7/Flag 2/Rules 2), users can flag taxonomy terms.  I am attempting to write a rule that compares a list of taxonomy terms that I have created with each user's list of flagged terms.

I generated the list of flagged terms by using the Fetch content flagged by user action, which provides a variable of type list of flag items.  However, I cannot directly compare this with my other variable, which has a type of list of taxonomy terms, because when I iterate through the list of flagged terms using a loop in Rules, the current item from the list of flagged terms is not recognized as a taxonomy term.

Is there a way to force Rules to recognize that the flagged item in question is in fact a taxonomy term?  If not, what is the nature of the list of flagged items variable?

The action 'Fetch content flagged by user' definitely only returns node type content.  I just tested it out and sent the items provided by that action to a rule component which checked the content type.  It only sent nodes, not terms, though my user definitely had flagged terms...

Here's what I did to look into it.

Create a rule component: /admin/config/workflow/rules/components/
Make sure it's a rule or rule set component
I have mine accept 'any entity' as a parameter, because I want my original rule to supply it with the 'Fetch content flagged by user' list_item, which this component can check
Eventually, you can have it accept a second parameter, which could be a list for it to add to, if the supplied entity is determined to be a type 'taxonomy term'... no need to do this yet, because we'll find out that none of the content passed is of this type.  :-(
Once you've set the parameters, continue to your rule, and add a condition "entity is of type".  Set this to 'taxonomy term' and then in an later iteration to 'node' to compare the results of each of these settings
I set the action based on the above test to be 'Show a message on the site' for now.  This could have been something like 'add item to list' if the above test actually ever was true for terms.
Save the rule component, and go back to your original rule where you loop through the content tagged by the user.  Add an action IN your loop, in which you call the above component (components appear at the very end of the list) and provide your current list item as the component's parameter.
You'll see that only flagged nodes are ever sent to the component, and never terms.

It seems that though flagging of terms was recently introduced in the Flag 2.0 module, the integration of that piece with rules is a little behind.  :-(

Anyway, I hope the above helps shed some light in your situation.  Let us know if you find a way around this.  I've played around with it some more, and couldn't find a round-about way to get to what you need yet.


Moving Drupal to a new host but same domain I am planning to switch web hosting provider for  one based in the UK, as the data centers and offices for my current web hosts are in the US which makes it a lengthy process if I need to contact them etc. I am going to transfer my domain name (so I think that all of my URLs will be the same) and I have downloaded my public_html directory and MySQL database to my computer. If I just upload everything to my new host will everything work?

I have checked and I know that my new hosts have similar spec'd servers with PHP 5, but it just seems a little too simple. The biggest thing I am concerned about is the different timezones and the MySQL database really. If it makes any difference, I will be using shared hosting.

Few things to check.

Which version of PHP? I've seen Drupal sites break going from 5.3 to 5.4

You might want to check what the TTL of your domain is. If it's long you'll have people visiting the new site and the old one at the same time. You can set it to 5 minutes (300) which should make sure everbody moves across to the new site at roughly the same time.

Stress testing. Can the new hosting actually handle the expected load? Things like uploading images will take a lot of memory.


Alternative to panels Is there any alternative to Panels that can be used for smaller websites where Panels may be a overkill?
I recently took up DP development again, haven't worked with DP7 for approx a year now, did lots of work on DP7 earlier.
When settings up a new site I always feel blocks are sufficient, if only the configuration had been made "correct" from the beginning - sorry for being biased.
But is the only alternative to blocks full blown Panels and mini panels if you want to be able to configure blocks differently depending on the the context in which they appear?
Update
after having tested Context and Display Suite I have to admit they fit perfectly! As stated by @j-reynolds in his comment, the Display Suite makes it possible to create column based layouts in which you can determine what data you want to see eg. splitting your node into a 2 column stacked view where body is in the left region and tags in the right, title goes into the header region.
Using the Context module you can control which blocks or regions are being shown based on eg. term view or node view.
Combining the 2 and you have something easy to work with and manageable without going full blown Panels.
Both modules can do a lot more, I am just mentioning a few of the options.

Check out Context.

  Context allows you to manage contextual conditions and reactions for
  different portions of your site. You can think of each context as
  representing a "section" of your site. For each context, you can
  choose the conditions that trigger this context to be active and
  choose different aspects of Drupal that should react to this active
  context.

  Think of conditions as a set of rules that are checked during page
  load to see what context is active. Any reactions that are associated
  with active contexts are then fired.


How do I use hook_update_N() to create a vocabulary? I want to create a standard vocabulary (no extra fields) in Drupal 8.7.5 programatically, using hook_update_N. I've never used this function before. So I'm a complete newbie.

I've modified a simple delete script I was shown, but something tells me it can't possibly be this simple.

Here's my starting point:

<?php

use Drupal\taxonomy\Entity\Vocabulary;

/**
 * create vocabulary testname.
 */
function ent_create_update_8105(&$sandbox) {
  $vid = 'testname';
  $vocabulary = Vocabulary::load($vid);
  if (!$vocabulary) {
    $vocabulary->create();
  }
}

I assume that, once the script is created correctly, I simply run drush entup.

You should be able to do it like this:

<?php

use Drupal\taxonomy\Entity\Vocabulary;

/**
 * create vocabulary testname.
 */
function ent_create_update_8105(&$sandbox) {
  $vid = 'testname';
  $vocabulary = Vocabulary::load($vid);
  if (!isset($vocabulary)) {
    Vocabulary::create([
      'vid' => $vid,
      'description' => '',
      'name' => 'The vocabulary’s name',
    ])->save();
  }
}


How to Get data of Content type in a custom view I have a content type "tasks", I created a custom view.i want to show all data of content type "tasks" in that custom view.

I believe you are looking for this module:
https://www.drupal.org/project/viewsnodefield


The "tag" plugin does not exist The issue is about page loading like the following ones:

Front page
Taxonomy pages (for instance, https://talash.by/taxonomy/term/33)
Any view pages in edit mode /admin/structure/views/view/block_content
Content list page /admin/content
User list page /admin/people

I have a message "The website encountered an unexpected error. Please try again later."

Apache log shows:

  Uncaught PHP Exception Drupal\Component\Plugin\Exception\PluginNotFoundException: "The "tag" plugin does not exist." at /var/www/site/public_html/core/lib/Drupal/Component/Plugin/Discovery/DiscoveryTrait.php line 52,

The issue happens even if I make a site copy (files and database) on the same physical server, but as different virtual server. Internal pages can be loaded (for example, https://talash.by/terms-of-use)

I am using Drupal 8.2.4 (standard) on Ubuntu 16.04, with PHP 7.0.8-0ubuntu0.16.04.3 (cli).

These are the non-core modules:

Media                Colorbox (colorbox)                               Module  Not installed  8.x-1.2

Other                Backup and Migrate (backup_migrate)               Module  Not installed  8.x-4.0-alpha1
Other                Colorbox Inline (colorbox_inline)                 Module  Not installed  8.x-1.0-rc2
Other                Disqus (disqus)                                   Module  Enabled        8.x-1.0-rc3
Other                Exclude node title (exclude_node_title)           Module  Not installed  8.x-1.0-beta1+7-dev
Other                Ultimate Cron (ultimate_cron)                     Module  Not installed  8.x-2.0-alpha1
Web services         HAL (hal)
Bootstrap            Bootstrap (bootstrap)
Theme   Enabled        8.x-3.1
Bootstrap            Bootstrap Clean Blog (bootstrap_clean_blog)
Theme   Enabled        8.x-1.0-rc2

Tag is the views cache plugin: \Drupal\views\Plugin\views\cache\Tag, that is in core.

If you are missing that then the files of your installation are messed up, you are possibly missing other files as well. You might want to re-upload all files and also consider using a more reliable deployment method like composer and not upload files over FTP or so.


Rewrite a Views Field to get rid of accents. I need roman alphabet characters for a csv export I'm using Views Data Export to generate CSV files for end-users to use and then re-upload using Feeds. I need Vietnamese characters like â ỏ ể to be converted to a o e before export as these are in users' names.
I tried utf8_decode in Views Data Export settings but it doesn't work for all characters and even then, changing Feeds to use ISO-8859-1 still results in a "This isn't a UTF-8 file" error.
It seems that changing a setting in Excel can fix this but that isn't an option for me for usability reasons. I'm not the one who will be using these CSV files so I need these names to be exported properly.

Setting "Character encoding conversion" in the data export view's CSV file settings to:

ISO-8859-1//TRANSLIT

should accomplish what you're attempting. That will convert the names to the ISO-8859-1 character set, with transliteration of characters not included in the set to something that appears similar.


How to get slick slider working well on multi-directional(RTL/LTR) site? After install slick slider and Slick Views modules on multi-directional site, Slider does not work well on RTL, There is option in slick slider module for RTL sites, but this broke slider on LTR, So we need this an option enabled only on RTL sites, I found this solution. How can accomplish this?

This is possible by implementing template_preprocess_slick

use Drupal\Component\Serialization\Json;

/**
* preprocess variables for slick.html.twig templates.
*/
function template_preprocess_slick(&$variables) {
  $language = \Drupal::languageManager()->getCurrentLanguage();
  if($language->getDirection() == 'rtl') {

    $settings = $variables['content_attributes']->offsetGet('data-slick');
    if(!empty($settings)) {
      $settings = Json::decode($settings->value());
      $settings['rtl'] = true;
      $settings = Json::encode($settings);
      $variables['content_attributes']->setAttribute('data-slick', $settings);
    }
  }
}


Redirect node form to view after submit I have a view for a Drupal 8 site that uses 'work' as its path. I want to redirect user to this path right after the node has been submitted.

Form alter seems to be the right solution as it was in Drupal 7, but it's more complicated then it was before. In Drupal 7 we just used a direct path and redirect took place; now we need to provide a route name which isn't that obvious anymore. How do we find proper route name value? It's different for nodes, views, custom paths etc.

What I should use as argument for $form_state->setRedirect('')? How do I find what route name I should use in different cases?

function work_form_alter(&$form, \Drupal\Core\Form\FormStateInterface\FormStateInterface $form_state, $form_id) {
  switch ($form_id) {
    case 'node_work_form':
      $form['actions']['submit']['#submit'][] = 'work_redirect';
      break;
  }
}

function work_redirect($form, FormStateInterface $form_state) {
  // Set redirect to some path.
  $form_state->setRedirect(''); // What should I provide here as an argument/arguments
}

For Views, the route pattern is view.(view_id).(display_id).

For instance, if I have a view called Articles, and a display that I named "All", it would be:

$form_state->setRedirect('view.articles.all');

If you don't rename your display ids (I usually do), it is probably page_1 or something of that nature.

Beyond that it's similar to how it was before. Here is a redirect with query string args attached:

$form_state->setRedirect('view.articles.all', ['keywords' => $form_state->getValue('keywords')]);


node_overview_types no hook? how to customize Ok, i'm finally starting to understand how to use hooks! I am trying to customize the table that appears on admin/structure/types  I would like to add a custom link between manage fields and manage display.  I have tracked the creation of this down to the node_overview_types function in content_types.inc.  I did not see any hooks like hook_theme_table.  My initial response was to look for a hook_table_alter but I did not see one in the drupal api. Any help would be appreciated.

Since there's no specific theme function used the easiest way I can think of is to implement hook_page_alter() and alter the table directly. The following code works for me:

function MYMODULE_page_alter(&$page) {
  if (request_path() == 'admin/structure/types') {
    // Get the types, they will automatically be in the same order as the rows
    // in the existing table
    $types = array_keys(node_type_get_types());
    $limit = count($types);

    for ($i = 0; $i < $limit; $i++) {
      // Get the existing row
      $row = $page['content']['system_main']['node_table']['#rows'][$i];

      // Get the type related to this row
      $type = $types[$i];

      // Make a link to add to the table
      $link = l('Link Text', 'my/path/to/' . $type);

      // Make up the new cell. I know there's an easier way to do this but
      // I can't for the life of me remember it right now
      $new_row = array($row[0], $row[1], $row[2], $link, $row[3], $row[4]);

      // Overwrite the existing row with the new one
      $page['content']['system_main']['node_table']['#rows'][$i] = $new_row;
    }

    // Increase the colspan of the header to take into account the new column
    $page['content']['system_main']['node_table']['#header'][1]['colspan'] = 5;
  }
}


Update.php: Page not found Currently using D7 (specifically the Commerce Kickstart installation profile). When trying to reach update.php, I get a "Page Not Found" error. I also noticed that the url Drupal is trying to reach is /core/update.php.

Has anyone else encountered this?

Do you have the .htaccess file from 8.x instead of the one from 7.x?
The directory structure of Drupal core changed from 7.x to 8.x, and 8.x includes additional mod_rewrite rules to redirect to the changed locations of update.php and install.php


How is a field's key (rather than value) obtained? In Drupal 7, I have a page content type that has a field called group (so the machine name is field_group).  The field is a List (integer) field type.

This field might have allowed values as follows:

0|Description 1
1|Description 2
2|Description 3

If I want to see the value of this field for the current page, the following code correctly works:

echo render(field_view_field('node', $node, 'field_group'));

If the key were set to 1 for this page, the above code would display the value "Description 2."

However, is there a way to instead get the key (e.g., 0, 1, 2, etc.)?

You can change the display in your content type "Manage Display" and ask to have the key and not the label :)
It's here : /admin/structure/types/manage/[your type]/display

Programmatically for a nude value as asked :

$items = field_get_items('node', $node, 'field_list');
$key = $items[0]['value'];


Redirect to "Access denied" page? Is there a path with which I can call the "Access denied" page?

I'm trying to implement a rule that redirects to such a page because I want to prevent users and search robots from visiting certain nodes.

This is for Drupal 6.

You don't need to redirect to any page; you can produce the access denied page by calling drupal_access_denied().


Exposed filter in view should display all available values in select box I added an exposed filter to my view where users can enter the desired value to filter the results accordingly. But I want to make it easier for them by changing this filter to a select box style dropdown where they can select a value out of all available values.
To make this more clear; I'm talking about a year, so each article has a field "year" and because there are many articles published in many years, I want to group all available years from all articles and show them to the user in this select box.
But I can only make this possible by adding the years in the grouped filters manually, that means each year I have to add a new option to the filter manually. And if there are articles added later which originally were published earlier than years available in the options, I probably will never cover all years in this set of static options.
So is there a way to get all years of all articles and showing them in a select box?

A little bit more research would have helped, I found out myself how to do this. (Though I don't know if it would work without custom code.)
I hooked into hook_form_FORM_ID_alter() inside my theme (would also work in a custom module) and altered the form like this:
function MYTHEME_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  if ($form['#id'] == 'views-exposed-form-MYVIEWID-MYFORMID') {
    $nids = \Drupal::entityQuery('node')->condition('type', 'article')->execute();
    $nodes = \Drupal\node\Entity\Node::loadMultiple($nids);
    $options = ['' => 'All'];

    foreach($nodes as $nid => $node) {
      $value = $node->get('field_article_year')->getString();

      if (isset($value)) {
        $options[$value] = $value;
      }
    }

    asort($options, SORT_NUMERIC);

    if (isset($form['article_year'])) {
      $form['article_year']['#type'] = 'select';
      $form['article_year']['#options'] = $options;
      $form['article_year']['#size'] = 1;
    }
  }
}


Getting the pretty url for a node if it's a term I'm using 'pretty urls' with autopath for my nodes so example.com/node-name but I'm having trouble getting that in the context of a term page.

So on the node template itself I'm doing:

 if ( arg(1) == 'term') {
      //do stuff
 }

To get the link to the nodes page:

<a href="<?php echo $base_url . '/node/' . $node->nid; ?>" class="btn btn-primary" role="button">View details &raquo;

But this takes me to the node number url so example.com/node/23 or something like that. I would like the nice url. When I var_dump $node all I can get to build a url is the id, any ideas? Preferably something in the code, I like controlling stuff in the templates if I can.

Figured it out, using drupal_get_path_alias. So something like in the node:

$url = drupal_get_path_alias('node/' . $node->nid);


How do I apply loop into node twig template? This is code I am using.

{{ content.field_article_main_content[0] }}

{{ content.field_article_main_content[1] }}

How can I change that code to make it loop over content.field_article_main_content?

I would use code similar to the following one.

  {% for key, item in content.field_article_main_content %}
    {% if key == 0 %}

{{ content.field_article_main_content[key] }}

    {% else %}

{{ content.field_article_main_content[key] }}

    {% endif %}
  {% endfor %}

If it happens that some values of key start with #, then I would use the following code.

  {% for key, item in content.field_article_main_content if key|first != '#' %}
    {% if key == 0 %}

{{ content.field_article_main_content[key] }}

    {% else %}

{{ content.field_article_main_content[key] }}

    {% endif %}
  {% endfor %}


hook_mail is not sending rendered HTML email I'm rendering HTML template for email

demo_test.module

use Drupal\Component\Utility\SafeMarkup;

function demo_test_theme() {   return [
    'contact_mail' => [
      'variables' => ['params' => NULL],
    ]
  ];
}

function demo_test_mail($key, &$message, $params) {

  $render_email = [
    '#theme' => 'contact_email',
    '#params' => $params,   ];

  $mail = drupal_render($render_email);

  $message['body'][] = $mail;
  break;
}

contact_mail.html.twig

    <meta name="viewport" content="width=device-width">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Test</title>

test

Tried:

$message['headers']['Content-Type'] = 'text/html; charset=UTF-8; format=flowed; delsp=yes';

But still not working.

I have done the same what you done above. Using hook_mail_alter function will not work for this case either.

Better is to use Mime Mail module to achieve this HTML Format.

  It permits users to receive HTML email and can be used by other modules. The mail functionality accepts an HTML message body, mime-endcodes it and sends it.


How to get all the field and value of node as an array? I am trying to render all field and value of a node as an array dynamically. How can i achieve that?

You can use the built-in Entity::toArray():

$node = \Drupal\node\Entity\Node::load(1);
print_r($node->toArray());


security kit module settings are blocking own site jQuery calls I am using Security kit module to enhance security for my website. In that I have enabled Enable JavaScript + CSS + Noscript protection  option. This setting is blocking one of Jquery call that is .load functionality. The description of this option is here:

Enable protection via JavaScript, CSS and Noscript tag. This is the most efficient Clickjacking prevention technique. If webiste is not being framed, seckit.document_write.js starts commenting with document.write() and stops when reaches stop SecKit protection. Thus seckit.no_body.css, which sets body display to none, is ignored. If particularly this JavaScript file is being blocked (with XSS filter of Internet Explorer 8 or Safari), seckit.no_body.css sets display: none to body. If JavaScript is disabled within browser, it shows a special message.

Below is the js code:

$("[name='dest-target']").click(function(e){
 jQuery("#test_file_download").load(Drupal.settings.basePath + Drupal.settings.pathPrefix + "node/hit/ajax", {'path': filenodeurl});
 return false;
});

Please suggest me any alternatives i can use for this.

If this code inline, then try with this:

'unsafe-inline'

Allows the use of inline resources, such as inline  elements, javascript: URLs, inline event handlers, and inline  elements. You must include the single quotes.

'unsafe-eval'

Allows the use of eval() and similar methods for creating code from strings. You must include the single quotes.

Howewer, the proper way to set up this module you can find  this.


How can I require that browscap.ini / get_browser() is functioning before allow a my module to be installed? I have a module for my Drupal 7.x installation which needs browscap.ini / get_browser().

The module works perfectly, but I want to make sure the browscap.ini is installed before installing of enabling the module. That way the module will not work unless browscap is installed correctly.

How can I do this?

I fixed it using the following code:

/**
 * Implementation of hook_requirements().
 *
 */
function aserv_support_requirements($phase) {
  $requirements = [];

  if ($phase == 'install' || $phase == 'runtime') {

    if (!get_cfg_var('browscap')) {
      $requirements['aserv_support'] = [
        'title'    => t('Browscap not installed'),
        'value'    => 'Browscap has not be installed. Please install Browscap before enabling this module.',
        'severity' => REQUIREMENT_ERROR,
      ];
    }
  }

  return $requirements;
}

/**
 *  Implementation of hook_enable()
 */
function aserv_support_enable() {
  if (!get_cfg_var('browscap')) {
    drupal_set_message(t('ERROR Enabling Aserv_Support: Browscap has not be installed. Please install Browscap before enabling this module.'), 'error');
    module_disable(['aserv_support']);
  }
}


Is there a way to group different taxonomy/content type in a single Select List (in a View)? I have different content types, each content type has its own taxonomy terms - see screenshot.

International News
|--- Diplomacy
|--- War
-National News
|--- Economy
|--- Politics
-Entertainment
|--- Movies
|--- Theater
-Sports
|--- Football
|--- BasketBall

I built a view that, by default, lists all the content from the different content types/taxonomy terms and i wanted to add a select list that will allow the visitor to filter through content and get the nodes they're interested in (Football for example)

As you can see in the screenshot i have a filtering select lists block with a select list for each Content Type.
Is it possible to have a single select list that groups all the content types and their taxonomy terms ?

If that's not possible. How can i reset the filters each time a filtering occurs.
Right now, if i select Politics for example, the filtering is done and in the results we only get nodes that are tagged with that term which is exactely what it's supposed to do but on the resulting page, the filters do not reset themselves
If i select another taxonomy term, the first term i chose (Politics) stays on so unless there are nodes that are tagged with both terms, no nodes appear in the results page.

Any help is welcome

Thanks

You can follow this using below step:

Go to Administration -> Structure -> Views
Edit your existing view or create new new.
Add Filter for taxonomy terms you need
Click on "Rearrange" filter icon in Filter section
Click on "Create new filter group" and move filter taxonomy terms you need in new filter group.
Select Operator as "Or" in new filter group and save the form.


Filtering out duplicate dates from different nodes in views I have a "This day in history" page on my website, which when viewed in a monthly view shows of list of everything that has happened on each day in the month (so, for example January might say January 1: Monkeys learn to motorbike, January 2: Otters invade, etc.)

My issue is we have some new historical dates we want to add, so in this view I'm starting to see duplicate dates that have different content. (i.e, January 10: Yeti discovered, January 10: Moose have picnic with Bears).

The problem is I don't want to have duplicate dates on this view, rather I only want the most recently published/updated node to show up. Is there a way I can order a unique based off of a date field in views?

I'm sure I could probably do this through a views template and just manually remove the duplicate dates, but I would rather just limit the amount of data I'm receiving in the first place.

I'm wondering if this could be done through aggregation? Group my responses together based on their date, and only allow one item per group?

If there was a way to do this purely in views, I haven't discovered it.

What I was able to do though, was to use templates to remove the second item if it had a date that matched another item.


Editing author of a node Drupal 6 After some painful searching, I think I've deduced a solution (to try) to fix my real problem. That solution involves changing the Author of a node.

The real problem is the Workflow tab showing on a few products for Anonymous users. I've been all through all the permissions, rules and workflows. What I found was that if an Authenticated user who created some content is deleted, that content is assigned to an Anonymous author.

So, I was trying to find the data in phpmyAdmin to edit one there as a test but I haven't found the information.

As the super user, I cannot edit the authorship of a node as I haven't found a tab/setting etc to do so.

Can anybody steer me in the right direction?

The node author is usually editable in the 'Authoring Information' tab/section of the node-edit page. If that data isn't available for you (may have been removed by another module or other customization).

If you're comfortable editing the data in the database (via phpMyAdmin or another tool), have a look at the node table. You will see that each row contains a value in the uid column - this refers to the user id (uid) of the authoring user. User ids can be matched up to the corresponding users in the users table. Simply update the uid value in the node table for the appropriate nodes (likely ones with uid = 0) and you should be good to go.