Large search box on front page I want to make my front page look like simple google search page.

Elements:

Large search box
Footer
Login/Register

I'm having hard time figuring out how to have only these 3 elements.How can i edit search box area and its position?

The first step is to set "search" as the path of your homepage in the "Site Information" configuration section of the site. This step requires that you have already enabled the search module.
If still have blocks of content on your home page the edit each one of the and make sure to set home page " < front > " as the place where they are not visible.
Add the login block to the footer and you are done.
If the any menu is still showing the create a page-front.tpl.php (D6) or page--front.tpl.php (D7) by duplicating page.tpl.php and the remove the code that shows the menus.
To make the search field larger you can use CSS.


Changing proxy settings and making them effective I'm running a Drupal training course at work. For the exercises I've set up an Ubuntu Server VM (with Unity GUI) using VirtualBox. This allows me to port the VM around between my home workstation (with no proxy) and two work locations (each behind different proxies).

Since we work in French, the exercises make extensive use of translations for the various modules installed.

Drupal accesses the Internet from the server in the following different ways:

drush downloads of modules
drush pm-updates
UI verification of module updates
UI verification of translation updates (using l10n_update module)
drush verification of translation updates (also using l10n, but with commands)

Every time I make a change to the VM in one location I have to update the proxy settings in the others, and I'm having great difficulty in working out how to do this. Proxy settings seem to be in three places:

/etc/wgetrc - this changes the wget proxy settings, and it seems to work fine for drush dl and drush pm-update, but does not get taken into account by the UI or drush translation updates
in settings.php: here it seems to be possible to set them in either Drupal-7 format, like so:

$conf['proxy_server'] = '10.154.61.3';
$conf['proxy_port'] = 3128;

or in Drupal-8 format, like so:

$settings['http_client_config']['proxy']['http'] = '10.154.61.3:3128';
$settings['http_client_config']['proxy']['https'] = '10.154.61.3:3128';
$settings['http_client_config']['proxy']['no'] = ['127.0.0.1', 'localhost'];

You can also install a module called http_proxy, and this puts the settings directly into Drupal variables in the database (in the 'variable' table).

What's been bugging me is getting the proxy configuration changes to work. I get into situations where drush works for downloads and module updates but not for translation updates, and the UI doesn't work at all.

Of course, some of this is due to the imponderables of proxy settings (impossible to know what the settings are, and they change unpredictably - at one point for example I had to use the user agent settings).

But I have some questions I'm hoping someone might be able to answer:

What operations exactly do drush dl, pm-update, l10n-update, and the
UI equivalents use? Are there differences that might cause one to
work and others not?
Do both the D7 and the D8 formats in
settings.php work?
What is the difference between using settings.php and the variables in the database?
How do the database variables get updated? Does the fact of changing them in settings.php also update the database?

Summary answer to your questions:

What operations exactly do drush dl, pm-update, l10n-update, and the UI equivalents use? Are there differences that might cause one to work and others not?

**
drush dl: donwload a module or theme
pm-update: update Core
l10n-update: update translation
**

Do both the D7 and the D8 formats in settings.php work?

No there are Some differences between D7 and D8

What is the difference between using settings.php and the variables in the database?

In Drupal 7 there is not any different. The settings store in DB. But in Drupal 8 None on Setting Configuration store in Database So there is no way to change them via DB

How do the database variables get updated? Does the fact of changing them in settings.php also update the database?

Yes, When you changed a config in settings.php  the equivalence variable in database got updated but in Drupal 8 There is no config or variable in DB to store settins.pp configuration.

you can get settings in Drupal 8 by Settings::get(YOUR_CONFING_NAME).


Adding 's on the user login page The following code is adding
's and link to the form action. How can I add them before the form?

function ajax_register_form_user_login_alter(&$form, &$form_state, $form_id) {
  $form['bigletters'] = array(
    '#type' => 'item',
    '#markup' => 'Big letters',
  );

  $form['smallletters'] = array(
    '#type' => 'item',
    '#markup' => 'Small letters',
  );

  $form['links'] = array(
    '#type' => 'item',
    '#markup' => '',
  );
}

If you need the form elements you are adding to appear before the other ones, you should use the #weight property, and give them a negative value, since the default value is zero. Differently, the form elements you add to a form via hook_form_alter() are normally appended to the form, with the exception of when there is a form element with a positive #weight value higher than the #weight value you assigned to your form element.

user_login() doesn't set the weight of its form elements. The following code should work.

function ajax_register_form_user_login_alter(&$form, &$form_state, $form_id) {
  $form['bigletters'] = array(
    '#type' => 'item',
    '#markup' => 'Big letters',
    '#weight' => -10,
  );

  $form['smallletters'] = array(
    '#type' => 'item',
    '#markup' => 'Small letters',
    '#weight' => -8,
  );

  $form['links'] = array(
    '#type' => 'item',
    '#markup' => '',
    '#weight' => -6,
  );
}

If the code doesn't work, then there is probably another module that alters the weight of the other form elements.


Mobile website translation problem (losing language prefix) I have site translations that works with language prefix

m.mysite.com/ - default language (lithuanian)
m.mysite.com/en - english
...

If i translate site to foreign language and pushed menu button on mobile website, it redirects to the default language.
For example, if I were in m.mysite.com/en (website translated in english) and pressed button "News" it redirects me to m.mysite.com/news-page that is in default language.

I should redirect to m.mysite.com/en/news-page that is translated in english and has language prefix /en/.

So, how to add language prefix to the link and redirect correctly (without losing current site translation)?

We've come across a similar problem in our site on a desktop platform. So far, we've discovered the following about links in Drupal (for example, the href on an <a> tag in a Block Body):

If you use a link without a preceding /, Drupal will replace the last url element with your link name (i.e. mysite.com/en/area1/thing1 will become mysite.com/en/area1/thing2 when a user clicks a link configured as href="thing2" on a page in area1).
If you use a preceding / in your link, Drupal appends it to the domain directly (i.e. href="/thing2" directs to mysite.com/thing2).

We leveraged this to make language prefixes work, with limited success. As long as all our links are within the same uri path (i.e. all links on pages within area1 go to area1 pages), the language prefix is preserved. Once you try to leave that path, though (i.e. href = "/area2/thing3" on a page in area1), you must use the / and lose the language prefix. For those pages, you'll need to add URL aliases. We're still looking for a module/solution that saves us the time and effort of aliasing our menu system and cross links.

Note that in any case the base url (mysite.com) is preserved, so you should get the same results regardless of your platform (mobile or desktop).


Programmatically customise fields in node views I'm developing a module that exposes a node type (by the usual hook_node_info() and hook_install()) and a set of custom fields.

I would like to programmatically define what/how those fields have to be shown in the node views (at least "full"). For example: the field XYZ should be hidden in the "full" mode, and the field ABC should have the lable inline (I'm able to do this by UI, but I would like to define it programmatically).

In any case my need is to exactly modify the view mode (not to always hide a field), in order to allow users to modify the default visualisation way after installation, if necessary.

I can't figure what hook I have to implement, or what code I have to write in the hook_install.

Thank you for your help

I want to share the solution I found, in order to help future readers.

In Drupal 7 the concept of "formatter" helpt to control the output of a field. For example this tutorial allow you to programmatically define a custom formatter for a given field.

Then by UI site admins (by admin/structure/types/manage/<nodetype-name>/display) are able to chose that formatter (or others) for any specific field.

If you want to declare a default formatter for a field, the best way seems to be while the install phase of the module.
In that moment (At least in my case and in all tutorial I found on the Internet) you use a field_create_instance method to add a specific instance of a given field. According to the official documentation, you can also add the display options that exactly allow you to define the formatter to be used for a specific display (or the formatters if want to declare for more than one display).


Composer error installing Address module I had a previous error with the Address module, here. Unfortunately the solution is no longer helping.

I'm installing the Address module as follows:

composer config repositories.drupal composer https://packages.drupal.org/8
composer require "drupal/address ~1.0"

Unfortunately I get the following error:

Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - The requested package commerceguys/addressing (locked at v0.8.4, required as ~1.0) is satisfiable by commerceguys/addressing[v0.8.4] but these conflict with your requirements or minimum-stability.
  Problem 2
    - The requested package commerceguys/zone (locked at v0.7.1, required as ~1.0) is satisfiable by commerceguys/zone[v0.7.1] but these conflict with your requirements or minimum-stability.

I've tried the solution linked above, but it doesn't help. I've also checked I'm running the latest version of Composer (1.2.1).

Any ideas?

James

The problem seems to be that I had installed a previous version of the Address module in the sites/all/modules directory, which seems to have been confusing Composer. Composer installs into the modules directory, and after deleting the older copy, I was able to run the composer require command without problems.


How to programmatically create a product display(node) with reference to the product? I want to programmatically create a product display, product and link them.

How can I do it?

Try this function in a custom module

function commerce_display_product_create_method($product){
    $node = new stdClass();
    $node->type = 'product_display';
    node_object_prepare($node);

    $node->title    = $product->title;
    $node->language = LANGUAGE_NONE;

    $node->field_product['und'][0]['product_id'] = $product->product_id;
    node_save($node);
}


Disable cache for one JS file / library I'm using Drupal 8.1.7 and use group module. When a user display a group or an article linked to a group (/group/... or node/...), I want to specify some specific CSS for each group.

I develop a module that do the trick (verify if we display a group or an article, get the group and load a JS file that modify the CSS style of the page). Work great on my dev drupal with no cache, but when I test the module in production with cache active, the JS file seems to be load only once. Have to do a drush cr to load again the file.

There is any way to tell Drupal to load the file everytime, or don't put it in cache ? In the mymodule.libraries.yml maybe ?

color:
  js:
    js/mymodule.js: {}
  dependencies:
    - core/jquery
    - core/drupalSettings
    - core/drupal

I can not believe that you will have one different JS for every group. So caching is cool, and I assume your problem is the triggering of a function in the JS.

You can use the Drupal.behaviors to call a function in your JS everytime a page is loaded, i.e.

(function ($, Drupal) {

  Drupal.behaviors.anyInit = {
      attach: function () {
        myInitFunction();
      }
  }
})(jQuery, Drupal);

function myInitFunction() { do something }

And you can pass variables to the JS (like your group name), by attaching them to your rendering array, like so:

$build['#attached']['library'][] = 'bootasde/asdejs';
$build['#attached']['drupalSettings']['bootasde']['proreos_server'] = SystemTools::getProreosServer();
$build['#attached']['drupalSettings']['bootasde']['checktyp'] = 'a';
$build['#attached']['drupalSettings']['bootasde']['id'] = $id;

Then you access that variables in your JS like:

  var server = drupalSettings.bootasde.proreos_server;
  var id = drupalSettings.bootasde.id;
  var tp = drupalSettings.bootasde.checktyp;

Hope that helps.

Another way could be to add the group names to the CSS classes in your twig template and have some special selectors for each groupname.


CKEditor and IMCE: how to access to public files directory I have a problem that I can't access public files directory from IMCE as file browser (and CKEDITOR as editor). When an user write a blog post, he can't upload images to public directory because this path doesn't appear in the IMCE directory tree.
Prior to post this question I have searched in Drupal Answers, in Drupal forum and in Google if there is an answer to my question but without success. I've read some other answer to similar questions but without success. I put here my configuration.

Config media file system:

Public path: sites/default/files
Private path: sites/default/files/private
Temp path: tmp
Checked: Private files served by Drupal

CKEditor file explorer: IMCE (for all)

Users, that can write blog post, has permission to "Bypass file access control", "Administer files", "add and upload new files", etc.

When they write a blog post and open IMCE to upload an image in the body, the paths shown in the directory tree are all relative to private directory and they can't select public path.
It's for Drupal 7.

How should I do to allow user to upload files to public path with IMCE?

UPDATE
After some days searching about this question, I have found where is the problem. There are two, very old, open issues in IMCE that are just my problem.
https://www.drupal.org/project/imce/issues/2018863
https://www.drupal.org/project/imce/issues/1700438
CKEditor launch IMCE according to the method you have selected to download files in Admin > Configuration > Media > File system, under the "Default download method". If you select private download then CKEditor always open IMCE in private folder and then you can't switch to public folder, despite of the new node will be public (blog post).
I think it's a very big problem. I should have the option to select if I want public or private directory in IMCE when It was launched by CKEditor.

Chances are you haven't set filebrowser permissions within the IMCE config page.

Go to Configuration > Media > IMCE
Setup/confirm the IMCE Profile for filebrowsing.  NOTE:  IMCE has its own "profiles" which can be used as roles specific to the filebrowser functionality. The default User-1 role has the ability to see all files/folders.  If you need more granular access to subfolders/specific folders within the files directory, setup a new profile.
Check that your blogger/blog contributor role has a profile assigned in Public Files column (and if necessary, private files column).

In addition to checking the IMCE filebrowser permissions, you'll want to check the individual field settings.  It can only be set to save/upload to either Drupal's public files directory or private files directory.  It doesn't allow content managers to choose which directory to upload/save to at time of upload/per piece of content.


Is there any clean way to have the Drupal login form create a session for phpBB also? I've made my peace with having two DB's and two sets of roles, permissions, etc. But I'd like to have just one login.

Is there a simple way to have the Drupal login throw a session cookie for phpBB with the same parameters as the drupal one?

If what you want is a clean way to integrate phpBB with Drupal, I think phpBB Forum Integration is want you need.

This module will not only "embed" phpBB within a Drupal site (and synchronize account info, such as user names, roles, passwords, emails, signatures, and avatars, with only one login), but it also let phpBB topics be created from Drupal nodes.

The phpBB forum can be displayed in a full window, in a frame inside Drupal, or in a Drupal page.


Additional parameters to aliased panels paths I'm trying to build a news/blog feed for each of our internal departments.  I have a vocabulary with terms for each department, and have successfully created a panels page at extranet/news/<tid> which displays a content pane view of the most recent N posts.  The departments want to be able to alias their newsfeed, to something like hr-news, so add a url alias hr-news => /extranet/news/<tid-for-hr>.  This all works fine thus far.

The problem comes when I try to put a summary view in another pane on the same panel to link to previous months of posts, where the goal would be to use a path like hr-news/2011/10 or similar.  But to do this, it seems that I would have to create a url alias for each month/year/department combination.

The other option would be to use GET parameters, but I cant figure out how to load a GET parameter into a panels context so i can pass it to the view.  Am I approaching this problem wrong?

I have a similar problem on a Drupal 7 site, and am posting as much to share my solution as to "subscribe" and hear from others about the potential pitfalls or alternative solutions.

In my case, I have a number of panels that display "related" content to a node.

Let's say that it's an artist node, and that I have a few panels or variants representing the

artist (url artist/[artist-nid])
their albums (albums/[artist-nid])
their band history (history/[artist-nid]).

For SEF urls, I want to alias those to something like

artist-name-profile
artist-name-albums
artist-name-band-history

Because pathauto doesn't "see" the panels, and because the urls are of an unusual structure (no '/' ) I wrote a custom module to do url rewriting using hook_url_inbound_alter() and hook_url_outbound_alter().

For Drupal 6 you can use http://drupal.org/project/url_alter It's baked into Drupal 7.

So basically, I maintain a cck field on the artist node containing a url friendly version of the artist name. Then use code something like the following.

function myModule_url_outbound_alter(&$path, &$options, $original_path) {
  $parts = explode('/', strtolower($original_path));
  $prefix = array_shift($parts);

  switch($prefix) {
    case 'albums':
      if (!empty($parts[0]) && is_numeric($parts[1])) {
        $url_fragment = myModule_get_unique_url_safe_artist_name($parts[1]);
        $path = $url_fragment.'-albums';
      }
      break;
    // etc
  }
}

function myModule_url_inbound_alter(&$path, $original_path, $path_language) {
  $parts = explode('-', strtolower($original_path));

  $suffix = array_pop($parts);

  switch ($suffix) {
    case 'albums':
      $map = implode('-', $parts);
      $nid = myModule_get_nid_from_unique_url_safe_artist_name($map);
      $path = 'albums/'.$nid;
      break;
    // etc
  }
}

Pros,

I get a great deal of flexibility on the url design - non-conventional urls are possible
I do not need to have over 50,000 records in the url_alias table.
I can quickly and easily change the urls without having to rebuild the alias table
I can reach those pages pathauto can't
It works.

Cons,

every url passes through this test and the ones that match will be slowed down by at least one db query. (this doesn't appear to be much of a performance hit by YMMV)
url changes require developer intervention
For large numbers of panel variants, this function can become difficult to maintain, particularly because you have to be careful not to allow conflicts to arise. See below for example.
This doesn't smell right as an approach

Conflicts can come up based on your url matching methodology. I the above case we split on '-', this can become a problem in this specific case if the artist url were simply artist-name and the artist's name was literally "Michael-albums" since this would be interpreted as an album page for "Michael" rather than an artist page for "Michael Albums".


Display block on homepage depending on value in user profile field? I'm currently displaying a block on my D7 site' homepage.

Now I've a requirement to display that block only if the logged in user has a specific value in their profile.

I know it can be done using php evaluation by navigating to the bottom of the block and then click (Pages > Pages on which this PHP code returns TRUE ) but have no experience in writing php scripts.

Can anyone help with this please.

thanks

You can do something like this

global $user;

 If($user->your_profile_field_value == 'requiredvalue') {
    Return true;
    }
    Else {
    Return false;
    }


Facebook does not use article image We installed the metatag module,
and we activated all metatag entries on the modules administration page.
On the module settings
we selected content type Node:article and went to Open Graph.
We edited the tag image with the value [node:field_image],
the same for tag image url

In the page source, we checked the meta properties:
"og:image" content="https://domain name/sites/default/files/field/image/name of image.jpg"
"og:image:url" content="https://domain name/sites/default/files/field/image/name of image.jpg"
Using this internet address directly in the browser, the article image is displayed as expected.

Meanwhile, Facebook still does not show the article image. The main logo image is shown, even after emptying the cache of the Drupal site and the cache of the browser.

What does go wrong?

Having been through this before with OG tags and Facebook, if your site has been up and you verified the OG tags are in the source and work, then the likely culprit is that Facebooks crawler cached the page before you added the tag and you will need to wait a while.

If the image url resolves and the tag is right, it just takes time.

Perhaps try to look into using the Facebook debugger, something like in this article: https://www.braveriver.com/how-to-clear-facebook-open-graph-and-twitter-cards-cache-on-demand/

We saw this behavior with both Facebook and Twitter. IIRC it took about 3-6 hours to see them "appear" after initial attempts.


Remove the strict warnings from being shown I have a site using Drupal 6; after upgrading PHP to 5.4 , some strict warning appear.

I set error_reporoting in settings.php with the following code, but I still see the E_STRICT warnings.

error_reporting(E_ALL & ~E_NOTICE & ~E_STRICT & ~E_WARNING);
ini_set('display_errors', TRUE);

Why do I still see them? What can I do to avoid seeing them?

From the link :

  If you're going to hack core, a much better solution is to properly
  fix the error handler. Add this line to the top of the
  drupal_error_handler function in includes/common.inc:

  if ($errno == E_STRICT) { return; }


Why node export:import link is not displayed? I want to export drupal 7 nodes with node export. I have downloaded and enabled the node export module. The node export option has been added in the content tabs next to view,edit,translate.
I exporte the nodes in a file however I cannot find the import link in order to import them!
Is there something else to configure?

Go to node/add/node_export (Content > add content > Node export: import) and paste the code or load from file.


What are the modules / pages / panels / or other features in Drupal which can be used to display an object which is made up of several content types? I know views can be used, I have a functioning view which displays the relationship between the content types, using a limited number of fields.

Next I would like the hyperlink to resolve to a display of the contents of a "composite object" which includes a number of content types. What can I use?

Using: Views, Entity Reference, Panels, Page Manager

The first view is a LIST (alphabetical) of story titles, showing Relationships to other content types, as follows:
- Person (firstname, lastname, etc.)
- Story (field_story_title, orig copyright, description, etc.) Note: [content:title] is automatically generated and not used.
- Series (field_series_title, body)

and these content types which are join tables
- PersonStory (field_personstory_person_id, field_personstory_ story_id, relationship [e.g. author])
- StorySeries (field_storyseries_story_id, field_storyseries_series_id, field_storyseries_logical_order)

Person to Story is many to many, Story to Series is many to many.

I would like the hyperlink to resolve to a "page" which shows all of the fields from multiple content types which relate to that one story. This will be quite a lot of data: title, author, copyright, short blurb, synopsis (1K words) and a couple of images. So Views Megarow doesn't feel like an appropriate destination to me.

What are possible methods to show data from multiple content types?

what's the best way to...

That is subjective. Here is a way to do it, not necessarily the best:

Views Megarow

  This module allows you to display content coming from a menu callback
  between two items of a views result set as a modal-like. You can use
  it to display a preview of your node or to build an administrative
  form.

  Said otherwise, you can dynamically display content below a row of a
  table of results coming from a view. This content is shown when you
  click on a link, it means that you can display anything from a preview
  of your node for instance to a moderation form of an entity.


How to add a custom row class or ID to type table render elements I'm trying to add row ID's for a custom table I implemented via a custom module. But when I append an ID to the '#attributes' array it becomes the table ID, not the row ID. How can I define IDs for rows?

This is what I have so far:

$form['table'] = [
  '#type' => 'table',
  '#header' => $header_table,
  '#rows' => $rows,
  '#attributes'=> ['id' => 'IdforRow'],
  '#empty' => t('No Data found'),
  '#prefix' => 'Total Tenders : '.@$count.'
',
  '#suffix' => '',
];

Can you try code the below.

$row = array('data' => 'some data');
$rows[] = array('data' => $row, 'class' => 'some class');
);

Or maybe

$row = array('data' => 'some data');
$rows[] = array('data' => $row, 'class' => array('some class'));

Reference answer https://www.drupal.org/forum/support/post-installation/2016-04-21/add-class-in-row-with-theme-table


Filter to only nodes with an image in an imagefield in Views 3 In my view, I want to include/exclude nodes that do not have an image in a specific field with exposed filter. The field allows an unlimited number of images. I don't care about the exact quantity, just that there are more than 0. How do I create this filter?

'Is not empty' is an option for the operator of filters.  Did you try that?

So you can add a filter to your view, and just select that as your operator.  Here's a screenshot to help:


how to force drupal to create tables with ENGINE=MyISAM this is a popular error in drupal that you guys might have seen this before :

PDOException: SQLSTATE[42S02]: Base table or view not found, table .... does not exist.

when I'm trying to install drupal7, it reports an error that semaphore table does not exist. I tried to create it manually by this query

CREATE TABLE IF NOT EXISTS `semaphore` (
  `name` varchar(255) NOT NULL DEFAULT '' COMMENT 'Primary Key: Unique name.',
  `value` varchar(255) NOT NULL DEFAULT '' COMMENT 'A value for the semaphore.',
  `expire` double NOT NULL COMMENT 'A Unix timestamp with microseconds indicating when the semaphore should expire.',
  PRIMARY KEY (`name`),
  KEY `value` (`value`),
  KEY `expire` (`expire`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='Table for holding semaphores, locks, flags, etc. that...';

it reported the same error. I changed InnoDB to myISAM and it worked!!!
I found out that tables with the InnoDB engine are not supported in mysql on the server and unfortunately drupal7 creates all the tables with this engine by default. is there any way to change this default to MyISAM ?

The schema definitions can take an argument of 'mysql_engine', which defaults to 'InnoDB', in createTableSql().

In theory you could thus alter all the defined schemas with a custom module, and change the engine.

It's highly questionable to do so though. If you value your site and data, you should NOT use MyISAM unless you understand the difference the two engines.

Switch to a provider that supports InnoDB instead. MySQL itself defaults to InnoDB as of 5.5. I would be very suspicious of any provider that didn't support InnoDB.


Views Data Export Module hide button when unfiltered I'm using the Views Data Export module to export an Excel spreadsheet of search results from a View. The problem is that the button is still visible when the View is unfiltered, and the full export of several thousand records (on the fly) chokes the server. Is there a way -- through the Drupal admin interface, since I don't have server access -- to simply hide the "XLS" button when the full dataset is being displayed? Hiding the button when the search results are above a certain threshold count would be even better.

You have a number of options, you can apply a default views filter that is applied on page load through the view settings.

You can also use javascript to test if all the filters are on "All" then hide the button with CSS


Block with articles from the same author My websites publishes articles by third party authors. Articles are inserted by an admin. Every article has its author.
The authors' info are in a content type called Bio, which has these fields: title (full name of the author), picture, body, links to social networks. The path to each author's bio is /author/.
In each author page, I want to show all the articles this author has already published on my website. So I made a view that should display a block in each of those pages.

The problem with the view is that it works in preview, when I manually enter the name of the author, but it isn't working when in the page as a block. It doesn't retrieve the  from the url, I guess.

Here's some screenshots of my view:

Don't use Content Titolo use Contenuto: Identificativo uid dell'autore

and use the following settings


Check new form-input against old form-input I have added some extra options in the My Profile page which users can edit. But now I have to track down the change of this value...

It's a checkbox and whenever the user (un)checks this box, something must happen. So I thought this would be in the $form_state, but no luck there.

Next thing I did was to preform an EntityQuery on the user object and try to cross-reference it with the input, but again, no luck.

So how can I (programmatically) detect if a form-element goes from unchecked to checked or the other way around?

EDIT: What I try to do is an implementation with Campaign Monitor (a newsletter plugin). If a user has changed it's checkbox, his subscription must be updated (of leave it as it is when there is no change)

When you change something in form, that change can be found in $form_state. You need to add an AJAX callback and do your changes in that callback.

Sample code:

function MYMODULE_form_alter(&$form, $form_state, $form_id) {
  switch ($form_id) {
    case 'MY_FORM_ID':
      $form['field_select']['#ajax'] = array(
        'event' => 'change',
        'callback' => 'your_ajax_callback',
        'progress' => array('type' => 'none'),
      );
    break;
  }
}

/**
 * AJAX Callback.
 */
function your_ajax_callback(&$form, &$form_state) {
  // dpm($form_state);
  // Check $form_state here and update subscription.
}

Hope this helps!


Pre-populate an Entity Reference when Adding a Node : Based on URL Alias I am trying to pre-populate an entity reference with a specific game node, when a profile node is added; based on URL of the game the add button is on.

The game node I want to reference in profile node is in the URL of the profile's add page.

By using views to contextually filter, matching the first portion of the url (the game node title), with a game node. Then to be used as the field's select list.

Only selection in drop down would make it seem pre-populated.

                         --

Two content types
 - game
 - profile

*game nodes alias pattern is [node:title]. so just /game1/  , /game2/

I added an alias for each game node to go to the profile add page
  game1/add  >  node/add/profile
  game2/add  >  node/add/profile

Using Entityreference prepopulate module i use /node/add/game-profile/?field_gmeprfl_game_eref=[node:nid]  to generate id to reference; the ? (question mark) prevents the [node:nid] from processing to an id. it stays literaly "/node/add/game-profile/?field_gmeprfl_game_eref=[node:nid]". if i take out the "?" it will process to the nid number.

If I use view entity reference list to contextual filter the game1 part of url against the nodes alias , there is not alias for me to add in contextual filter. (id prefer this way so my links look better than  ?field_gmeprfl_game_eref=14

**i use d7 prepopulate entity reference node (?field_gmeprfl_game_eref=[node:nid]), i cant use ? with [node:id] as the ? prevents the tokens from processing. if i can do this and make urls the same as OP: id consider that also.

Your latest update mentions you're having trouble constructing the link, so I'll focus on answering that.

It seems that if you construct the link manually (simply type in the addressbar) everything is working correctly (this is to test that the Entityreference prepopulate module is working correctly on your side).

The problem then seems to be how to construct the link automatically for each of your game nodes, so that by clicking on the link, a Profile creation form is shown with the relevant entity reference prepopulated.

Add Prepopulate links to Views

In your Games views add a field Content: Nid and Exclude from display
After that field (it's important the Nid comes before this) add a new field Global: Custom text
In the Text textarea of that field enter:
Add new Profile referencing this Game

Check that the token really is [nid] under Replacement patterns.

Now you have a list of Games with links that when clicked open the Create profile page with the related Game pre-selected.

Add Prepopulate links to Node pages

If you need to display the link on the actual node page, you can se the same Views as above only create a Block with a Contextual filter.

This has to be done through Views block because the module you're using (Entityreference Prepopulate) doesn't have the URL widget feature implemented so you have to work around it.

Create a Block display View of Games
Add the same Fields as above (use the same Views)—the hidden Nid and Custom text with the link code.
Add a Contextual filter Content: Nid and configure it:
When the filter value is NOT available
Provide default value
Content ID from URL

This will limit the list to show the Prepopulate link for the current node only, otherwise it would show links for all games, like above.

This filter isn't responsible to the link contruction! Link is being constructed using the Fields!
Place your block in Content region or whereever you want the link to display, restrict the Block visibility to Game pages

Visit some Game pages and click on the links, see they are prepopulated with the nodes where you clicked the link.


Uncaught TypeError: Cannot set property 'bootstrap' of undefined I'm receiving the following two errors, i'm unsure how to fix them. after doing some research this file has had issues before. The solutions did not solve my problem. Could this be a simple script load order?

  Uncaught TypeError: Cannot set property 'bootstrap' of undefined (anonymous function) @ bootstrap.js?ny6rj2:13

var Drupal = Drupal || {};

(function($, Drupal){
  "use strict";

  Drupal.behaviors.bootstrap = {
    attach: function(context) {
      // Provide some Bootstrap tab/Drupal integration.

  (anonymous function) @ bootstrap.js?ny6rj2:230

})(jQuery, Drupal);

Drupal exports in javascript the Drupal variable that has several subitems inside depending on your configuration. Your error suggest that the bootsrap property does not exist (at least yet). You can easily make sure that this is the case by opening the console in your browser (f12 in chrome) and type: console.log(Drupal.behaviors); if the property is not there you cannot use it.

Make sure you re loading the bootstrap library correctly. Usually you can do this by downloading the bootstrap module/theme or by using the libraries module.

Also note that Drupal behaviors intend to run every time an 'ajax' call is made by in a drupal page. I m putting ajax in quotes because drupal actually uses a legacy way for ajax called AHAH


How to get the context node in a custom block inside a views list? I have a view which displays all pictures of the content type photo.
I've set some fields in this view for the display.

This is how iIrender the list of pictures:

views-view-fields--photo.html

{{ fields['field_date'].content }}

{{ fields['field_lieu'].content }}

{{ drupal_block('comment_block') }}

I use the Twig tweak module to render a custom block in this template. This block should load all comments for the picture. For that, I need to pass the nid of the node to my block.

Here's the code of the block:

CommentBlock.php

/**
 * Provides a 'CommentBlock' block.
 *
 * @Block(
 *  id = "comment_block",
 *  admin_label = @Translation("Comment block"),
 *  context = {
 *    "node" = @ContextDefinition("entity:node", label = @Translation("Node"))
 *  }
 * )
 */
class CommentBlock extends BlockBase implements ContainerFactoryPluginInterface {

  /**
   * Drupal\Core\Entity\EntityTypeManagerInterface definition.
   *
   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
   */
  protected $entityTypeManager;

  /**
   * Constructs a new CommentBlock object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param string $plugin_definition
   *   The plugin implementation definition.
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->entityTypeManager = $entity_type_manager;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static(
      $configuration,
      $plugin_id,
      $plugin_definition,
      $container->get('entity_type.manager')
    );
  }

  /**
   * {@inheritdoc}
   */
  public function build() {

    $build = [];

    $node = $this->getContextValue('node');
    kint($node->id());

    $build['#theme'] = 'comment_ajax';

    return $build;
  }

}

What I try is to get the context of the views row into my block. But I get this error:

Drupal\Component\Plugin\Exception\ContextException : Required contexts without a value: node

What am I doing wrong?

I can load my block from template_preprocess_views_view_fields() to link with the nid but I try to understand the context annotation.

Update

Here's a picture of the view, my custom block returns just a link name "Comment".

I now load the block programmatically instead of using drupal_block in the preprocess.

$block             = \Drupal\block\Entity\Block::load('commentblock');
$variables['test'] = \Drupal::entityTypeManager()
  ->getViewBuilder('block')
  ->view($block);

Then I print this block in views-view-fields.html.twig:

{{ fields['title'].content }}
{{ test }}

If I kint the context in my block I still get an error except if I set the annotation required = FALSE.

 *   context = {
 *     "node" = @ContextDefinition(
 *       "entity:node",
 *       label = @Translation("Current Node"),
 *       required = FALSE,
 *     )
 *   }

But the context is still empty.

When placing the block you have to choose from where the block will get the node value.

Select a node value

Node from URL

Ah! I found my own issue on DO. You also might have to unrequire the context like following:

 *   context = {
 *     "node" = @ContextDefinition(
 *       "entity:node",
 *       label = @Translation("Current Node"),
 *       required = FALSE,
 *     )
 *   }


How to insert html tag "id" in an image field in a view I need to add id tag to an image which is a field of a view. Currently it seems only possible to add a class name.

 <img id="xxx" typeof="foaf:Image" ...

Searching for typeof="foaf:image" I found that was set by rdf module preprocess_image, not in views. Therefore I added a preprocess function

function MYTHEME_preprocess_image(&variables){
  // compute first MY_UNIQUE_ID
  $variables['attributes']['id'] = array('MY_UNIQUE_ID');
}

now it works.


How render view with programmatically passed parameters of contextual filter I am using Drupal 8. Added new view My Vocabulary and created a contextual filter with paragraph ID. Now I need to render the view with passed parameters to contextual filter. What hook to use to solve my problem. Thanks.

Use hook_views_pre_view

function mymodule_views_pre_view(\Drupal\views\ViewExecutable $view, $display_id, array &$args) {
  // Modify contextual filters for view_name.
  $paragraph_id = 22;
  if ($view->id() == 'view_name') {
    $args = [$paragraph_id]; // args must be an array.
  }
}


SQL injection and lot of database updates are visible My Drupal Website is possibly compromised through a SQL injection and lot of database updates are visible. How to avoid further SQL injection?

Install Security Review for maintaining security of your website. Or if you have custom modules, make sure form handling is done only via drupal forms.


Views Slideshow: keeps showing all images below slider It shows the normal slider on top... and then all of the images that are suppose to be sliding are stacked below it.

I've gone through several different tutorials and done them all the same way, and I'm still getting this. There has to be something simple that I'm doing wrong here.. but I don't know what it is.

I wanted to post a picture, but my reputation is only a 6..

Edit:   Just realized when you hover over these they change the top slide, like thumbnails normally do.  But I have no idea how to turn them off or change them to a different size.  I created an image style for this, but it apparently isn't working.

Edit x2:  It has nothing to do with the thumbnails. It just keeps showing all content that's suppose to be cycling.  For example, it's showing every number and every title.  Is there no CSS at all with Views Slideshow to not display things?

Figured this out. I guess all I needed to do was make a post about it. On the toolbar go to Structure > Views > Your_Slider (whatever it's called) Under Format click on settings beside slideshow Scroll to the bottom. Go to Widgets and make sure there are no pagers selected here. Save and you're done.


"View any coupon of any type " permission for anonymous reduces the Score in acquia In my e-commerce website, anonymous user can't able to view the add coupon field until and unless I gave "View any coupon of any type" permission. Because its having notice like this: Warning: Give to trusted roles only; this permission has security implications. Acquia Reduced the score of our website.So any other way is there to solve this problem?

The Acquia Insight tool (I am assuming you are referring to that score) is a tool that helps you find potential problems in your website and configuration. It is an automated tool that performs simple checks. It is a guide and a tool. Not exact science. (It could throw a false positive.)

However in my installation of Commerce Coupon 7.x-2.0-rc2, there is also the permission to Redeem any coupon (and the per type Redeem <type> coupons permission). And that works for anonymous user as well. Perhaps you should try that instead?


Using Flags for 'Out of office' I'm trying to use flags to create 'Out of office' functionality for my site users where user profiles are built into panels.

How can I add a flag where user can only see flag on his own profile
When user flags 'out of office' he gets displayed with a text field and then that text    field get rendered within user profile displaying 'out of office' message.

Thanks

I achieved 'Out of office' flag functionality using rules module.

Placed an out-of-office flag on user profile and set visibility rules (panels) to show flag only if its user's own profile
Within flags used flagging form to capture user out-of-office message
Added an extra field 'out-of-office' within user's profile.
Created a rule on flagging-event to populate 'Out-office-field' with text from flagging form.
Created a rule to delete the text from 'out-of-office' field on unflagging


Redirect after purchasing How can I perform a redirect after purchasing a product? I tried to create a custom checkout pane for this purpose, but it doesn't work as the form is not submited:

public function buildPaneForm(array $pane_form, FormStateInterface $form_state, array &$complete_form) {
  if ($this->getStepId() == 'complete') {
    $form_state->setRedirect('<front>');
  }
}

Is there any possibility to do this with a pane or do I have to create an event subscriber and redirect on the checkout event?

In your "submitForm" method write below code:

$form_state->setRedirect('<front>');
return;

To redirect you can also use the following code:

//after the namespace
use Drupal\Core\Url;

//In your "submitForm"
$url = Url::fromRoute('<front>');
$form_state->setRedirectUrl($url);

To redirect you can also use the following code:

//after the namespace
use Symfony\Component\HttpFoundation\RedirectResponse;

//In your "submitForm"
global $base_url;
$response = new RedirectResponse($base_url);
$response->send();
return;


correct way to implement multipule users registration form I want to create a site where users get to chose between being an employee or employer.

So when users first go to the registration they need to be asked which role will they be, and on that choice a different registration form will appear.

What would a good implementation method be?
Thanks

First you need to use Profile 2 module and create two separate profiles for employee and employer roles.

Then you can use module Auto Assign Role or Profile2 Registration Path to allow users select which role do they want to register with.


Displaying a field of an entitiy reference In my Page content type there is an image field called gallery, and an Entity reference field refering to a related page.

I need to display the images contained in the gallery field of the related page.

I have created a Display Suite a code field. In the tokens I found [node:field-related-page:field_gallery] but it seems to be empty (it prints nothing).

I have used Devel's dpm() method to display $entity's content but it does the related page fields do not contain any info about the gallery (which makes sense as recursion could be an issue):

If you want to do it only in code, do a node_load($node->field_related_page['und']['0']['target_id']. If you want a view, use a relationship and show gallery field with the relationship.


Header region causing the page to be too wide When viewing my website on Internet Explorer there seems to be a big space on the right where the page has scroll bars to take in the full width. I think its to do with my header image. It seems ok in Firefox and chrome. Can anyone suggest a way to get this working on IE?

Its because of your fb_reset facebook iframes.

If you remove the css rules in the style and change to

Add to css:

.fb_reset {
display:none;
}


No way to install or add libraries? I've been trying to set up a site on Acquia for a good 3 days now, and am baffled - Acquia doesn't allow Composer, the Acquia Dev Desktop does not sync libraries.  I've tried ludwig with no luck.

Is there any way to add csv/league libraries to Acquia? W/o this capability, I'm not sure how useful Acquia is, or am I missing something simple?

Acquia has to have the full site, core, modules, themes, libraries, et.al. checked into their git repo in the format like:

git root
  docroot
    core
    modules
    themes
    etc.
    (includes index.php and other root files)

As Clive said, there is a pay for it CI process.  However, for the normal sites, you need to manage the site as a whole entity.  They do have Deployment hooks, but that is generally for clearing cache and the like.

FYI - I use composer on all my sites.  You run it locally and check in the composer files to the repo (e.g. the composer.lock, etc.).  Things like js libraries are added by manually adding repo's to the composer.json file if they are not composer friendly. E.g., here's how the jquery chosen plugin gets added:

"harvesthq.chosen": {
  "type" : "package",
  "package" : {
    "name" : "harvesthq/chosen",
    "version" : "1.8.7",
    "type" : "drupal-library",
    "dist" : {
      "url" : "https://github.com/harvesthq/chosen/releases/download/v1.8.7/chosen_v1.8.7.zip",
      "type" : "zip"
    },
    "require" : {
      "composer/installers" : "^1.2.0"
    }
  }
},

It's also best to have the Drupal friendly paths defined in your composer file.  E.g.:

"extra" : {
    "installer-paths" : {
        "docroot/core" : [
            "type:drupal-core"
        ],
        "docroot/libraries/{$name}" : [
            "type:drupal-library"
        ],
        "docroot/modules/contrib/{$name}" : [
            "type:drupal-module"
        ],
        "docroot/themes/contrib/{$name}" : [
            "type:drupal-theme"
        ]

These make sure things get placed properly by composer.


How to unflag/reset a flag again, when matching some conditions in onFlag event? in my custom module I have an event subscriber service for flag module. I used the tutorial here as a base for learning: Link to Tutorial
Here is my code:
namespace Drupal\MYMODULE\EventSubscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Drupal\flag\Event\FlagEvents;
use Drupal\flag\Event\FlaggingEvent;
use Drupal\flag\Event\UnflaggingEvent;
use Drupal\user\UserInterface;
use Drupal\user\Entity\User;

class MYMODULEFlagSubscriber implements EventSubscriberInterface {

  /**
   * Do the logic when the upgrade flag is triggered to flag.
   */
  public function onFlag(FlaggingEvent $event) {
    $flagging = $event->getFlagging();
    $flag = $flagging->getFlag();
    $flag_machine_name = $flag->id();
    if ($flag_machine_name === 'my_awesome_flag') {
      $entity_nid = $flagging->getFlaggable()->id();
      $user = User::load($entity_nid);
      $user_is_active = $user->isActive();
      $field_1 = $user->get('field_1')->value;
      $field_2 = $user->get('field_2')->value;
      $break_with_error = FALSE;
      $upgrade_message = '';
      $roles_to_ignore = [
        'administrator_junior',
        'team_sales',
        'administrator',
      ];
      if (!$user->hasRole('authenticated_level_2')) {
        if (($user_is_active == TRUE) && ($field_1 == 1) && ($field_2 == 1)) {
          foreach ($roles_to_ignore as $role_to_ignore) {
            if ($user->hasRole($role_to_ignore)) {
              $break_with_error = TRUE;
              $upgrade_message = 'The User has a company role already and can not being upgraded as a Level 2 user.';
              break;
            }
          }
        }
        else {
          $break_with_error = TRUE;
          $upgrade_message = 'The User can not being upgraded as a Level 2 User. Reasons: 2. The account is not activated yet, 3. The user has not yet checked field 2';
        }
      }
      else {
        $break_with_error = TRUE;
        $upgrade_message = 'The User was upgraded as a Level 2 User already.';
      }

      switch ($break_with_error) {
        case TRUE:
          \Drupal::messenger()->addError($upgrade_message);
          $flagging->unflag($flag_machine_name, $entity_nid);
          return;

        case FALSE:
          $user->addRole('authenticated_level_2');
          $user->save();
          \Drupal::messenger()->addStatus('The User was upgraded as a Level 2 User sucessfully.');
          return;
      }

    }
  }

My Problem is
How can I unflag the flag again, when my logic checks settings and my variable $break_with_error becomes true?
$flagging->unflag($flag_machine_name, $entity_nid);

throws me an PHP error.
Update:
My intention was the following:
I use the flag here as a substitute for a link/button to trigger the "business logic" checks and to give the user a additional role with more privileges if the checks are passed.
In my opinion it's a easy way to quickly have a link/button in multiple variants (e.g. in a view or as a field in user account). Another advantage is, that other people (in my case sales team or other admins) see the business logic checks have performed already when the user entity is flagged. But in case the logic checks are failing, the user entity should unflagged again.
For other opportunities to have a "business logic trigger" I'm open and thankful of course.

I'm guessing the problem is that in the onFlag event, the flag is still being created, so it can't be unflagged because it hasn't been fully saved yet.
But I think the bigger problem is that your code has a logic error-- validation should happen before the action, not after the action.
It looks like you are trying to do this:

When a user is flagged,
check if the flag meets certain "unflag" conditions,
if the conditions are met, unflag the user.

However, validation in Drupal usually is applied before something happens, not after.  Validation is not supposed to be a kill switch to stop a problem; you should stop the problem before it happens.
One reason to stop the problem before it happens is that you later may add code that does something when a node is flagged (for example, in hook_entity_insert()); in such a case, you would also have to undo the code in your flag event subscriber.
So, what you probably want to do is apply the validation login in hook_form_alter() so you can stop the flagging before it happens.


Drush commands report "hostname: Name or service not known" Many Drush commands are reporting this error once or more:

  hostname: Name or service not known

The commands seem to run fine, though.

This is Drupal 7 running on a local development environment on OpenSUSE 13.1.
The status reported by Drush is the following one. (I have edited out username and password.)

  Drupal version:  7.34
   Site URI:  http://default
   Database driver:  mysql
   Database username:
   Database name:
   Database:  Connected
   Drupal bootstrap:  Successful
   Drupal user:  Anonymous
   Default theme:  zen
   Administration theme:  seven
   PHP executable:  /usr/bin/php
   PHP configuration:  /etc/php5/cli/php.ini
   PHP OS:  Linux
   Drush version:  6.2.0
   Drush configuration:
   Drush alias files:
   Drupal root:  /srv/www/htdocs
   Site path:  sites/default
   File directory path:  sites/default/files
   Private file directory path: ../files/private
   Temporary file directory path: /tmp

Running "drush up --debug" shows the error message:

  Cache MISS cid: 6.2.0-alias-path--c4cc2b4982c6401ca3d49ce3d0e075b4
  hostname: Name or service not known

How can I fix this error message?

Drush calls the hostname program to determine if a given fqdn for a remote site alias is actually the localhost.  There appear be other incidental uses for this program, since it is called when you run drush status.

If your system is saying 'name or service unknown', it means that you networking is not completely configured on the host server.  This isn't a Drupal/Drush issue, but see:

http://www.linuxquestions.org/questions/linux-networking-3/ssh-name-or-service-not-known-479307/

If that does not solve your problems, try asking in a SuSe forum.


Add link type field confused? There is a requirement in my website: The post content should have a link (it is for IOS device to install apps) like the following.

Install APP

I used the Ckeditor and it can make it.

Is there any other ways to make it? I tried the Link module, but it failed.

Drupal has a function called filter_xss_bad_protocol that strips unknown protocols from links created with the l() function - This is a very smart idea but makes it difficult when you want to include emerging link protocols like skype:// for example. Dave Reid has created a fantastic module that works around this and allows developers to add their own protocols to the list.

http://drupal.org/project/filter_protocols

With that module installed, and your specific protocol added to its configuration screen, it would then be possible to do something like this in your code:

<?php print l("Displayed Text", "itms-services://?action=download-manifest"?>

Additionally, use the attributes and query parameters of the l() function to pass your url parameter to the link. See this for an example... http://api.drupal.org/api/drupal/includes%21common.inc/function/l/7 - You'll find the particular comment regarding passing parameters on that page here: http://api.drupal.org/comment/38198#comment-38198

Hope that helps! Good luck.

P.S. To clarify, simply adding the above module and configuring it will also allow the Link module to respect the protocol since it passes everything through l() - So no code required. :) Merely for completeness.


Using webservice to popolute/search Address Field fields I'm busy developing a custom shipping module and want to have an auto-complete/select list of towns but the available data for the list is from a webservice (the reason for this is so that the shipping company can update their details without me having to update on my side the whole time).

How do I interact/modify/manipulate Address Field fields?  I tried to modify field.tpl.php to hide a country but it does not affect the address section in checkout, only the products section of the cart (and somehow I don't think this is the way to go anyway).  I also looked at addressfield.api.php but that looks very limited.  Should I just use normal fields one by one (street, town, zip code etc) and try and modify them. I'm not sure where to even start researching what to do to accomplish this so any pointers in some direction will be appreciated.

More than likely, the best approach you can take here would be to add the AddressField reference to wherever it needs to be, and then add in logic to poll and collect address data inside a form validation call inside a module, using a hook_form_FORM_ID_alter() 1 call, when new Entity is created or edited.

This guide provides additional information on using validation calls in Forms: https://api.drupal.org/api/examples/form_example!form_example_tutorial.inc/7


Invalid datetime format for a field never submitted? I'm working my the edit page for my mobile app which is fetching data from a Drupal site. I'm fetching data, I'm editing it, and submitting it. However, when submitting back, I'm getting Internal Server Error : An error occurred (22007): SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '2009' for column 'field_yapim_yili_value' at row 1 but I'm not even fetching that field. It's a field collection, if that matters. In fact, I even grep'd my codebase for that field, it doesn't even exist. I checked the content type, it's not required. Any ideas how I can debug this?

UPDATE: Below is what I have in Chrome development tools network tab

node[type]:oyuncu
node[title]:Ergün YOLSUZ
node[language]:und
node[field_tc_kimlik_no][und][0][value]:1737769758
node[field_sgk_durumu][und][value]:devam_ediyor
node[field_kategorisi][und][0]:oyuncu
node[field_kategorisi][und][1]:yardimci_oyuncu
node[field_telefon][und][0][value]:05352107332
node[field_telefon_2][und][0][value]:02122111048
node[field_adres][und][0][value]:Mecidiyeköy mah Şehit Ertuğrul Kabataş Cad.
node[field_yasadigi_sehir][und][value]:34
node[field_e_posta][und][0][value]:ergun@magicleaves.com
node[field_cinsiyet][und][value]:bay
node[field_gogus][und][value]:75
node[field_bel][und][value]:96
node[field_kalca][und][value]:116
node[field_dogum_tarihi][und][0][value][date]:1 Nis 2016
node[field_boy][und][value]:170
node[field_kilo][und][value]:75
node[field_goz_rengi][und][value]:kkahve
node[field_ten_rengi][und][value]:esmer
node[field_ayak_no][und][value]:46
node[field_egitim_duzeyi][und][value]:Lisans
node[field_oyunculuk_egitimleri][und][0][value]:-
node[field_diller][und][0][value]:Almanca, İngilizce, Türkçe
node[field_beceriler][und][0][value]:Bateri, gitar, piyano, okçuluk, kılıç sanatları, dans, bilgisayar,
node[field_kisisel][und][0][value]:Çok acayip adamım ben. Cidden bak.
node[field_videolar][und][0][video_url]:
node[field_videolar][und][0][description]:
node[field_okudum_anladim][und][value]:0

It may be possible your field_yapim_yili_value field has a default value and that default value is invalid for datetime format.


How do I use Viz.js? Viz.js is GraphViz converted to JavaScript. There is a demo at http://webgraphviz.com.

What I would like to do is send a string (dot syntax) created by a PHP function to Viz.js to produce svg output for display as "content". I know zilch about JavaScript and my trial and error attempts with drupal_add_js() and Drupal.behaviors are getting me nowhere.

Hoping someone can guide me through this. (The string from my PHP function is valid - it displays correctly if I paste it into the demo site).

Some background:

I have a working system using locally installed GraphViz and the PEAR Image_GraphViz class. The problem is shared hosting providers don't want to install GraphViz -- so this js conversion could get around that.

I have a link on a Views display that calls a function to build a chart through calls to methods in Image_GraphViz. At the end of the function I do

<?php
return $gv->fetch();
?>

which opens a page displaying the chart in the site theme content area.

In my attempt to use Viz.js I have first placed scripts[] = Viz.js in my .info file -- that seems correct to me and does get Viz.js into the html header. According to the author I only need one line of javascript like svg = Viz("digraph { a -> b; }", "svg");.

My problem is: where do I put it? Obviously, I need to pass a string to replace the 1st parameter and that is easily obtained by

<?php
$gvdata = $gv->parse();
?>

Pasting such a string into the demo site produces correct results.

Does the one-liner need to be in a separate file or can it be tacked on to the main function?

I tried this:

<?php
$gvdot = $gv->parse();
$gvdata = array('gvdata' => $gvdot);
drupal_add_js(array('ftree' => $gvdata), 'setting');
return drupal_add_js('jQuery(document).ready(function () {
Viz(Drupal.settings.ftree.gvdata, "svg"); });', 'inline');
?>

gives a blank screen.

I also tried calling a separate file:

<?php
$gvdot = $gv->parse();
$gvdata = array('gvdata' => $gvdot);
drupal_add_js(array('ftree' => $gvdata), 'setting');
drupal_add_js('dot2viz.js');
return;
?>

that contained:

(function ($){
  Drupal.behaviors.ftreeBehavior = {
    attach: function (context, settings) {
      var gvdata = Drupal.settings.ftree.gvdata;
      document.body.innerHTML += Viz(gvdata, "svg");
    }
  };
})(jQuery);

also returns a blank screen.

And that's where I am -- hoping someone can explain what I'm missing and/or doing wrong.

p.s. a better formatted version is at https://drupal.org/node/2153353

I have managed to coerce the system into providing the desired result, but I'm not entirely happy with the method.
I have the main function listed in my module's .info file as previously stated.
The function that builds the dot script is a "menu callback", triggered from a views display. I have mimicked the method found here.

After the dot script is built, the function returns:

 <?php
 $gvdata = $gv->parse();
  $return = '

';
  $return .= '<textarea id="dotscript" rows="20" cols="80" width="100%" wrap="off">';
  $return .= $gvdata."\n\n";
  $return .= '</textarea>';
  return $return;
?>

I get the javascript into the output using the js_injector module to put the following into the footer:

    jQuery(document).ready(function () {

  var svg_div = jQuery('#svgarea');
  var graphviz_data_textarea = jQuery('#dotscript');

  function UpdateGraphviz() {
    svg_div.html("");
    var data = graphviz_data_textarea.val();
    // Generate the Visualization of the Graph into "svg".
    var svg = Viz(data, "svg");
    svg_div.html("
"+svg);
  }

  // Startup function: call UpdateGraphviz
  jQuery(function() {
      UpdateGraphviz();
  });

});

It seems to me there should be a more elegant way to do this.


Pass Parameters to views via Ajax While viewing a views generated page, like for instance a taxonomy term page, is there a way to update the views generated content by passing it some parameters, like for instance a new taxonomy term.

The purpose of this would be to update a view page content via an ajax request.

Thanks

You can easily execute and render a view with arguments in a custom module.

I would:

1 - Set up some JS code to trigger an AJAX call to the server

2 - Use hook_menu() to define a custom menu callback on a specific URL, ie: /views/ajax/view_name/view_display/view_arguments

3 - Create your callback function()

4 - Load and render the view with arguments: (this is From Views 2 API):

$view = views_get_view('foobar');  // get the view named `foobar`
$view->set_display('page_1');  // Set the view display you want to use
$view->set_arguments(array($foo));  // Pass an array containing one or several variables you want to use as arguments in the view
$result = $view->render(); // Returns HTML

5 - Return your result in JSON (practical sometime if you want to pass more information than the view itself). You can use drupal_json_output() in D7.


Add a Drupal site wide contact form to the maintenance page How do I add the Drupal site wide contact form to the maintenance page?

I'm currently using a custom maintenance-page.tpl.php template page in my theme.

I would try to override the default template file through maintenance-page.tpl.php and then use template_preprocess_maintenance_page to alter the variables stack and basically add the rendered form as a variable. But I don't know what would happen if you submit the form while in maintenance.


Is there a way to stop Order checkout in Commerce 2.x? Is there a way to stop an Order checkout process in Commerce 2.x when a product is out of stock?

Requirement:

I have a product with quantity in stock available as zero
A user/customer logs in
Customer clicks Add to cart button
Product must not be added to cart since it is unavailable in stock

I have used getSubscribedEvents() with Commerce order event commerce_order.commerce_order_item.insert. But the following code just won't work. I suspect it has something to do with the order of execution of  Symfony events but really don't understand where am I missing out. My code :

  /**
   * {@inheritdoc}
   */
  public static function getSubscribedEvents() {
    $events['commerce_order.commerce_order_item.insert'] = ['stopOrderExecutionOnStockUnavailability', 100];

    return $events;
  }

  /*
    -----
    -----
    -----
    -----
    -----
  */

  /**
   *
   * @param \Drupal\commerce_order\Event\OrderItemEvent $order_item
   *   OrderItemEvent object.
   */
   public function stopOrderExecutionOnStockUnavailability(OrderItemEvent $order_item) {

    $ordered_quantity = $order_item->getOrderItem()->getQuantity();
    $purchased_entity = $order_item->getOrderItem()->getPurchasedEntity();
    $stock_entities = $purchased_entity->get('field_stock_management')->getValue();

    // Check for available quantity in stock - in total.
    $available_quantity = 0;
    foreach ($stock_entities as $stock_entity) {
      /*
        Get total available stock quantity here.
      */
    }

    if ($ordered_quantity > $available_quantity) {
      $order_item->stopPropagation();
      drupal_set_message(t('Ordered quantity is not available in stock.'), 'error');
    }
  }

Use Commerce's AvailabilityManager service.

See https://www.drupal.org/node/2511266 and https://www.drupal.org/node/2710107 for more information.


How to read file submitted through file field in block configure form I have created a block through custom module and added file field in block configuration form using below code.

function mymodule_block_configure($delta){
if($delta=='mymodule'){
    $form = array();
    $form['mymodule_file']=array(
        '#type'=>'file',
        '#title'=>'Upload text file',
        '#name'=>'files[sample]',

    );
    return $form;
      }
 }

When I try to check this field in hook_block_save, the form element is empty even when the form is submitted after browsing the file.

 function mumodule_block_save($delta,$edit=array()){
    if($delta=='mymodule_block'){
    dpm($edit);
    }
     }

$edit['mymodule_file'] is empty after the form is submitted.

Am I missing anything?

You want to use the #type 'managed_file' instead of just file: http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/7#managed_file.

That will then automatically save the file and create a row in {file_managed}, You just need to set it as permament, as explained in the link above and then save the fid, for example with variable_set().

You can also set the #default_value for the fid, and it will display the field again.


Use drush make to load only modules? I have a dev site with many modules.  I have another dev site on a different server that I'd like to populate with the same modules.  I can zip 'em up and move the file, or use rsync, but I wanted to see if drush-make would do it faster.

I can create only modules without core using: "drush make --no-core makefile.make" within the module directory but this creates the sites/all/modules directory hierarchy.

How can you use drush make to just build the modules in the modules directory without that structure?

If you run drush make --contrib-destination=sites/mysite, then modules will be placed in sites/mysite/modules.  rsync is going to be faster than Drush make. (Edit: This speed comparison presumes roughly equal transfer speeds between the endpoints. I can see how make might be faster if you have a fast connection from the target to d.o, but a slow connection between the source and the target.)

If you want to create a makefile for an existing site, you may use drush generate-makefile, or build a whole installation profile with drush generate-profile.


Created custom entity with Entity Construction Kit but cannot filter in Views by taxonomy I'm new to D7 but have extensive experience as a site builder in D6.

I created a custom entity type using the Entity Construction Kit(ECK) and then added a bundle with a term reference field using a hierarchical taxonomy and the Simple Hierarchical Select widget.  Everything works fine except when I try to build a view to display the fields and filter by the taxonomy terms selected using the SHS widget.

When you start building the view the preselector screen asks what to show; content, users, my custom entity/bundle, etc.  If I select my custom entity bundle, taxonomy terms don't show up as available for filtering.  If I select content, then my custom entity is not available presumably because content means nodes.

How do I build a view that displays fields from my custom entity and can be filtered using taxonomy?  If I create a custom content type instead of an entity, there's no problem filtering by terms, as expected.  What am I missing?

Tnx,

Jeff

SHS doesn't work with entities, only nodes.  The Hierarchical Select module doesn't support Views exposed filters yet either.

The taxonomy terms didn't show up as filters because I hadn't selected the bundle in the Views preselector screen.  I was trying to generalize the view to filter at any level with SHS but no workee.

This forces me to use nodes where entities are more appropriate, or try some other taxonomy scheme to get some useable exposed filter UI, using entities.

Ugh.


How do I link a thumbnail image to its content programatically? I have the following php code in a rule. It displays a picture that was uploaded by a user.

How do I link the thumbnail to the content?

$imgpath = file_load(($node->field_image['und'][0]['fid']))->uri;
print theme_image_style(array( 'path' => $imgpath, 'style_name' => 'thumbnail'));

Something like this...

$imgpath = file_load(($node->field_image[LANGUAGE_NONE][0]['fid']))->uri;
$image = theme('image_style', array('path' => $imgpath, 'style_name' => 'thumbnail'));

$link = l($image, "node/$node->nid", array('html' => TRUE));
print $link;


What is the difference between creating fields programmatically and by exporting settings? We are developing a custom app with decoupling approach. There are going to be many custom entities with fields. What is your preferred way to create fields programmatically, so we have all information in the code and can build our custom logic on it? So far I have identified three ways how to do it:

using the BaseFieldDefinition::create in the entity class.
using .yaml files in the modules config/install directory
using Features

With the first option, there is a problem that Workflow modules, which would be helpful, does not support the creation of the entity fields in the code (see https://www.drupal.org/project/workflow/issues/2960185). However, we can still replace Workflow module with custom entities and logic.

With other two options I am not entirely sure what are the pros and cons of using them. They just seem to me quite difficult to add custom logic, and/or methods to entities or create new field types (plugins).

Any suggestions will be much appreciated.

For modules common practice is to define base fields with the first option and bundle fields with the second option. Concerning option 3 most use cases of Features are now covered by the configuration management, which you can use to synchronize fields configured in UI to a cloned site. Not only those fields created in UI , but also base fields from option 1 in case they are overridden or bundle fields installed by option 2 if they are modified in UI.


Auto-populating Storm Invoice I'm using Storm for a bunch of its varying functionality, and figure it thus makes sense to use its Invoice module as the final part of a multi-part project (see previous SO post).

Everything in Storm Invoice seems like it needs to be entered on the fly, all the time. What I need to have happen is for a computed field from another node or a view to provide a price to the Invoice module, autopopulating some fields. Is this at all possible with Storm Invoice?

Addendum: If Storm isn't the best way to create dynamically-generated invoices from node CCK fields, please suggest an alternative.

I'm not sure but maybe the Computed Field can be used, you can even use it to fill another field.

If you are ready for some custom code (although Computed Field will probably require some code too), you can implement hook_nodeapi() when $op == 'prepare'(or hook_prepare() in Drupal 7). There you can pre-fill new Invoice node (when $node->nid is not set, the node is being created).


Is cache_form table making a site faster by any way? Drupal Commerce refuses to flush the cache_form table when cron tasks run. I know it is most likely a known bug and it has tens of solutions. (I will probably just set cron task to flush it somewhere in the midnight every day.)

Does it speed up Drupal in any way?

It is part of a cache obviously, but I did not noticed any better performance whether the table size. More or less I experience slowdown, but it might be related to something else.

The cache_form table holds forms that have been loaded by the system for your visitors. Eg, if a person went to a form before the form has expired, it exists in the form_cache by default.

Sometimes forms can bypass the form_cache if they are required to be rebuilt on every page request, such as with Ajax requested forms, or external services.

If you have a Shopping Cart driven application the cache_form may contain stuff added to your visitors cart -- which they have not purchased yet (I'm not sure if commerce stores cart entries in a separate table), but in general be wary of clearing the form cache because some of your visitors state may be lost.

Expired forms should be cleared by the system on cron run.


user menu not changing I think that was drupal 6 where the user menu e.g.:

-Login

will turn into:

-Log out

link when the user is not logged in and when the user is logged in respectively.

I do not know how to make this behave like this in Drupal 7.

Any ideas?

Drupal 7 out of the box will recognize these if you add them to any menu. It will automatically hide/reveal them based on their context.

Create two menu items, one pointing to user/login and one to user/logout


How do I fetch the password from the database? Suppose I entered ABC as password; its hash is like $S$DNcgO9.CUWosQrms0/CqWvLIUFikmoczZ42n9bL6wxiH1OhIQbd5, which is stored in the user table.  I need to retrieve the plain password.

How can I achieve this?

The short answer is you cannot. Drupal is using a SHA-512 which is a cryptographic hash function. SHA-512 is one way which means it is not possible to get the original data back.

You can check this api. https://api.drupal.org/api/drupal/includes%21password.inc/function/user_check_password/7.x and this https://api.drupal.org/api/drupal/includes%21password.inc/function/user_hash_password/7.x.


EVA + Corresponding Node References + Views + Sort by Order of Appearance on Page Node Thanks in advance for any help or suggestions with this problem. I will try to be as clear as possible. Basically, what I want to do is customize my Page node "County" to show a table of "Organization" nodes (along with their contact information) referenced in the county node.

So what I have done is to use the EVA + Corresponding Node References modules to create a table view on my county page. The problem is that I cannot figure out how to configure Views so it will list the organizations in the same order that I referenced them in the county node --  See screenshot http://www.diigo.com/item/image/16wo5/0jmw. As you can see from my screenshot I have ordered them first "Org 3" and then "Org 1", but in the views table they are ordered first "Org 1" and then "Org 3".

From reading other posts I suspect that I need to add a relationship in my view but I feel like I have tried almost everything and I still can't get it to sort correctly. Here's a screenshot of my Views admin page -- http://www.diigo.com/item/image/16wo5/x7hr

Thanks again for any help.

-Scott

Ok, I think I figured this out after some ideas I got while researching kalabro's answer. Basically I needed a better understanding of the logic of how EVA works with node references and related objects in views. So here's what I did --

First I changed the contextual filter in my view to "Content: Nid" with a default value of "Content ID from URL". Next I added a relationship to the field "Related Org" (which is the node reference field in my County content type) and did not check "require this relationship. Then I filtered my results to only include County content types and added the "Related Org" relationship to the title and body of my included fields -- except for the first title field (the related county itself) which I used to group the related organization by. Finally, I removed all sort criteria from the table settings and from the sort section.

Here's a screen shot of my views set-up: http://www.diigo.com/item/image/16wo5/7chr

Here's a screen shot of my county view: http://www.diigo.com/item/image/16wo5/r1dx

After thinking about this problem some more I'm not sure that I actually needed to create the corresponding node reference in order to accomplish this. I haven't tested it yet. Also, there may still be some tweaks to this set-up that don't show up because of my limited testing. Still, I feel like I'm on the right path now with a better understanding of how EVA, node references, contexts and relationships work together in views. And I am definitely left with a greater appreciation of the power of Drupal 7.

If anyone wants more details about my set-up please let me know.

Thanks to kalabro for helping me to get started thinking in a different direction.

-Scott


Load required libraries with content using ajax So I created a form and and attached a Drupal library to it. From there I created a route that uses that form. Last a added a link that uses ajax to render that form.

For some reason when I look at the context that is rendered from that ajax request the /core/misc/vertical-tabs.js?v=8.2.6 gets loaded onto the page along with the form content, but my attached custom library does not.

If I visit the page without using the ajax request both the /core/misc/vertical-tabs.js?v=8.2.6 and my custom library load fine.

How can I get my custom library to load with ajax?

So after playing with this for a while I figured out that Drupal only pulls in the js Assets through ajax, not the css. I guess this make sense on some level. But I figured I can easily pull in the necessary css in using js.


Alter a query using hook_views_query_alter() to filter a view by month I successfully created a view gathering, let's say, events, sorted by date.  I also created exposed filters so one could filter the view.

I'm attempting to create another exposed filter that would filter the data on their field_date, but only by month. I quickly understood that this feature is not provided out of the box, so I managed to implement hook_views_query_alter() in the .views_execution.inc file.

This is what it contains.

function djm_views_query_alter(ViewExecutable $view, QueryPluginBase $query){
    if($view->id() == 'calendar'){
        $date_format = $query->getDateFormat("node__field_precise_date.field_precise_date_value", "m");
        $query->addWhere(5, $date_format, 12, "=");
    }
}

$date_format should return DATE_FORMAT('node__field_precise_date.field_precise_date_value', '%m').  The thing is that (I inspected the query my view outputs) the view totally strips my parentheses, percentage signs and, I guess, any special character, so it becomes DATE_FORMATnode__field_precise_date.field_precise_date_valuem.

Has anyone ever experience something like this?  I can't figure what to do to "fix" this. Am I using the right hook?

I managed to get my code working, if anyone is stucked at the same point, you have to use addWhereExpression instead of addWhere.  Here's what it looks like overall.

function HOOK_views_query_alter(ViewExecutable $view, QueryPluginBase $query){
    if($view->id() == 'calendar'){
        $definition = array(
            'table' => 'node__field_precise_date',
            'field' => 'entity_id',
            'left_table' => 'node_field_data',
            'left_field' => 'nid',
            'extra' => [ // These are extra conditions views adds by default, I just copied them so it looks like any filter.
                0 =>[
                    'field' => 'deleted',
                    'value' => 0
                ],
                1 => [
                    'left_field' => 'langcode',
                'field' => 'langcode'
                ]
            ]
        );
        $join = Views::pluginManager('join')->createInstance('standard', $definition);

        $query->addRelationship('node__field_precise_date', $join, 'node_field_data');
        // ouptuts "LEFT JOIN {node__field_precise_date} node__field_precise_date ON node_field_data.nid = node__field_precise_date.entity_id AND (node__field_precise_date.deleted = '0' AND node__field_precise_date.langcode = node_field_data.langcode)"

        $date_format = $query->getDateFormat("node__field_precise_date.field_precise_date_value", "m")." = :value";
        $query->addWhereExpression(2, $date_format, [":value" => 12]); // Where 12 is the month I need.
    }
}

I'm still opened to better ideas so feel free to share them !


Using jQuery to communicate to Drupal 7 via AJAX I've been learning how to use AJAX with Drupal 7. I already know how to use the '#ajax' attribute with a form and also how to use the 'use-ajax' class with a link.

I have a nice jQuery slider on my page that emits a jQuery event (called 'slide') every time the slider moves to a new picture. The event also contains which slide number we will be viewing. I can bind to the event using jQuery like this:

$('.slider').bind('slide', function(e, data) { alert(data.slide); });

That will pop up an alert showing the current slide. Instead I want to make an AJAX call using Drupal 7's AJAX and pass this current slide number to Drupal.

I've been searching for an answer and I think it might have something to do with the Drupal.ajax DOM object but I'm not sure.

I am assuming you'd like to display some data when you're moving the slider around.

The way I do it is without using the '#ajax' attribute.

Implement the AJAX call, send the slider value as POST variable to '/foo/ajax':

    jQuery('#slider').slider({
            // Define your slider (min, max etc)
            ...
            // Add event handler
            change: function(event, ui) {
                jQuery.ajax({
                    type: 'POST',
                    url: '/foo/ajax',
                    dataType: 'json',
                    success: ajaxCompleted,
                    // Might want to use 'ui' instead of jQuery('#slider').
                    data: 'slider_value=' + jQuery('#slider').slider('values', 0);
                });
            }
    });

Make a menu item that's called when the slider moves around:

function foo_menu() {
  ...
  $items['foo/ajax'] = array(
    'title' => t('foo AJAX'),
    'type' => MENU_CALLBACK,
    'page callback' => 'foo_ajax',
    'access arguments' => array('access content'),
  );
  ...
  return $items;
}

Implement the foo_ajax page callback:

function foo_ajax () {
  // Retrieve the slider value
  $slider_value = (int)$_POST['slider_value'];

  // Get some id's from the foo table
  $result = db_query('SELECT id FROM {foo} WHERE value = :value', array(':value' => $slider_value));
  $data = array();
  foreach ($result as $row) {
    // Do something with data
    // Parse to json

    $data[] = $row->id;
  }

  // Return json
  drupal_json_output($data)
}

Implement ajaxCompleted (within your javascript):

function ajaxCompleted () {
    // Parse Json
    // Add some stuff to your DOM.
}


logging of access to images in image field If someone hot links an image attached to a node via the image field, does Drupal add a log entry?

I was thinking along the lines of creating a mechanism where I can use images in Drupal nodes to track who reads emails, much like Mailchimp does. If I embed an image hosted by Drupal, would the log show the node as accessed, when an image from the image field was embedded in an email?

Take a look at the Mail Tracking module.

Drupal can only register requests for public files that aren't present yet (e.g. image derivatives that have not yet been created). Otherwise the file will be served directly by the web server.


What's the right way to have a contextual link on controller action? I just installed a custom module and created a controller with index function in it. I want to have a contextual link for this. I have following code in index function.

public function index() {
    return [
        '#type' => 'markup',
        '#markup' => $this->t('Implement method: hello'),
        '#contextual_links' => [
            'mymodule' => 'mymodule.another_action',
        ],
    ];
}

File : mymodule.links.contextual.yml

mymodule_configure:
  title: 'Configure Custom Module'
  route_name: 'mymodule.another_action'
  group: 'my_module'

Please suggest the right way.

I did this using a reference from below.

Adding the contextual link render element

I added a variable to the theme, and passed contextual link in controller function to twig template using that variable. Please see code below.

File : mymodule.module

function mymodule_theme() {
  return [
    'mymodule' => [
      'template' => 'mymodule',
      'variables' => [              //Added a variable content
        'content' => '',
      ]
    ],
  ];
}

File : mymodule.links.contextual.yml

mymodule_configure:
  title: 'Configure My Module'
  route_name: 'mymodule.route_name'
  group: 'mymodule'

File : IndexController.php

public function index() {
    $data['content'] = [
        '#type' => 'markup',
        '#markup' => $this->t('Implement method: index'),
    ];

    $data['#contextual_links'] = [
        'mymodule' => [
            'route_parameters' => [],
        ],
    ];

    return [
        '#theme' => 'mymodule',
        '#content' => $data,        //Pass Contextual link to the variable
    ];
}

File : mymodule.html.twig

{%
set classes = [
'contextual-region'
]
%}

<div {{ attributes.addClass(classes) }}>
  {{ title_prefix }}
  {{ title_suffix }}
  {{ content }}                     //Render here
</div>

--

Thanks


Disable caching for custom block for anonymous users I have created a custom Block that extends BlockBase. I don't want the content to be cached for anonymous users (also not for authenticated users). To be more precise, caching would be fine but depending on some url query argument. In my case the url contains a parameter 'mode' (?mode=1 or ?mode=2 and so on). Depending on the parameter the content of the block varies.

I added the following function:

 public function getCacheContexts() {
    return Cache::mergeContexts(parent::getCacheContexts(), array('url.query_args:mode'));
  }

Still the block content seems to be cached. Is it neccessary to disable the internal page cache module? Actually I don't want to globally disable caching, I just want my block to be cached correctly depending on the url parameter mode.

The problem is, you don't render the block in a normal way and Display Suite is obviously not able to retrieve the plugin cache metadata.

Most times it is a better option to include the cache metadata in the render array together with the data it depends on:

public function build() {
  $build = [];
  $request = \Drupal::request();
  $mode = $request->query->get('mode');
  $build['mode'] = [
    '#markup' => t('The query argument is mode=@mode.', ['@mode' => $mode]),
  ];
  $build['#cache']['contexts'][] = 'url.query_args:mode';
  return $build;
}

Then the cache metadata can bubble up, no matter where and how this block content is embedded.


How to get values which changed during node edit in node api? I have a node with user entity reference field. Now I want to get newly added users id's to this node via this field in hook_node_update

What is the best way?

The $node argument to hook_node_update contains a $node->original object. With that you can identify the newly added user IDs by comparing $node->your_user_ref_field to $node->original->your_user_ref_field.


Drupal 7 and MongoDB module howto Just installed 7.x-1.0-beta1 to Drupal 7rc1.

Should I see some new option in the configuration? Where should I set the connection settings? I have no idea how to use this module...

I (and my team) wrote most of that module and -- as Jeremy says, it's only needed for extreme scalability. Because of that, it's supposed you know what you are doing (otherwise you will have no chance of scaling to the levels where MongoDB is necessary) and so no UI is provided, just use $conf overrides.

There's a DBTNG driver too but it's more in a proof-of-concept stage so it's in a separate project.


How do users can login automatically through URL when they click on the link received in Email In Drupal 7, I am sending E-mail to each user with some content. Here I need to send link to automatically login through URL means when they click on the link they should redirect to the site and submit the form. This form should submitted by only authenticated users. How to generate those Unique URLs. Is there any module for this or give me any ideas please.

Try the Login one time module

  Login one time provides the ability to email one-time login links to users. You can also choose the pages they will land on.

Another module is urllogin

  This module provides a way to transparently log users into the web site when they follow a link. The primary use is for mass email where users are send individualized URL’s which take them to a page on the site, in a “logged in” state. Every effort has been made to minimize the potential security risks.


Exclude a free product from total calculation In Drupal Commerce, how can I exclude a product from partial total calculation? The product is inserted as free product via a Commerce Discount rule, but in total calculation it appears and then is subtracted.
I would exclude this insertion/delete operation.

Create a rule with the event Calculating the sell price of a product.

There, you can check for the SKU of the product and set its price to zero (using the Set data value action).

You can also use the Subtract an amount from the unit price action to assign the value to a price component so that it appears in the totals (this will require extra configuration)


How do I send verification mail from my drupal custom module? I have written a custom module, which can send simple mail. how do I send mail so that user should get the verification link or something similar.

<?php
/**
* implements hooks_menu
*/

function planet_extension_menu(){
$items['planetext']=array(
'title' => t('DEMO Planet Extension'),
'description' => 'Feeds aggregation ',
'page callback' => 'drupal_get_form',
'page arguments' => array('planet_extension'),
'access callback' => TRUE,
);
return $items;
}

// callback function
function planet_extension($form,&$form_submit){
$form['url']=array(
'#title' => 'URL',
'#type' => 'textfield',
'#required' => TRUE,
'#size' => 35,
'#description' => t('Enter the URL'),
'#attributes' =>array('placeholder' => t('www.example.com'))
);
$form['title']=array(
'#title' => 'Title',
'#type' => 'textfield',
'#required' => TRUE,
'#size' => 35,
'#description' => t('Enter the Title'),
'#attributes' =>array('placeholder' => t('Title'))
);
$form['email']=array(
'#title' => 'email',
'#type' => 'textfield',
'#required' => TRUE,
'#size' => 35,
'#description' => t('Enter you valid email'),
'#attributes' =>array('placeholder' => t('example@example.com'))
);
$form['submit']=array(
'#type' =>'submit',
'#value' => 'Submit',
);
return $form;
}

// below is the form submission function
function planet_extension_submit($form,$form_state){
//store the values entered in form into variables
$values = array(
'url' => $form_state['values']['url'],
'title' => $form_state['values']['title'],
'email' => $form_state['values']['email'],
);
//insert the variables into the table
$insert = db_insert('planet_extension')
                -> fields(array(
                        'url' => $values['url'],
                        'title' => $values['title'],
                        'email' => $values['email'],
                ))
                ->execute();

drupal_mail('planet_extension', 'planet_extension_mail', $form_state['values']['email'], 'en', array('values' => $values));

        drupal_set_message(t('Form submitted. Check your email for verification')); //custom message after form submission is successful
}

//implements hook_mail
function planet_extension_mail ($key, &$message, $params) {
  switch ($key) {
    case 'planet_extension_mail':
      $message['subject'] = t('Hello');
      $message['body'][] = t('Hello user');
      $message['body'][] = t('The main part of the message.');
      break;
  }
}

I am not sure about what kind of verification emails you are sending, though I believe if you peep inside drupal core user module you can get hold of function which does the same,as for user registration process we have email verification option also.

A very simple straight custom way might go in the following way

How you will be generating the verification code?

while sending the email create a link something like www.mydomain.com/email-verification/%random_string%

Create a custom table with column as email,random_string,verified
once you have generated it, make a db query to insert the link you created a point back against the email user entered and set verified to 0 in the custom table.
send the email
In your custom module implement hook_menu() with menu entry fir "email-verification" .
In the page callback using wild card check if the random_string exists in you custom table, if so set verified to 1

Not exact but close to what you may need.

Update:

global $base_url;
$random_string = substr(str_shuffle(md5(time())),0,10);
// Link
$email_link = $base_url . "/email-verification/" . $random_string;