Encrypt module; Is there a way of using db_query() on encrypted values? I've installed the encrypt module because we will be handling a lot of personal data. For those in the EU there is serious consequences under GDPR for failing to protect users data.

I've also installed Real AES and Field Encryption.

So I have got the values encrypted and followed the instructions. I can see the encrypted values in the database. For example:

  a:6:{s:4:"text";s:88:"fYGWIfFfoQuar4yy/ySsyTtK2Qt/flgz9mg4GdRD6hlDOM8f8fevf9Q6O35Yp+WDwByB7SXGg0yPQLXfCC3FlQ==";s:6:"method";s:17:"authenticated_aes";s:12:"key_provider";s:4:"file";s:7:"options";a:1:{s:6:"base64";b:1;}s:15:"method_settings";s:0:"";s:17:"provider_settings";a:2:{s:4:"path";s:15:"../keys/xscodes";s:6:"method";s:13:"base64_decode";}}

Views also displays the decrypted values. I can also see them when viewing and editing one of my entities.

This particular Drupal install is used to store customer and sales info from many Commerce sites in a centralised place. As a result I'm doing lots of db_query()'s when I receive some order information via a JSON call.

My plan was to encrypt the values given. Then use that encrypted value in my call to db_query().

In the PHP block that comes with Devel I have this while testing:

  $lastname = encrypt('Jones', $options = array('base64' => TRUE), $method = 'authenticated_aes', $key_provider = 'file', $config = 'real_aes_encryption');
dpm($lastname);

    $lastname2 = encrypt('Jones', $options = array('base64' => TRUE), $method = 'authenticated_aes', $key_provider = 'file', $config = 'real_aes_encryption');
   dpm($lastname2);

    $lastnamede = decrypt($lastname);
    dpm($lastnamede);

    $lastname2de = decrypt($lastname2);
    dpm($lastname2de);

So the $lastname gives me:

  a:6:{s:4:"text";s:88:"dQApE9dYu1QE2Cz5N5f9rLRW8xuDEYKvDaq3jmJFEC+GBljGqbQ68XfQjv92fNicECsPnoK+s11agTPX0LRQuQ==";s:6:"method";s:17:"authenticated_aes";s:12:"key_provider";s:4:"file";s:7:"options";a:1:{s:6:"base64";b:1;}s:15:"method_settings";s:0:"";s:17:"provider_settings";a:2:{s:4:"path";s:15:"../keys/xscodes";s:6:"method";s:13:"base64_decode";}}

The $lastname2 gives me:

  a:6:{s:4:"text";s:88:"RDsHVHv2wvcK9012xAElHs/tx3rltR57DjyhUXGcBVXrN1j/RqBt/UVkLY6hxEmyLm9zQkqXtET9SgtKmB8q/Q==";s:6:"method";s:17:"authenticated_aes";s:12:"key_provider";s:4:"file";s:7:"options";a:1:{s:6:"base64";b:1;}s:15:"method_settings";s:0:"";s:17:"provider_settings";a:2:{s:4:"path";s:15:"../keys/xscodes";s:6:"method";s:13:"base64_decode";}}

Both values then de-crypted as expected. $lastname and $lastname2 being different values presents me with a problem when it comes to db_query() calls.

The query I'm trying to do is this:

$firstname = encrypt('Peter', $options = array('base64' => TRUE), $method = 'authenticated_aes', $key_provider = 'file', $config = 'real_aes_encryption');
$lastname = encrypt('Jones', $options = array('base64' => TRUE), $method = 'authenticated_aes', $key_provider = 'file', $config = 'real_aes_encryption');
$email = encrypt('pj@some.com', $options = array('base64' => TRUE), $method = 'authenticated_aes', $key_provider = 'file', $config = 'real_aes_encryption');

$customer_id = db_query("SELECT c.id
  FROM {eck_customer} c
  LEFT JOIN {field_data_field_customer_first_name} first_name ON c.id = first_name.entity_id
  LEFT JOIN {field_data_field_customer_last_name} last_name on c.id = last_name.entity_id
  LEFT JOIN {field_data_field_customer_email} email ON c.id = email.entity_id
  WHERE email.field_customer_email_email = :email
  AND first_name.field_customer_first_name_value = :first_name
  AND last_name.field_customer_last_name_value = :last_name
  AND type = 'customer'", array(':email' => $email, ':first_name' => $firstname, ':last_name' => $lastname))->fetchField();
if ($customer_id) {
dpm($customer_id);
 }

The above query is correct. It works without encryption being involved.

I tried entity field query in case that worked but no joy there.

So the question is, does anyone know of a method to achieve what I want? How can I query the database on encrypted fields?

You can see from your DPM that your encryption method is returning an array containing several different values. You can't use an array for a database field value it would need to be a string in this case. So you need to use just the  encrypted hash string from that array in your db_query e.g.

array(':email' => $email['text'])


How to enable endpoint without RESTUI module? I've created a rest Plugin that returns some data at /api/custom/{nid}.

Drupal core provides four modules that together can handle RESTful API, these are: Serialization, RESTful Web Services, HTTP Basic Authentication, HAL. I can't find any information how do I enable custom (or even build-in) API endpoint without restui module.

So the question is:

Is there a way to enable custom rest resource without restui module? If so, how?
Is there a way to enable build-in rest resources without restui module? If so, how?

Ok, I finally found out how to enable an endpoint to be accessible without RESTUI module. This gives more flexibility to keep everything in code and one custom module.

This instructions applies to Drupal > 8.2 only.

First you need to know how to create a custom rest resource, which can be found here or here.

So, let's say we have a custom module named 'custom_rest' that contains REST plugin resource. Module returns only a single node json data. The structure of the module looks like this:

|custom_rest
|--|config
|  --|optional
|      --rest.resource.custom_rest_resource.yml
|--|src
|  |--Plugin
|     |--rest
|        |--resource
|           --CustomRestResource.php
|--custom_rest.info.yml
|--custom_rest.module

The most important files for us are:

 -  CustomRestResource.php
 -  rest.resource.custom_rest_resource.yml

CustomRestResource.php is a plugin with the custom rest resource. My get method looks like this:

  public function get($nid) {
    if (!$this->currentUser->hasPermission('access content')) {
      throw new AccessDeniedHttpException();
    }
    $data = node_load($nid);
    return new ResourceResponse($data);
  }

This method returns a json node structure for an existing node. That's it, it's just for testing purposes only. It can do anything you want.

As for the enabling an endpoint it needs an extra yml file that should be located in:

/custom_rest/config/optional/rest.resource.custom_rest_resource.yml

The contents of the rest.resource.custom_rest_resource.yml file for this particular endpoint looks like this:

langcode: en
status: true
dependencies:
  module:
    - custom_rest
    - hal
    - serialization
    - user
id: custom_rest_resource
plugin_id: custom_rest_resource
granularity: method
configuration:
  GET:
    supported_formats:
      - hal_json
      - json
      - xml
    supported_auth:
      - cookie

Of course, the name of the file, dependencies, id, plugin_id, configuration should be adjusted to your needs.

If you have all of this and you will enable the module this endpoint should be accessible in browser or any app that handles http requests (postman, etc.).

Notice that this yml file won't be triggered if you already enabled the module. If you've added this file after module enable, you should uninstall the module and enable it again.


Where do views/panels get their source html code I'm working on a few sites that use views/views-ui/panels to display content.

The entry points of the templates are located in the active theme directory
for example 1 view with settings of Format: Bootstrap Thumbnails renders the file views-bootstrap-thumbnail-plugin-style--title.tpl.php

But inside here is only a loop which prints out $rows of large html strings.

This is the same for most sections which simply print $variable.

I've tried using xdebug and followed the stacktrace but get completely lost in the nested functions, and can't keep up with the large unorganised $this variable.

I've also tried root directory searches of strings from the HTML which only finds html in the cache.

Where do views/panels get their source html that's inserted into $row $content etc.. ?

It will depend on the contents of the panel or view display as to the actual content to be displayed.  For example a panel/view might contain a node, in which case a specific display mode would be used dependant on the output settings.  Using your example whichever module provides the Format: Bootstrap Thumbnails is likely to be the candidate which can either be further overridden with a different template, or with an appropriate hook_theme.


How do you contribute patches to Drupal core? What is the proper process to contribute patches to Drupal core?

Let's say I find a bug in Drupal core, fix it, and create a patch.  How do I submit it?

If the bug is in Drupal 7, do I have to also fix it in Drupal 8, and submit two patches?  Does this also apply to documentation bugs/improvements?

Do all patches also require a unit test?

If the bug is in Drupal 7, do I have to also fix it in Drupal 8, and submit two patches?

If the bug is present in the version being developed (in this case Drupal 8), and the previous version (Drupal 7), then the bug should be first fixed the currently developed version, and then on the previous version(s).

If the bug is not present in the latest developed version, for example because the bug is for a function that has been removed, or that has been already changed, then the patch should be provided for the version before the currently developed one.

The workflow that is followed is:

First the patch is created, and submitted for reviews, for the most recent version, even if still under development (such as in the case of Drupal 8)
Once that patch is applied to Drupal, a patch that applies for the previous version is created, and submitted for reviews

You can create patches for two Drupal versions at the same time, but since the patch for the latest Drupal version could require changes, it is better to work on the patch for the currently developed version, than working on two different patches that both require to be changed.

See also: Backport Policy.

  Does this also apply to documentation bugs/improvements?

Yes, it does. Also in this case, if the currently developed version removed the function/method to which the documentation is referring, then the patch needs to be provided for the previous version.

  Do all patches also require a unit test?

If the patch is for the documentation, it doesn't require tests. The test bot running on http://qa.drupal.org checks the Drupal code after the patch is applied; if the patch introduces syntax errors (for example because the comment is closed before the needed), then the test bot will report an error about the patch before tests are run.

If the patch is for a new feature, then the tests are required.

If the patch is to fix a bug, then the tests could be required from the maintainers, if there isn't already a test checking a specific feature. The test is generally necessary to avoid re-introducing the same bug when changing in future the same code. If the bug is merely a variable that is initialized, but never used from a function/method, then chances are the tests are not required.


Commerce quantity limit In Commerce Line Items quantity field which is an integer field, user can not enter more than 9999, what should i do to unlimit the field?

Although that limit appears sane to me, to adjust the maxlength, look at

commerce_line_item_field_widget_form

  $element['line_items'][$line_item_id]['quantity'] = array(
    '#type' => 'textfield',
    '#datatype' => 'integer',
    '#default_value' => $quantity,
    '#size' => 4,
    '#maxlength' => max(4, strlen($quantity)),
  );

You could use hook_field_widget_form_alter and adjust the #maxlength property there.


How to install a specifc commit in Composer The commerce_webform_order module (currently in dev status) recently changed one of its dependencies from Webform 5.x (stable) to Webform 6.x (alpha). I want to temporarily freeze commerce_webform_module so that Composer keeps it at a particular git commit just before the dependencies changed. I've done this successfully in the past by following a post here but I can't get it to work this time.
I've tried doing
composer require drupal/commerce_webform_order:1.x-dev#30668342035ae3add3a2e5163e84816fc96edd92
or adding "drupal/commerce_webform_order "1.x-dev#30668342035ae3add3a2e5163e84816fc96edd92", in my composer.json file and I've tried shorter versions of the commit hash (30668342) as shown on the drupalcode.org project here.
I keep getting this message
Your requirements could not be resolved to an installable set of packages.
- Can only install one of: drupal/webform[6.x-dev, 5.19.0].
- drupal/commerce_webform_order 1.x-dev requires drupal/webform ^6 -> satisfiable by drupal/webform[6.x-dev].
- Installation request for drupal/commerce_webform_order 1.x-dev#30668342035ae3add3a2e5163e84816fc96edd92 -> satisfiable by drupal/commerce_webform_order[1.x-dev].

What might be causing this? What's changed in the last 6 months since it worked for me on the same module last time?
Can you think of any other work-around that allows me to update everything else without pulling in this latest change and the dependency for an alpha version of Webform?
Thanks

composer require drupal/commerce_webform_order:dev-1.x#30668342035ae3add3a2e5163e84816fc96edd92

dev-1.x points to a git branch so it accepts the commit ref
1.x-dev is dev release at drupal.org and it does not have git commits to reference like that


Taxonomy vs Values module in my case I'm using the Values module for creating a list of subscriptions the user can choose of when they register (it's a field in the registration form). Now I've seen I can also create a list with the Taxonomy module. I'm just curious what's the best practice for this? Should I use the module already implemented or is Values module better in my case?

The Values module is a field for users to enter their own list of values in a key-value format.

Core taxonomy module is used to create lists of terms which can be placed as a field on the registration form using a 'term reference'. This would then appear as either a select list, radios or checkboxes (checkboxes if the field is multi select).

The difference is that with Values, users enter their own values and with term reference and Taxonomy, users choose from your list of terms in the taxonomy. Which do you want? I think if you're looking for subscriptions, it's term reference and Taxonomy.


How to use a between operator in an entity field query? I wanna use a between operator. Can anyone tell how to use this? I am using it like this

$query->propertyCondition('nid', array(4, 3), 'between');

But it is also including node id 4 and 3, and I want to show only "2", which falls in between. How can this be done?

If you want to include 2 then simply pass 2.

$query->propertyCondition('nid', array(2));

While using between operator, it includes the range values too. So you can just pass the range values you want to include. Still if you want to exclude these range then add one more condition like :

$query->propertyCondition('nid', array(1, 3), 'BETWEEN'); // 1, 3 to get the nid 2
$query->propertyCondition('nid', array(1, 3), 'NOT IN'); // exclude these nids


D7: Create an administration page for my module I have a custom module that sends an email with an order to the customer. I hardcoded the email body text in a string inside the module code but my client want to have control over it and I need to create an admin page for him:

I need to save it and use that text as a variable.

I started the page like this:

function shop_admin_settings($form, &$form_state) {
     $form = array();
     $form['mail_template'] = array(
       '#type' => 'fieldset',
       '#title' => t('Shop Email Template'),
       '#colapsed' => FALSE,
       '#collapsible' => TRUE,
     );

     $form['mail_template']['body'] = array(
       '#type' => 'textarea',
       '#title'  => t('Email template'),
       '#rows' => 10,
     );
     return system_settings_form($form);
 }

and use hook_mail_alter to append $form['mail_template']['body'] to the existing email body

function shop_mail_alter(&$message, $form_state) {
$client_body = $form_state['mail_template']['body']
if (is_array($message['body'])) {
    $message['body'][] .= $client_body;
  }
}

Now if you please help me, I am a bit stuck:

I need to retrieve the body provided by client, I don't know how (my code is not correct)
Do I need to create a separate admin.inc in order to work? Or do I simply need to add a menu path like admin/config/system/shop and a corresponding callback?
Is it possible for client to use tokens inside the body?

First of all hook_mail_alter() only has 1 parameter, no $form_state. Second of all, the system_settings_form() will save the form values into the variables table in the database. To access that value you should use variable_get().

Now, your code should look like this:

// try to change body to something more specific to your module, like custom_email_body
$form['mail_template']['custom_email_body'] = array(
  '#type' => 'textarea',
  '#title'  => t('Email template'),
  '#default_value' => variable_get('custom_email_body', ''),
  '#rows' => 10,
);

then:

function shop_mail_alter(&$message) {
$client_body = variable_get('custom_email_body', '');
if (is_array($message['body'])) {
    $message['body'][] .= $client_body;
  }
}


How can I cache pages indefinitely? I'm upgrading a small site currently in Drupal 6 to Drupal 8, it's for a non-profit and doesn't receive all that much traffic. It's a relatively static site, content will be added regularly, but certainly not every day. While the amount of traffic is easily handled even on shared hosting, I'd like to keep the page loading times low. I used Boost for that on Drupal 6, but now with Drupal 8 I want to use the internal page cache.

From what I understand, Drupal 8 should be able to automatically invalidate the cache when nodes are edited. So what I'd like to do is to cache all pages of my site indefinitely until the data behind them actually changed. But the cache dialog on the performance admin page only allows a page cache maximum age of 1 day.

Is there a way to configure a stock Drupal 8 to cache pages forever? The cache should only be invalidated if nodes are edited and the page actually changes content. Ideally I'd like to automatically pre-warm the cache as well.

The setting on the performance page, unlike D6/7, does not affect the page cache module at all. The page_cache module always caches indefinitely, you can not configure it otherwise. Invalidation happens through cache tags, as you said.

The setting that you can see only affects external caching through the HTTP Cache-Control header, for example Varnish and in browsers. There are ways to invalidate caches in varnish using cache tags, but there is none to invalidate pages that are cached client-side in browsers, so I would recommend to not set that value too high.


how to get a list of all the boolean fields of a node? I need to get a list of all the boolean fields of the node

My code

 $query = \Drupal::entityQuery('node')
   ->condition('status', NODE_PUBLISHED)
   ->condition('type', 'product')

Please help me

You can get a list of an entity's field definitions with EntityFieldManager::getFieldDefinitions(). You should then have a list of fields defined on that entity and should be able to determine which are the boolean fields.

You can access this via a service like:

$product_field_definitions = \Drupal::service('entity_field.manager')->getFieldDefinitions('node', 'product');


Configure NGINX on Centos 6.8 I have nginx installed on our server and configured with a previous drupal 7 installation and it works well.

I have installed a new drupal 7 installation and i want to configure it to also work with NGINX already installed on the server. Is there a configuration file i have to update? Please someone point me to the right direction.

This new site is running on the same server but a different cpanel with the previous site.

You need to create a new Server Block for the new domain.

This is the file that NGINX reads in order to determine where it will look for the site when a request for a domain come through.

The configuration will be under

/etc/nginx

The relevant/current entry could be in nginx.conf, in a file under conf.d or sites-available.


'Media File Selector' blank screen To use already existing image, I choose 'Media File Selector' Widget.
But, it gives me blank page like this when I click on 'Library' to choose already existing image in Drupal-7.

Version of the Media:
1) Media: YouTube
(media_youtube) 7.x-2.0-rc4

2) Media
(media) 7.x-1.4

In Media browser settings, Allowed file extensions are
(jpg jpeg gif png txt doc docx xls xlsx pdf ppt pptx pps ppsx odt ods odp mp3 mov m4v mp4 mpeg avi ogg oga ogv wmv ico)

Thanks!

I am not sure whether to making 'jQuery' version down to some level is good or not. But, I tried to downgrade the jquery version to 1.5 and it works well with my website.

I refereed this post:
Media 7.x-1 Library tab empty

Now, I can see all my images by selecting 'jQuery' version - 1.5.

To do so:
Go to
Home » Administration » Configuration » Development

Thanks!

Vidushi


How to change "add to comment" in comment form? When CCK was not in core, as in Drupal 6, and you selected a node type for comments on other node types, the comment form would say the name of the content type instead of comment. In this case, I want the comment form to say 'Add New Review' instead of 'Add New Comment'. Does anyone know how to do this through a module or configuration?

Create a seperate .tpl file for comment-wrapper named comment-wrapper.tpl.php.

To create a seperate template file for node specific comment wrapper you can create using
comment-wrapper-contenttype.tpl.php copy the code from core comment-wrapper.tpl.php and change the title in the code given below.

While copying from core comment-wrapper.tpl.php don't forget to remove the validation which is meant for forum node types only.

<?php print t('Add new comment'); ?>


Does Views cache row entity? I have a Views of users.

Does user_load($row->id); will load a user from cache?

Yes and no.

user_load() leverages a per-request cache.  This is implemented as a static cache in the entity controller (see the DrupalDefaultEntityController class).  So, if the same user is loaded multiple times during the same request, the subsequent loads will come from the static cache.

In a base install, entities are not cached between requests.  But, fields attached to entities are cached in the cache_field bin.

Data for views may or may not be cached, depending on your global Views settings and overrides for a particular view.

If you have the Entity Cache module installed, then entities are cached between requests in whatever backend you have defined.  There are almost no reasons to not have this module installed on a site.  It provides huge performance improvements, especially with non-SQL cache backends.


Avoid caching pages for authenticated users with Varnish I have the following problem: when a user logs in and navigates through pages that he visited when was an anonymous user, he "sees" the cached page instead seeing the page version for logged users.
I'm using Varnish and I have tried the following code without result:

  if (req.http.Cookie) {
    set req.http.Cookie = ";" + req.http.Cookie;
    set req.http.Cookie = regsuball(req.http.Cookie, "; +", ";");
    set req.http.Cookie = regsuball(req.http.Cookie, ";(SESS[a-z0-9]+|NO_CACHE)=", "; \1=");
    set req.http.Cookie = regsuball(req.http.Cookie, ";[^ ][^;]*", "");
    set req.http.Cookie = regsuball(req.http.Cookie, "^[; ]+|[; ]+$", "");

    if (req.http.Cookie == "") {
      # If there are no remaining cookies, remove the cookie header. If there
      # aren't any cookie headers, Varnish's default behavior will be to cache
      # the page.
      unset req.http.Cookie;
    }
    else {
      # If there are any cookies left (a session or NO_CACHE cookie), do not
      # cache the page. Pass it on to Apache directly.
      return (pass);
    }
  }

How can avoid this issue?

Thanks

In your settings.php are you using $conf['omit_vary_cookie'] = TRUE; ?

If so, logged in users who have previous viewed a page when logged out will be served the varnish cached version of their page until they manually refresh their browser.

The solution is to simply comment out $conf['omit_vary_cookie'] = TRUE; in your settings.php.

This is explained in default.settings.php (drupal 7.34):

 /**
 * Page caching:
 *
 * By default, Drupal sends a "Vary: Cookie" HTTP header for anonymous page
 * views. This tells a HTTP proxy that it may return a page from its local
 * cache without contacting the web server, if the user sends the same Cookie
 * header as the user who originally requested the cached page. Without "Vary:
 * Cookie", authenticated users would also be served the anonymous page from
 * the cache. If the site has mostly anonymous users except a few known
 * editors/administrators, the Vary header can be omitted. This allows for
 * better caching in HTTP proxies (including reverse proxies), i.e. even if
 * clients send different cookies, they still get content served from the cache.
 * However, authenticated users should access the site directly (i.e. not use an
 * HTTP proxy, and bypass the reverse proxy if one is used) in order to avoid
 * getting cached pages from the proxy.
 */
# $conf['omit_vary_cookie'] = TRUE;

This DA question answers this issue too: What does the "Vary: Cookie" header actually do for serving pages from Varnish?


Unusual text inserted in the SQL I am getting some unusual text which is getting added to my queries in views. I am referring to the part setting view_name.

SELECT users.name AS users_name, users.uid AS uid, 'cardinality_user_test:page' AS view_name
FROM
{users} users
LEFT JOIN {node} node_users ON (SELECT nodeINNER.nid AS nidINNER, ':default' AS view_name
FROM
{node} node INNER LEFT JOIN {users} users_nodeINNER ON nodeINNER.uid = users_nodeINNER.uid
WHERE (( (users_nodeINNER.uid = users.uid ) ))
ORDER BY nodeINNER.nid DESC
LIMIT 1 OFFSET 0) = node_users.nid
LIMIT 10 OFFSET 0

This additional SQL is creating an error:

  SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 2 column(s)

What is causing that text to be added in Drupal 7?

That extra field is added from the Views module itself, in particular its views_plugin_query_default::add_signature() method, which is described as:

  Add a signature to the query, if such a thing is feasible.
  This signature is something that can be used when perusing query logs to discern where particular queries might be coming from.

If you look at its code, it is setting the view_name field.

function add_signature(&$view) {
  $view->query->add_field(NULL, "'" . $view->name . ':' . $view->current_display . "'", 'view_name');
}


Taking check box option and turn into select list I want to take the value of multiple checkbox options while creating node and then when viewing the node, I want these values which were selected in a multiple checkbox to be in a select list.

Any idea how to implement this?

you could do that in your module, try to implement hook_node_view and get the values of the node variable, and then do your changes.

Im pretty sure you dont want to save those values from the select list, just show it in an another matter, no?


Select menu's hierarchy show I would like it to show the hierarchy of menu's links. Testimonials and Company are under About us. How can I achieve this effect? Let me specify with an image:

You just need to make the About us as Expanded and place the menu items Testimonials, Company under the About us. Please see the attached screenshots

Here, About us acts as parent item of Testimonials and Company.
After that just need to add and set the css in style.css file to the menu to be displayed accordingly.

Hope it works for you!


Fatal error: Failed opening required file I am quite new in Drupal. When installing Kickstart module in a Acquia based Drupal 7 setup on a localhost, I got this message. I looked on the internet and saw a lot of answers, but it didn't help me. It seems the plugins.inc file is fine, but I can't do anything now.

  Fatal error: require_once() [function.require]: Failed opening required '/Users/aztem/Sites/acquia-drupal/sites/all/modules/panels/plugins/export_ui/panels_layouts.inc' (include_path='.:/Applications/acquia-drupal/common/pear:/usr/lib/php') in /Users/aztem/Sites/acquia-drupal/sites/all/modules/commerce_kickstart/modules/contrib/ctools/includes/plugins.inc on line 475

Commerce Kickstart isn't a module, it's an installation profile. If you want to add Commerce to your site, try install using drush, or just load all the modules manually.

drush dl commerce

Using the drush command will install Ubercart essentially, and you can setup commerce that way.


Drupal Content Access and if anomynous show login block I have this website where every pages are viewed by anonymous users.

I want to create a new page (and add it to the menu) where only the authenticated users can have access to it.

I installed Content Access module but somehow it does not work...

What I want is this: If it is an authenticated user - show page.
If not, show login block, and then redirect to the page.

I installed Rules module as well but I don't know how can that help me at all...

Thank you in advance, hope you guys can help!

This depends what method is used to create the page. Pages that  are created by the Views module define the permission settings in the "Access" configuration, as does page manager. But it sounds this is just a typical node page. Content Access should do the trick, but if not, you may want to try the Node Access module instead. Be sure to read the README on these modules, as they usually require you to rebuild permissions after enabling and configuring them. The permissions of the node should be understood by the menu system, so restricted pages will not appear to un-authorized users, which should satisfy the need to hide the menu item. If un-authorized users do land on the page somehow (such as yourself, after clicking a bookmark after your session has expired), then you can try something like the "Redirect 403 to User Login" module Although, in my opinion, the more sensible option might be to simply define your default 403 (Access denied) page as the login page. The only reason not to do this might be if you are trying to obscure the login process from anonymous users for some reason.


Fatal error: Call to a member function fields() on a non-object I have the following code that is throwing an error:

/**
 * Custom content function
 *
 * Get system status from the helpdesk database
 *
 * @return
 *   An key => value pairing of systems and their status
 */
function system_status_sjhc_status_check() {
    //connection info for the helpdesk database
    $helpdeskDB = array(
            'database' => 'mydb',
            'username' => 'myuser',
            'password' => 'mypass',
            'host' => 'myhost',
            'driver' => 'mysql',
    );
    Database::addConnectionInfo('helpdeskDB', 'default', $helpdeskDB);
    db_set_active('helpdeskDB');

    //grab the current light status
    $result = db_select('hd_lights', 'l')
        ->fields('l')
        ->leftJoin('hd_status', 's', 'l.id = s.id')
        ->fields('s', array('stamp', 'message'))
        ->orderBy('`order`', 'ASC')
        ->execute();

    db_set_active(); // without the paramater means set back to the default for the site

    return $result;
}

The error I'm receiving is:

  Fatal error: Call to a member function fields() on a non-object

and its being thrown on this line:

    ->fields('s', array('stamp', 'message'))

I can't figure out what I've done wrong, everything looks OK to me and the code runs fine without the join and additional table fields.

Any thoughts?

SelectQuery::join(), SelectQuery::leftJoin() etc. don't return the query (they return the alias to the created JOIN), so they can't be chained.

Just separate your code out like this:

$query = db_select('hd_lights', 'l')
  ->fields('l')
  ->fields('s', array('stamp', 'message'))
  ->orderBy('`order`', 'ASC');

$query->leftJoin('hd_status', 's', 'l.id = s.id');

$result = $query->execute();


Outputting front page to a different url I currently have this site tobyNews that is up and running with Drupal 7. However,
while in the process of giving the site a mobile version, I thought maybe it would be easier if the front page content that is displayed when you first visit the site was simply output to another page, like m.tobynews.com . Is there any way to sort of add another output without altering the main page?

I would personally suggest putting breakpoints into the CSS and making the site adaptive. You would save yourself a lot of time building a separate mobile site.

Plus, especially with adaptive widths, and not fixed widths, you allow your site to display nicely on all sizes of device screen, and when a user reduces the size of their browser window on a desktop.

Alternatively, To detect a device and show a different site e.g. m.yoursite.com have a look at this answer.


How a field collection item is linked to a node I was looking through the database for a field_collection_item, but am still confused how it is actually linked to a node.

field_collection_item has 2 fields item_id and field_name

It seems item_id uniquely identifies a field collection item and field name is the machine name of the field_collection. Where do I find a table that links entity_id's (field collections) to nodes?

If you check admin/structure/field-collections, you will find the machine name of you collections in the first column. Prepend the machine name with "field_data", just like any other field, and you will find a table with an "entity_id" column.
In my case I have a collection called field_coworkers, and with

SELECT entity_type, entity_id FROM field_data_field_coworkers;

I can find the entities, that the fields are attached to.


How to log the history of nodes viewed by a user, and report about them? I want to have this feature that for each user logs the nodes that the user viewed.

In another words, recent nodes viewed by each user.
I want have a block that shows each nodes user viewed , something like imdb.com user history view.

How can I achieve this job? Do you know good module for Drupal 7?
Do you think it is possible achieve that with views or my custom query?
Or I should write custom simple module and get help hook_node_view .... ?

You can try using Recently Read module...

  Recently read allows site administrators to enable blocks displaying a
  history of recently read content (nodes) both to anonymous and
  authenticated users. For logged in users, each user has its own
  history. For anonymous users, the history is based on sessions. This
  module may be useful i.e. for displaying recently viewed products on
  the e-commerce site.


Custom fivestar widget does not display custom icons I am struggling to get my custom widget for the Fivestar module to work. The only time when I can see my new star icons is when I change the options in manage display for the field in content type. Otherwise, the default stars are shown (in the dimension that I state in the css).

I created the widget following the tutorial number 17. I kept the same names, just changed the size of the stars. Here is my code for the .module:

function my_stars_fivestar_widgets() {
  // Letting Fivestar know about my custom stars.
  $widgets = array(
    drupal_get_path('module', 'my_stars') . '/my_stars.css' => 'my_stars',
   );
 return $widgets;
}

And here is the css:

/* Static View-only Star Version */
.fivestar-my_stars div.fivestar-widget-static .star {
  width: 28px;
  height: 28px;
  background-image: url(my_stars.png) no-repeat 0 0;
}
.fivestar-my_stars div.fivestar-widget-static .star span.on {
  background-image: url(my_stars.png) no-repeat 0 -56px;
}

.fivestar-my_stars div.fivestar-widget-static .star span.off {
  background-image: url(my_stars.png) no-repeat 0 0;
}

/* Javascript Star Version */
.fivestar-my_stars div.fivestar-widget .cancel,
.fivestar-my_stars div.fivestar-widget .star {
  width: 28px;
  height: 28px;
}
.fivestar-my_stars div.fivestar-widget .cancel,
.fivestar-my_stars div.fivestar-widget .cancel a {
  background: url(cancel.png) no-repeat 0 0;
}

.fivestar-my_stars div.fivestar-widget .star,
.fivestar-my_stars div.fivestar-widget .star a {
  background: url(my_stars.png) no-repeat 0 0;
}

.fivestar-my_stars div.fivestar-widget div.on a {
   background-position: 0 -28px;
}
.fivestar-my_stars div.fivestar-widget div.hover a,
.fivestar-my_stars div.rating div a:hover {
 background-position: 0 -56px;
}

I am using Drupal 7.38, fivestar 7.x-2.1, Voting API 7.x-2.12, and Halfstar 7.x-1.1 is installed but deactivated at the moment.

Without seeing your file structure it is difficult to discern your problem.  But I suspect the hook is having issues with the path to your css.  I have found a really nice tutorial to do this, it setups a widgets folder in your custom module and uses file_scan_directory to scan all custom star folders in that folder.

https://www.drupal.org/node/234391

Be mindful that there is a slight error in the code as it is outdated, in the foreach, you need to use $file->uri instead of $file->filename for the array key.

foreach ($files as $file) {
    if (strpos($file->filename, '-rtl.css') === FALSE) {
      $widgets[$file->uri] = drupal_ucfirst($file->name);
    }
  }


How to hide comments from indexing? I am using Drupal 7. I do not want comments to index in search module. How can I achieve this?

One possibility is to create a custom search page using Views and Search API. With Search API you can select precisely what you want to get indexed.


Services 3.0 Json string reveived with underscores I am using D7 services 3.0 and im sending data from an app. I use the json.stringify function before sending the data to my endpoint. However some characters are being replaced by underscores. For instance test@gmail.com becomes test@gmail_com. Any ideas?

http://php.net/manual/en/language.variables.external.php

When PHP receives POST/GET it replaces dots in keys with an underscore. I would look at the app receiving the data and see if you can work around it there.


Job queue – dealing with stuck records I have a cron job that gets stuck because I have a loop claiming items from the queue that ends on numberOfItems() == 0, which never happens because one of the queue items is stuck and cannot be claimed.

Clearly this is a flaw on my side, but I am trying to understand how to best address it. The claimItem() method returns FALSE every time in this case, so it should be easy to handle cases of bad queue processing, for example:

while ($item = $queue->claimItem()) {
    // process item
}

However, what if the first queue item is "faulty", while there are other queue items that are perfectly fine? I will never be able to retrieve them in this method. It also seems impossible to move on to the next item in the queue if claimItem() returns false (please correct me if I am wrong).

What is the correct way to handle such cases with Drupal's queue?

When looking at the code from the claimItem method it only returns FALSE if no items are available to claim.

So if $queue->claimItem() returns FALSE you can be sure that all available items are claimed (or failed to be claimed).

public function claimItem($lease_time = 30) {
  // Claim an item by updating its expire fields. If claim is not successful
  // another thread may have claimed the item in the meantime. Therefore loop
  // until an item is successfully claimed or we are reasonably sure there
  // are no unclaimed items left.
  while (TRUE) {
    try {
      $item = $this->connection->queryRange('SELECT data, created, item_id FROM {' . static::TABLE_NAME . '} q WHERE expire = 0 AND name = :name ORDER BY created, item_id ASC', 0, 1, [':name' => $this->name])->fetchObject();
    }
    catch (\Exception $e) {
      $this->catchException($e);
      // If the table does not exist there are no items currently available to
      // claim.
      return FALSE;
    }
    if ($item) {
      // Try to update the item. Only one thread can succeed in UPDATEing the
      // same row. We cannot rely on REQUEST_TIME because items might be
      // claimed by a single consumer which runs longer than 1 second. If we
      // continue to use REQUEST_TIME instead of the current time(), we steal
      // time from the lease, and will tend to reset items before the lease
      // should really expire.
      $update = $this->connection->update(static::TABLE_NAME)
        ->fields([
          'expire' => time() + $lease_time,
        ])
        ->condition('item_id', $item->item_id)
        ->condition('expire', 0);
      // If there are affected rows, this update succeeded.
      if ($update->execute()) {
        $item->data = unserialize($item->data);
        return $item;
      }
    }
    else {
      // No items currently available to claim.
      return FALSE;
    }
  }
}


How to track and notify employees when their certifications have expired? I am creating a Drupal 7 site where it tracks an employee's certification status, and notifies them if it has expired/is about to expire.

Currently, I have a content type called "Employee Info," where different types of certifications (under the "certifications" field, a list type) can be checked off for each employee, depending on which certs their job requires them to have.

For example, say I'm entering Billy John as a new employee who was certified in CPR, Cycling, but not Swimming. The CPR certification only lasts one year, and the Cycling cert lasts two. I would like it so the user can enter that Billy was certified for CPR on say, 1/1/15, and Cycling on 6/1/15, once their respective box is checked. Then, when 1/1/16 has rolled around, they get the notification that their CPR certification has expired (and likewise on 6/1/17 for their Cycling cert).

However, I am unsure how to do this, or if this is even the best approach to the problem.

Any help or guidance would be greatly appreciated!

Your question doesn't specify how such notifications should be implemented. Though there are at least 2 possible implementations:

Send an eMail to such employee when the time is right.
Create some type of alert when the employee visits the site.

Read on for more details about either implementation.

Create an alert

Enable the Menu Badges module, which can be used to add notifications to any menu item and/or menu tab of your choice. Here are some details about it (from its project page):

  Provides a method for adding iOS-style badges to menu items. (see screenshot)

Because of how it integrates with the Views module, you basically reduce the solution specific to your question here to something like this:

Create an appropriate view about "expired certifications" (as in your question).
And create a menu item or menu tab for it.
Perform the required Menu Badges configuration to tell it which menu item/tab you used for it in your view.

Refer to the video Defining Menu Badges with Views in Drupal (from the module maintainer) for more details.

Send an eMail

You could use the Rules module to send an eMail when the time is right. To do so, have a look at the question about "Rule to store user's last post date and scheduled rule based 30 day reminder", which may be considered as a variation of this question here. My answer to that question should be pretty close to what you're looking for.

If you'd replace field_next_article by an "expiration date" of a certificate, you already have what's suggested in "Step 1". You should be able to reuse most of the Rules Component included in Step 2, and the Rule included in step 3, with only some minor changes.


Rename images while uploading and put in specific folder I am using drupal 7.

I have created an Advertisement content type. This contains a field where end user can upload images of their Brands.

I want to rename the images which are uploaded by the field of content type and put in specific folder named user id of the user. So uploaded file location would look like it:
/sites/default/files/images/user_id/

File (Field) Paths let you set file name and file path for file field:


Fetching(GET) image url with applied image styles using jsonapi module Looking to make request using the jsonapi module to GET all urls that point to the images optimized version of the image.

If I use the Drupal front-end with Twig and view my page and inspect the images on the page I get something like this

http://local.mysite.com/sites/default/files/styles/promo_background_image/public/promo-backgrounds/MYIMAGE.png?h=df23a951&itok=fslZ-kmD

If I make a request to my api endpoint and drill down to the image field it does not have the included image style url.
```

{
"data": {
    "type": "file--file",
    "id": "b74b73fb-19fd-48a2-ac91-8a7aacd7fe18",
    "attributes": {
        "fid": 2,
        "uuid": "b74b73fb-19fd-48a2-ac91-8a7aacd7fe18",
        "langcode": "en",
        "filename": "MYIMAGE.png",
        "uri": "public://promo-backgrounds/MYIMAGE.png",
        "filemime": "image/png",
        "filesize": 37624,
        "status": true,
        "created": 1508723420,
        "changed": 1508723610,
        "url": "/sites/default/files/promo-backgrounds/MYIMAGE.png"
    },
    "relationships": {
        "uid": {
            "data": {
                "type": "user--user",
                "id": "b044b880-ab4e-495b-b2d1-6a4fe58dc609"
            },
            "links": {
                "self": "http://local.mysite.com/api/file/file/b74b73fb-19fd-48a2-ac91-8a7aacd7fe18/relationships/uid?language=en",
                "related": "http://local.mysite.com/api/file/file/b74b73fb-19fd-48a2-ac91-8a7aacd7fe18/uid?language=en"
            }
        }
    },
    "links": {
        "self": "http://local.mysite.com/api/file/file/b74b73fb-19fd-48a2-ac91-8a7aacd7fe18?language=en"
    }
},
"links": {
    "self": "http://local.mysite.com/api/file/file/b74b73fb-19fd-48a2-ac91-8a7aacd7fe18?language=en"
}

}

```

How can one get access the image style uri using the jsonapi as my api server?

I would do it

create file: test_api.info.yml

name: Test API
type: module
description: Custom RESTful API module with GET/POST/PUT/DELETE etc.. method examples.
author: Minnur Yunusov
core: 8.x

create file: test_api.routing.yml

test_api.getparameter:
  path: 'my-api/get/{nid}'
  defaults: { _controller: '\Drupal\test_api\Controller\TestAPIController::getpara_example' }
  methods:  [GET]
  requirements:
    _access: 'TRUE'

create file: /src/Controller/TestAPIController.php

<?php

/**
 * @file
 * Contains \Drupal\test_api\Controller\TestAPIController.
 */

namespace Drupal\test_api\Controller;

use Drupal\Core\Controller\ControllerBase;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\user\Entity\User;

/**
 * Controller routines for test_api routes.
 */
class TestAPIController extends ControllerBase {

  /**
   * Callback for `my-api/get.json` API method.
   */
  public function getpara_example($nid, Request $request ) {

    //get node;
    $node=node_load($nid);

    //get image uri
    $image =$node->field_image->entity->getFileUri();

    $style = \Drupal::entityTypeManager()->getStorage('image_style')->load('thumbnail');

    $url = $style->buildUrl($image);

    $response['nid'] = $nid;
    $response['uri'] = file_create_url($image);
    $response['image_original'] = file_create_url($image);
    $response['image_style_thumbnail'] =file_create_url($url);

    return new JsonResponse( $response );
  }

}

test:
url: localhost/drupal8/my-api/get/30
method: get

note: 30 is nid.

result:

{
  "nid": "30",
  "uri": "public://2017-10/generateImage_1RwT72.png",
  "image_original": "http://jeremiselxi.260mb.net/drupal8/sites/default/files/2017-10/generateImage_1RwT72.png",
  "image_style_thumbnail": "http://jeremiselxi.260mb.net/drupal8/sites/default/files/styles/thumbnail/public/2017-10/generateImage_1RwT72.png?itok=Dzg02oew"
}


Why anonymous users can only see 1 link in navigation menu? I'm trying to show navigation links to anonymous users/ visitors of my site. However, they can only see 1 of the many links while the administrator can see all links just fine.

I'm using Drupal 7 and Zen theme.

My settings : http://i.imgur.com/MVRwejG.png

This is what anonymous users/ visitors see: http://i.imgur.com/3uNNR9Y.png

That is because they do not have the necessary permission. So for example they do not have permission to create contents of type (article, blog, basic page and product) in your case. And I want to believe you don't want anonymous users to create products, pages, e.t.c.

To assign anonymous users new permissions, go to admin/people/permissions


Update image in image widget (automatically upload?) on another ajax reference field's autocompleteclose event So I have a few fields that are automagically populated when an entity reference field is 'autocompleted'. Text and Image data (path, etc)

...field_widget_form_alter(&$element, FormStateInterface $form_state, $context) {
    $element['target_id']['#ajax'] = [
      'event' => 'autocompleteclose',
      'callback' => 'ajax_callback',
    ];

This is not an issue with text, but how do I update my image-widget (upload field) with a new image path and automagically upload?

...function ajax_callback(array &$form, FormStateInterface $form_state) {

// For text field this is pretty straightforward.
$response->addCommand(new InvokeCommand('input[name="field_....[' . $delta . '][subform][field_..._name][0][value]"', 'val', [$text]));

Is it possible to pass a path and filename to an image upload input(image-widget) and maybe mock .click() (or something) to trigger an automatic upload when selecting said field reference autocomplete?

Use case (total of 3 fields):
User completes autocomplete field and two additional fields, say description and image (upload input) are automatically populated/image uploaded. (But I can go back if the user wants and update the image (separately) using normal options on the image upload input, if needed.)

No that isn't possible. You can't automate completion of a file input field, it would be a massive security hole (I think browser plugins for chrome/Firefox can do it, but they run in a different security context to website scripts anyway)

If it were possible, anyone with a website could steal any file from any visitor's computer they fancied.


Make my view the default for content type I am probably doing this the wrong way, so please correct me if I am wrong!

I have created a new content type, called "Entities". My content type has many fields, and the default view when you visit "/node/123" is ugly, and doesn't permit much customization. So I created a new View with all my fields displayed exactly how I want, and set the path to be "entity/%", so when you visit "/entity/123" you get my new, prettier version.

However, the default view at "/node/123" still exists, and is the default display when you click on a link in the search results, or admin interface, etc.

How can I make it so "/entity/123" (my view) completely replaces "/node/123" (default view) everywhere? Eg. becomes the default view for the "entity" content type?

Your main concern is you don't want the /node/123 link to be available publicly or in search results?  You could unpublish the node and then make a Boolean field in your content type and for your view choose to show the piece of content based on your new boolean field INSTEAD Of the stock published/unpublished checkbox.  So your view by default will only show "published" content but you can change that so that it shows "live" content (new boolean field you created for that content type)  or like that and ignores the published/unpublished field.  So node/123 won't show up for anonymous users or in search results but will still be processed by your view.  Assign the view to the path of your choice /contact-page or whatever and you're golden.


Hierarchical select ajax conflict in custom bootstrap theme I have created a custom theme from scratch using twitter Bootstrap. In my content type there is Taxonomy term Hierarchical Select (HS) list.

Problem: When authenticated user try to select any term from first level, HS keeps on loading...for ever.

Note: Hierarchical select is working fine for admin with core Seven theme enabled and with jQuery update version 7.

Please help.

It was Colorbox which was conflicting with HS. I disabled the colorbox module and it worked perfectly. I don't know why this happens, but this should be raised as an issue since both are contrib modules.


How to sort in accordance to best match on the results returned by a views filter? I have a search functionality which lets user search for people based on their names. To achieve this I am using a view with an exposed filter on the field and the operator being "Contains any word". Now I want to sort the results with the best matched result appearing first. Say I am searching "Amy Jackson", I get all the users with "Amy" first and then the results with "Jackson", thus Amy Jackson does not appear first.

You can do this if you have the core search module installed.  For your filter use "Search terms" (exposed), and for sort use "Search score" (descending).

You'll be able to influence what factors are dominant in the ordering of results by adjusting the settings at admin/config/search/settings.

If you want more control over the ordering then it could be worth looking into the Search API module but setting this up is a lot more involved.


Custom module wiped out all content of type I've recently written a custom module for my site that deletes nodes older than two years whenever cron runs. It worked perfectly!

However a few weeks later, after updating Drupal 8 to 8.1.10, all the nodes of type "recent" were deleted! I don't know if it is connected to the module or not, but I have a hunch that it is.

Here is the .module file:

<?php

function delete_old_nodes_cron() {

        $node = $variables['node'];

        $query = \Drupal::entityQuery('node')
        ->condition('created', strtotime('-2 year'), '<=')
        ->condition('type', 'recent');
        $nids = $query->execute();
        foreach ($nids as $nid) {
            $node = node_load($nid);
            $node->delete();
        }
}
?>

and the .info.yml file:

name: Delete old nodes
description: Deletes nodes older than 2 years.
package: Custom
type: module
version: 1.0
core: 8.x

Your query seems to be ok, irrespective of drupal version it should work. Here are the few pointers to debug.

Check the query output, is your query returning all nodes of type 'recent' without filtering by created

function delete_old_nodes_cron() {
  $query = \Drupal::entityQuery('node')
      ->condition('created', strtotime('-2 year'), '<=')
      ->condition('type', 'recent');
  $nids = $query->execute();
  dpm($nids);
}

Make sure for your recent created nodes created time is not altered somewhere.


Flag a content with Scheduler Flag a node using scheduler & Rule. But not getting the way how to achieve that.

Scenario:

I have a Content type "xxx" and I have set a flag with this content type.
So, whenever a user creates a content,I want to use scheduler so that user can specify at which particular date & time it should be flagged.

(Scheduler provides when to publish and unpublish content,I want to Flag the content)

Let me know if anyone having any idea about this.

Thanks in advance.

I know it was not that difficult but I was not getting the actual thing how to achieve it but now it is working for me.

Things to do:

Go to your /admin/config/workflow/rules/components and click on "Add new Component"
Select "Action set" under Component plugin & Press Continue.
Give appropriate Name.E.g: Flag Node.

Data type : Content, Label: Node, Machine name:node & Press Continue.
Click on "Add action"  & select "Flag a node" ,once it returns the result data,Select which flag should be clicked.

For => node :Data selector use node &

For =>User on whose behalf to flag : Data selector use node:author

& Press Save.

Done with the component.

Now Add a New Rule
Go to your /admin/config/workflow/rules and click on "Add new Rule"
Give appropriate Name.E.g: Flag Node Rule.

React on event : After updating existing content. (as you need)

& Press Save
You can add conditions if you want whether it should be published or should belong to any content type or what so ever you need.
I have used Content is of type.
This is the thing which works like a magic to schedule your event(Here Flag).
Click on "Add action" & Select "Schedule component evaluation" under Rule Scheduler

& Select the Component Value ** as (**Flag Node) which we created just before configuring this rule & Press Continue.
Enter Scheduled evaluation date which will schedule your event when to get triggered.

Data selector :(Enter Your values as +2 minutes, +2days, +2 weeks etc as your need)
Identifier => Value : [node:title] has been Flagged.(You can use any message you want to see on /admin/config/workflow/rules/schedule along with list of scheduled events.)
Node => Data selector : node

& Press Save.

Done with the Rule.

Configuration is done. You can test it now.

But please have a look into this. I was not checking such thing so was not able to see the result.
Your event will respond you only after the cron run because it is executed by the cron. The cron triggers a query to check whether something should be published or flagged.If your cron runs every hour and you want something published on 22:35 and it is past that time it will be actually published the next time your cron runs. So if your cron runs at 22:30 and 23:30 the publish will be at 23:30.

Hope this will be helpful for someone.


How to create menu item with panels? I am using Drupal 7. In one of my projects I used Panels to create a custom layout to one of my pages. As per the needs I also created a menu "item" with the panels. But when i access the menu path of "item" i get the menu to be displayed. When i click the home or other tabs the menu "item" disappears.

Is this a bug in panels or am I missing something that can term me as a novice?

It may or may not be important to understand, but Panels does not handle menues at all, it only deals with the layouts their UI. Page manager, a part of Ctools, however does handle menues, which is probably what you are using.

To figure out where the issue is:

Start by going to admin -> structure -> menues and check, is the expected menu entry in the right menu?  If so, go to step 2. If not, you have a miss-configuration or bug in Page manager.
Page manager seemingly has done it's part, and now the question is, how do you render the menu on the different pages? Do you output the menu at all on the page where it doesn't show up?


Fetch content from another website into a new one I want to fetch content from a website into another website. When I edit that content, it will automatically display changes. I am using Drupal 6.

Does anybody have an idea about I can achieve this?

You should take a look at the Feeds module. It can import many different things into your Drupal site. I am using it to import RSS feeds as nodes.


drupal Newsletter based on taxonomy I make a content type that called "commission".
And also I have created a Taxonomy called "commission" too.
In the taxonomy we have some terms like "Fun" or "sports" and etc.
When the user want to create commission node, they should choose one of the taxonomy terms.
Now my question is this:
I want a module to make a subscribe link for people that they can subscribe on the content with the just "sport" taxonomy term or "fun" taxonomy term or something else.
It means I need a subscribe Newsletter module based on the Taxonomy terms.
What shall I do?

Try using Total Subscription which says :

Total Subscription provides functionality which would allow the user to subscribe to node pages, taxonomy terms, etc. The main feature which distinguishes it from other subscription modules is that it allows subscription for Anonymous along with Authenticated users.

Or you can try Simplenews module as well, which has feature of rules integration so that you can customize it with taxonomy.


on delete of one field delete other field too I want to implement some logic using what I can define that one delete of one field delete other related field.

so is there any module available or anythings else using what I can define cascade delete.

You can use hook_field_delete to determine which field is removed, and if its "yours" - find out which field you need to delete next and delete it

function hook_field_delete($entity_type, $entity, $field, $instance, $langcode, &$items) {
   if ($field['field_name'] == 'YOUR_FIELD_NAME') {
       //do some stuff to determine which
       //field you need to delete
       //and delete it
       //how to remove the field - the link below
   }

}

how to remove the field


Authenticating users and uploading content with Services module I am trying to learn how to set up a service that will accept http-posts including user login and password, authenticate the user, then allow the user to upload a file that will be used to create a new piece of content.  I could not find any good resources explaining how to handle user authentication with the services module nor did I find any good resources about how an upload or content creating could be accomplished.  Does anyone know of any such resources I may have missed?

http://drupal.org/node/736522 should help you.


Commerce account pane email change I am using Drupal 7 with commerce module. In the commerce shipping pane I have created a new email filed through admin -> store -> Customer profiles -> Shipping Information and it is displaying in the shipping section that’s all fine.

Now what I have to do here is use this email while creating the account for anonymous users instead of using email from the account pane and also I need to hide the email filed in account pane.  Can anyone guide me how to implement this? Thanks in advance.

Ratheesh

I have resolved the issue like adding a submit handler function when click on continue button click. Code is provided below

your-module_form_alter(&$form, $form_state, $form_id) {
   global $user;
   if(!$user->name){
      $form['account']['login']['mail']['#required'] = 0;
      $form['account']['login']['mail']['#prefix'] = '
';
      $form['account']['login']['mail']['#suffix'] = '
';
      array_unshift($form['buttons']['continue']['#validate'], 'your-module_submit_handler');
    }
}

your-module_submit_handler(&$form, &$form_state){
    $form_state['values']['account']['login']['mail'] = $form['customer_profile_shipping']['field_email']['und'][0]['value']['#value'];
}


Drush alias partially working My Drush alias file is:

$aliases['mysite'] = array (
  'uri' => 'mysite.com',
  'root' => '/var/www/mysite',
  'path-aliases' => array(
    '%dump-dir' => '/tmp',
  ),
);

when I do drush @mysite status I get

 Drupal version         :  7.36
 Site URI               :  mysite.com
 Database driver        :  mysql
 Database hostname      :  localhost
 Database port          :  3306
 Database username      :  dbuser
 Database name          :  dbname
 PHP executable         :  /bin/php
 PHP configuration      :  /etc/php.ini
 PHP OS                 :  Linux
 Drush version          :  7.0-dev
 Drush temp directory   :  /tmp
 Drush configuration    :
 Drush alias files      :  /home/deploy/.drush/mysite.aliases.drushrc.php
 Drupal root            :  /var/www/mysite
 Site path              :  sites/default

But I'm unable to run other Drush commands.

eg:

drush @mysite dd
You need to specify an alias or run this command within a drupal site.           [error]
Target 'root' not found.        [error]

OR

drush @mysite cc all
No Drupal site found, only 'drush' cache was cleared.                            [warning]
'all' cache was cleared.                                                         [success]

But drush dd commands works this way:

drush dd @mysite
/var/www/mysite

I tried like that, but this one doesn't work though
drush cc all @mysite

Any ideas why is that so, the site is running perfectly.

In drush status you should have the following lines right after Database credentials:

Database                        :  Connected
Drupal bootstrap                :  Successful

When you don't have it, this suggest your Drupal instance is not properly configured and drush has problem bootstrapping it. For example, you may check if you can connect to the database, try: drush @mysite sqlc.

When executing dd on a remote machine, Drupal needs to be able to bootstrap on the configuration level, so it can read the variables. When you don't have the proper access, you'll have the error like:

  Target 'root' not found.

See also: drush_core_drupal_directory().

Other suggestions:

Make sure that on your local and remote you have got the same version of drush.
Other problems could include issues with specific PHP version (see: #779).
If you've still problems, run drush with verbose (-v) or debug options (-d).


prevent user creating a duplicate node title how to prevent user creating a duplicate node title for a content type?

I already try uniqueness module (https://drupal.org/project/uniqueness) but it's only list out the duplicate content title but not return any error message when user save the new content. Any suggestion module or code? :)

You can try the Unique field module.

  This module performs additional validation when a node is created or
  updated by a user to require that a node's title, author, language,
  and CCK fields are unique within a given context.

I have not tested it yet, but it seems promising.


Implementing a view relationship plugin Using Drupal 8, I am trying to create a view plugin to add a relationship to an existing view.
I'm basing the code off of this example https://www.foreach.be/blog/how-build-complex-filters-drupal-8 since I haven't found an explanation of how to add a relationship in D8.

I don't have any error messages but I'm not sure what I need to do to get this working.

I have a class file for the plugin at module_name/src/Plugin/views/relationship/CustomRelationship.php

// CustomRelationship.php

<?php

namespace Drupal\custom_module\Plugin\views\relationship;

use Drupal\views\ViewExecutable;
use Drupal\views\Plugin\views\display\DisplayPluginBase;
use Drupal\views\Plugin\views\relationship\RelationshipPluginBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Url;

/**
 * Add custom view relationship
 *
 * @ingroup views_relationship_handlers
 *
 * @ViewsRelationship("custom_relationship")
 */

class CustomRelationship extends RelationshipPluginBase {

  /**
   * Relationship plugin.
   *
   *
   */
  public function init(ViewExecutable $view, DisplayPluginBase $display, array &$options = NULL) {
    parent::init($view, $display, $options);
    $this->valueTitle = t('Node Revision');
  }

  public function query() {

    $configuration = array(
      'table' => 'node_revision',
      'field' => 'nid',
      'left_table' => 'node_field_revision',
      'left_field' => 'nid',
      );

    $join = Views::pluginManager('join')->createInstance('standard', $configuration);
    $this->query->addRelationship('node_revision', $join, 'node_field_revision');

  }

}

And in the main module folder there is a views.inc file

// custom_module.views.inc

<?php
/**
 * Implements hook_views_data_alter().
 */
function custom_module_views_data_alter(&$data) {
  $data['custom_module']['custom_relationship'] = array(
    'title' => t('Node Revision'),
    'help' => t('Provide node revision relationship.'),
    'relationship' => array(
      // ID of relationship handler plugin to use.
      'id' => 'custom_relationship',
    ),
  );
}

You shouldn't need to create a Views relationship plugin, although that might depend on any special cases with your relationship.

I've got two custom entities - a student and a school, which have been scaffolded using Drupal console. The Student has an entity reference field (school_id) which relates a Student to a School but the opposite relationship - Students belonging to a School - isn't generated by default. So to create the relationship that can be used in views, I built this hook method:

/**
 * Implements hook_views_data_alter().
 */
function school_student_views_data_alter(array &$data) {
  $data['school']['student']['relationship'] = [
    'title' => t('Student'),
    'label' => t('Student'),
    'group' => 'School',
    'help' => t('Reference to students of a school'),
    'id' => 'standard',
    'base' => 'student',
    'base field' => 'school_id',
    'field' => 'id',
  ];
}

If you examine the $data array, you'll see all the data for all your views tables. It's a big list with lots of array elements. It'll make sense when you look at it. Set a breakpoint in your views_data_alter hook to inspect it (or use dpr/kpr/dpm).

What we're doing is creating a relationship from one table to another, as this relationship currently doesn't exist. I believe that the array element names 'school' and 'student' should refer to the table names we are dealing with. We're creating a relationship data alter and so 'relationship' is the child array element we need to create. Below that is just configuration.

title refers to the relationship title in your "Add relationship" modal window

label is the default name of the relationship when you create it

group is the name of the relationship group your new relationship belongs to

help is helper text/description for the relationship

This next bit is important!

id refers to the the name of the views relationship plugin you are needing to use. Because I'm not creating a complex relationship (basically a simple inner join), I'm using the Standard views relationship plugin (found in Drupal\views\Plugin\views\relationship\Standard).

Finally, base is the base table we're creating the relationship from.

base field is the join field in our base table and finally field is the field in the school table we're creating our join to.

So in use, views will create a join that in SQL looks like:

INNER JOIN {student} student_school ON school.id = student_school.school_id

Hopefully this makes sense and helps you or others out.


custom user login/register menu tabs I'm making a website with 2 different kind of users. using the Profile2 module, and i'm kind of stuck.

Tourists who register with the normal user/register form.
And Guides who register with a custom guide/register form.

On the homepage we have a simple user menu with login and register button.

I want to customize the tabs on the user/register page to have two tabs:
Register as tourist and Register as guide

So I want the tabs of login and request password to be gone on the registration forms.

BUT I do want the login and request password tabs on the login page.

It sounds like you're wanting the use case covered by the Profile2 Registration Path module:

  By default, the Profile 2 module permits you to add fields from chosen
  profile types to the default user registration form. Unfortunately,
  there is only one user registration form. Thus, every user will be
  presented with these fields during registration. If you have two
  profile types targeted at two different audiences, you cannot have two
  separate registration forms.

Anything else, might need to be covered by a form/menu altering custom module or Tab Tamer.


Where should I begin in creating a page to allow authenticated users to submit a short story that will become it's own independent page? I have installed the most recent version of Drupal on my computer using xampp as the local host.

I would like to allow authenticated users to be able to publish content (ie a short story & accompanying imagine) that would appear on a stand alone page, not like a blog; for example, if a user submits 3 stories, then each story could be accessed independently.
Ultimately, during the submission process I would like the user to identify the category of the story (adventure, romance, sci-fi, etc) that would then appear in the appropriate section of the website.
In my mind it would be similar to a user submitting a recipe on a cooking site. I imagine the submission page would not be dissimilar to the page I'm on now to submit this question.

All of which is to say, where do I begin? What modules will best assist me? Can I develop the submission page and then institute the taxonomy?

Hope this gets you off the ground. Of course you need some more reading/googling.

Give users the right to register an account on your site.
Create a content type with all the fields you need. You can do this with the built in fields features.
Create a role that has the right to create/edit/delete a this content type. This is a drupal core feature as well.
Assign a role to this users up on register (auto assign role module).
Make sure nice descritptive URLs are created automatically from the node titles (and maybe some fields) (path auto module)
Done.


how to display the last mailchimp campaign? I need to display the last campaign (preview, description, name) in my website but currently mailchimp module doesn't have a block or view to do this, is there another alternative?

I think you use mcc module for create mailchimp for node. when you disable this module its show list of all campaign which you created.

you can also use mailchimp function for getting list of campaign:

$campaigns = mailchimp_campaign_load_multiple();


Date Of birth in drupal I am newer in Drupal. I am using Drupal services. I want to insert user birthdate by Drupal rest services. I want How we do this, Any help would be appericiated. Thanks in advanced

You can do that using the  Date module

This package contains both a flexible date/time field type Date field and a Date API that other modules can use.


parent page title on sub menu I am building a website where i generate a submenu based on my main navigation.
The structure looks like this:

Home
About
Work at

vacancies

contact

when you land on one of the level 1 pages, a submenu will appear in the sidebar with the children links of this page.
i want the title of the parent page to show above this menu.

also, on the vacancies page there's a overview of vacancies, and when you go to one of the detailed vacancies i want it to show
"Work at" and not "vacancies" in the submenu title.

i've tried alot of things but can't find the right solution for it.

The menu_block module with the patch in https://www.drupal.org/node/2809699 should work.

Note: you'll have to select the "Use the following as title" field to "Active trail's parent title" when configuring your block.


Group context on pages generated by views I have two group page

node/%/posts and node/%/activity.

Inside these pages, I have a mini panel which requires group context to display. For some reason, the pages generated by views are not recognized as group context though its a menu tab inside the group. Did anyone had the same issue ?

This has been an issue on the Organics Groups page. Please refer to comment #6 for the solution.

The other way to work around this is to Use page manager to create pages instead of using views. Page manager helps to maintain the context of the group across its pages.


How to override version of drupal-library (JavaScript library) included with composer merge-plugin? I'm using Webform with the composer-merge plugin to bring in its libraries:
Relevant parts of my composer.json file:
    "extra": {
         "installer-paths": {
             "public_html/core": ["type:drupal-core"],
             "public_html/libraries/{$name}": ["type:drupal-library"],
             "public_html/modules/contrib/{$name}": ["type:drupal-module"]
         },
         "merge-plugin": {
             "include": [
                 "public_html/modules/contrib/webform/composer.libraries.json"
             ]
         }
     }

I can define my own version of the same library successfully, by using the same code as Webform's composer.libraries.json does but changing the version— successful in that it is recognized:
    "repositories": {
        "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        },
        "jquery.inputmask": {
            "type": "package",
            "package": {
                "name": "jquery/inputmask",
                "version": "5.0.6-beta.45",
                "type": "drupal-library",
                "extra": {
                    "installer-name": "jquery.inputmask"
                },
                "dist": {
                    "url": "https://github.com/RobinHerbots/jquery.inputmask/archive/5.0.5.zip",
                    "type": "zip"
                },
                "require": {
                    "composer/installers": "~1.0"
                }
            }
        }
    },

But unsuccessful in that it does not have priority over the one defined in webform:

Root composer.json requires jquery/inputmask 5.0.6-beta.45, it is satisfiable by jquery/inputmask[5.0.6-beta.45] from package repo (defining 1 package) but jquery/inputmask[5.0.5] from package repo (defining 1 package) has higher repository priority. The packages with higher priority do not match your constraint and are therefore not installable. See https://getcomposer.org/repoprio for details and assistance.

But i don't know how to take priority.

But unsuccessful in that it does not have priority over the one defined in webform:

There is a way, just define custom repository before Drupal packages repository .
Change your composer.json to
   "repositories": {
        "jquery.inputmask": {
            "type": "package",
            "package": {
                "name": "jquery/inputmask",
                "version": "5.0.6-beta.45",
                "type": "drupal-library",
                "extra": {
                    "installer-name": "jquery.inputmask"
                },
                "dist": {
                    "url": "https://github.com/RobinHerbots/jquery.inputmask/archive/5.0.5.zip",
                    "type": "zip"
                },
                "require": {
                    "composer/installers": "~1.0"
                }
            }
        },
       "drupal": {
            "type": "composer",
            "url": "https://packages.drupal.org/8"
        }
    },


Automated backreferences between taxonomies Talking about DRUPAL 7, I've found some modules that manage automated backreferences between content types, but these are based on nodereference fields: i need something based on TERMREFERENCE.

I'll try to explain better:

I've a vocabulary (i'm talking about taxonomies, NOT content types) and I've added a termreference field type pointing to the same vocabulary. The scope is to have a "see also related terms" feature when someone is viewing a taxonomy term page.

What I need is a backreference between terms, so, when I add a term B as term reference on term A, automatically term A is also attached to term B as termreference itself:

term A -> Term B

Automatically I need a term back reference:

Term B -> Term A

How can this be done?

Thank you very much!

MXT

Disclaimer first: I am one of the relation maintainers. That said, the very reason we came up with relation is because backreferences were too hard.


Create a mock Form for WebTestBase? Is there a way in the testing framework to define a generic form intended only when tests run?

I have created some custom form item Element classes. I have working Unit tests with them, but I would also like to provide Simpletests for them as well.

Core provides several examples of this.  The basic pattern is to create a test module, and have that module provide the form.  In your test ::setUp(), you add the test module to $modules, and then your form should be available for use.

Look through 'core/*/tests/modules' for the test modules, and if you have an IDE that class completes, a lot of the test form are (wait for it) TestForm.

However, in your case, I would look at existing Element classes and see what their integration tests look like.   I suspect you can just emulate what they are doing w/o needing your own test module.


How to use Views & Entity Reference to create dynamic URLs that are based title from the referenced node Here's my situation:

I have two content types: Procedure, and Testimonial. Testimonial has an entity reference field where you can point to one or more procedures.

My goal is to create a view of testimonials with a dynamic URL like 'example.com/testimonials/procedure1', where procedure1 is the title of the node that is referenced from the testimonial. So, the idea is that this page would exclusively show testimonials that reference the procedure1 node.

So, I created the view. I added a relationship "Entity Reference: Referenced Entity". I then created a contextual filter that uses this relationship.

At this point, if I do not use a relationship in the contextual filter, I can get this working by using the following pattern: example.com/testimonials/7, where 7 is procedure1's node ID. But, I'd like to use the title in the URL- not the node ID.

Does anyone know where to go from here?  Am I going about this the wrong way?

Thank you!

This is how I solved a similar problem:  Create a filter on the title and use the relationship: entity.  Then, in a custom module put something similar to:

    function MYMODULE_views_pre_view(&$view, &$display_id, &$args){
      switch($view->name) {
        case 'view_name':
          $value = arg(x);
          $view->display['default']->handler->options['filters'['field_name']['value'] = $value;
        break;
      }
    }

I'll probably go ahead and build a more universal module out of this because of how often I use it.  The benefit is you can inject an argument as a filter.  I use dashes for spaces and include a str_replace(); to replace dashes with spaces for the filter.  You loose some validation, etc. but there's a bunch of modules that provide filters but no contextual relationship.  This binds the two in a hacky way.


Create Linestring Between 2 Points I have a series of letters, each with a recipient and sender address stored with Addressfield, with spatial data added Geocoder into lat/long and stored in a Geofield. I'm using IPGV&M, Views, and Leaflet to render these points - 1 letter to each row, with 2 points (sender / recipient). This is working fine.

I'd now like to add a linestring between those two points, but am at a loss for how to do that. Can Geofield store linestrings? Can I automatically generate a linestring and store that in a Geofield field based on the geo POINT values of the sender / recipient Geofields?

I ended up using Rules to automatically populate a text field with the linestring data LINESTRING(lat lon, lat lon) after every new entity add or existing entity update, with the condition that both geofields (sender and receiver) were filled. Created another geofield to hold the LINESTRING, geocoded from the text linestring field as WKT. Ran VBO to update all existing nodes. Plots well in IPGV&M and should handle itself automatically from now on.


Best way to build pages, or page equivalent I manage a Drupal 6 site that has various content types and is set up to display them in various methods, all of which work just fine.

However, marketing likes to generate specific campaign based landing pages.  These are primarily static pages, and historically have had no usability extras at all.

Using drupal, the design team has started to request a higher level of interaction, different blocks depending on role, use of the customers name if we have it... little things for the most part.

The solution I'm seeking:

...ideally lets the designers to be able to do this themselves.  Dropping in the html and images, css, video, whatever.

...is potentially free of the site theme... this is trickier.  I'd like them to be able to not include the header and footer if they didn't want it... or use a different body background.

...doesn't require a large number of modules.  I stated this in a way that confused people before... we use a lot of modules.  I don't mind modules.  But I'd to find a solution that isn't a kludge of 8 modules mashed together in a way that isn't exactly what they were designed for and doesn't deliver exactly what you want.

Or as mtro put it as concise and eloquent as possible: designers regularly give me html/img/css packs that need to live on a single page within the site, and you want to streamline creating those pages without recurring template work?

My question is what do other What do other Drupalers do when you have non-standardized content that is regularly added and has partial or no theming?

I would suggest checking out Panels and CSS Injector.

Panels does most of what you are looking for; it presents a user interface for laying out varied content on a page without having to dig into HTML. It's not quite a pure WYSIWYG interface (theme styling might not apply to the Panels UI depending on your set-up), but it is as close as you can get with an out-of-the-box solution in Drupal.

CSS Injector will allow your designers to write CSS specifically for one Panels configuration through the UI, without having to touch the theme files.


How to remove unused files from directories I want to remove/delete files from site directories (e.g. /sites/default/files/*) that are not used in site. There are thousands of files that causing fillup size. Any suggestions for this?

I found this post https://drupal.org/node/733258... may help...

The main purpose talked in this issue is about removing the images which doesn't have any use directly from database via SQL queries.

Audit files module is suggested as a good start (because doesn't delete files) to find files which are unused.

This code snippet is one of the suggested solution from the issue :

<?php
//db_query to find all files not attached to a node:
$result = db_query("SELECT fid FROM file_managed WHERE NOT EXISTS (SELECT * FROM file_usage WHERE file_managed.fid = file_usage.fid) ");

//Delete file & database entry
for ($i = 1; $i <= $result->rowCount(); $i++) {
  $record = $result->fetchObject();
  $file = file_load($record->fid);
  if ($file != NULL) {
    file_delete($file);
  } }
?>


How do I remove the progress bar in Webform module? I am using Drupal 7 and I have version 7.x-4.23 of Webform. When I create a Webform it is a simple one-page submission form. There is a really unnecessary "Start > Finish" progress bar right in the middle of the page. I go to Configuration > Webform Settings > Progress Bar and make sure "Show Progress Bar" is unchecked. However, even after clearing all cache and refreshing the page the progress bar is still there.
How do I get rid of this progress bar?

long and short of it  just use css to hide it.


Execute drush command against against multiple groups We have a large set of Drupal instances, and we use Drush alias groups to group them logically. For example, we have a group "dev" for all sites "in development", and, for example, another called "7_36" for all on Drupal core 7.36.

I can currently run commands against all sites in a single group (drush @dev status), but is it possible to run a command against all sites which are in both groups? For example, I'd like to run a command against all sites found both in @dev and in @7_36.

Is this possible?

You can create a new alias group that is the combination of the two (by hand):

$aliases['newCombinedGroup'] = array(
  'site-list' => array(
    // Dev group 1 sites
    'site1',
    'site2',
    'site3',
    // 7_36 group 2 sites
    'site6',
    'site7',
    'site8',
  ),
);

This is discussed in this other thread:
How to use Drush's concurrent execution capability?

Another option as pointed out by the maintainer of Drush here:
https://drupal.stackexchange.com/a/134472/3279

is to compose your alias group site names for example from a PHP array of site names, then build your alias entries programmatically by looping through these site  names and filling out the contents of the drush alias itself.

So something like:

// This is untested example code.
$sites_in_dev = array('site-dev-1', 'site-dev-2');
$sites_in_736 = array('site-1', 'site-2');

$aliases['newCombinedGroup'] = array(
  'site-list' => $sites_in_dev + $sites_in_736;
);
$aliases['@dev'] = array('site-list' => $sites_in_dev);
$aliases['@7_36'] = array('site-list' => $sites_in_736);

foreach ($sites_in_dev as $sitename) {
  if ($sitename == 'site-dev-1') {
    $aliases['Dev1'] = array( /* ... */ );
  }
  if ($sitename == 'site-dev-1') {
    $aliases['Dev2'] = array( /* ... */ );
  }
}

foreach ($sites_in_736 as $site) {
  // ... etc ...
}

.... You get the idea. Also I would refrain from using @7_36 as an alias name. In general PHP variables shouldn't start with numbers -- and while an alias isn't a php variable persay you're playing with fire by giving it a name that would be an invalid php variable name; when evaluated now and in future versions of Drush ... who knows how that will behave.


Different fields in user profile for different user roles I have created user roles parent, teacher and student. I want to relate parents with a student by creating a Field Related student for only parents. I tried using User References. But that makes the field common for all user roles. I also tried Profile2 module. But that doesnot exactly fit what I want. Is there any other way to achieve that ? Any suggestions please. Thank you.

Field Permissions will let you assign different permissions to a field based on role.

  The Field Permissions module allows site administrators to set field-level permissions to edit, view and create fields on any entity.

  Features

  Enable field permissions on any entity, not just nodes
  Role-based field permissions allowing different viewing patterned based on what access the user has
  Author-level permissions allow viewing and editing of fields based on who the entity owner is
  Permissions for each field are not enabled by default. Instead, administrators can enable these permissions explicitly for the fields where this feature is needed


How do I get the Commerce order type programmatically? I have two Commerce order types, order_a and order_b, which I created at /admin/commerce/config/order-types.

I'm using Commerce 2 on Drupal 8.

I want to process them differently in hook_commerce_order_presave().

How can I programmatically get the order type?  When I check the entity type, it only has commerce_order, but I want to know what type of commerce order it is.  I can't find a method to get the order type specifically.

Here's the code I am using:

function MYMODULE_commerce_order_presave(\Drupal\commerce_order\Entity\OrderInterface $entity) {
  if ($entity->isNew()) {
    kint($entity->getEntityTypeId());
    die();

The order type is the bundle so you can use EntityInterface::bundle() to get that info:

$type = $entity->bundle();


How to make expandable text on clicking more button in views? I have created a views with trimmed fields and displaying more button to show the full content.I want to do something like collapse text ie.,when i click on more button it has to expand and show the full text.Any help will be much appreciated on how to do this.Thanks in advance.

This will require some custom theming to accomplish:

In your view, don't trim the field, just show it all for now. This will mean if a user has JavaScript disabled they will still have access the all the content.
In order to enhance the interface as you've described for users with JavaScript enabled, you should take a look at this tutorial.
You will have to tweak things to get it working with your theme. If you're unsure about adding Javascript to a theme, check this out.


How to disable page redirect on node edit? Thank you for reading my question.

I have a node type and all I want is it not to redirect to the node on edit submission.

Currently, when on the node edit page submissions are sent through ajax, however when the node is submitted it also redirects to the node page, making the ajax pointless :( ...

How do I stop the edit page redirecting on submission.

Thanks for any help

I am not sure what the ajax is doing in your specific case, but if all you want to do is redirect back to the node/###/edit page instead of node/###, you are wanting to swap out the submit handler with one that doesn't do the redirect.

The core one, assuming your hook-nodeapi tag implies Drupal 6 anyway, looks like this....

function node_form_submit($form, &$form_state) {
  global $user;

  $node = node_form_submit_build_node($form, $form_state);
  $insert = empty($node->nid);
  node_save($node);
  $node_link = l(t('view'), 'node/'. $node->nid);
  $watchdog_args = array('@type' => $node->type, '%title' => $node->title);
  $t_args = array('@type' => node_get_types('name', $node), '%title' => $node->title);

  if ($insert) {
    watchdog('content', '@type: added %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
    drupal_set_message(t('@type %title has been created.', $t_args));
  }
  else {
    watchdog('content', '@type: updated %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
    drupal_set_message(t('@type %title has been updated.', $t_args));
  }
  if ($node->nid) {
    unset($form_state['rebuild']);
    $form_state['nid'] = $node->nid;
    $form_state['redirect'] = 'node/'. $node->nid;
  }
  else {
    // In the unlikely case something went wrong on save, the node will be
    // rebuilt and node form redisplayed the same way as in preview.
    drupal_set_message(t('The post could not be saved.'), 'error');
  }
}

So, if you created almost a duplicate of it in a custom module...

function YOURMODULE_node_form_edit_submit($form, &$form_state) {
  global $user;

  $node = node_form_submit_build_node($form, $form_state);
  $insert = empty($node->nid);
  node_save($node);
  $node_link = l(t('view'), 'node/'. $node->nid);
  $watchdog_args = array('@type' => $node->type, '%title' => $node->title);
  $t_args = array('@type' => node_get_types('name', $node), '%title' => $node->title);

  if ($insert) {
    watchdog('content', '@type: added %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
    drupal_set_message(t('@type %title has been created.', $t_args));
  }
  else {
    watchdog('content', '@type: updated %title.', $watchdog_args, WATCHDOG_NOTICE, $node_link);
    drupal_set_message(t('@type %title has been updated.', $t_args));
  }
  if ($node->nid) {
    unset($form_state['rebuild']);
    $form_state['nid'] = $node->nid;
    // $form_state['redirect'] = 'node/'. $node->nid; // just remove or comment out this line
  }
  else {
    // In the unlikely case something went wrong on save, the node will be
    // rebuilt and node form redisplayed the same way as in preview.
    drupal_set_message(t('The post could not be saved.'), 'error');
  }
}

with the only change being the removal or commenting out of the redirect, you are halfway there.  Now you need to have this one called when you are editing nodes, which is done with a form_alter, something along these lines...

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

  if ($form_id=='TYPE_node_form') { // TYPE is the machine name of the content type you are dealing with here

    if (arg(2)=='edit') {

      foreach ($form['buttons']['submit']['#submit'] as $h => $handler) {
        if ($handler=='node_form_submit') {
          $form['buttons']['submit']['#submit'][$h]='YOURMODULE_node_form_edit_submit';
        }
      }

    }

  }

}

and now, assuming no copy/paste typos, you should be able to edit that node type and if you hit submit, it does not redirect to the node page but rather redirects back to the node/#/edit page.

Now, if somehow your ajax stuff is doing something similar like swapping out the various handlers, then you will have to do something different yet similar, and the above should be able to guide you a bit.  (The point I am trying to make here is that hitting submit causes drupal to go to/load another page unless that button itself has been ajaxed or otherwise modified)

UPDATE:

I changed the name of the handler from YOURMODULE_node_form_submit to YOURMODULE_node_form_edit_submit because, as I just found out, if you happen to have a module and content type of the same name, drupal goes all recursive on you upon trying to submit the edits of those node types due to hooking into TYPE_node_form_submit automatically.


CCK Node Reference options not showing "this post can't be referenced." I have a CCK field of node reference. As user 1 I can set the node ference field to a node. I will see something like Node Title[nid:123]. When I go in as another user I see [nid:123]. When I go to save the node I get the message:

  Field: this post can't be referenced.

I can't work out why I am getting this. Any ideas?

Nodereference checks that the node is valid before allowing it to save. This check is either a 'standard' check that sees if the node is of the appropriate content type (if you configured the nodereference under the Content types that can be referenced checkboxes); or if you're using Views it can be a 'views' check (if you configured the nodereference under Advanced - Nodes that can be referenced (View)) that sees if the specified node is in the output of the view.


How should I file an issue on drupal.org that affects multiple modules? I have an issue that is caused only when three modules are enabled together (logintoboggan, pathauto, and entity).  When I upgrade entity from rc1 to rc3, one of the functions of logintoboggan breaks if pathauto is enabled.  I have attempted to determine which module is interfering with logintoboggan, or if it in fact is logintoboggan itself that is at fault, but this exceeds my debugging ability.

So, in cases where one has an issue where a specific combination of modules causes an error, where should the issue be filed?  Should only one issue be filed, or should multiple issues be filed and linked to one another?

Personally, I would pick the one with the highest level (or least mature), and post in that issue queue.  By highest level, I mean the one closest to the user, the one with the modules dependent on it, etc.  In your case, I think logintoboggan would be most appropriate.

Then in the issue, explain the situation in detail and mention the other modules.

If the project owner thinks a lower level module is the culprit, then they will decide what to do.  More than likely, they will post a comment, and reassign to a new queue.

I would not post the issue in multiple queues, though.  It makes tracking things too hard.