Using feeds_ex to import content to drupal using 2 steps API calls I am trying to import data to Drupal 8 website using Feeds and Feeds_ex module and here is my scenario:

I need to make a call to the first JSON API and extract the IDs from it, here is a sample of the API

{
"rm": [{
    "mn": "Friday",
    "id": 3003,
    "ra": "JEB  ",
    "md": "2019-11-01 00:00:00.0"
}, {
    "mn": "Saturday",
    "id": 3014,
    "ra": "SHJ  ",
    "md": "2019-11-02 00:00:00.0"
}]

}
Then I want to use the extracted IDs to construct custom URLs to get the actual data that I want to import.

http:/somewebsite/api/index.php?id=1234

I looked to Feeds documentation to create a custom fetcher with no luck.Any advice?

The trick is to create a new parser, not a new fetcher.
I created a new module and a new parser at the following:
New files at MY_MODULE/src/Feeds/Parser/MymoduleJsonPathParser.php

I wanted to build on top of the feeds_ex module so I used their interfaces as the following:

use RuntimeException;
use Drupal\Core\Logger\RfcLogLevel;
use Drupal\feeds\FeedInterface;
use Drupal\feeds\Result\FetcherResultInterface;
use Drupal\feeds\Result\ParserResultInterface;
use Drupal\feeds\StateInterface;
use Peekmo\JsonPath\JsonStore;
use Drupal\feeds_ex\feeds\Parser\JsonParserBase;
use Drupal\feeds_ex\feeds\Parser\ParserBase;
use Drupal\Core\Form\FormStateInterface;

If you would like to add custom options that appear at the feeds UI add your custom form at the following:

public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);

$form['FIELD'] = [ .....];
return $form;

}

Now you can build on your custom parser:

    protected function executeContext(FeedInterface $feed, FetcherResultInterface $fetcher_result, StateInterface $state) {
    $raw = $this->prepareRaw($fetcher_result);
    $parsed = $this->utility->decodeJsonArray($raw);
    // Your code gose here.
  }

I am writing a custom module and I will share it here when it's finished.


Are absolute paths allowed in info files? I'm writing a .info file for a module, and I want to include a script which has been installed in /sites/all/libraries:

So I have included the line below in my .info file:

scripts[] = /sites/all/libraries/zeroclipboard-2.2.0/dist/ZeroClipboard.js

However, with or without the leading slash on this path, I always get the same result: Drupal treats this as relative to the module directory and tries and fails to load

/sites/all/modules/custom/clipboard//sites/all/libraries/zeroclipboard-2.2.0/dist/ZeroClipboard.js?nsnrjh

So maybe I've answered my own question, but I can't find any definitive answer to this in the Drupal docs?

Thanks all,

MB

_system_rebuild_module_data is responsible for that. There is a whole section in code just to make sure:

// Prefix stylesheets and scripts with module path.
$path = dirname($module->uri);
if (isset($module->info ['stylesheets'])) {
  $module->info ['stylesheets'] = _system_info_add_path($module->info ['stylesheets'], $path);
}
if (isset($module->info ['scripts'])) {
  $module->info ['scripts'] = _system_info_add_path($module->info ['scripts'], $path);
}

My guess is that module should never assume that something exists if module itself does not install it. It's a way to introduce errors. Also, allowing modules to reach outside their directory might be a security breach.

If you need a script you can't include in your module, use Libraries API. Of course there are other ways, but most of them is problematic, and fixing all problems would pretty much result in cloning this ready module anyway.


403 Forbidden when creating a page with RESTful API Referencing this tutorial, I am trying to create a page with RESTful API:

{
  "_links":{
    "type":{
      "href":"http://www.example.com/drupal/rest/type/node/page"
    }
  },
  "title":[
      {
        "value":"My first page"
      }
    ]
}

The POST request is: http://203.80.250.46/drupal/entity/node

The POST request headers are:

Content-Type: application/hal+json
PHP_AUTH_USER: (admin_username)
PHP_AUTH_PW: (admin_password)

But Drupal responded with: 403 Forbidden (Access Denied in response HTML)

Drupal 8 is installed at: http://www.example.com/drupal/

Enabled: HAL, HTTP Basic Authentication, RESTful Web Services, Serialization, REST UI

What did I miss?

The tutorial example using Dev Client is probably what is throwing you off because PHP_AUTH_USER and PHP_AUTH_PW are not valid request headers for Drupal 8 REST. The tutorial does give a curl command using the --user parameter which should do the correct behavior - add an Authorization header. I demonstrated this by manually adding that request header in User login REST format.

Content-Type: application/hal+json
Accept: application/hal+json
Authorization: Basic admin_username:admin_password


Change views exposed filter format I am build a JSON export using a View in Drupal 8. Problem is that the parameters for retrieving the json doesn't seem to work as I would want.

In my View I need use two exposed filter criteria to select a date range.  Both fields are Date and Time fields. When clicking on one of the criteria I have created it says:

  Value type

  A date in any machine readable format. CCYY-MM-DD HH:MM:SS is
  preferred.

I would like this url with this parameter values to work: http://example.com/api/?start=20161101&end=20161102

I thought it was working at first, but apparently not when I get my results.

This works:

http://example.com/api/?start=2016-12-08%2000%3A00%3A00&end=2016-12-21%2024%3A00%3A00

I am trying to have those clean parameters instead. How can I change the filter format to use the YYYYMMDD format? I don't want to change my field type because it is storing the time for my events. I want to get the data through only dates.

You need to:
 - Set the filter granularity to "Day"
 - Add a date format "Ymd" admin/config/regional/date-time/formats
 - Add a date type to attach that to...admin/config/regional/date-time
 - OR, just change whatever date type the view is using to use it


Tabledrag in grid shape for media form field widget thumbnails I am looking for a way to change the tabledrag into a grid shape. A nice looking solution for drag-and-drop uploading files and sorting them in a way that jquery sortable does. It should end up to be something like the uploaded thumbnails in Facebook's status update form.

Looks like I'll end up writing a custom solution from scratch like the one here: jQueryUI Sortable + HTML5 File API examples?

Can you show me a starting point or do you know about any work has been done so far?

Plup seems a good place to start altough it looks abandoned.

Additionally there is this wiki page for comparison of similar modules.


Bind payments and auto return a certain amount of it with PayPal I had the idea to create a Drupal site with the feature of bid wars between two users in a certain product.

User A and User B will pay the same amount of money which will be bind in the website. Then both users will have something like a mini game between them and when both users mark the war as finished, both amount of money will moved to one of their PayPal account. Except of a fixed fee percentage.

Example:

User A and User B pay 50$ each of them.
After their "fight", user B wins and he gets 100$ - 2% fee= 98$.

Is there any way to do this automatically with the PayPal module or with another indirect solution?

this would get complicated with paypal .. as only a transaction is refundable .., and no 'payouts' are supported in commerce ..

why don't you convert payments to userpoints, and safe the paypal refund fee. and do the payout of the points on request manually or with massrefunds.com ?


Watchdog and translations Coder says:

The $message argument to watchdog() should NOT be enclosed within t(), so that it can be properly translated at display time.

Does this mean that $message will be translated by watchdog() by default?

As per the core documentation we should use the watchdog function without the t() because it is translating when reading and outputing the log message.

Watchdog invokes dblog_watchdog() in "modules/dblog/dblog.module" and dblog_watchdog() is not translating anything before writing into the database BUT it is translating when reading and outputing the log message.

Reference:

https://api.drupal.org/api/drupal/modules!dblog!dblog.module/function/dblog_watchdog/7
https://api.drupal.org/api/drupal/modules!dblog!dblog.admin.inc/function/theme_dblog_message/7
https://api.drupal.org/api/drupal/includes!bootstrap.inc/function/watchdog/7


Views fields configuration is not working I set a few fields as FIELDS section of a view. the problem is when I click on the fields the Style settings ,No results behavior , Rewrite results and More links are not collapsible . this is the screenshot

what it is like that?

Apparently you're not the only one to encounter this issue. Here are some similar situations:

https://www.drupal.org/node/2151785
Views UI doesn't provide links to expand fieldsets anymore

It appears that no one has found out the solution yet. It doesn't seem to come from jQuery Update or backend theme. However, these advices show up each time:

Make sure that the needed JavaScript file is loaded in the header of the node (collapsible.js)
Perhaps a conflict with another module that would use Views hook. Disable enabled modules one by one and test.

If you find which module interferes with Views or why JS file is not loaded, I think you will make more than one happy people.


Wysiwyg in views module Can I add a wysiwyg field in Views so that users can write and post text on my page?

Would I need to enable this as a block?

I have installed ckeditor and views already.

The only way WYSIWYG works with Views is with either an embedded comment or using the Editable Views module:

  Editable Views lets you create Views where the fields can be edited.
  Fields show both the current value and a form to edit it. A 'Save'
  button allows saving of all the entities shown in the View.

  Editable fields can be added on the base entity as well as on entities
  brought into the View by a relationship. Other, non-editable fields
  may be added to the View, in which case they function normally.


Custom exposed filter with single on/off checkbox doesn't respect the default value and the $_GET parameter I've created a custom filter with a checkbox exposed field in my module.

class my_module_helper_handler_filter_timetracking_children extends views_handler_filter {

  /*...*/

  function value_form(&$form, &$form_state) {
    $form['value'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show subtasks'),
      '#default_value' => isset($this->value) ? $this->value : NULL,
    );
    return $form;
  }

  /*...*/

}

When by default in Views UI settings checkbox is disabled, everything works fine; when it's enabled, it doesn't work. It doesn't respect the default value and the $_GET parameter.

I can't understand this strange behavior of single on/off checkboxes in exposed filters in a view.

I also tried using '#attributes' => array('checked'=>'checked'), but the filter didn't work correctly.

Might somebody can show his code how to create custom exposed filter with single checkbox? Or give usefull link

Views doesn't handle the default checkbox state because when you load your view page for the first time (or if the user clicks the Reset button), the URL doesn't have any parameter in it, so that the $_GET parameter is useless. Here is a complete form definition that will handle the checkbox, whether the URL has parameters or not:

class my_module_helper_handler_filter_timetracking_children extends views_handler_filter {

  /*...*/

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

    $params = my_module_get_params();

    // First time the view is loaded (or user click the Reset button), URL doesn't have parameters
    if(!$params) {
      $value = 1; // checkbox checked by default
    }
    // If URL has parameters
    else {
      // If our filter is present in the URL as parameter and its value is '1'
      if (isset($params['timetracking_children']) && $params['timetracking_children'] == 1) {
        $value = 1;
      }
      else {
        $value = 0;
      }
    }

    $form['value'] = array(
      '#type' => 'checkbox',
      '#title' => t('Show subtasks'),
      '#default_value' => isset($this->value) ? $this->value : NULL,
      '#value' => $value,
    );
    return $form;
  }

  /*...*/

}

function my_module_get_params() {
  global $base_url;
  $query = array();

  $url = $base_url.request_uri();
  $url = parse_url($url);

  if(isset($url['query'])) {
    parse_str($url['query'],$query);
  }

  return $query;
}


hook_node_access not working I am trying to use hook_node_access to change some permissions when viewing a node type.  The problem is that even when I call it in my module, it doesn't work.

function MyModule_node_access($node,$op,$account) {
  die("it works!");
}

I can 100% confirm that other hooks in the same module are working fine.  I have disabled and reenabled the module.  I have cleared all cache.  I can confirm that my test user is not uid = 1, and it does not have the "Bypass content access control" permission.  So why is hook_node_access not working for me?  Does it not work by itself?

I used hook_node_access() and had the same issue: It wasn't firing and driving me nuts.

What worked for me was NOT to be logged in as an admin. I went in as a different role and all worked as expected.


Export and import configuration settings and content I have created two sites. They have the same modules and themes available, however I want them to be complete clones of each other without doing a manual database export and import.

I attempted using Drupal 8's configuration synchronization but I receive the following message

The staged configuration cannot be imported,
because it originates from a different site than this site.
You can only synchronize configuration
between cloned instances of this site.

I've attempted using the Features module. But I don't see an option for exporting and importing to separate sites.

I've also looked at a similar question here Sync content between two Drupal sites
However that applies to Drupal 7.

Is there a way to import and export nodes, site settings, and configurations such as menu items and what modules are turned on or off from one site to another?

UPDATE: I've discovered that I might be able to use configuration synchronization if I get the UUIDs to match, but I'm having trouble running drush on my multisite. Is there a way to manually change the UUID in the database?

See this question and answers on why what you want to do is not possible at the moment.

How to add the configuration changes from a website to another website?


Is there a way to programatically create a commerce coupon fixed amount? I'm using the Commerce Coupon Fixed Amount module to create fixed coupons, which works fine in the interface.  But I'm wondering if there is a way to programmatically create them.
I'm able to create normal commerce coupons with this helpful snippet of code.

Using this tutorial and the above modules/code It makes making a commerce coupon fixed amount (or in this case, a gift card) easier to see.
The only difference between making a regular coupon and one with a fixed amount is that the product (gift card product) price needs to be loaded before hand and the amount of the coupon being created upon gift card purchase needs to load the price from that gift card:

$coupon->commerce_coupon_fixed_amount[LANGUAGE_NONE][0] = array(
'amount'  => $product->commerce_price[LANGUAGE_NONE][0]['amount'],
'currency_code' => $product->commerce_price[LANGUAGE_NONE][0]['currency_code'],
);


Filter criteria according to the get variable user/* have allowed certain roles user pages to been seen by an anonymous user. I have then created a block that displays the latest post of the role user pages.

Is there a way in views to create a filter criteria from the get variable of the anonymous users URL

For example user/30 profile page is requested from the anonymous user. The view gets the id 30 from the url and then sorts the posts in the block view according to that users id

Below I have added some images on the view.

When an anonymous user accesses the authors user profile via the url it needs to display the content the author has created in the block view. The block itself only displays on the user pages by the use of user/* in the block configuration.

I hope this helps thanks again

Here are the steps to achieve your requirement

Go to view and add contextual filter User: uid

Then select 'Provide default value' and select Type : 'Raw value from URL' and Path component: 2 (as URL is user/* .we select second component to get User ID)

That's it. I've tested this and working perfect.

Hope it helps.


How to use Profile 2 with Services? I want to  use Services and Profile 2 together.

Like following json code:

request:

http://localhost/api/user/1

response:

{
  "uid": "3",
  "name": "test1",
  "theme": "",
  "signature": "",
  "signature_format": "filtered_html",
  "created": "1393554511",
  "access": "1393562420",
  "login": "1393562420",
  "status": "1",
  "timezone": "Asia/Chongqing",
  "language": "",
  "picture": null,
  "data": false,
  "roles": {
    "2": "authenticated user"
  },
  "rdf_mapping": {
    "rdftype": [
      "sioc:UserAccount"
    ],
    "name": {
      "predicates": [
        "foaf:name"
      ]
    },
    "homepage": {
      "predicates": [
        "foaf:page"
      ],
      "type": "rel"
    }
  },

  "profile 2 field": "test",
  "profile 2 field2": "test",
  "profile 2 field3": "test",
  "profile 2 field4": "test",
  "profile 2 field5": "test",
  "profile 2 field6": "test"
}

I find some code detail in Services Module :

modules/services/resources/user_resource.inc

/**
 * Get user details.
 *
 * @param $uid
 *   UID of the user to be loaded.
 *
 * @return
 *   A user object.
 *
 * @see user_load()
 */
function _user_resource_retrieve($uid) {
  $account = user_load($uid);
  if (empty($account)) {
    return services_error(t('There is no user with ID @uid.', array('@uid' => $uid)), 404);
  }

  services_remove_user_data($account);

  // Everything went right.
  return $account;
}

It seems services invoke user_load() method to get user's default information.

So I think:

Can I implement hook_user_load() to load Profile 2 fields?

You can use the Services Views module to expose the Profile 2 data you need.

  Views support for the Services module version 3.x and later.

  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

  Demo video http://youtu.be/DZEhJKMeR5w


$scripts variable in drupal 6 adding unwanted script codes From where does the $scripts variable in drupal gets generated? I am getting an unwanted code generated in the html code like this

 <script type="text/javascript" src="/js/js_01770598d5388f7cbcfe786a6df4ef2a.js"></script>

I want to remove that code, for that I need to know the details about $scripts varialble used in tpl file

You should start at template_preprocess_node() where the $scripts variable is initialised:

$variables['scripts'] = drupal_get_js();

Then have a look at drupal_get_js() and follow the functions from there to find out how that mechanism works.

Then have a look at any implementations of hook_page_alter() throughout your site, where the $vars['scripts'] variable might be being manipulated.

Even though that technically answers your question, I'd be surprised if you find what you're looking for there. I've never heard of any malware that specifically targets Drupal (which is what this would be if it's manipulating the $scripts variable).

I'd check the rest of your page source to see if there's some JS being injected somewhere which is adding that <script> tag to the <head> dynamically, just in case.


How do I write migrate group files? I'm trying to create a Migrate group with following code. But it is not detected & listed in admin/structure/migrate. Both migrate plus & Migrate tools modules are installed.  I"m trying to create migration from WordPress tables. The module is called migrate_wordpress & migrate group is defined in config/install with the name migrate_wordpress. migrate_group.wordpress.yml

id: wprdpress
label: WordPress Imports
description: Import from WordPress blog
source_type: Custom tables

What is wrong with above Migrate group configurations? What is the correct way to write an migrate group configuration file in Drupal 8?

I believe that groups are a feature of the migrate_plus module. In order for them to be recognised, the file needs to be named migrate_plus.migration_group.<group_name>.yml. The actual migrations also need to be formatted like this migrate_plus.migration.<migration_name>.yml.

One other issue I see is that your id: wprdpress should be id: wordpress. (Just in case that typo is in your code :) )

The last thing is that migrations are only defined on module install. This means that you have to uninstall and re-install every time. (Or you can implement some drush commands to do it for you. Check out this tutorial.)


Module dependent on field configuration in another module I have two modules that rely on the same field; A simple boolean field that represents a state for taxonomy terms. My problem is my configuration management for this. My ideal situation would be to put this field storage configuration in my site's config directory and then both modules' info files specify a configuration dependency (using the field config's ID) on this field. But I cannot get it working.

This is what I have tried to far in both my module's info files:

dependencies:
  - taxonomy
  - config:
    - taxonomy_term.field_my_field

and

config_dependencies:
  - taxonomy_term.field_my_field

For both of these methods, the field.storage.taxonomy_term.field_my_field.yml file is among the rest of the site's config. I can move it to either module's config/install directories and it makes no difference.

My field's storage config file is as so:

uuid: 8e23dc90-2da9-4824-9783-093181987869
langcode: en
status: true
dependencies:
  module:
    - taxonomy
_core:
  default_config_hash: pr_yX1hCVsd_ni59pjsAQh5n7hCJ2eAnPNzJCBCHJig
id: taxonomy_term.field_my_field
field_name: field_my_field
entity_type: taxonomy_term
type: boolean
settings: {  }
module: core
locked: false
cardinality: 1
translatable: true
indexes: {  }
persist_with_no_fields: false
custom_storage: false

So my question is, what is generally the best practice for managing a single piece of configuration that's required by 2+ modules?

Updating Drush solved my problem...
I went from 8.1.16 which I used deliberately due to it's compatibility with D7 & 8 as I'm still working with lots of 7 sites. After updating to 9.4.0, the field's storage config in the site's configuration directory gets imported no problem.


How to send email using Rules from user references CCK Field? I have 2 types of content that are: Videos and Customers.

A video can be related only by 1 customer. I want that when a video is created or edited, will send an email to the customer associated with the video.

"Videos" has a Node_reference that is the customer reference. "Customers" have a user_reference referencing the corresponding user.

Then, using Rules for send mail but I don't know how to get the email of the user from the field node_reference from "Videos" to user_reference of "Customers".

How can I do this?

In the recipient input, try to write a php code which returns the email :

$customer_node = node_load( $node->field_customer['und'][0]['nid'] );
$account = user_load( $customer_node->field_user['und'][0]['uid'] );
print $account->mail;

Note that a better way is to use a custom function in a custom module :

print _get_customer_email( $node );

and

function _get_customer_email( $node ){
  $customer_node = node_load( $node->field_customer['und'][0]['nid'] );
  $account = user_load( $customer_node->field_user['und'][0]['uid'] );
  return $account->mail;
}


Convert to Entity Query Drupal 8 I want to get the created column from the file managed table of the node field which stores file.Can we have entity query for the same.

SELECT file_usage.id AS file_usage_id, node_field_data.nid AS nid, file_managed_node__field_image.fid AS file_managed_node__field_image_fid
FROM
node_field_data node_field_data
LEFT JOIN node__field_image node__field_image ON node_field_data.nid = node__field_image.entity_id
LEFT JOIN file_managed file_managed_node__field_image ON node__field_image.field_image_target_id = file_managed_node__field_image.fid
LEFT JOIN file_usage file_usage ON node_field_data.nid = file_usage.id AND file_usage.type = 'node'
WHERE (( (node_field_data.status = '1') AND (node_field_data.type IN  ('article')) AND (file_managed_node__field_image.changed <= 1473325611+157766400) ))

You can not query file usage with entity query, it is not entity data.

You can also not do reverse joins or load specific data. Entity query gives you entity IDs, which you need to load, and then from that get the data you want.

Meaning, to do what you are doing in an enitty query, you need to build an entity query that gives you the nodes you want, then load them, then get the referenced file and then get the created value from that.


What is the equivalent of hook_user with $op='form' in Drupal 7 What is the equivalent of hook_user with $op = 'form' in Drupal 7? According to the documentation of hook_user, 'form' means:

  form: The user account edit form is about to be displayed. The module should present the form elements it wishes to inject into the form.

But I couldn't find any equivalent hook in Drupal 7 user.api.php.
Thanks

hook_form_user_profile_form_alter(&$form, &$form_state)
I think its what you need


Implement boolean search in apache solr search I am working on Apache solr search. I want to implement boolean search in apache solr search.

On  google i found following article and many more articles.

I have also seen the hook_apachesolr_query_alter but i have no idea how to implement the apache solr alter function.

If any one have prior information how to implement it, please guide me to achieve it

Here is a basic example of adding an extra parameter to the search query using the hook_apachesolr_query_alter()

/**
 * Implements hook_altersolr_apachesolr_query_alter().
 */
function mymodule_altersolr_apachesolr_query_alter($query) {
  $query->addParam('fq', 'my_field:(value)');
}

Check this page for more possibilities on altering the search query: http://drupalcontrib.org/api/drupal/contributions%21apachesolr%21apachesolr.interface.inc/interface/DrupalSolrQueryInterface/7


Where should I install the LESSPHP compiler? Hello I just bought a premium theme for Drupal. This theme works with the Less css preprocessor module, and I've installed and enabled this module:

The problem is, the site still doesn't look designed, and I get Drupal errors printed to the screen indicating on problems with Less. Thus I went to the themes' suport forum, ran a search and understood I need to download something called "LESSPHP" (A PHP based LESS-CSS comipler I guess) and install it somewhere in my Drupal installment, but I just don't know where and if it even a right step. Moreover, my site also indicated I miss this "LESSPHP" preprocessor at admin/config/development/less:

Where should I install this "LESSPHP" compiler and what else do you think I missed given the errors I see above?

In the Less Processor Module page it says:

  Requirements

  Libraries API

  less.php and unpack it so that
  'lessc.inc.php' is located at
  'sites/all/libraries/lessphp/lessc.inc.php'.

Which means:

1) you need to download and enable the Libraires API module

2) Then you need to download Less.php <-- click here to download it

3) Open the zip file, and grab the lessc.inc.php file only

4) Next you'll need to create some folders in your web directory (create a libraries folder inside the all folder, and a lessphp folder inside the libraries folder) so it looks like this

sites/all/libraries/lessphp/

5) Upload the lessc.inc.php file to the lessphp folder.


how to load 2 services (or more) through dependency injection if i have 1 service, i can load my service through dependency injection like:

class MyForm extends FormBase {

  protected $coreService;

  /**
   * Class constructor.
   */
  public function __construct($coreService) {
    $this->coreService = $coreService;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static( $container->get('arm_core.core_service') );
  }

but now let say i have 2 services, how i load the service through dependency injection rather than globally?

class MyForm extends FormBase {

  protected $coreService
  protected $mainService;

  //then...?

Thank you

The key idea here is that if the class you are using implements the ContainerInjectionInterface, you get passed a container object from which you can get any service you like.  Since FormBase implements this, your form will already be able to do this.

Here's some code from D8's file example, from the Example Module, as an example:

  /**
   * Constructs a new FileExampleReadWriteForm page.
   *
   * @param StateInterface $state
   *   Storage interface for state data.
   * @param FileSystemInterface $file_system
   *   Interface for common file system operations.
   * @param StreamWrapperManagerInterface $stream_wrapper_manager
   *   Interface to obtain stream wrappers used to manipulate a given file
   *   scheme.
   * @param ModuleHandlerInterface $module_handler
   *   Interface to get information about the status of modules and other
   *   extensions.
   * @param RequestStack $request_stack
   *   Access to the current request, including to session objects.
   */
  public function __construct(
    StateInterface $state,
    FileSystemInterface $file_system,
    StreamWrapperManagerInterface $stream_wrapper_manager,
    ModuleHandlerInterface $module_handler,
    RequestStack $request_stack
  ) {
    $this->state = $state;
    $this->fileSystem = $file_system;
    $this->moduleHandler = $module_handler;
    $this->requestStack = $request_stack;
    $this->streamWrapperManager = $stream_wrapper_manager;
    $this->sessionSchemeEnabled = $this->moduleHandler->moduleExists('stream_wrapper_example');
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    $state = $container->get('state');
    $file_system = $container->get('file_system');
    $module_handler = $container->get('module_handler');
    $request_stack = $container->get('request_stack');
    $stream_wrapper_manager = $container->get('stream_wrapper_manager');
    return new static($state, $file_system, $stream_wrapper_manager, $module_handler, $request_stack);
  }

Your create() function calls your constructor, and since you've received a services container, you can ask for whatever and however many services you want.


adding open graph metatags to head Doe's anybody know how to add metatags such as fb:admins or fb:app_id into drupal 7 ?
I use meta tags module for D7 but for some reason theese tags are not included.
Thank you for answers.

The drupal 7 Metatags module has built-in Facebook opengraph support as an add-on module. If your specific metatag is not covered, the Meta tags module allows you to add it manualy.

Although not recommended, if you need custom code for specific pages, you may use the theme's preprocess hook. For example, here is the one I wrote on the preprocess-page.inc file on the preprocess directory of my Omega sub-theme (for other themes, you may need to write the code in a hook_preprocess_page function on template.php):

<?
  // Add og:title and og:description for the front page
  if($vars['is_front'] == TRUE){
    $element = array(
      '#tag' => 'meta',
      '#attributes' => array(
        "property" => "og:title",
        "content" => t("Druvision - Drupal News"),
      ),
    );
    drupal_add_html_head($element,'og_title');

    $element = array(
      '#tag' => 'meta',
      '#attributes' => array(
        "property" => "og:description",
        "content" => t("Druvision is a team of web solution experts focused on enterprise systems, open source development, responsive design and Drupal project management."),
      ),
    );
    drupal_add_html_head($element,'og_description');
  }

  // Add og:image
  global $base_url;
  $img =  $base_url.base_path() . drupal_get_path('theme', 'MYTHEME') . "/logo.png";
  if($vars['is_front'] != TRUE){
    if(isset($vars['node']->field_image['und'][0]['uri'])){
      $img = file_create_url($vars['node']->field_image['und'][0]['uri']);
    }
  }
  $element = array(
    '#tag' => 'meta',
    '#attributes' => array(
      "property" => "og:image",
      "content" => $img,
    ),
  );
  drupal_add_html_head($element,'facebook_share_image');
?>

Note: The question is old, but I've found it in search so other people are looking for it, so I answer it for the completeness of this thread.


FontAwesome character added via CSS only appears when logged in I'm pretty new to Drupal and CSS; I'm stumped with this issue. I have a FontAwesome camera character that I've written to appear before my caption div in Flexslider. Here's what I have:

div.flex-caption:before {
    content: "\f083";
    font-family: fontawesome;
    margin-left:10px;
    padding: 10px;
}

This works fine when I'm logged in as a user to the site, but the icon doesn't appear if I'm not logged in to my Drupal site. Not sure why—any ideas? I'm using Drupal 7.31

Edit: Just to clarify, all other FontAwesome characters are working fine. It's just this particular bit of code that isn't working.

Is it possible that your CSS rule is in the CSS for your administrative theme (by default "Seven"), but not in the theme for your public (non-logged-in) users (by default "Bartik")?

If so, you need to copy this CSS fragment into the public theme too.


Submitting a form with AJAX causes page reload but only on mobile I am submitting the user profile edit form by hooking the user profile edit form like this:

$form['actions']['submit']['#ajax'] = array(
'callback' => 'user_profile_submit',
'wrapper' => $form['#attributes']['id'],
'method' => 'invoke',
'effect' => 'fade',
);

The callback function user_profile_submit invokes a simple jQuery alert notification specifying if the form was saved successfully. The setup works perfectly on the desktop i.e. the form is submitted with AJAX with no page reload whatsoever. However, saving the same form using mobile devices causes always a page reload. Any idea what might be causing this behavior? Thanks.

Update:

Problem can be observed in Chrome/Dolphin but not in Firefox.

Solved:

I have just downloaded the latest development version of jQuery Update module and the problem was solved. It has to do with this module nothing else.


Drupal Form Suffix + Suffix As a href + pop up the drupal users listing with checkboxes by click on that link I have requirement like ..

I have to put one link in the  Drupal Form, That i achieve with using suffix while creating Drupal form..

Now I want to pop up the list of all drupal users & their email ids with checkboxes by on click that Link..

now if i choose the check box in front of particular user .. the name of the users with semicolons replace that link that i made with suffix..

so how to achieve that...? Any suggestions guys..?

What you need is pretty much a huge select box :)

i can think to a couple of different approaches, but to mention one, i would proceed like this

Create your form and set the default values obviously.
At the end of your form add a  that will wrap around the list of possible choices
Target that  with the show/hide script triggered by the click on the link.
Create the list, using either a table or several divs, as long as you give each row an #id, something like
user-$uid".
since you are here you can even set a class for the rows that will highlights the row on hover.
Split each row into, assuming tables, cells and populate the table with the user data you need.
give each cell the same #id of its row, extend with something else to obtain things like

"user-$uid-mail"
"user-$uid-name"
I would avoid the checkboxes and go with an onClick event on each row, that calls a function passing the row #id as parameter.
The function will, hide the list, use the row #id to read the values of the fields, like

document.getElementById("user-$uid-name").value

and write the values inside the form elements.

profit.
i may have typed some function wrong, but that's the idea


Create a webform which creates a user account I'm looking to create a user registration form on a Drupal 8 site that has multiple clearly defined sections (possibly on separate pages).

I've explored doing this with the standard Drupal registration form building tools in account settings but it doesn't seem possible to create a form with such a layout using just account settings (correct me if I'm wrong).

The webform module allows me to create a form which is styled exactly how I want but I'm not sure how to create a user account with data entered into a webform. Is there another module I can use for this or can I do it from within the webform module?

There is a module for that.

Forms Steps provides an UI to create forms workflows using forms modes. It creates quick and configurable multisteps forms.


SMB shared video files from Windows to Linux So, this might be more of a general Linux question, but I've tried everything I can think of with permissions, andI'm having the issue in Drupal, so I'm hoping someone here has an idea.

What I want to do: Use the Video module to play video files from a shared network folder; the folder is on a Windows Server 2012 system. (I realize the Vide module is geared towards uploading files, but if I manipulate the uri in the file_managed tables, I can change it, so I'm going to use the module to add the content, then edit the uris accordingly.)

1) Video defaults to the files/default/videos/originals folder for storing uploaded videos
2) I mounted the network folder at files/default/videos/originals/movies
3) Then I changed the uri for the video file to point to the mounted network folder

Now, I can change the uri to other local directories, and it works fine (I even had a symlink at one point leading out to my own user directory), but whenever I try to play the file (with the DivX player, since it seems to be the only one I tried that gives me an error message, instead of just hanging), I get a 403 error.

I've set the group and user of all involved to apache (and using ls -l, that seems to have been set), and my mount command in /etc/fstab is listed below

\\192.168.0.3\movies /var/www/html/sites/default/files/videos/original/movies cifs uid=48,gid=48,ro,suid,username=userName,password=passWord 0 0

(I used uid and gid because if I tried user and group, nothing happened.)
I've been fighting with this for hours, and I have no clue. Thanks for any help.

Running the following code from within Drupal returns nothing, but running the exact same code after placing it in "file.php", and calling "php file.php", and it returns the files in the directory fine.

glob('/var/www/html/sites/default/files/videos/original/movies/*.*')

I could really use some help with this.

Found the problem! It has to do with SELinux. After looking at the folder with

ls -Z

And seeing that files that were accessible had a context that the folder didn't (httpd_sys_rw_content_t), I disabled SELinux with

sudo setenforce 0

and I was able to access the files. Of course, I have more work to do, and I don't intend on keeping it turned off, but this at least shows me where the problem is. Wu!


Get Last Register User's ID I am trying to retrieve the details of the last user who registered to the site. There is a similar question here: How to get the uid of a newly created user?
but it assumes that the registration is also done programmatically, while I don't have any such assumption.

The only way I saw how to do it was to go to the DB directly (not recommended by basically every resource I read). Is there a way to do this through some other interface?

You don't need to query the DB directly, you can use an entity query:

$uids = \Drupal::entityQuery('user')
  ->sort('created', 'DESC')
  ->range(0, 1)
  ->execute();
$uid = reset($uids);


How to change the default variant globally? Is there a way to change the default variation (e.g. size, color) for thousands of Drupal Commerce products on a site? I found the Commerce Default Product Variant module that does it on a per-product basis, but I need to do it globally.

I am open to doing it directly in MySQL if it won't break anything, but I am not sure how to do so at the moment.

Typically speaking, the default product variation is the first value in the reference field. You can see this in action on a vanilla install by creating a product display that references multiple products and switching the order of the SKUs in the product reference field (easiest if you're using the autocomplete widget). I doubt there's a way to change the order of your field values en masse, and I'm not sure there's a safe SQL query we can pass on to you.

However, if you're similarly open to writing custom module code to solve this, you can do so using hook_commerce_product_reference_default_delta_alter(&$delta, $products). The products variable will be an array of the fully loaded products on the display and the delta value will be initialized to the first one and available for alteration. You can inspect the field values of the products in the array to find the one whose attributes match what you want the default variation to be and update the delta accordingly.

(If you just wanted to write a script to actually update the storage instead of doing this on run-time, you'd want to process your product displays one at a time and do a similar product load / field value inspection to move the items around in the reference field's values so delta 0 was your desired default variation.)


Drupal doesn't output list of children on custom module page I am on Drupal 7. I want to create a page that lists its children, the same way you see the list of links in 'admin/structure' (Blocks, Content types, Entity types ...).

I have modified child 1 and child 2. They aren't really important for this example.

on mymodule.module I have inside function mymodule_menu():

  $items['admin/mymodule'] = array(
    'title' => 'My module parent page',
    'page callback' => 'mymodule_admin_page',
    'access callback' => 'mymodule_admin_list',
    'access arguments' => array(1),
    'file' => 'mymodule.admin.inc',
  );

  // Child 1
  $items['admin/mymodule/child1'] = array(
    'title' => 'Child 1',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_something_01', 1),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'mymodule.admin.inc',
  );

  // Child 2
  $items['admin/mymodule/child2'] = array(
    'title' => 'Child 2',
    'page callback' => 'drupal_get_form',
    'page arguments' => array('mymodule_something_02', 1),
    'type' => MENU_NORMAL_ITEM,
    'file' => 'mymodule.admin.inc',
  );

Then, on mymodule.admin.inc, I have this function:

function mymodule_admin_page() {
  $item = menu_get_item();
  if ($content = system_admin_menu_block($item)) {
    $output = theme('mymodule_admin_list', array('content' => $content));
    // This gets printed on the page
    drupal_set_message('This gets printed on the page');
  }
  else {
    $output = t('You do not have any administrative items.');
    // This doesn't get printed on the page because my base page has children.
    drupal_set_message('This doesnt get printed on the page because my base page has children.');
  }
  return $output;
}

Finally, according to documentation I have read, I should add a function like the one below:

function theme_mymodule_admin_list($variables) {

  $content = $variables['content'];
  $output = '';
  // This doesn't get printed on the page...
  drupal_set_message('this doesnt get printed... Why???');

  if ($content) {
    $output = '
';
    foreach ($content as $item) {
      $output .= '
' . l($item['title'], $item['href'], $item['localized_options']) . '
';
      $output .= '
' . filter_xss_admin($item['description']) . '
';
    }
    $output .= '
';
  }

  return $output;
}

Check my drupal_set_message above. Messages on function mymodule_admin_page get printed, but messages on theme_mymodule_admin_list don't get printed... Actually, admin/mymodule responds as a page, but instead of displaying links to its children, it will display a blank page...

I must be missing something, but I really don't know what. Thank you!

========

SOLUTION

I am posting the solution below. Thank you, Geoff, for your comment. It did the trick! I was missing one of the pieces in this puzzle, which was the mymodule_theme function.

function mymodule_theme($existing, $type, $theme, $path) {
  return array(
    'mymodule_admin_list' => array(
      'variables' => array('content' => NULL),
      'file' => 'mymodule.admin.inc',
    ),
  );
}

Another Solution here would be to do what the admin pages do for those pages

$items['admin/somemodule'] = array(
 'title' => 'My Module Section',
 'description' => 'Manage My Module',
 'page callback' => 'system_admin_menu_block_page',
 'access arguments' => array('access administration pages'),
 'file path' => drupal_get_path('module', 'system'),
 'file' => 'system.admin.inc',
);


Get view result depending on pager url In drupal 7 ,this returns the results of the view first page, if using a pager:
Is there a way to get the results depending on the page? (depending on url argument maybe?)

$result = views_get_view_result('viewname', 'displayname');

I didn't test the code. But you can use this code.

$page = 1;
$view = views_get_view('payment_schedule_students');
$view->set_display('payment_schedule_students_select');
$view->set_current_page($page);
$view->execute();$view->result;

Where you can set the $page variable from the url.


strcmp() expects parameter 2 to be string error on configuration and system status page I am getting the following error on the configuration and the system status page:

Warning: strcmp() expects parameter 2 to be string, array given in
_system_sort_requirements() (line 2805 of   /srv/bindings/00fd0ded5def4c8289075262cb552d75/code/modules/system/system.module).
Warning: strcmp() expects parameter 2 to be string, array given in _system_sort_requirements() (line 2805 of /srv/bindings/00fd0ded5def4c8289075262cb552d75/code/modules/system/system.module).
Warning: strcmp() expects parameter 1 to be string, array given in _system_sort_requirements() (line 2805 of /srv/bindings/00fd0ded5def4c8289075262cb552d75/code/modules/system/system.module).
Warning: strcmp() expects parameter 2 to be string, array given in _system_sort_requirements() (line 2805 of /srv/bindings/00fd0ded5def4c8289075262cb552d75/code/modules/system/system.module).
Warning: strcmp() expects parameter 1 to be string, array given in _system_sort_requirements() (line 2805 of /srv/bindings/00fd0ded5def4c8289075262cb552d75/code/modules/system/system.module).
Warning: strcmp() expects parameter 2 to be string, array given in _system_sort_requirements() (line 2805 of /srv/bindings/00fd0ded5def4c8289075262cb552d75/code/modules/system/system.module).
Warning: strcmp() expects parameter 2 to be string, array given in _system_sort_requirements() (line 2805 of /srv/bindings/00fd0ded5def4c8289075262cb552d75/code/modules/system/system.module).
Warning: usort(): Array was modified by the user comparison function in system_status() (line 2351 of
/srv/bindings/00fd0ded5def4c8289075262cb552d75/code/modules/system/system.admin.inc).

Has anyone seen this before?  It's something to do with core but I have no idea what's caused it.

It looks like this issue can occur if two modules return the same array key from hook_requirements?

Here's a similar result affecting LinkedIn Integration:

#1711604: On installation errors reported from system.module and system.admin.inc

According to that issue, this will happen if two separate modules add a requirements check with a key of curl. The solution is to namespace requirements checks (use a key of linkedin_curl, simpletest_curl and so forth).

You could debug this and check the issue queue for the affected module(s).

Disabling the most recently added modules might help you identify the cause (see if the symptom goes away).
If you still feel stuck and don't feel able to dig further, try updating your question with the list of enabled modules on your site. That may help narrow it down.
If you're running all contrib modules, googling for "strcmp _system_sort_requirements drupal" might show results that help you identify the affected module.
If you have Drush + Devel module, try drush fn-hook requirements to see which installed modules are implementing hook_requirements.
Or just start hacking on your system settings page and trace the problem down old-school :)

If this is the cause, once you identify the module(s) causing the issue you should check the issue queue, file an issue if none already exists, and help be a part of getting it fixed!

I've tagged several affected modules in #933684 - Same requirements from different modules causes warnings in _system_sort_requirements()


Custom formatter for paragraphs field I want to build a custom formatter for a paragraphs field that renders some of the fields of the paragraph. However, I don't know how to access the single files of the paragraph field.

So far I've only written the skeleton of the formatter, but it doesn't do much, except that I can return a serialised string of all of the entire field, which does include the necessary information, but I only need three particular fields rendered themselves in a nice way (a term reference field with a label, a boolean field as "yes" or "no" and a text field. A Twig template is not an option for this.

The function looks like this:

public function viewElements(FieldItemListInterface $items, $langcode) {
  $element = [];

  foreach ($items as $delta => $item) {
    // Desired fields: field_network_name, field_network_specific_site_code, field_network_verified

    $element[$delta] = [
      '#markup' => "Output: " . serialize($item)
    ];
  }

  return $element;
}

I'd need to know how to elegantly access the fields inside $item.

Thanks to the comment above I was able to find a solution. This function allows to access three fields within a paragraph (term reference field, text field, boolean field).

public function viewElements(FieldItemListInterface $items, $langcode) {
$element = [];

  // Render each element as markup in case of multi-values.
  foreach ($items as $delta => $item) {

    // Desired fields: field_network_name (term reference), field_network_specific_site_code (text), field_network_verified (boolean);
    // this return the termID
    $network_name_tid = render($item->entity->field_network_name->target_id);
    // this termID is used to load the term object
    $full_taxonomy_term_object = taxonomy_term_load($network_name_tid);
    // then you can get the name of the term, or any other information about the term
    $network_label = $full_taxonomy_term_object->getName();

    // getting the values for the text and boolean fields is more straightforward
    $network_site_code = render($item->entity >field_network_specific_site_code->value);
    $network_site_verified = render($item->entity->field_network_verified->value);

    // in the end you put them together, have conditions and format them as you need
    $element[$delta] = [
      '#markup' => $network_label . $network_site_verified . $network_site_code
    ];
  }

  return $element;
}

However, the problems of hard-coding something like this persist. Even though this can be tackled by having the right failsaves in place.

Edit: You don't need the "render" either. Addtionally, the "render" causes a notice in the system logs. I also stumbled upon this useful cheat sheet: https://www.metaltoad.com/blog/drupal-8-entity-api-cheat-sheet


Tournament or competition module I'm running Drupal 7.2 web site embedding a multiplayer card game and am looking for a module, which would help me to run a tournament between users.

It should at least show a list of participants and a tree of games with 3 players and 1 referee.

I've searched around already and suspect there is no such module waiting for me (surprise suprise), so my question is more about how would you try to program such module yourself or maybe adapt some core module (seemingly there aren't many non-core modules for Drupal 7).

I have a bit experience in programming custom blocks and menus. I've read, but haven't understood the documentation on programming nodes yet.

You will need to create a custom module to do this. Not having experience with Drupal development it will be hard.

Since you are doing this in Drupal 7 you should not use nodes for this, but instead create your own entity. It takes a bit of extra effort, but it will help you, as you can design your entity to fit your needs. The entity API will help you do create an entity without having to think about much of the boring CRUD stuff.

You will also need to define a database table, where you entities can be stored, you will need a unique identifier, store the participants and the referee, the outcome and other useful data like when the entity was create, when the game was held etc.

Using the entity API module you can also create views integration for you entity which will allow you to display lists of games, like the 5 most recent and those sort of things, For displaying a tree of games you might need to do some custom coding. I'm guessing you want to display a tournament style list, which won't be easy. If that is the case you'll need to create some relationship between the games and use advanced CSS to create the display you want.


Custom text output for entity reference fields In my content type I have an entity reference field. With this field editors can create internal links effordlessly with the autocomplete function.

What I want to achieve is that editors can now customize the text to output the referenced node. E.g. The editor creates a reference to a node and in a different field creates the "title" of the reference, she has just created. Thus references can have custom display titles.

I have tried the token formatters module (http://drupal.org/project/token_formatters) but to no avail.

In my particular case I have a field reference_text and have set the format of my entity reference field to "Tokenized text". In the "Text to output" field I have tried the following:
1) [node:reference_text]
2) [current-page:reference_text]

With 1) an empty field is displayed. With 2) I get an error message: Text output uses the following invalid tokes: [current-page:reference_text]

Not sure what else to try. Any help would be greatly appreciated. Big thanks in advance.

Two different options here (there are probably more!):

Use the linkit module in combination with wysiwyg and, say, the tinyMCE editor. This allows users to insert node reference links into wysiwyg text areas.
a.  Create a textfield for the link text in addition to the entity reference field.

b.  In the template file for the content type (node--CONTENT_TYPE.tpl.php), output the links manually, something like:

$path = 'node/' . $node->YOUR_ENTITY_REF_FIELD['und'][0]['target_id'];

$link_text = $node->YOUR_LINK_TEXT_FIELD['und'][0]['value'];

print l($link_text, $path);


Help with event signup module I'm looking for a module that allows registered users to signup to events with a few options. I found the "Signup Module" but I can't figure out how to make it work, at least to try it out. So two questions:

Does the Signup Module allow for getting different input depending on the event type? For example, if an event is a dinner, I would need to get the menu choice and any dietary requirements.
If the above is a yes, how can I make it work? I can't find much documentation around and I'm still a Drupal newbie. If the above is no, can you please recommend a more adeguate module?

Thanks in advance for any hints!

I think you can use the Signup Module for this. The Signup form itself can be modified and changed for your needs. Have a look at the file signup_form.inc in the signup/theme folder. Copy the theme_signup_user_form($variables) function to your template.php in your theme and start modifying the form.


Getting current node id in views I'm on drupal 8, and I'm trying to figure out how to get the current node id in an override of views-view-unformatted.html.twig.

I have a view filled with titles with added links and I want to add a class to the one the corresponds to the current node id.

You'll find the node id from each row in _entity:

{{ row._entity.id }}


Roles are not correct while getting it in hook_user I have added a new role called pre-auth i.e. if a user is registered and has not clicked the confirmation link(using LoginToboggan module) from the mail and the other is authenticated role its the normal authenticated role. I have a hook_user to check the role but it gives me as "authenticated user " always but in admin/user/user/ it shows the role as  "pre-auth"

function mynewmod_user($op, &$edit, &$account, $category = NULL){
  switch ($op){
  case 'insert':
  case 'after_update':
    $user_details = user_load($account->uid);
    drupal_set_message('<pre>'. print_r($user_details->roles, true) .'</pre>');
}

Can any one tell me how can I get the exact role.

The variable $account already has the loaded user object. Calling $account->roles will give you an array of roles.


Access item url in views-view-fields.tpl.php I'm using views-view-fields.tpl.php to theme the output of a content type.

What I need to do is the below, except I don't know how to get 'url_for_this_item' without either printing all the variables and referencing it in a long array lookup, ie like $fields[smth][ddd][0][44][ui][uri].

Is there a simple, clean way to get the url in the template?  I have tried outputting a link but then views still insists on giving the full link with an closing tag on the end.  Of course, I can parse this and remove the closing tag but it just seems too hacky.  Is there not a better way?

print '';
    print $fields['title']->content;
    print $fields['field_this']->content;
    print $fields['field_that']->content;
print '';

I want to to get the url for

If I understood it right, you can simply add a new field in Views which holds the URL to the item. And then in the template file you can print this field as you described in you question.


How can I hide certain values of CCK on node view page? When a cck field can have multiple values I would like to hide certain values to print on node template.

For example,
If field_example has the value "red" "blue" "yellow" "black" "white"  I need to hide "black" and "white" and print only the rest on template file.

You can use the Field Permission module. It allows to give different access rights to different roles per field.


How to display block with term image field when viewing term node I'm using the default Taxonomy term view in drupal 7.
I have Vocabulary: Portfolio with terms: Wedding Photos, Kids Photos, Other Photos. And I want to show a block of the term image field when a specific term is visited.

similar to this ( Add taxonomy term image to a view )

But because there are many content types in the same category the block is showing many term image fields instead of just one.
I try different Contextual filters and Relationships and Query settings: Distinct. But no result so far.

I found my error: In the Format: Settings I had Grouping field N1 selected with the category term image field, which caused the duplication of the image.

Contextual Filters: Content has taxonomy term ID (with depth), Depth:0, Provide Default Value: Taxonomy term ID from URL > Load default filter from term page
Relationships: Entity Reference: VocabularyName - Require this relationship
Fields: Taxonomy Term - the term image field - using Views Distinct I select Filter Repeats


Template tpl File Naming Question I am currently assigning a theme using hook_custom_theme and just allowing the pathing system for .tpl files to override displays that I want to edit by using custom .tpl files. I CANNOT find the correct file name for this path:

(base url)/admin/content/node/article   <-- Where in admin, it is displaying all node content types of 'article'.

I think I've tried every combination possible of page, node, article, admin... think I'm going crazy, please help. Other overrides are working just fine. Thank you for sanity check!

Isn't your admin theme uses a different template.php? I am assuming you try to theme /admin/content/node/article. If so, your active admin theme is where your override should go.


How do we stop the heartbeat module from recording node update activity for certain specific content types we have created? How do we stop the heartbeat module from recording node update activity for certain specific content types we have created?

We created a content type that collects voting information. When a user votes, a new node is created or an existing node is updated for this content type.

The heartbeat module seems to be recording this event and creating a new activity. In Drupal Commons this activity is displayed in a block called the "Recent Activity" block. We would like to avoid having this update to our "voting" content type from being recorded as an activity, and being shown in the "recent activity" block.

How would we do this?

seems like you use D6 since you mentioned Commons. I've only used Heartbeat in D7. Click on the "heartbeat streams" settings and you have an option for "Choose message types you want to deny from display". There you can select the ones you do NOT want to record. Repeat that for each of the streams.

Also, checkout the "heartbeat templates" for "add_node" and "edit_node", there is an option "Disable the message - Defines whether this message template is disabled from logging and viewing."


Autoload files by patterns instead of listing each file Drupal's "autoloading" requires one to include the files in files[] declarations in the .info file.

When there are a lot of files, this becomes:

A large, huge, list.
Hard to maintain.

Is there a way to e.g include with patterns. Say lib/*.php?

You can potentially use hook_registry_files_alter along with the PHP directory functions.  Something like

function foo_registry_files_alter (&$files, $modules)
{
  $include_path = drupal_get_path('module', 'foo') . '/includes';

  if ($handle = opendir($include_path)) {
    while (($entry = readdir($handle)) !== FALSE) {
      if (preg_match('/\.php$/', $entry) === 1) {
        $files[$library_path . $entry] = array(
          'module' => 'foo',
          'weight' => 0,
        );
      }
    }
  }
}

This is untested, but the idea is to use scan an "include" directory for PHP files, and then tack them onto the array that the class registry uses for the autoloader.  This should work, but I can't remember exactly what readdir() returns, so you may need to adjust the paths a bit.


hook_field_extra_fields on node types stored in variable I am developing a module. It adds a button to certain content types:

function mymodule_node_view($node, $view_mode, $langcode) {
  ....
  $node->content['mymodule_button'] = drupal_get_form(....);
}

I give the option to configure what content types must have this button:

function mymodule_admin_settings() {
  ....
  $form['mymodule_node_types'] = array(
    '#type' => 'checkboxes',
    '#options' => $options, //node types
    '#default_value' => variable_get('mymodule_node_types', array()),
    .....
  )
  return system_settings_form($form);
}

I want to configure the weight of the button through the 'manage display' page of each content type. For that I use the hook_field_extra_fields() implementation:

function mymodule_field_extra_fields() {
  $extra_fields=array();
  $mymodule_types = variable_get('mymodule_node_types', array());
  .....
  $display_elements['mymodule_button'] = array(
     ...
    'weight' => 0,
  );
  foreach ($mymodule_types as $type) {
    $extra_fields['node'][$type]['display'] = $display_elements;
  }
  return $extra_fields;
}

I need when the admin changes the content types in the configuration page, the 'extra fields' will be shown only in the content types selected, not in the other ones. This function is not working this way with this code.

hook_field_extra_fields is invoked by FieldInfo::getBundleExtraFields. This method caches the extra fields info in the database.

cache_set("field_info:bundle_extra:$entity_type:$bundle", $info, 'cache_field');

So you want to empty cache when the affected bundles changes. That is, add a custom submit callback for mymodule_admin_settings() and check what bundles changes over the previous settings.

Tip to Empty the cache:

$cid = "field_info:bundle_extra:$entity_type:$bundle";
cache_clear_all($cid, 'cache_field', true);

You may prefer to empty the cache for all bundles. In this case, $cid is the common prefix for all bundles:

$cid = "field_info:bundle_extra:$entity_type";


Passing a contextual filter value to a view via a link with entityreference prepopulate? I have two content types, Ad and Reply (think of how posting works on Craigslist for the Ad, and the Reply is an on-site form to reply).  I am using Entity Reference Prepopulate to automatically create an entity reference back to the Ad when users click a link to make a Reply.  The link looks like this:

  node/add/reply?field_reply_orig_node=NID

Where NID is the node ID (filled in with a token using Panels).

Using Panels, I'd like to display the original Ad on the Reply edit page (to make it easier for users to write their message.  I have overriden the node edit page (using Page Manager) and I added a view that has a contextual filter (NID).  However, I don't understand how to pass a value for NID to the content pane using the reply link.

Ideally, I could make use of the ?field_reply_orig_node=NID that is already present in the link (how?), but if that is not possible, I could rewrite the link in Panels.  I just don't understand how to rewrite it so that the contextual filter can pick up the value.

One solution would be to add a custom panel to a panel page overriding the node edit form.

To do so you'll want to go into Panels Page Manager (/admin/structure/pages) and enable node_edit adding a variant that uses context to evaluate Node: type where Node being viewed is type "Your Content Type"

Then go into the panel page content section and choose "New Custom Content" from the panel selection dialog.

In the dialog that opens, makes sure to choose and input format that allows hyperlinks.

Make sure "Use context keywords" is checked and in the substitution choices you'll see %node:nid

You can use this to build the url:

Reply


set field value from function after user account edit/registering action I need to assign one custom field value from user profile. One field is nickname (this field is filled by user) and I need to generate another field with function.

The function takes nickname and using external library takes this nicknames ID. I need to run one function and save this ID everytime new profile is saved or existing updated.

I can not find good way to do it.

I tried with Rules module setting event after account updated with action evulate value with php, but there i can not load my api library to do the function.

Any information will help me

Have you tried hook_user_presave() ?

https://api.drupal.org/api/drupal/modules!user!user.api.php/function/hook_user_presave/7

You have access to all fields of your new user and can pick up your value, call your custom code and get your new id. Then add it wherever you need to.

Use dpm($account) to inspect your user object.(devel module)


How to make hook in custom module to execute only on condition How to make contributed module hook execute only if conditions are met. Those functions seem to get automatically invoked. Environment is a custom module.

examples:
1.

if ($condition) {

   function mymodule_modulename_alter ($parameters) {
     //altering code here
   }

}

2.

    if ($condition) {
           //if condition is met, i call the function included in this custom module
           mymodule_modulename_alter ($parameters)
      }

  function mymodule_modulename_alter ($parameters) {
         //but this function will get auto-invoked! I want it run only if $condition is met.
       }

Thanks

Let the hook be called, but put your operations(that your hook executes) inside your required condition.

function mymodule_modulename_alter($parameters) {
  if ($condition) {
    // Your code.
  }
}


Can I recreate content types via db tables only? My D7 (7.18) got corrupted, but just about functioned. However, I couldn't update modules, core or anything, so I took as many backups as I could and did a clean install of 7.24.

I'd like to recreate the custom content types and content I had in the old system (there's a lot). Can I import specific tables into the new MySQL db (from a MySQL export) and expect Drupal to pick it up ok?  If so anyone know which tables I should bring in/merge.

Otherwise anyone got any suggestions for how to recreate content without a few weeks worth of cut+paste?

Thanks
Sparks

If you have a full backup, you could get the old version running locally.

Then

Content: Migration (http://drupal.org/project/migrate) or Feeds (http://drupal.org/project/feeds)
Content Types and other code-ish stuff: Features http://drupal.org/project/features


Image array on a node page Is there a simple way to add an array of images to a node page?

I would be using the file directory that I am using to upload my images to, using IMCE (sites/theme/files). The array would return all the images I have stored in that folder. I just need a very simple solution, being very new to PHP.

Are you using Drupal 6, or Drupal 7? You should look into the Content Construction Kit module, which would easily allow you to add images to nodes and arrange them. You can set the number of allowed elements to "unlimited" for multiple images.  If you want to be able to place your node images on different parts of the node page, try the Panels module.

Update in answer to first question, below

Why yes; one of the great strengths of Drupal is its ability to let you just plop down some php anywhere in the page you need to put it (but please, don't put your php in the database, if you can help it!).  If all you wanted to do was display images from a folder at a given URL, rendered in your own code, all that you would need would be a menu with 'page callback' set.  If you want to modify a node, though, then you will need to learn about the scary render array.  When you find something in the page that you want to change, the easiest thing to do is to set the #markup element to the exact HTML content you want to display. If you do not want to replace an element, you can use #prefix or #suffix to put HTML before or after the given item.

If you make yourself a theme, you can add a preprocess hook to it (in template.php):

function MYTHEME_preprocess_node(&$variables, $hook) {
  if ($variables['node']->type == 'page') {
    $variables['content']['field_document_file']['#prefix'] = '
';
    $variables['content']['field_document_file']['#suffix'] = '
';
  }
}

This snippet, simplified from the above-quoted article on render arrays, adds a div around the CCK field called 'field_document_file'.  In your case, you'd probably just want to put some HTML into #suffix after the node body, which I believe is simply $variables['content']['field_document_file']['#suffix'].  To find out what's in a render array, install the devel module, and add a dpm($variables) to your preprocess function.  You're also likely to find the search krumo module to also be highly useful.

As far as actually getting the images onto the page, I trust that you can write your own code with file_scan_directory. Just remember to write secure code when outputting any data that was supplied by the user.

Anyway, that is what you would do; in general, just adding cck image fields and populating those with the images you currently have stored in folders might be easier.  drush entity might help out here. If you have a special need to keep your images in folders, then it's render arrays for you.

An easier option might be to just put your php code in a node-page.tpl.php. I rejected this as an option at first because I felt it would not give you enough flexibility to position your elements in the html output. However, with node-page.tpl.php, you could put your images before or after the node contents, and perhaps adjust the positioning to your satisfaction with css. This would be easier than fixing up the render array.


Add drush alias with arguments I'm working with drush & git and I would like to create a custom drush alias to perform a "git pull" action on a remote server.

This is possibile creating a drushrc.php file in drush home directory with this command:

$options['shell-aliases']['git-checkout'] = '!git checkout';

So if I run

drush @mysite.test git-checkout

the system performs a "git checkout" on the test server.

The problem is that I would like to send parameters, like:

$options['shell-aliases']['git-checkout'] = '!git checkout %branch';

and so:

drush @mysite.test git-checkout my_custom_branch

should checkout a specific branch.

Is there a way to do this?

Drush will pass any extra argument in the shell alias to the command. So define the shell alias as:

$options['shell-aliases']['git-checkout'] = '!git checkout';

and simply run

drush @mysite.test git-checkout my_custom_branch


How to add icons to a menu? I use Drupal 8.

I would simply want to add icons to one of the menus with a <span>.

Have you runways?

This is how I'm doing it for dropdown operations(Font Awesome icons).

/**
 * Implements hook_preprocess_links().
 */
function HOOK_preprocess_links(array &$variables) {
  if (stripos($variables['theme_hook_original'], 'links__dropbutton__operations') === 0) {
    $variables['attributes']['class'][] = 'menu';
    $links = &$variables['links'];
    foreach ($links AS $key => &$link) {
      switch (Html::getClass($key)) {
        case 'view';
        case 'canonical':
          $icon = 'eye';
          break;

        case 'edit':
          $icon = 'pencil';
          break;

        case 'delete':
          $icon = 'trash';
          break;

        case 'clone':
          $icon = 'clone';
          break;

        case 'add':
        case 'create':
        $icon = 'plus';
          break;

        case 'manage-fields':
          $icon = 'list';
          break;

        case 'manage-form-display':
          $icon = 'server';
          break;

        case 'manage-display':
          $icon = 'th';
          break;

        case 'devel':
          $icon = 'code';
          break;

        case 'pay':
          $icon = 'money';
          break;

        case 'enable':
          $icon = 'toggle-off';
          break;

        case 'disable':
          $icon = 'toggle-on';
          break;

        default:
          $icon = 'question';
          break;
      }

      $link['link']['#title'] = [
        '#type' => 'inline_template',
        '#template' => '{{ title }}',
        '#context' => [
          'title' => $link['link']['#title'],
          'icon' => $icon
        ]
      ];
    }
  }
}


Changing value of min / max resolution for an image field dynamically based on a previous select list Does anyone know if there is a way in Drupal 7 to change dynamically the value of minimum / maximum resolution for an image base on a previous select list.

Example :

I have a select with 3 elements :

Square
Portrait
Landscape

When I select Square, the min / max resolution would be set to 200x200, if Portrait 200x400 and landscape 400x200.

I could create 3 different image field but in the future I'll have more type of layouts and I'd rather have only one image field (for database and theming purpose)

I was thinking State API but no solution there.

I came up with a good solution using #ajax property from the Form API :

I declare hook_form_alter and add the #ajax on my push type select field.

/**
 * hook_form_alter
 */
function my_module_form_node_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'push_node_form') {
    // Add id to field image for ajax reload
    $form['field_push_image']['#prefix'] = '
';
    $form['field_push_image']['#suffix'] = '
';
    // Create ajax reload function
    $form['field_push_type'][LANGUAGE_NONE]['#ajax'] = array(
      'callback' => 'reload_image_field_resolution',
      'wrapper' => 'image-field-to-reload',
      'method' => 'replace',
      'effect' => 'fade',
    );
  }
}

Then in the field settings I put a resolution as a key from the select list like this :

200x200|Square

200x400|Portrait

400x200|Landscape

And then I reload the image field with the proper resolution base on the select value key.

/**
 * Ajax callback to reload the image field
 */
function reload_image_field_resolution($form, $form_state) {
  // Get the value of the push type
  $type_value = $form['field_push_type'][LANGUAGE_NONE]['#value'];
  // Explode the value to make sure that it's a good safe key value representing
  // a resolution like this : 100x100
  $resolution = explode('x', $type_value);

  if (count($resolution) == 2 && is_numeric($resolution[0]) && is_numeric($resolution[1])) {
    // If the value is good, build a new array containing the new resolution
    $min_max_resolution = array(
      $type_value,
      $type_value
    );
    // Reset the max and min with of the image field
    $form['field_push_image'][LANGUAGE_NONE][0]['#upload_validators']['file_validate_image_resolution'] = $min_max_resolution;
    // Set the variable to pass to the theme function with empty description otherwise
    // the old string (with the basic resolution) will be concatenated to the new string.
    $variables = array(
      'description' => '',
      'upload_validators' => $form['field_push_image'][LANGUAGE_NONE][0]['#upload_validators']
    );
    // Return the approriate altered string using theme_file_upload_help()
    $form['field_push_image'][LANGUAGE_NONE][0]['#description'] = theme_file_upload_help($variables);
  }

  // Return the image field with its new resolution
  return $form['field_push_image'];
}


select image from existing folder without programming I uploaded a folder of images to my drupal7 server using WinSCP. I know the path name to these folders as shown below.

I have a field image0 defined for a image for each node.

The only option I have for defining what image is assigned to the field is to upload a new file from my computer. I don't see any way to select an existing file I already have on my server. The way I would like to do this is to display a list of files for a ceratin path on my server, like File Explorer on Windows. How do I point the field to the path sites/default/files/images/plants/Plant001/photo01.jpg?

There is a community module for this purpose which can be paired with a WYSIWYG. It's called IMCE. Alternately, you can look at the Media module in Drupal 7 which can help accomplish a similar thing.

P.S. Have to agree with the commenter. I think you might have answered this searching for "File management Drupal". :) Hint: https://www.drupal.org/node/265416


No access to admin page after change my server and domain I have changed my website to a new domain and server. I can navigate throught my content. However, after login I can't access to admin pages. No error is shown, only blank page.

What I did was upload a new .htaccess, delete the cache tables, uncomment on settings.php the line "Base URL (optional)". $base_url (replacing example.com with my site).

I don't know what can I do. Any idea please?

I had the same problems and there are the several steps that you should do for solving your problems:

1.Add the Error reporting debug ability in settings.php by adding these lines:

error_reporting(-1);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

These lines should be comment out after debug or after solving problems.

2.Browse the website and see what error information that you will get. If there is error with timeout or memory problem. Please change the memory_limit or max_execution_time if your hosting support to do that.

3.If there are some problems with the PHP version(There are some differences between PHP 4 and PHP 5). You will consider to upgrade or not.

4. Sometime there are several issues that are related to database or .htaccess. You'll see on the debug information and try to fix one by one


Can you add a 'select all' option to a webform_select_options_list? I have a webform that collects a list of flagged items. I'd like to add a "select all" option, because the list can get fairly long (50+) selections, and it can be tedious to manually check the boxes.

I'm using webform with views, sessions, and custom webform_select_options_info function.

Any ideas?

The Checkall module enables this functionality for any checkboxes form element.

  This module provides an extension to the builtin checkboxes element
  that allows developers add "check all" / "toggle" / "uncheck all"
  actions to them. This is specially useful for checkboxes that have a
  lot of elements.

A hook_form_alter() on your webform with this module should get you there.


Redirect to mobile page (not theme switching) I'm looking for a way to redirect mobile users to a mobile landing page (and I'm not looking for a theme switcher). I have a specific page that I'd like to redirect mobile users to: www.mysite.com/m/

Is there a way to utilize Mobile_Detect.php and specify a single page as the redirect target?

I suppose if you really wanted to, you could do something along the lines of this in a custom module:

function YOURMODULE_init() {

  if ($_SERVER['REQUEST_METHOD']=='GET' // most ajax/ahah etc use POST
      && arg(0)!='admin' // admin theme/backend
      && strpos($_GET['q'], 'sites/default/files')===FALSE // are we looking at anything under files that doesn't "really" exist, eg imagecaches that aren't created yet
      && $_GET['q']!='m') { // aren't already "here"

    include 'PATHTOSCRIPT/Mobile_Detect.php';
    $detect = new Mobile_Detect();

    if ($detect->isMobile()) {
      drupal_goto('m');
    }

  }

}

but they could never leave, or rather, be able to go to any other page on your site.

Addition:  per @MPD's comments, some further protections.


How to add select years and months select Drupal 8.1 date picker? There is no configuration option available in the backoffice nor from configuration synchronisation variables that allows to edit the settings for the jQuery datepicker widget embed in core.

My question is: how to select years and months in Drupal 8 core's date picker widget ?

By default years and months can only be changed by slowly navigating through adjacent months with left and right arrows.

From locating the core datepicker source code in core/modules/locale/locale.datepicker.js, I was able to inspect the $.datepicker object.

Then _defaults settings can be altered in a custom javascript fil as easy as:

(function ($) {
    Drupal.behaviors.alterDatePicker = {
        attach: function (context, settings) {
            $.datepicker._defaults.changeMonth = true;
            $.datepicker._defaults.changeYear = true;
        }
    };
})(jQuery);

All datepicker settings are documented here: http://api.jqueryui.com/datepicker/#option-changeMonth


Need to limit Commerce Shipping Condition to only fire if there are no items that do not match We need the condition to trigger only if the cart items match the categories listed and there are no products that do not match.
Is there a way to limit Commerce Shipping Method Conditions (Product->Order Contains Product Categories) to trigger only if the order products match the categories and there none that do not match?

Unfortunately, the way that condition was written, it only matches for, "Order contains any products from these categories." The logic you're looking for is, "Order contains only products from these categories." For that, you'd need to write a custom condition plugin. This would be a reasonable core feature request for Drupal Commerce and would apply for the other "contains" conditions as well ... which leads me to believe we might implement it as an "operator" select list on the condition itself.


How do I get the number of rows selected from the query? In my custom module for Drupal 8, I am using the following code.

$query = $this->connection->select('node_field_data', 'nf_data');
$result = $query->execute();

I can get the number of rows looping over $result.

foreach ($result as $row) {
  $num++;
}

Is there a way to get the number of rows with a function / class method?

Use $query->countQuery()->execute()->fetchField(); This is fast.

See detail example.

$number = $this->connection->select(static::TABLE_NAME, 'f')
    ->condition('event', $name)
    ->condition('identifier', $identifier)
    ->condition('timestamp', REQUEST_TIME - $window, '>')
    ->countQuery()
    ->execute()
    ->fetchField();


Using Page Title with Node Tags I'm using the following modules

Meta Tags
Page Title

I need to be able to make the sites title work like this:

Use the title set in Meta Tags for each Node first of all, if this isn't set then default to the Page Title module.

If this isn't set, just use the pages title.

How do I set a precedence for the titles?  Do I have to hook into html_head_alter?

Any help is greatly appreciated,

Cheers

Have you checked the auto nodetitle module with the token Module. Then you can create the node Titles with tokens.
Check also the Automatic Entity Label i think its better for your Usecase


Customize the title field I want to display updated content's field with views block on the front page.

2019/06/20 newly posted content1-title
2019/06/19 updated content2-title

The words updated and newly posted before the title want to customize according to whether the content was first posted or updated.
My code is as follows.

However, even at the time of initial content posting, durpal has different created and changed timestamps, which is not the expected result.
Is there are good ways? Thanks.

Views module comes with the field Has new content that outputs New or Updated depending on the status of the node as being viewed by a visitor.

Anonymous visitors don't see anything because there is no history record about that users visits to a particular node.

Authenticated users will see the word New if they never visited that node. If they have visited that node in the past, but the node has been updated in the meantime, they will see Updated. Once they visit the node again, they won't see any output for that field.

So this doesn't work quite as you described in your question, but it still may be what you're after.

You can add that field to your Views, Exclude it from display, and then Rewrite the Title field to include it before the actual title text.

The way you've written your condition in the screenshot is criss-crossed, you're trying to output "updated" for nodes that are new (at least according to your logic of those times being equal).

Your rewrite would also always show output for all nodes, even the ones the visitor has seen. Visitors usually don't expect that to behave like that. That's why it makes more sense to use Has new content field, but it all depends on your project and your visitors' expectations.

The created and updated time always differ because the created time is the one when the Create node form was loaded in the browser, and the updated time is the actual time when the Save button was hit, when the node was actually saved. The difference in created and updated times is the time it takes to fill in the form ;)


How to redirect into a specific page variant I installed panels, page manager, ctools and page manager redirect.

I made a (panel) page say foo1
- admin/structure/pages/add with variant type Panel. In this I put 5 variants named foo1variant1, foo1variant2, foo1variant3, foo1variant4, foo1variant5,

I also setup a page manager redirect say foo2:
- admin/structure/pages/add with variant type redirect.
In the end I should give the url it should go to foo1 en into foo1variant3, .

How to do this?

Variants on the same Page always have the same URL.  The variant that is shown is determined by the selection criteria.

If the selection criteria for Variant 1 fails, it moves on to Variant 2.

If the selection criteria for Variant 2 also fails, then it will try to show Variant 3.

The only exception to the 'same URL' rule is if you have optional Arguments (that start with ! instead of %) in which case you can have a url of foo and foo/bar handled by the same page.


How to print a field value in page front tpl file? I'm trying to load a field value (machine name: field_theme_image) from a content of node value 3, in "page--front.tpl.php".

<?php
  $node=node_load(3);
  print $node->field_theme_image[$node->language][0]['uri'];
?>

Using the above code I'm not getting full URL value. Please see the image below. I can see the path value in Devel themer.

I am not sure if this is what you are asking for, I think you want to show a download link for an image on your home, you have image on your node with node id 3.

In this case you can use download_file module, it allows to create direct download link for fils/images.All you need to do is create a view(through views module) of display type block, in your view add image field and keep the formatter as direct download file, place this block on front page.

If you want to render the download link programmatically, you can use the same function as defined in download_file module to render the links.

If you want to print image programmatically consider this:

print theme('image_style', array('path' => $node->field_theme_image[$node->language][0]['uri'], 'style_name' => 'home_theme'));


Print registration and login forms on same page How do I print the register and login forms on the same page?

I think I am really looking just for the form IDs, but if you've got the right render function handy it would be very appreciated.

print(drupal_render(drupal_get_form('user_register_form')));
print(drupal_render(drupal_get_form('user_login_block')));

See user_register_form() and user_login_block() for details. Note that user_register_form is an unusual form builder function: it redirects in some cases.


How to remove a value from URL parameter? I'm using entity reference prepopulate and views. On the start of my node add form I'm using views to display some products and I have created a PHP button to pass the nid of those products to the URL. Here is the code:

<?php
$url = token_replace('[current-page:url]');
$l = l( t('SELECT THIS VENUE'), $url,  array('query' => array('field_product_venue' =>$row->nid )  ));
echo $l;
?>

And on the last part of my node add form the user can see the summary of all the products he or she has chosen but he or she must also have the ability to remove those items, since the form gets its selected products from the url I want to create a button that deletes that specific product (nid) from the URL.

Any help would be greatly appreciated.

You need to get the value of the parameter, then check if the parameter contains the nid, then replace/remove the nid on your parameter from your url.

Use this code on your Views: PHP

<?php
$url = token_replace('[current-page:url]');
$venue =$_GET['field_product_venue'];
if (strpos($venue, $row->nid) !== false) {
$change= str_replace($row->nid .',', '', $venue);
$l = l( t('DELETE'), $url,  array('query' => array('field_product_venue'=>$change)  ));
echo $l;
}
?>


How do I create a custom action? I want to create simple actions that will change the field_support_status field value to 1 or 0. I enabled the "Actions" module and created a custom module with my actions, but after the module is installed the actions do not appear.

In my module, I created files with the following structure:

/src/Plugins/Action/SupportStatusYes.php

<?php
namespace Drupal\support_action\Plugin\Action;
use Drupal\Core\Action\ActionBase;
use Drupal\Core\Session\AccountInterface;
/**
 * Change support status on yes.
 *
 * @Action(
 *   id = "support_status_yes",
 *   label = @Translation("Change support status on yes"),
 *   type = "node"
 * )
 */
class SupportStatusYes extends ActionBase {

  /**
   * {@inheritdoc}
   */
  public function execute($entity = NULL) {
    /** @var \Drupal\node\NodeInterface $node */
    if ($entity->hasField('field_support_status')) {
      $entity->field_support_status->value = 1;
      $entity->save();
    }

  }

  /**
   * {@inheritdoc}
   */
  public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
    /** @var \Drupal\node\NodeInterface $object */
    $result = $object->access('update', $account, TRUE)
      ->andIf($object->field_support_status->access('edit', $account, TRUE));

    return $return_as_object ? $result : $result->isAllowed();
  }

}

/src/Plugins/Action/SupportStatusNo.php

<?php
namespace Drupal\support_action\Plugin\Action;
use Drupal\Core\Action\ActionBase;
use Drupal\Core\Session\AccountInterface;
/**
 * Change support status on no.
 *
 * @Action(
 *   id = "support_status_no",
 *   label = @Translation("Change support status on no"),
 *   type = "node"
 * )
 */
class SupportStatusNo extends ActionBase {

  /**
   * {@inheritdoc}
   */
  public function execute($entity = NULL) {
    /** @var \Drupal\node\NodeInterface $node */
    if ($entity->hasField('field_support_status')) {
      $entity->field_support_status->value = 0;
      $entity->save();
    }

  }

  /**
   * {@inheritdoc}
   */
  public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) {
    /** @var \Drupal\node\NodeInterface $object */
    $result = $object->access('update', $account, TRUE)
      ->andIf($object->field_support_status->access('edit', $account, TRUE));

    return $return_as_object ? $result : $result->isAllowed();
  }

}

/config/install/system.action.support_status_no.yml

langcode: en
status: true
dependencies:
  module:
    - node
id: support_status_no
label: 'Change support status on no'
type: node
plugin: support_status_no
configuration: {  }

/config/install/system.action.support_status_yes.yml

langcode: en
status: true
dependencies:
  module:
    - node
id: support_status_yes
label: 'Change support status on yes'
type: node
plugin: support_status_yes
configuration: {  }

/config/schema/support_action.schema.yml

action.configuration.support_status_yes:
  type: action_configuration_default
  label: 'Change support status on yes'

action.configuration.support_status_no:
  type: action_configuration_default
  label: 'Change support status on no'

Tell me please what am I doing wrong?

The correct directory structure is src/Plugin, not src/Plugins.

The files in config/schema/ and config/install/ look correct to me. I struggled with those mightily. And I'll emphasize that actions only seem to be registered when the module is installed.


How to count number of published nodes of a specific content type in twig template? I'm looking for a way to achieve this in my Twig file; if the number of published entities of a content type 'promotions' is at least one, a certain entity should be displayed in a content type Shop. I'm trying to show a banner only if there is at least one published promotion entity.
I could use some help with the if-function. I've written it down with I'm trying to do.
if(published promotion entities > 0){
{{ drupal_entity('node', 2668) }}
}

Any ideas to get me going? Thanks!

In a preprocess hook function for your template, you can code something like this.
function MYTHEME_preprocess_TEMPLATE_HOOK(&$variables) {
    $query = \Drupal::entityTypeManager()->getStorage('node')->getQuery();
    $query->condition('type', 'promotions');
    $query->condition('status', 1);
    $query->range(0, 1); // only need one
    $results = $query->execute();
    $variables['has_published_promotions'] = (bool)count($results);
}

has_published_promotions will be available in your Twig template and will be TRUE only when there are published nodes of that type.


Loop through multiple values from an array to create multiple arrays I have $host_entity which contains:
field_eventorganizer (Array, 1 element)
und (Array, 3 elements)
0 (Array, 1 element)
target_id (String, 2 characters ) 20
1 (Array, 1 element)
target_id (String, 4 characters ) 345
2 (Array, 1 element)
target_id (String, 2 characters ) 678

and the below code in which I need to create multiple arrays inside the array('#markup'.
$organisers=user_load($host_entity->field_eventorganizer['und'][0]['target_id']);
$organiser_email=$organisers->mail;
    $build['field_eventorganizer'] = array(
    '#theme' => 'registration_property_field',
    '#label' => 'Event Organiser(s)',
    '#items' => array(
        array('#markup' => l($username, 'mailto:' . $organiser_email, array('absolute' => TRUE)),),
        ),
        '#classes' => 'field field-label-inline clearfix',
    );

Do I need to create a foreach loop after array('#markup' => ?

Try this to loop the $build variable :)
// define variables
$organisers[] = "";
$organiser_email = "";
$organiser_name = "";
$email_delimiter = "; ";

// recreate the array from your example
$organisers['und'][0]['target_id'] = 20;
$organisers['und'][1]['target_id'] = 345;
$organisers['und'][2]['target_id'] = 678;

// populate $build variable
$build['field_eventorganizer'] = array(
      '#theme' => 'registration_property_field',
      '#label' => 'Event Organiser(s)2',
      '#classes' => 'field field-label-inline clearfix',
    );

// because the numbers are nested in the array, I've chosen to use `for` instead of
// `foreach` to use $i as the iterator then rebuild what I'm looking for in the loop. I've
// used count($organisers['und']) because the next piece of the array is the number we are
// using to load user data.

for ($i = 0; $i < count($organisers['und']); $i++) {
    // load the user object based on $i
    $organisers = user_load($host_entity->field_eventorganizer['und'][$i]['target_id']);
    // fetch loaded users email
    $organiser_email = $organisers->mail;
    // fetch loaded users name
    $organiser_name = $organisers->name;
    // populate $build variable
    $build['field_eventorganizer'][] = array(
      '#items' => array(
        array('#markup' => l($organiser_name, 'mailto:' . $organiser_email, array('absolute' => TRUE)),),
      ),
    );
}

Side note: Not sure if it was intentional or not, but be careful of your plurals. You are using $organisers and $organiser_email which can sometimes be missed and cause a headache.