using drush for upgrade drupal 6 to 7 - create alias problem I want to use drush for upgrade my drupal 6 to drupal7. i read this document. i have a problem with create alias. i have been doing this

1- create a subdomain in my plesk (create sub.domain.com)

2- go to /var/www/vhosts/domain.com/httpdocs and download this file and rename this to "aliases.drushrc.php"

3- remove aliases.drushrc.php content and replace with

<?php
$aliases['sub'] = array(
  'root' => '/var/www/vhosts/domain.com/sub',
  'uri' => 'sub.domain.com',
);
?>

4- run command: drush @sub status and i get this error:

The drush command '@sub status' could not be found.  Rundrush cache-clear drushto clear the commandfile cache if you have installed new extensions

Although the Drupal root is a valid place to store alias files, Drush will not be able to find the alias records described there until the Drupal root as been specified.  Therefore, drush @sub status has a chicken-and-egg problem; you want to use @sub to specify the Drupal root, but Drush won't load the alias file that defines @sub until the Drupal site it is defined in is bootstrapped.

To resolve this problem, move your aliases file to $HOME/.drush/aliases.drushrc.php.  Once you do that, then your status command will work.

You may define your 'onward' alias either in $HOME/.drush/aliases.drushrc.php, or in /var/www/vhosts/domain.com/httpdocs/aliases.drushrc.php, per your preference.


Passing object in routing.yml I have an entity and when I try to pass the whole entity object, only the name is passed through the routing.

Here is the relevant code in routing.yml:

mymodule.myentity_info:
  path: '/admin/config/mymodule/myentity/{myentity}/info'
  defaults:
    _content: '\Drupal\mymodule\Controller\MyModuleController::info'
    _title: 'Myentity Info'
  options:
    parameters:
      myentity:
      type: entity:myentity
  requirements:
    _entity_create_access: 'mymodule_myentity'

After clicking the link, I get this error: Trying to get property of non-object

I've added an issue regarding this to my sandbox project: https://www.drupal.org/node/2301021

What you are looking for is now called upcasting, the handbook page is https://www.drupal.org/node/2122223

I do not think options is necessarily for entity upcasting. For example, check the node.type_edit in core/modules/node/node.routing.yml for a routing definition not using any options (or user.admin_permission in user).

As with your previous question, I wonder whether your entity class properly defines its storage controller? If you have a debugger, the parameter conversion happens in core/lib/Drupal/Core/ParamConverter/EntityConverter.php


Feed import breaks due to ajax error When I tried to do a feed import, I got the following error.

An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: /batch?id=1726&op=do
StatusText: OK
ResponseText [Omitted text]

(There are quite a few similar errors on the web, for example https://www.drupal.org/node/1125060.)
When I changed the author field to 'site-admin' (see attached image), auto-complete seems running and popup the following error.

An AJAX HTTP error occurred.
HTTP Result Code: 200
Debugging information follows.
Path: http://site-prod.local/user/autocomplete
StatusText: OK
ResponseText: my_site_name | my_username
[url1]
[url2]
[url3]
[Search form]
[Primary tab: View (active tab)]
[Edit]
[Shortcuts]
[Broken links]
[Devel output]
[My username]
[Email]
[Omitted text]

The log message is the following.

Warning: Cannot modify header information - headers already sent by (output started at /var/aegir/platforms/production/drupal-7.27/includes/common.inc:2700) in drupal_goto() (line 703 of /var/aegir/platforms/production/drupal-7.27/includes/common.inc).

If I put exit() right after drupal_json_output(). The related problem seems resolving itself.
When I run drush -d -v search-index, the indexing stuck at around 61%. This indicates some problems with a node.

By using xdebug and vdebug (plugin for vim), I am able to step into the code and ping point the issue.

In https://api.drupal.org/api/drupal/includes!common.inc/function/drupal_cron_run/7

I put a watchdog: watchdog('bug_cron', '
'. print_r($module, true). '
'); inside.

// Iterate through the modules calling their cron handlers (if any):
foreach (module_implements('cron') as $module) {
      // Do not let an exception thrown by one module disturb another.
      try {
        // NOTE: put a watchdog and look at your log message.
        // You should able to see which module causes issues.
        watchdog('bug_cron', '
'. print_r($module, true). '
');

        module_invoke($module, 'cron');
      }
      catch (Exception $e) {
        watchdog_exception('cron', $e);
      }
    }

It is the search module causes issues. Disable it, then uninstall the setting via the drupal menu GUI, then it is fixed, but I am not sure why search module causes issues.

Updated at 2015-05-26

It turns out my module uses hook_url_inbound_alter + drupal_goto caused issues. It is not easy to debug, because there are couple of side effects.


How do I update the documentation on someone elses module? I want to update the documentation on the Agenda module on Drupal to provide a bit more clarity on how to get it set up.

I have contacted the author and he said great!

How do I do this on drupal.org?  I see the code can be changed via git, is the documentation part of the git repo?

Documentation pages on drupal.org are normal Drupal nodes. You need special permissions in order to edit these nodes. There is documentation on drupal.org about how to contribute to documentation.

If the module in question includes a README.txt file, then you can submit a patch to the module maintainers that includes the updates. If the module doesn't have a README.txt file, then submit a patch that adds one.


Flexible gallery solution for Drupal 7 I'm trying to build a site which should have gallery functionality. I think we should be able to solve this with Drupal 7. So my question is: is there any module/feature etc. (or any combination of modules), which can solve the following?

The site is on Drupal 7.
(A) We will have a gallery manager role. Every user with that role should be able to upload and manage his/her own galleries. We will have at least 10 person with this role.
(B) A gallery should be able to contain/display/manage ~100 pictures, so batch uploading and editing (for captions, ordering, etc.) is necessary.
Support for usual Drupal goodies like image styles, Views etc.
Support for a clearbox-like display, preferably integration with the Colorbox module.
Support for YouTube videos in galleries would be nice, but not a must have.

I've already checked a lot of suggestions in the topic. Alternatives that probably won't work in my case (please correct me if I'm wrong):

A Drupal 7 version of Node Gallery would solve almost all of this, but it's not likely that we will see anything like that soon.
edit: Node Gallery is now completely and totally unsupported, meaning that we won't see a D7 port ever.
Media Gallery is a somewhat incomplete module - I've tried to build the functionality above with that, but I can't see any way to support point (A), not to mention a big bunch of bugs that would make it impossible to use it on a production site. Also it's not maintained well.
Field Slideshow is just a nice formatter, I don't think it's possible to use anything like that in my use case. As far as I can understand, a formatter-based solution won't scale well enough for (B), not to mention the missing management functionality. Gallery formatter is the same from my point of view.

I would appreciate any suggestions on solving this. I'm not afraid of building something from scratch (whether it means playing around in Views, coding or both), but at least I would like to know where to start to achieve all of this.

In D7, I do galleries with the image field and the plup module. Nothing fancy, but at the same time, probably because it is nothing fancy, you automatically get support for colorbox, permissions (standard core or from contrib like Field permissions module), image styles, image captions (using the image caption module) and any other (image-)field related functionality.

So far it has fully satisfied my needs


Printing raw field value to use in path to files I have field called "field_cat_id" which has a numerical value (10201; 10202 etc). The field represents a category id and it is also used to arrange PDF files,

I would like to print this (raw) value and use it in the path as shown below in the snippet of my node.tpl.php:

    <?php
     $catid = print $content['field_cat_id'][0]['#markup'];
       $path = "/home/site/library/files/" . $catid . "/";// to switch to this once all is working
    $files = scandir($path); ?>

      <?php foreach ($files as &$value) {
        echo "
 ".$value."
";
    }?>

The output for $path comes out like this:

/home/site/library/files/1/

Where am i going wrong? When I run

   <?php print $content['field_cat_id'][0]['#markup']; ?>

The output is for example "10201"

$catid = print $content['field_cat_id'][0]['#markup'];

Try removing the print.


Entity reference additional field In D7 I have two new node type defined e.g. branch and leaf. The branch is a collection of leaves that I'm referring to using the entity_reference module. In the picture below the leaves are the nodes representing the colors. The leaves could be re-used in several branches.
Here is a picture of my collection
I would like to add for each of the referenced leaves, two checkboxes to add some information about that leaf that is referenced in that branch. I have added on the picture manually the checkboxes. This is what I would like to achieve. Then, programmatically when I read the branch and all its leaves, I want to be able to retrieve the checkboxes value as well. Everything is working far, I just need to know how to add the leaves, so that at edit time when I edit a branch I can tick the checkboxes as needed.
How could I do that? If there is no module that exists, which hooks should I use for adding this fields to the referred leaf node in the branch?
I do not want to add new fields for the leaf node type, I need the new fields/chekboxes to be added to a branch for each leaf thus at the moment of referring to the leaf and for each leaf.

One of the ways to solve it is to use the Paragraphs module.
How to start with Paragraphs for Drupal 7
It's basically entity reference fields with layers.
You create a Paragraph field as a container for each data set, then within paragraph create fields for color and lists (checkboxes).
BTW why not upgrade to D8? D8 supports this type of structure better.


Creating a vanilla instance from a site already set up I have a Drupal site which is set up, running and being continuously used.  It has a variety of content_types, taxonomies and field_collections etc saved in the database.  The plan is to sell on vanilla instances of this Drupal site - which means, clearing out all the content and resetting all table indexes to 1 etc.

Any ideas how to achieve this?

There are 2 easy options:

Use the Delete All Module and it's Drush interface.
If that's not thorough enough, I typically just end up using an SQL script to set foreign key checks to 0; and then truncate all fields, cache, revision, users, user_roles ... etc tables specific to my site. While it seems like alot of work it's basically a 1 time audit of the underlying DB for the script creation and simply tracking what new tables are needed for wiping when you add new modules. I've then used Rules_Link and the php filter to make this SQL statements runnable via a button press from a displaysuite panel ...


Why would just adding a product to cart create a payment with method type "unknown" and credit card of "4111--------1111" We have the Payment Method Example module turned OFF. And, we only have one payment type set up (Authorize.net) in the Enabled Payment Method Rules.

Yet, when we add just one product to the cart and click submit (without going to checkout, so without filling in any payment fields) we can go to orders/shopping cart and see that a payment with the following fields has been added to the order in process:

Date: "6/25/2015" (even though today is 6/22/2016)
Method: "Unknown"
Remote ID "-"
Result Message: -    Number: 4111--------1111  Expiration: 06/2015
Amount: $1,788 (which is $4.00 less than the total for this particular order. Note that this amount will vary, though.)

This causes the following Authorize.net issues:

1) In the above example, Authoize.net comes in and accepts a transition for $4.00. The order balance is then zero, based on the above $1,788 "unknown" payment plus the $4.00 from Authorize.net.

OR

2) Authorize.net comes back with the below error when the "Unknown" method payment is larger than the actual order:

REJECTED: A valid amount is required.
AVS response: AVS not applicable for this transaction
CVV match: -

If it helps, here are the rules that fired on the product submit page:

Commerce Pricing Attributes (default)
Calculate taxes: Sales tax (default)
Calculate taxes: VAT (default)
Reset the cart order status on product add or remove (default)
Add to Cart message (overridden)
Redirect after product add to Cart (custom) - a page redirect after submit

So - I need some help to debug/fix this:

1) Is there anything obvious I should look at? I have analyzed the setup of all modules, rules, etc.

2) How would what looks like an example payment type be added before even going to any checkout page - when we have the Payment Method Example module turned OFF.

3) And, since there is no error message - where do I even begin to debug this (I am a novice)?

4) Will Devel help? It seems you need some code added to a module. How do I figure out what module, what code, and where to add the code?

Thanks! Any help you can give would be highly appreciated!

Fixed it!

When you delete an order on the order page, the associated payment does NOT get deleted. And, once the order is deleted, there is no way to delete the payment in Drupal commerce, since you only have a view of the orders.

Then, when you create a new order, the order number you deleted can get 'reused'. So, the old payment is then associated with this new order. That is why we saw the errant payments on the new orders.

So, I fixed this issue by going into the database and manually deleting all of the errant example payments in the commerce_payment_transaction table. So far, so good….

Bottom line: NEVER delete an order once live. Or, minimally, always delete the order's payment FIRST, then the order.


Pull content from production to staging server I have a setup that consists of a Drupal 8 instance on my localhost, a staging instance on a develop server and a productive version on a production server. Initially, I was co-designing the theme, the configuration and so on on my machine. But now, the site is live.
For configuration changes, I can update my local instance and export the configuration. Pushing this to my develop branch in my git repository automatically triggers a deployment on the develop server. Creating a new release triggers a deployment on the production server.
Now this situation: Content editors create new nodes on the instance on the production server. On some piece of the new content, they discover an issue and want a fix for that and maybe even want to review this fix on the develop instance.
I already have such a neat deployment for the configuration, so I really want to avoid copying databases around. For images, there's a module, that can replace local static files with links to the productive version. What would be the equivalent solution for the content in the database?
What might be a useful flow for the case that there's no better automation:

I do a composer update on my local machine
The content from develop gets pulled to my local instance
I commit my changes and pull them to the develop instance
The develop instance pulls content from the productive instance
The develop instance reads my new configuration

It would be even better if there would be some API magic that enables my instances on localhost and develop to read the content directly (and cache it).
So, is there some API magic around? Or do I have to write scripts and everything to pull databases from server to server?
Additional requirement: I did most of the work so far and have all the administrative rights, but in the future, this should work for additional developers who should not need to login onto a server.

Content is particularly difficult to Migrate. It's not as clean as Configuration. Generally, what you are talking about is not done - as Kevin points out, content is created on prod, and databases are pulled from prod to any other environment that needs that content. That said you could set up a Migration strategy with the Migrate API that could be used to migrate content around between environments. You're mostly on your own with this though - I haven't seen any tutorials for your specific issue.


Hide dates in the present in .tpl.php files I've got a content type (Events) and they have event dates. Some of them have multiple dates, some of them haven't. But I want to hide the dates which are in the past.

Obviously, February 15th and April 18th are already passed. How can I hide them?

When I do var_dump($content) in the tpl, all I got is this:

15 February 2012 - 14:00 to 16:30

So it looks like I can't filter in PHP since it's already converted into HTML. Any idea how I can filter this?

EDIT: screenshot of my date section

Presuming you are using the Date module. In the Manage Display settings for the content type, modify the setting for the Date output and put 'now' in the 'starting from' box.


Search is not throwing any result It is Drupal 7.

This is kind of strange behaviour of the website.

This is my website http://www.protecdental.com. If you visit this website, you will see the right-hand top search field. Please see the screenshot https://snag.gy/LfCDxs.jpg

If you type any junk keyword (That means the site will definitely throw 0 results) for example "werewe" then you will see the proper search result page with no result.

But if you type a keyword related to the website's content for example "dental" or "contact" or any related meaning full keyword then you will see the broken page with no content at all.

Not too sure the issues is: it seems like if there is a search result data, then it is somehow breaking the page:

I didn't find any error log for it even when I tried watchdog.

I cleared the cache
I re-indexed the search
I manually ran the cron

But no luck. Can anyone please help to at least narrow down the cause of this issue.

My default search result template:

<?php if ($search_results): ?>

<?php print t('Search results');?>

    <ol class="search-results <?php print $module; ?>-results">
        <?php print $search_results; ?>

    <?php print $pager; ?>
<?php else : ?>

<?php print t('Your search yielded no results');?>

    <?php print search_help('search#noresults', drupal_help_arg()); ?>
<?php endif; ?>

No problem, yeah when you see an error page like that, most of time the issue is in one of the template files.


How to add a subtitle field to a block view? I want to add an additional subtitle to a block view in Drupal 8. For example my View would be showing News on the site. So I want the title to be 'News' and then a subtitle underneath 'My Subtitle'. Then the list of news would follow. How would I do this? Can i add additional fields just like with custom blocks?

In the end it should look something like that:

 Subheadline

 Headline

      Block Content

The easiest solution is to add a Global: Text area in the HEADER and type your Subtitle there.

You can use FULL HTML and wrap it in a div class or ID so you can do some CSS work on it.

  Can i add additional fields just like with custom blocks?

You can add fields to your view

or attach another view that contains fields in the FOOTER, but fields in views and fields in custom blocks are totally different.


How to add a region to display only on a specified page? So, I have a region, which should only display on a specific page. Is there a way to have a page-checking condition in the page template to only display the region on the specified page, or do I need to create a page specific .tpl file which should have the region in it?

The issue I'm having is that region is being added to pages without content in them. This is evident, because the CSS border property for the region is being applied despite their being no content in it.
. You can see in the images that there is border applied to the element, which shouldn't be loaded into the page.
Here is the relevant excerpt from my page.tpl

    <?php print render($page['navigation']); ?>

  <?php if(drupal_is_front_page()) {unset($page['content']['system_main']['default_message']);} ?>

        <?php if ($logo): ?>
          <a href="<?php print $front_page; ?>" title="<?php print t('Home'); ?>" rel="home" class="header__logo" id="logo"><img src="<?php print $logo; ?>" alt="<?php print t('Home'); ?>" class="header__logo-image" />
        <?php endif; ?>

        <?php print render($page['header']); ?>

      <?php print render($page['hero']); ?>

        <?php print render($page['highlighted']); ?>
        <?php print $breadcrumb; ?>

        <?php print render($title_prefix); ?>
        <?php if ($title && !drupal_is_front_page()): ?>

<?php print $title; ?>

        <?php endif; ?>
        <?php print render($title_suffix); ?>

        <?php print $messages; ?>
        <?php print render($tabs); ?>
        <?php print render($page['help']); ?>
        <?php if ($action_links): ?>

<?php print render($action_links); ?>

        <?php endif; ?>
        <?php print render($page['content']); ?>

          <?php print render($page['blog_sidebar']); ?>

          <?php print $feed_icons; ?>

So, there's multiple ways to approach this: 1) views theme preprocess functions; 2) creating a page specific tpl; 3) jquery/js hacks to only show the content on the specified pages.

For the sake of maintenance and simplicity, I chose to re-build the page as a basic page and add the necessary views to the page and add the region to a page specific tpl. I chose the basic page option for simplicity as well as simplifying other tasks down the line such as breadcrumbs. I copied the page.tpl.php, and renamed it page--my-node-id.tpl.php and flushed the theme registry, restoring the original page.tpl. Just an FYI, going the node page route forced me to set the display for the article class inserted into the page to none, to keep my styling the same.


How can I use the Private Message module for anonymous users? I am using the Private Message module as a way of contacting the author of a node.

I have the problem that the button that says "Send author a message" only appears on the node when the user is logged in. If the user is not logged in, then the button that appears is the one that says "Log in or register to be able to post comments" (or something like that)

What I want to achieve is that the user (not logged in) can see the "Send author a message" on the node. And when this user clicks on this button he will be taken to the login form first, and then, after login, the user gets redirected to type the message to the node author.

How can I achieve this?

The Privatemsg module CANNOT be used for anonymous users ... Unless you are ready for some "tweaks" ... as detailed below.

I'm assuming your question is about D7, if it is for D6, you might consider using what's described in Issue # 490264. But it's worth reviewing that issue to get "an idea" about a possible work around ...

So how about D7? Issue # 554238 is about D7, and Comment #7 in it refers to the issue I mentioned above (which is for D6). However Comment #8 in that issue might be the solution. It contains this code sample:

<?php
$msg = "Hello there";
$source_tag = "from {$_SERVER['REMOTE_ADDR']}";
$result = privatemsg_new_thread( array(user_load(1)), "Browser visit {$source_tag}", $msg, array('author' => user_load(1)) );
// If you wanted to show an error, uncomment the following:
if (!isset( $result['success'] ) || !$result['success'])
{
  printf( "
Failed to send: %s
\n", $result['error'] );
}
?>

Apart from what is above, there is also the (way more) recent issue # 2231795. Comment #1 in it contains a code sample also. So if the above code doesn't fit (or work), consider this as an alternative.

So by using the Privatemsg module, and some tweaks (see above) you should be able to make it work somehow for anonymous users also


How to render a facet block? I've created a facet block according to this example Programatically render a block in a twig template

I've created the facet block as follows:

$variables['block_output'] = Drupal::service('plugin.manager.block')->createInstance("facet_block:topic")->build();

That works great, but I'm missing the block template itself on my page (the block around the facet links output). I need a custom suggestion for this block to format it. Unfortunately, the hook_theme_suggestions_alter() doesn't detect this block. How can I add a file name suggestion?

Thank you!

I'm using the module Twig Tweak, so you don't have to create a block, but you can add in in your twig file.

In my views-view--view-id--page.html.twig file I use it like this:

<div>
 {{ drupal_block('facet_block:facet_id') }}
</div>

Where the facet_id is the machine name of my facet.


Doesn't have author picture field I am building a drupal site using Views, search API module and user-points module.

I created the "database server", and indexed many fields of nodes.

I created a search page using views and the search API, that present content (image, title etc.)
In addition, I want to add to every content in this search view the name of the author that wrote it, his author picture.

I add the Indexed Content: Author relationship. Unfortunately, I can't find a way to add the author picture and the current total point to my view.

Can somebody advice how to do that?

I have not tried any of the following before, these are result of googling, so might not work.

I see two ways, hope any one helps you.

Solution might be as simple as using Apache Solr Image module, but not sure if it will work with user image.
The second needs custom coding, which will basically tell apache solr to index the image field uri and then add the uri field in your views and finally theme it as image using a custom template, Refer this for sample code.


Can I get integers from a dynamic query using fetchAllKeyed? So basically I want an array of integers from a query using fetchAllKeyed for the results.   The field is an tinyint in the db so I would expect an indexed array of integers but I am getting an indexed array of strings.

Here is the database call:

$query = $this->connection
  ->select('database_name', 'db')
  ->fields('db', ['first_index', 'value'])
  ->condition('db.value', 0, '<>')
  ->condition('second_index', $array, 'IN')
  ->execute();

$indexed_array_of_ints = $query->fetchAllKeyed();

I've tried to find other mentions of this issue and I haven't so maybe I'm just doing it wrong, I don't know.

I know that I can convert the values after the call, but I'm looking to make this operation as fast as possible so any help here would be greatly appreciated.

The issue here is that PDO returns strings, even for integer columns. Drupal handles this issue by providing the Typed Data API, which provides data typing used within Drupal, rather than PHP-level data typing.

In the Drupal 8 paradigm, database queries are generally made to query entity IDs, which are then used to load entities. Data is then retrieved from the entity. The Entity API on the back end will handle the setting/getting of the fields on the entity. The fields on the entity will all be of a Typed Data API data type, providing a consistent method of dealing with data types on the Drupal level.

The method of retrieving IDs, and loading entities is done for the sake of efficiency, as entities are cached, and may be loaded from backends such as Redis, therefore being much faster than retrieving the entity data from the database. And because fields are typed, it gives a consistent API for dealing with various data types, that can also be extended to provide additional data types through contributed modules.

So the question here becomes about what you are trying to do, and how you are trying to do it. If you are working with data that you've been saving to the database yourself, then you can switch to the Drupal way, and create a custom entity type then use the Entity API to set/get the field data. Or, if you are retrieving data from the DB that Drupal has saved there, it likely belongs to an entity that you should be retrieving, rather than directly retrieving the field data.


How to display a field of a referenced entity in views contextual block? I have read several questions on topic, e.g. 1 2 3, but couldn't manage to get it work.

My setup:
In a Drupal 7 environment, I have a node type called organizer, which contains two fields: node title (default) and a link (to the organizer's website).
A second node type called event contains several fields one of which is an entity reference to organizer.

My site's design only has the node title and node body of an event being displayed in main content. All other fields are displayed in a sidebar using a views block with filter on node type (= event) and a contextual filter on node id. Among these fields is also the field organizer and it's displaying the organizer's name (title field) alright.

My goal:
Now I want to have the organizer's name link to the organizer's website. But the link is actually a field inside the organizer content type.

My approach:
I've added a relationship to Entity Reference: organizer. Then I added the link field that is used in the organizer content type to the list of fields using the relationship. I rearrange the fields to have this link field being loaded before the entity reference field. Then I set up the latter field to being rewritten as link using the plain url from the link field.
[The link field is currently being displayed for debug purposes, later I want to exclude it from display, of course.]

My result:
The link field is always empty. Hence, the organizer's name is never linked to the respective website.

Questions I stumbled upon:
When I add a relationship, I have two options like

Entity Reference: Referenced Entity
A bridge to the Content entity that is referenced via field_organizer
 Entity Reference: Referencing entity
A bridge to the Content entity that is referencing Content via organizer

My understanding is that I have to user the first one, because I want to load the organizer that is referenced in the event. [The second one I would be using, if I have a organizer and want to get all events that are referencing this organizer, right?] However, I tried both options to no avail.

Is the ordering of fields relevant? I've tried both having the link field before and after the entity reference field, it stays empty in both cases.

Since each event could have more than only one organizer, the entity reference field is set to allow unlimited values. Could that cause a problem?

Could anyone point me into the right direction of what I am missing?

UPDATE: It seems to break the system if you have both relationship types set up at the same time or maybe the ordering plays a role, too. However, when the first relationship in list is the one I need it kind of works.

It is working absolutely fine for a single organizer, the name is displayed and linked to the organizer's website. But it will not work for any additional organizers. The block lists all organizers (when having more than one) but each of them is linked to the first organizer's website.

Thinking about how that works, that is reasonable, since the relationship only adds one related object. When displaying a field (e.g.) from that relationship it will be the same for each delta of entity reference field.

Actually, in that case I should be able to define how the entity reference field is displayed. It already has an option to link to the entity itself but you can't define any fields from the entity to be shown (e.g. instead of title).

The solution is a two step solution, but first you need to decided if you are going from Parent to Child or Child to Parent.

Background info

If you are going from Parent to Child, you setup a relationship using the "referenced" variable.

If you are going from Child to Parent, you setup a relationship using the "referencing" variable.

To make life simple for myself, when I specify the relationship, I also using the Administrative Option on the Reference Window and enter a more understandable name for the relationship.  In you case, since I would make the Admin Name Event reading Organizer or something like that.

Setup a relationship for Event reading Organizer in the Relationship
field under the Advanced tab.
Once you have related your Event content type to the Organizer
content type, you should now be able to see the Organizer fields
appear in your list of available fields.  Select the fields from the
Organizer content type that you want to appear in your view and hit
Apply. Here is the CRITICAL part, once you have defined a
Relationship, a new drop down menu (Relationship) will appear on the
Configure field windows.  For any fields that is in another table,
you MUST choose the appropriate relationship for the field. In your
case, you would choose the Event reading Organizer relationship.
This relationship instructs view to go Organizer table and bring
back that field.  If you do not specify the relationship in the
Configure field windows, this will not work.

Attached is a copy of the Configure field with a relationship.  Note: In your example, you would want the referenced variable. But in my example, I was working with the referencing variable. Please do not let that confuse you.  Just image the word in the relationship is referenced.

If you have any questions, please post them here and I will respond.


How to create a list of FULL Nodes without titles (Views) I would like to create a list of FULL nodes with comments but no titles (with the module Views) is that possible?

Currently I have already a list which shows the FULL node with comments. But also the title which is even an URL.

Can someone explain me how I can do this with Views? If it isn't possible, is it then possible to have the title listed as plain text instead of an URL (duplicated content etc.)?

Using Drupal 6.x

Thanks in advance!

Ps: Just thinking, or should this be done with theming?

To create a view of just comments,  Remove the Node:Title field (and all other fields), and add Comment: Body

To have the node title not a link, uncheck 'Link this field to its node'


How to create search indexes by path in Drupal 8? For a relatively small Drupal 8 website, I need to enable a search box, with multiple indexes based on the path or menu value.

For example; the main menu has 2 menu items linking to basic pages: Employers and Employees, and rest of the website pages are created under these two pages, and each page has a menu item with matching hierarchy.

Employers

Section A

Sub-section A-1
Sub-section A-2
Sub-section A-3

Section B

Sub-section B-1

Section C

Sub-section C-1
Sub-section C-2

Employees

Section D

Sub-section D-1
Sub-section D-2

Section E

Sub-section E-1
Sub-section E-2
Sub-section E-3
Sub-section E-4

Section F

Sub-section F-1
Sub-section F-2
Sub-section F-3

I need to be able to search only in Employers or Employees. And the search results must be limited to those indivual landing pages.

Thoughts?

I was able to resolve the issue by using the Views, not through the search indexes as I initially thought was the path for a solution.

Created a required field for the content-types that would be searched against. Let's call it Section for now, with the values of Employers and Employees. This will be used in the view to filter content by section. (Taxonomy terms can be used for this as well.)

Then created a view page for each section.

In the view, used Content for the row style with Search result highlighting input option, and sorted content by Search: Score (asc).

The real trick for this to work is enabling Search result highlighting input display mode and configuring it with the fields we want to be searched within.

Hope this helps who needs a similar solution in their projects.


How to change a field value to 500 products (commerce module) at the same time? I have about 500 product in my site powered by the commerce module. I need stock capabilities so installed the commerce_stock module. So far so good.

This module add a stock field and a checkbox to check Disable stock for this product in the product itself.

Thing is that stock field is set to 0,00 by default, then all the product are shown as Out of stock.

The solution is as simple as to mark the checkbox to check Disable stock for this product for all products. But I have 500 products, then this will be a waste of time...

Is there any way to do this programmatically? Any other idea to get this done?

I thing of doing this directly in the database with a sql query, but not sure if this is a good idea?

Well I can come out of two ways of doing this. One of them is Using the commerce API which is really good you just have to get all your 500 products with the following method:

 $query=new EntityFieldQuery;

    $query= $query->entityCondition('entity_type','commerce_product')->execute();

    foreach($query as $entity){
       $entity->commerce_stock[LANGUAGE_NONE][0]['value'] = 1;
       commerce_product_save($new_product);
    }

Or you can also do it on the database updating the value of the table field_data_commerce_stock:

update field_data_commerce_stock set commerce_stock_value=ANY_NUMBER;


What happens when you delete a field from an existing Content Type? When you delete a field from an existing Content Type, does the mysql field also get deleted or is it still there except it's simply not used? This is whether or not the content type already has data.

When you delete any of the field of the content type then all the log of that field from the database is deleted.

eg. Suppose we create a field named test in the content type A then it creates 2 tables in the database ie field_data_test and field_revision_test.

So when you delete the field test then both the tables are also deleted from the database.


Why doesn't my code for passing a PHP variable to JavaScript work? I am using the following code, but the JavaScript console prints undefined instead of the value of settings.api_key. What is wrong in the code I am using?

libraries.yml file

stripe_files:
  version: 1.x
  js:
    https://js.stripe.com/v2/: { type: external, minified: false }
    js/custom_stripe.js: {}
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once
  css:
    theme:
      css/custom_stripe_integration.module.css: {}

JavaScript file

(function ($) {
    Drupal.behaviors.stripe = {
      attach: function (context, settings) {
        alert('hello4');
         console.log(settings.api_key);
      }
    };
})(jQuery);

Form class

/**
 * @file
 * Contains \Drupal\amazing_forms\Form\ContributeForm.
 */

namespace Drupal\custom_stripe_integration\Form;
use Drupal\Core;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\user\SharedTempStore;
use Drupal\Component\Utility\Html;
use Drupal\Component\Utility\Unicode;
use Drupal\Core\Locale;

require_once 'modules/custom/donate_gateway/vendor/autoload.php';

/**
 * Contribute form.
 */
class StripeSponsorForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'stripe_sponsor_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state,$nid = 0) {
    $config = $this->config('custom_stripe_integration.settings');
    $api_key = $config->get('stripe_api_key');

    $form['#attached']['library'][] = 'custom_stripe_integration/stripe_files';
    $form['#attached']['drupalSettings']['api_key'] = $api_key;

    return $form;
  }
}

For anyone coming here looking for a simple example of stashing data in drupalSettings and pulling it back out on the js side. Here's an example in a form.

In  buildForm or form_hook_alter etc:

$form['#attached']['drupalSettings']['foo'] = 'bar';

Then in the js file of your choice (in your theme) be sure to wrap your code in a function and provide the things you want. In this example, I'm providing jQuery and drupalSettings.

(function($, drupalSettings) {

  console.log(drupalSettings);

})(jQuery, drupalSettings);

You should see in your console that the drupalSettings object has the key 'foo' on it alongside some other internal ones. That's why Kevin suggests putting your data a level deeper with ['drupalSettings']['my_module']['foo'], but it's not necessary. Additionally, you don't need to specify core/drupalSettings as a dependency in your libraries.yml or do anything else to make drupalSettings available. You get it for free.

As for actually answering the question . . . I'm not sure what @kiamlaluno is talking about when he says to replace drupalSettings with settings. I can, however, show you (@harshal) what your function should look like based on my example:

(function ($, drupalSettings) {
    Drupal.behaviors.stripe = {
      attach: function (context) {
        alert('hello4');
        console.log(drupalSettings.api_key);
      }
    };
})(jQuery, drupalSettings);

If you're still having trouble, try just adding a couple of lines to be sure things are sane:

(function ($, drupalSettings) {

    // What's going on?
    console.log('function is loading!');
    console.log(drupalSettings);

    Drupal.behaviors.stripe = {
      attach: function (context) {
        alert('hello4');
        console.log(drupalSettings.api_key);
      }
    };
})(jQuery, drupalSettings);


How do I see the names of all view fields in the formatter option form? I am extending the StylePluginBase to make a custom views formatter. I would like to add a select box in the option menu with a list of all the fields currently listed within the view. How do I pull the list of fields into the buildOptionsForm function? Does the FormStateInterface have the view buried in it somewhere that I need to do something like:

$options = [];
$view = $form_state->view;
foreach($view->fields as $field){
  $options[] = $field->name;
}

A little late, but maybe still helpful for someone.
You can use $fields = $this->displayHandler->getFieldLabels(TRUE); to get an array of all currently chosen fields in the view.


Export only non-default config drush config-export dumps my entire site config into files.

What I want is to only export config which is non-default.

ie. if I haven't changed my "automated cron settings" since installing my Drupal site, leave it out of my config.

Is this possible with drush? Some other tool?

Such a concept doesn't really exist in the config system. There is no overridden status like in cools/entity exports in 7.x.

Default config is only default config as long as it is a file in config/install. Once it is installed, it just is your configuration, there isn't really a connection anymore to the original default config file.

There is a hash in those files, so you could technically write something that looks for the default config file and compares the hash or even compare every single value. But keep in mind that default config can actually change, deciding whether you'd want your unchanged existing value or the new default is something that is surprisingly hard to do.

Not sure what you would want this for, the only thing that I can think of would be config for an install profile.


Is it possible to provide content editor ability to create sortable table? I know how to create a sortable table using

theme('table', $headers, $rows)

but is it possible to create a functionality so that a content creator can create a sortable table inside a content.
For example creating a sortable table inside a node.

You can use TableField module to create table that is a real html table. Sorting is currently unsupported, sadly, although it would be wonderful.

If all you need is sorting on display, you can create a patch or your own module, and implement one of the jQuery plugins for sorting. Personally I found tablesorter to work pretty OK.


Creating a custom aggregation for views I have implemented the data described here and now want to create a view that will work out the handicap for a particular player. I have so far created my view which list players and using a relationship to results for the player, and then aggregating these fields, can display things like the players best score and their average score.

Next I want to display the players "Handicap", which is a complex aggregation. Namely, it's the average of the best 8 of the last 20 results multiplied by 0.93. Can you write custom aggregation functions? Or should I create a new field on the result? I'm not sure of the easiest way to go about this.

Thanks!

EDIT: Thanks to @Jimajamma I was pointed in the right direction. You can do what he suggested purely from a module. I used the Fields UI to create a field that I can then manipulate to keep it simple. In the module I've used hook_theme to register a tpl.php file. I struggled to get my preprocess function to be recognised because of the base_hook directive which seems to then cause views/core to ignore the preprocess functions directive. The following is the simplest module you can create:

function golf_ladder_views_api() {
  return array('api' => 3.0);
}

function golf_ladder_theme($existing) {
  return array(
    'views_view_field__field_handicap' => array (
      'arguments' => array('view' => NULL, 'field' => NULL, 'row' => NULL),
      'template' => 'views-view-field--field-handicap',
      /* 'base hook' => 'views_view_field',
       * Don't do this if you want to use a preprocess that you control.
       * If you define base hook views seems to want to ignore the
       * 'preprocess functions' directive below
       */
      'path' => drupal_get_path('module', 'golf_ladder'),
      'preprocess functions' => array(
        'template_preprocess',
        'template_preprocess_views_view_field',
        'golf_ladder_preprocess_views_view_field__field_handicap',
      ),
    ),
  );
}

function golf_ladder_preprocess_views_view_field__field_handicap(&$variables) {
  $variables['output'] = '4'; // TODO: calculate proper handicap
}

After that create a template file views-view-filed--field-handicap.tpl.php which is simply:

print $output;

Whether this is the best, I don't know, but it is pretty easy:

Create a new field called handicap.  It doesn't need to have any value as you will be computing it.
Create a views template for that field.  It would be something like views-view-field--field-handicap-value.tpl.php. If you want it specific to the view, you will need to include its name in there as well, but just look in the Views Styles/Themes to find it.
In that template, do your custom aggregation function, and then output that result instead of the default $output.

Now, if all is good in the world, you will have your handicap output in the view and you can aggregate on that value as well later on in the view, too.


Anchor Tag Smooth Transition Right now my menu item will scroll to my anchor tag < front >#tag1, without a problem. However I do not like how "jumpy" it is. I would like a smoother scroll affect?

I found this module: https://www.drupal.org/project/scroll_to_destination_anchors .

I have jquery and javascript enabled, but I can't seem to get a smoother affect. Any Help? I am using Drupal 7 core.

Take a look at https://www.drupal.org/node/2492033 and check if your links to anchors are with or without a path. You could maybe use Void Menu to make special links without path.

As an alternative to this module I recommend to take a look at: Jquery Localscroll


How to configure D7 so files get uploaded to a different server In Drupal 7, the default path for uploading is set in the File system options in the Public file system path.  Is it possible to specify a different server in this path?  I have a Drupal 7 web site we are developing that is going to have about 20k files and I'd like to put them on a different server than the web server.  If not possible to specify a different server than are there any user contributed modules that can handle this?

I do something very similar.  If you're running infrastructure that is capable of this configuration, I recommend serving up a share on your file server (Linux or Windows Server) and just mount it in Drupal's public file path, wherever the public directory is for that particular field.

For example, take the following Samba configuration (found in /etc/samba/smb.conf if you run a Linux-based file server).  This comes at the very end of the file after all other configuration options:

[data]
    comment = Data directory
    browseable = yes
    writable = yes
    valid users = "@DOMAIN\Domain Admins"
    path = /data
    create mask = 0664
    force create mode = 0664

The valid users syntax there says "allows this group of users" to access this share.  In this case we're using PAM to hook up our file server to Active Directory, and this particular group is made available once you hook the two up.

On your web server, whatever is hosting your Drupal site, navigate to the public files directory.  Say the particular field you need to make the files available for is public://field_with_20k_files/.  You'd run a similar mount command like so:

sudo mount -t cifs -o user=domainadministrator,uid=domainadministrator,gid=apache //fileserver/data /path/to/field_with_20k_files

I have the gid set to whatever process is running the web server so it has access to that directory.  Most likely you'll want to ensure that the web service has read and write access to the web server is actually capable of uploading files.


Date question re date_popup In the Date module I'm trying to customize #date_popup; is it possible to completely eliminate the Timepicker field; it currently displays Date + Time fields. I only want the Date field and can't figure out how to remove it in Drupal and/or the Dashboard.

Anyone tried this?

Thanks!!!

On the "Date attributes to collect", uncheck "hour", "minute" and "second". These options are available on the "DATE FIELD SETTINGS" group of the field configuration screen.


Custom links in Views For a Taxonomy Vocabulary on my Drupal 7 site, I have added several custom fields for each Taxonomy Term, and want to have two different ways of viewing the Term information: a summary and a detailed view.

I've created the two Views for summary and detailed (myterm-summary/% and myterm-detail/%). But now the question is how to create a link between them. I'd like a link on myterm-summary/% to link to myterm-detail/% as a "Read More..." link. Is there some View element I can add to the View to create a custom link, using the dynamic URL variable  in the process?

I know I can create a Rich Text block header or footer for the View, but can I refer to the URL variable in that text block somehow?

I've found a solution that you can use the Replacement Tokens to this effect. In order for the field you want to show up as a possible Replacement Token, it must be in the Fields list. So I did:

Set Format to "Unformatted List"
Set Show to "Fields"
Add the "Term ID" field to Fields list.
During creation (or edit it afterward), check the "Exclude from display" box.
Create a new Footer element that's a "Global: Text Area" type.
Check the "Use replacement tokens" box
Insert More Info... in the box.


Removing "Home" from the title How do I remove Home from the page title?

I added in page.twig.html this part of code.

{% if not is_front %}

      {{ page.content }}

      {% endif %}

The title appears as follows.

I just want it to be Nekretnina.ba, without Home |.

Override html.twig.php in your template, not page.twig.html. May I also suggest metatag for better control over page titles?


Alternate title replacing Product Title This is a combobox showing a group of product referenced.

I have created an extra field in product list, short_title. How do I replace the Product Title with short_title? i.e. Chicken, Turkey, Pork, … Is this possible?

I’ve also tried Inline Form Entity. The YouTube tutorial: http://youtu.be/glRM_NzNVTA?t=5m3s : When the host edited the Variation Title, the Product Title remained unchanged. However, when I do it, the Product Title changed. Is this by design or the host was using an older version of Inline Entity Form?

I know that we can create attributes, but having a variety of product types complicates the form. All I wanted: one product type and just reference a group of product in product display.

The Product Title is too long in combo, but I can't shortened that because it's important as line-item title.

Any idea or workaround?

Instead of 'simple' selection, use a view for your entity reference. Here you can decide yourself how the title is shown.


connect to mysql with unix socket instead of tcp I'm not looking for the "use 127.0.0.1" solution.
I want to run the site on my local development environment and use the unix socket to connect to the database. In my settings file I've set the host to 'host' => 'localhost', and I've tried 'unix_socket' => '/tmp/mysql.socket', as well, but both result in a PDOException: SQLSTATE[HY000] [2002] error in the apache logs.

When I connect directly to mysql through the command line I connect through the unix socket, but when I run it through Drupal it only connects through the TCP connection. I am under the impression Drupal will connect through the socket if the localhost host name is used, but this doesn't appear to be the case here.

Perhaps there's some other local configuration I'm missing.

I quickly figured this out after posting. To connect using a socket use 'unix_socket' => '/tmp/mysql.sock', not .socket.

This allows me to connect to mysql using the unix socket instead of the networking IP address, 127.0.0.1. This may be an issue with core since I think by default Drupal should connect on this default socket.


Entity Reference to fields I'm using the Entity Reference module to relate different unique, particular pieces of equipment (identified by unique serial numbers) to different orders.  Equipment and orders are content types.  On the Order content type, I have an entity reference field with an inline entity form widget (autocomplete) for the user to scan in the serial number and form the relationship.

The problem is, the serial numbers could be in Hexidecimal or Decimal format, and the users should be able to use both interchangeably.  Thus, if a user is creating an order and scans in the decimal serial number, the system should be smart enough to associate that with the correct piece of equipment, even if that serial number was entered in hex.

Entity Reference seems to have a limitation here, in that all of the widgets I've found seem to only reference the "title" attribute of an entity.  Is there a way to make this attribute support multiple values, or to have Entity Reference reference nodes using multiple uniquely-valued fields (or maybe a single field with multiple globally-unique values)?

Ok, I've thought of a solution that somewhat inelegant, but it works

On the Equipment content type, a hex/dec signifier field is added--some sort of a select box (maybe a taxonomy selection box) where the user will select if the serial number in hex or dec.

When the form is submitted, a custom rule will check for the presence of the select box, convert the value in the "title" to the other numbering format, and then append that value to the original value in the title field, so that the title field will contain both formats of the number. After everything is said and done, the Equipment titles will all look like "1234567, 12D687".

Now, when the user creates an order and searches for existing serial numbers using the Inline Entity Form, as long as you have it set to "autocomplete", it will find the correct piece of equipment and associate it with the order.

Still, it would be nice if Entity Reference auto-complete would work with fields from those entities and not just their titles.  And, I'm still in needs of some sort of module that will add a hex converter to Rules.

Let me know if anyone finds better solutions!


How to resolve 'Unknown data property commerce_product' when adding a product in Drupal Commerce? I'm wondering if someone can help: I'm trying to add Drupal Commerce into an existing Drupal site, so I've followed the steps in this video about this topic and managed to install all modules without problems.

The issue I'm having is when I view a product I've added. Please note that I've added the product type. I can also add the node, but every time I try to view it I get this error (in the reports/error):

  EntityMetadataWrapperException: Unknown data property
  commerce_product. in EntityStructureWrapper->getPropertyInfo() (line
  336 of
  /my/local/server/php/mysite/sites/all/modules/entity/includes/entity.wrapper.inc).

I did follow all the steps in the tutorial. When I tried to view the product like in the video I get the error.

Any ideas?

Looks like an answer to "this" question might be similar to what I suggested in How to add Drupal Commerce to an existing Drupal site?, which originally was rather a request for manuals/docu about this topic. It has a comment (from the OPer) like this (bold markup added here now):

  ... After your post I've uninstalled all modules and installed again and still had the errors, however this time when I run Commerce Repair the fields were fixed and everything worked.

With that it appears to me that "this" question "has an answer" now also.

Ps: The "Commerce Repair" module is "looking for a new maintainer", and used in over 1.000 sites. To me it appears as the best possible alternative to consider, which is not the same as "the module is no longer maintained" I believe (as I read in a comment to the question here).


Hook form alter to check date field is empty or not First of all I'm new to custom modules, I'm using hook_form_alter to do some custom validation, in the middle I have to check if a date field is empty or not, if empty I will display an error message.

Problem:
I don't know how to get the value from date field after a form is submitted and check it with empty() function.

I have tried:

$form_state['input']['field_start_date']['und'][0]['value']
$form['field_start_date']['und'][0]['#default_value']['value']
$form_state['values']['field_start_date'] # no use of these.

What am I doing wrong?

The last one should be correct if the form has a field called field_start_date.

You fetch values from the form_state like this:

$form_state['values']['FIELD_NAME'];

To see which values are available in the form_state you can use the devel module to print the values from the form state using dpm($form_state['values']).

UPDATE: You can't really use drupal_set_message() to print arrays, you must use dpm, kint, print_r or other functions that allows you to debug an array.

You can use e.g dpm($form_state['values']['field_start_date']) to see where the values live.


Rendered Webform has no Javascript attached I've created a simple filter that allows webforms to be rendered anywhere in a node with a tag like this: [webform:machine_name]

The code to render the form is as follows:

$webform = \Drupal::entityTypeManager()->getStorage('webform')->load($machineName);
$viewBuilder = \Drupal::service('entity_type.manager')->getViewBuilder('webform');
$formBuild = $viewBuilder->view($webform);
return render($formBuild);

It works insofar as the form is displayed, client-side validation is working.

BUT none of the webform-specific JS is attached (e.g. input masks don't work). I assume this is because Drupal doesn't know it needs to attach the libraries.

How do I attach those libraries? Preferably in a method that can be invoked from the code that renders the filter, as if it's in a separate place things would start to get more complicated.

EDIT:

Following 4k4's feedback, here's the code that I'm now using. It works as above, without the libraries being attached:

foreach ($renderArrays as $tag => $renderArray) {
  $renderContext = new RenderContext();
  $renderedOutput = $this->renderer->executeInRenderContext($renderContext, function () use (&$renderArray) {
    return $this->renderer->render($renderArray);
  });
  $metaData = BubbleableMetadata::createFromRenderArray($renderArray);
  if (!$renderContext->isEmpty()) {
    $metaData = $metaData->merge($renderContext->pop());
  }
  $result = $result->merge($metaData);
  $text = str_replace($tag, $renderedOutput, $text);
}
$result->setProcessedText($text);

For completeness, $renderArrays contains:

['[webform:machine_name]' => [
  '#type' => 'webform',
  '#webform' => 'machine_name',
]]

Now you return bare HTML without any attached meta data for caching, libraries and so on.

Also Webforms provides a render element, so this is all you need to build a webform:

$build = [
  '#type' => 'webform',
  '#webform' => $machineName,
];

The important part though is that the filter you put the token in handles the attached metadata correctly. It needs to do it similar to Entity Embed:

    $result = new FilterProcessResult($text);
    ...
    // We need to render the embedded entity:
    // - without replacing placeholders, so that the placeholders are
    //   only replaced at the last possible moment. Hence we cannot use
    //   either renderPlain() or renderRoot(), so we must use render().
    // - without bubbling beyond this filter, because filters must
    //   ensure that the bubbleable metadata for the changes they make
    //   when filtering text makes it onto the FilterProcessResult
    //   object that they return ($result). To prevent that bubbling, we
    //   must wrap the call to render() in a render context.
    $entity_output = $this->renderer->executeInRenderContext(new RenderContext(), function () use (&$build) {
      return $this->renderer->render($build);
    });
    $result = $result->merge(BubbleableMetadata::createFromRenderArray($build));

https://cgit.drupalcode.org/entity_embed/tree/src/Plugin/Filter/EntityEmbedFilter.php

Edit: Improved bubbling of metadata:

    $render_context = new RenderContext();
    $entity_output = $this->renderer->executeInRenderContext($render_context, function () use (&$build) {
      return $this->renderer->render($build);
    });
    $meta_data = BubbleableMetadata::createFromRenderArray($build);
    if (!$render_context->isEmpty()) {
      $meta_data = $meta_data->merge($render_context->pop());
    }
    $result = $result->merge($meta_data);

If you are looking for an easier solution you could for example add the webform to $variables in preprocess to render it in a node template. Then the attached libraries bubble up in the right place automatically.


Why would custom fields not update? I am having trouble updating custom fields programmatically. The code appears below and is in the body of my custom module. When I run this changing the title, it changes OK. But, when I try to do this with the custom field, the field doesn't get updated and I don't understand why. Should I be wrapping this into some hook? Is there a cache not being cleared somewhere? Basically, what am I missing when it comes to programmatically updating fields.

$nodes_to_load = $query->execute();
if (isset($nodes_to_load['node'])) {
  $nodes = entity_load('node', array_keys($nodes_to_load['node']));

  foreach ($nodes as $node) {
  $node->field_myother_field[$node->language][]['value'] = '500';
  $node->title = "retest the test";
  node_save($node);
 }
}
 else {
  print "no nodes to load";
}

UPDATE: When I try to change the field by going into the admin panel, and simply typing in a new value I get a "The content on this page has either been modified by another user, or you have already submitted modifications using this form. As a result, your changes cannot be saved" error.

I suspect you don't have $node->language set, or perhaps the empty [] is causing trouble.

Try:

$result = $query->execute();
if (isset($result['node'])) {
  $nodes = entity_load('node', array_keys($result['node']));
  foreach ($nodes as $node) {
    // Set node language to default, if not set
    $node->language = isset($node->language) ? $node->language : LANGUAGE_NONE;
    $node->field_myother_field[$node->language][0]['value'] = '500';
    $node->title = 'retest the test';
    node_save($node);
  }
}else {
  drupal_set_mesage('no nodes to load');
}

Using entity_metadata_wrapper

$result = $query->execute();
if (isset($result['node'])) {
  $nodes = entity_load('node', array_keys($result['node']));
  foreach ($nodes as $node) {
    $node_wrapper = entity_metadata_wrapper('node', $node); // Get node wrapper
    $node_wrapper->field_my_other_field->set('500'); // Set field value
    $node_wrapper->save(); // Save entity
  }
}else {
  drupal_set_mesage('no nodes to load');
}


How can I retrieve the value of a field in a flagging? I have a global flag, spam, that has a textfield, reason, attached to it.

According to the Flag API documentation, I know I can check whether a user is flagged like this:

$spam && $spam->is_flagged($account->uid)

However, in this case, I want to retrieve the flagging, and then check the value of a field in that flagging.  I didn't see any directions for doing so in the documentation, so I'm at a loss about how best to proceed.

According to the Flag API

flagging_load

  Loads a flagging entity. Parameters

  $flagging_id: The 'flagging_id' database serial column.

  $reset: Whether to reset the DrupalDefaultEntityController cache.
  Return value

  The entity object, or FALSE if it can't be found

Therefore something like this might work:

$flaggings = flag_get_user_flags('node', $node->nid);
if (isset($flaggings['spam'])) {
    $flagging = flagging_load($flaggings['spam']->flagging_id);
}

You will then find your field in:

$flagging->field_reason


Resolving data in hook_views_data I have a custom table defined in hook_views_data().  One of my fields is an integer, which maps to some defined constants.  When they are queried and displayed by views, I'd like to change them to their string name that's represented by the integer.

So, my question is how can I manipulate values returned by views?

You can theme (you dont want to change the value stored in the DB, just change its displayed value) the view row value by using a template suggestion:

I prefer using a preprocessor function to do this on the field. This blog post covers how to do this for a specific view_name and field.

From the blogpost:

  There is an issue to let Drupal 7 and 8 themes implement a
  preprocess/process function per view as it is possible in Drupal 6,
  but it is in development (see issue).

  Until it is fixed there is a way to achieve that behaviour:

<?php
/**
  * Generic preprocess that is still working on D7
  */
function MYTHEME_preprocess_views_view_fields(&$vars) {
  if (isset($vars['view']->name)) {
    $function = __FUNCTION__ . '__' . $vars['view']->name . '__' . $vars['view']->current_display;

    if (function_exists($function)) {
     $function($vars);
    }
  }
}

/**
  * Then the specific preprocess that worked without the above code for D6
  */
function MYTHEME_preprocess_views_view_fields__VIEWNAME__DISPLAY(&$vars) {
  // my specific preprocess code
}
?>

There's also like views_custom_styles (sandbox project) and views_php which will let you do the same thing -- but for what you're asking (to my knowledge) you're gonna have to write code.

The preprocessor example I give is a clean solution re-using the Theme API (suggestions) and hooks.


Adding Module Config Form Leads to WSOD I am trying to create a configuration form for my test Drupal 8 module. I have followed the instructions from the following tutorials:

https://www.drupal.org/docs/8/api/configuration-api/working-with-configuration-forms
https://www.drupal.org/docs/8/api/form-api/configformbase-with-simple-configuration-api

Before I followed the instructions in these guides my module worked fine. However, after adding the form, I now get a WSOD when installing the module, with no error in the logs. I know that error reporting is on because I can make intentional mistakes in my module files and an error will be reported in the logs.

My question is: where have I gone wrong? It's hard to figure out a problem when you don't even have a stack trace to follow.

My company_info.routing.yml file:

company_info.content:
  path: '/company_info'
  defaults:
    _controller: '\Drupal\company_info\Controller\AdminController::content'
    _title: 'Hello World'
  requirements:
    _permission: 'access content'

company_info.admin_settings:
  path: '/admin/config/company_info'
  defaults:
    _form: '\Drupal\company_info\Form\AdminSettingsForm'
    _title: 'example'
  requirements:
    _permission: 'administer site configuration'

AdminSettingsForm.php:

<?php

namespace Drupal\company_info\Controller;

use Drupal\Core\Form\ConfigFormBase;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Form\FormStateInterface;

class AdminSettingsForm extends ConfigFormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'company_info_admin_settings';
  }

  /**
   * {@inheritdoc}
   */
  public function getEditableConfigNames() {
    return [
      'company_info.settings',
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state,
Request $request = NULL) {
    $config = $this->config('company_info.settings');

    $form['your_message'] = array(
      '#type' => 'textfield',
      '#title' => $this->t('Your Message!'),
      '#default_value' => $config->get('your_message'),
    );

    return parent::buildForm($form, $form_state);
  }

  /**
   *
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->config('company_info.settings')
      ->set('your_message', $form_state->getValues('your_message'))
      ->save();

  }
}

company_info.settings.yml

your_message: 'Default message here'

The namespace on your AdminSettingsForm class is incorrect.
It should be Drupal\company_info\Form;


Is there a way to have a customized content add page form depending on who has logged in? I have a website that operates through administrators. Obviously I have the ability to create content pages through drupal's dashboard, but is there a drupal included way (or module perhaps) that will allow me to limit what another logged in person could see? I know I can change permissions to what is accessible by different groups (i.e. users, partial admins, administrators, etc.). I want to be able to actually change what someone who isn't an admin will see. They shouldn't be able to see the drupal dashboard, for example, or certain sections of the "add/blocks" forms/create new content form.

If there is no option that comes defaul with drupal, firstly that is a huge undersight on drupals part, but is there another way to create this effect? One way I thought was to find drupal's core files that add the page (i.e. "node/add") and hardcode php permissions that check who the logged in user is. If they are admins, allow full priveleges, but if they are another group, then disable certain features of the page.

If this is the case, where can I find the files I'll need to edit? I'm having trouble doing so. It would be the actual form creation page that I'm looking for.

Thank you for any ideas and your time.

see this path on your drupal installation :

admin/people/permissions where admin had power to set accessbility of menus,content etc


How to add new item in menu_local? I'm using Drupal commons and I want to add new item next to View link, so I used hook_menu to create this.

function manage_child_menu() {
  $items['node/%node/demo'] = array (
    'title' => 'Demo',
    'page callback' => 'node_page_view',
    'page arguments' => array(1),
    'access callback' => 'manage_child_auction_access',
    'access arguments' => array(1),
    'type' => MENU_LOCAL_TASK,
  );
  return $items;
}

Well, it didn't work at all. Please help

In my case using hook_menu will never work. Then i have to use hook_menu_local_tasks_alter to make it work.
Here is how.

function manage_child_menu_local_tasks_alter(&$data, $router_item, $root_path) {
   if ((arg(0) == 'node' || arg(0) == 'groups') && arg(2) == '') {
   $nid = arg(1);
   $node = node_load($nid);
   if ($node->type == 'project_auction') {
     $link = menu_get_item("node/$nid/demo");
     $link['title'] = 'Auction List';
     $link['weight'] = 10;

     $data['tabs'][0]['output'][] = array(
       '#theme' => 'menu_local_task',
       '#link' => $link,
     );

     $data['tabs'][0]['count'] = $data['tabs']['0']['count'] + 1;
  }
 }
}


module's local *.tpl.php, defined in $theme_registry, "not found or invalid" when referenced later in module I built a custom login module for my Drupal7.26 install.

Extending it, I've added a *.tpl.php locally

ls sites/all/modules/custom/jl_login/templates/
    user-login-member-form.tpl.php

To get the tpl.php into theme registry, in "my_login_mod.module" I added

function jl_login_theme() {
    return array(
        'user_login_member_form' => array(
            'render element' => 'form',
            'template' => 'templates/user-login-member-form',
        )
    );
}

After module  disable/uninstall/enable, and clear all caches, I load my site/page.

Checking output with

<?php print '<pre>'; var_dump(theme_get_registry()); print '</pre>'; ?>

I see the form in the registry

 ["user_login_member_form"]=>
  array(6) {
    ["render element"]=>
    string(4) "form"
    ["template"]=>
    string(76) "sites/all/modules/custom/jl_login/templates/user-login-member-form"
    ["type"]=>
    string(6) "module"
    ["theme path"]=>
    string(43) "sites/all/modules/custom/jl_login"
    ["preprocess functions"]=>
    array(1) {
      [0]=>
      string(19) "template_preprocess"
    }
    ["process functions"]=>
    array(2) {
      [0]=>
      string(16) "template_process"
      [1]=>
      string(14) "ctools_process"
    }
  }

Later in my .module, I use the form:

function _jl_login_login_block_view($delta='') {
    $this_user_login_form    = drupal_get_form('user_login_member_form');
    ...

But on load I see in drupal logs,

Feb 24 16:32:16 dev d7: http://dev.loc|1393288336|php|127.0.0.1|http://dev.loc/||0||Notice: Undefined index: user_login_member_form in drupal_retrieve_form() (line 771 of /home/jl/d7/includes/form.inc).
Feb 24 16:32:16 dev d7: http://dev.loc|1393288336|php|127.0.0.1|http://dev.loc/||0||Warning: call_user_func_array() expects parameter 1 to be a valid callback, function 'user_login_member_form' not found or invalid function name in drupal_retrieve_form() (line 806 of /home/jl/d7/includes/form.inc).

What do I need to change to be able to use/reference the local form?

drupal_get_form() expects the name of a function that builds a form array, e.g.

function MYMODULE_some_form($form, &$form_state) {
  $form['#theme'] = 'user_login_member_form';

  $form['foo'] = array(
    '#type' => 'textfield',
    '#title' => t('Bar'),
    '#default_value' => t('Baz'),
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Submit'),
  );

  return $form;
}

function MYMODULE_some_form_submit($form, &$form_state) {
  // Process $form_state['values']
}

// In a hook...
$form = drupal_get_form('MYMODULE_some_form');

You don't need to add the form function to a registry as such, just giving it the same name as the string you pass to drupal_get_form() is enough.

hook_theme() is for registering theme functions, which is why you're currently getting an error.

The Form generation docs have a bit more information, and the FAPI reference is invaluable if you're new to the form API. For theming the form, there are some excellent answers to this question which should help.


Display menu Shopping cart (# items) and total amount In the user menu, I added a menu link to the shopping cart:

Title: "Shopping cart (# items)"

Path: "cart/my"

How to add the total amount of the order, at the end of the title ?

I think it is necessary to use the file "template.php" of my theme.

/**
 * Implements hook_menu().
 */
function commerce_cart_menu() {
  $items = array();

  $items['cart'] = array(
    'title' => 'Shopping cart',
    'page callback' => 'commerce_cart_view',
    'access arguments' => array('access content'),
    'file' => 'includes/commerce_cart.pages.inc',
  );

  $items['cart/my'] = array(
    'title' => 'Shopping cart (# items)',
    'title callback' => 'commerce_cart_menu_item_title',
    'title arguments' => array(TRUE),
    'page callback' => 'commerce_cart_menu_item_redirect',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );

  $items['checkout'] = array(
    'title' => 'Checkout',
    'page callback' => 'commerce_cart_checkout_router',
    'access arguments' => array('access checkout'),
    'type' => MENU_CALLBACK,
    'file' => 'includes/commerce_cart.pages.inc',
  );

  // If the Order UI module is installed, add a local action to it that lets an
  // administrator execute a cart order refresh on the order. Modules that
  // define their own order edit menu item are also responsible for defining
  // their own local action menu items if needed.
  if (module_exists('commerce_order_ui')) {
    $items['admin/commerce/orders/%commerce_order/edit/refresh'] = array(
      'title' => 'Apply pricing rules',
      'description' => 'Executes the cart order refresh used to apply all current pricing rules on the front end.',
      'page callback' => 'drupal_get_form',
      'page arguments' => array('commerce_cart_order_refresh_form', 3),
      'access callback' => 'commerce_cart_order_refresh_form_access',
      'access arguments' => array(3),
      'type' => MENU_LOCAL_ACTION,
      'file' => 'includes/commerce_cart.admin.inc',
    );
  }

  return $items;
}

/**
 * Returns the title of the shopping cart menu item with an item count.
 */
function commerce_cart_menu_item_title() {
  global $user;

  // Default to a static title.
  $title = t('Shopping cart');

  // If the user actually has a cart order...
  if ($order = commerce_cart_order_load($user->uid)) {
    // Count the number of product line items on the order.
    $wrapper = entity_metadata_wrapper('commerce_order', $order);
    $quantity = commerce_line_items_quantity($wrapper->commerce_line_items, commerce_product_line_item_types());

    // If there are more than 0 product line items on the order...
    if ($quantity > 0) {
      // Use the dynamic menu item title.
      $title = format_plural($quantity, 'Shopping cart (1 item)', 'Shopping cart (@count items)');
    }
  }

  return $title;
}

You can use https://www.drupal.org/project/menu_badges to accomplish that.

  Once enabled, go to Administration > Structure > Menus, and click
  "list links" next to the menu containing the target item. Click "edit"
  next to the item and select the badge to display with the Display Menu
  Badge select box.

Or you can set the parent menu item of the Shopping cart (# items) link provided by the cart module to your menu. This menu item is provided by commerce and by default can be found in the navigation menu at admin/structure/menu/manage/navigation


Limit the results returned by 'published' I am new to the Database API and SQL queries in general. I needed to create a custom module that could be given a list of fields and would output the average value of each of these fields. I am pleased to have got my module to do this.

Unfortunately it includes all of the values for my fields, irregardless of whether they belong to a published node or not. To get it to exclude results from unpublished nodes I'm guessing that my query needs to draw in information from the node table. Could someone please point me in the right direction of how to exclude results from unpublished nodes?

Please find my module code below.

    function custom_aggregate_data_block_info() {
  // This example comes from node.module.

   $blocks['custom_data'] = array(
    'info' => t('Custom Data'),
// DRUPAL_CACHE_PER_ROLE will be assumed.
  );

  return $blocks;

}

/**
* Implements hook_block_view().
*
* Prepares the contents of the block.
*/

function custom_aggregate_data_block_view($delta = '') {
  // This example is adapted from node.module.
  $block = array();

  switch ($delta) {

      case 'custom_data':

    // initial output for block
        $block['subject'] = t('feild test');
        $blockoutput = "
";

    // searches the database and displays the results in a block

      /* database table name, table cell name */
      /* ie DRUPAL_MACH_NAME_value, field_data_DRUPAL_MACH_NAME */
      $feilds_to_query = array ("field_test_2004","field_test_2005");

      foreach ($feilds_to_query as $dbfeild) {
          // Do something with each $record
          $dbfeild_tablename = $dbfeild + "_value";
          $dbfeild_cellname = "field_data_" + $dbfeild;
          $querystring = "SELECT " + $dbfeild_tablename + " FROM " + $dbfeild_cellname;
          $query =  db_query($querystring);

          $total_field_value = 0;
          $total_records_field_value = 0;
          $average_records_field_value = 0;

          foreach ($query as $record) {
              // Do something with each $record
              $total_field_value = $total_field_value + $record->$dbfeild_tablename;
              $total_records_field_value = $total_records_field_value + 1;
          }

          // when looping through the results is finished then average the total by the number of records returned.
        $average_records_field_value = $total_field_value/$total_records_field_value ;

        // add the averaged data to the values stored ready to be returned
        $blockoutput .= "
Average results: " . $dbfeild . ": " . $average_records_field_value . "
";

       }

       // when finished looping through all the queries then close the html div, then return the results as a block
       $blockoutput .= "
 ";
       $block['content'] = $blockoutput ;

    break;
  }
  return $block;
}

Note that I have the case statement included as I plan to make use of several blocks in the completed module.

The node table has a field called status - 1 is published, 0 is unpublished.

Are field_test_2004 and field_test_2005 Drupal generated tables?

Normally table names take the form of field_data_field_test_2004...

Anyway, assuming they are Drupal generated tables they will have a field called entity_id which you can join to the node table with.

If you are building queries like this I would suggest you look into using Drupal Dynamic Queries as opposed to string concatenation - it is much easier to add bits to and manipulate the query.

Also feilds is spelt fields (sorry, couldn't help myself)


When is using --package-handler=git_drupalorg appropriate with drush? In which situations are using

drush pm-downlaod --package-handler=git_drupalorg ...

appropriate?

For example, if I am developing a normal site and want to version it with git, I assume it just best to just use the normal drush commands and version it outside of git?

Would using the git package handler, especially when combined with submodules, be most appropriate with sandbox environments where I may want to contribute patches and/or push changes back to git.drupal.org?

The second half of your question is easiest to answer: yes, if you are planning on creating a patch for drupal.org, --package-handler=git_drupalorg is a good option to use, as you may then easily create patches with git diff.  For an additional tool to help create and apply patches, see drush_iq.

The answer to the rest of your question is more subjective.  How you download projects for inclusion on a production site depends on your strategy for managing your code.  There are many options, but it's important to pick one that will work for you, because Drupal will commonly WSOD on you if you miss-match your code and your database -- that is, you must use any particular database snapshot with the version of the code that created it.  If you ever end up with an older database with newer code, you can just run updatedb; however, you can never use a newer database with older code.

Sometimes, I check in my entire Drupal source code tree into git.  When I do this, I do not use --package-handler=git_drupalorg to download modules; I just update them with drush pm-updatecode, and commit the result to my repository after testing.  When I do this, sometimes I deploy with git (git pull on production), and sometimes I keep my .git files on dev/stage only, and push just the code to production with drush rsync, leaving the .git files behind.

Using submodules might be a viable option.  There is a project to help manage Drupal submodules in your repository:  see Drupal on Git, aka "dog".  I don't really use submodules or dog myself yet.

Another option is to build an installation profile from your code, and commit just that to your repository.  The advantage here is that there's less in your repository, and it is easier to understand how versions change by tracking a makefile than trying to parse and understand the history of an entire Drupal tree committed to a repository.  See http://drupal.org/node/1368242.  I am just starting to use this, and have not really adopted it as a standard practice yet.


How to prevent CKEditor from removing content and tags written in source? I'd like to be able to use things such as the  tag for purposes of using font awesome icons, but CKEditor strips tags like this. If I place
 when in 'source' mode in ckeditor it gets removed as soon as I return to the standard mode. Is there a way to ensure that ckeditor allows these tags?

I saw that someone provided a solution here How to stop CKEditor 3.6.3.7474 from stripping <script> tags however in drupal 8 admin/config/content/ckeditor/edit/advanced does not exist.

I also saw the CKEditorPluginConfigurableInterface here https://api.drupal.org/api/drupal/core%21modules%21ckeditor%21src%21CKEditorPluginConfigurableInterface.php/interface/CKEditorPluginConfigurableInterface/8.2.x
But I wasn't sure how to make use of that.

Is there a way to prevent CKEditor from removing content and tags written in 'source'?

I had the same requirement, I followed this tutorial for that, How to Display Icons in Drupal using Icon API.

It needs two modules (1) Fontawesome and its dependencies Library module & Fontawesome Library. (2) Other module you need is Icon API which has sub-module Icon_filter that will convert the icons in the images.

I am afraid that Icon API module will work for D8 or not, but it has D8 version but unstable as you can see on the module page.

I am using this way on D7 site.

Update: Filter setting


How to add "Add to Cart" button using Ubercart? I'm building a website on Drupal 8 that involves kids videos, that can be sold as separate files. I'm using Ubercart module.

I'd like to know how I can put an "Add to cart" button, linking the video content page with the appropriate cart page.

Please put forward your opinions.

According to this answer:

  ... The content type has to be an Ubercart product content type, then the
  add-to-cart button will automatically show up on that content type
  along with all the other fields that are necessary for an Ubercart
  product like price, sku, etc.

  To make a content type an Ubercart product content type, edit the
  content type at /admin/structure/types/manage/{name of content type},
  choose the "Ubercart product settings" tab in the lower left of the
  page, select "Content type is a product", then save the content type.


Tokens keep 'disappearing', drush rr fixes the website for a time, sometimes hours sometimes seconds As title suggests my problem is missing tokens, at random intervals tokens will just cease to work on the site in question which makes any webform entries that are emailed out to a client appear empty. It also gets rid of all metatags from pages.

Metatag shows this while broken:

Then if I catch it in a good mood after running drush rr:

I am unable to see any errors in the database logs, no warnings/notices around the time of this happening either. Haven't got Entity Tokens enabled. The behaviour seems entirely random. I have read en earlier question with similar problems being caused by Node Export, I do not have this installed either.

Latest Drupal Core, latest Metatag, latest Webform versions. Infact everything is latest version as I ran a bunch of updates hoping that would fix the ongoing issue.

The URL Alias Patterns page is also empty, regardless of whether I have run drush rr and appeased the bug.

SimpleTest run on Token results in 0 fails 0 exceptions and a few debug messages that don't seem relevant.

Webform seems to be the culprit here, as it happens more often when I'm submitting webforms, though I'm not sure if it is. Version 4.1 of Webform.

Any help/ideas greatly appreciated

We've run into this problem as well on a shared hosting production environment, as well as our staging environment. The first on PHP 5.5.9 with Zend OPcache v7.0.3, the latter with PHP 7.0.22 with Zend OPcache v7.0.22. In both environments some site un-deterministically "forgets" tokens. I debugged this down to function_exists() in the implementation of the hook system of Drupal. It seemed PHP just forget that modules implement the hook_info() functions.

A restart of PHP (PHP-FPM in these cases) fixes the problems, so my best guess is that the Zend OPcache is responsible for this erratic behavior. Note that the fact that environments are shared will probably increase the odds of this bug to surface.


Custom form validation is missing I have a registration form :

{{ form.status_messages_user_register_form }}

{{ form.field_first_name }}

{{ form.field_last_name }}

{{ form.account.mail }}
{{ form.account.name }}

{{ form.account.pass.pass1 }}

{{ form.account.pass.pass2 }}

{{ form.form_build_id }} {# required #}
{{ form.form_token }}{# required #}
{{ form.form_id }} {# required #}
{{ form.actions }}

Now i want to add custom validation for the registration.I have a custom ajax handler for registration using form alter:

$form['actions']['submit']['#ajax']  = [
         'callback'    => 'custom_register_form_ajax_validate',
         'event'       => 'click',
         '#attributes' => [
           'class' => [
             'use-ajax',
          ],
         ],
       ];
       $form['#attached']['library'][]      = 'core/drupal.dialog.ajax';
       $form['#attached']['library'][]      = 'core/drupal.ajax';

       $form['#prefix']                     = '

';

And this is my function :

function custom_register_form_ajax_validate(&$form, $form_state){

$response = new AjaxResponse();

  $form_state->setTemporaryValue('entity_validated', TRUE);

  $firstname = $form['field_first_name']['widget']['#default_value'];

  $email = $form_state->getValue('mail');

  $pass1 = $form_state->getValue('pass1');

  $pass2 = $form_state->getValue('pass2');

    if($firstname == ''){
         $text = '
Firstname is required.
';
          $response->addCommand(new InvokeCommand('.form-text', 'css', array('border-bottom', '2px solid red')));
      $response->addCommand(new HtmlCommand('#email-valid', $text));
    }
    if($lastname == ''){
         $text = '
Lastname is required.
';
          $response->addCommand(new InvokeCommand('.form-email', 'css', array('border-bottom', '2px solid red')));
      $response->addCommand(new HtmlCommand('#email-valid', $text));
    }
    if($email == ''){
         $text = '
Email field is required.
';
          $response->addCommand(new InvokeCommand('.form-email', 'css', array('border-bottom', '2px solid red')));
          $response->addCommand(new HtmlCommand('#email-valid', $text));
    }
}

I want to validate "Firstname is required" condition.But when i submit and  validate the form,always showing "Email field is required".

How can i solve this issue?

You're probably not printing something required by the form since you are printing items individually. To start debugging, you can comment your entire form twig out and just use {{ form }} and see if it triggers validation.

At the same time, you are copy pasting the wrong thing in each error case:

      $response->addCommand(new InvokeCommand('.form-email', 'css', array('border-bottom', '2px solid red')));
      $response->addCommand(new HtmlCommand('#email-valid', $text));

This will always apply to elements with .form-email class and #email-valid id.

You're trying to evaluate $lastname but that variable is never set. If the email validation error always shows, then validate that you are using the right key in $form_state->getValue().

Since you are applying it to the same id, you are going to overwrite your own message each time as well. Check the documentation on HtmlCommand. It implements jQuery's html(string):

  When .html() is used to set an element's content, any content that was
  in that element is completely replaced by the new content.

You need to provide different divs to print these errors for the users sake, or rethink how you are doing this.


Drupal 8 variable_get I have some code in Drupal 7 what are using variable_get. Now I would like to write the code in Drupal 8. So I was reading this but its didn't help me a lot.

How to write this code in Drupal 8 from code in Drupal 7?

$types = array_values(variable_get('test_content_types', array()));

or this

'#default_value' => variable_get('test_content_types', array()),

Some suggestion.

In Drupal 7

 $data =  variable_get('test_content_types');

In Drupal 8

 $data = \Drupal::state()->get('test_content_types');

For more information about about "get", "set", "delete" visit - Step 5: How to upgrade D7 variables to D8's state system.


How to show separate values in Views from multi-value field I made Multi-valued field in content type. I created image type of field and let it has unlimited number of images.
Is it possible in Views to show only first image from this field? And only 5th?

Adjust these settings in your view for the image field:


Why is Drupal displying missing core tables for an external DB? I'm using an external non Drupal DB to import some data from. The importing itself work, but I also get error like the ones below:

Uncaught exception thrown in shutdown function.

PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table &#039;lager_db.semaphore&#039; doesn&#039;t exist: DELETE FROM {semaphore} WHERE (value = :db_condition_placeholder_0) ; Array ( [:db_condition_placeholder_0] =&gt; 480420510502a64252605e0.49437518 ) in lock_release_all() (line 269 of /srv/www/002/drupal/includes/lock.inc).

Why is Drupal even looking to base tables in that Database and how do I get rid of these errors?

My DB setup in settings.php:

$databases['default']['default'] = array(
    'driver' => 'mysql',
    'database' => '002_db1',
    'username' => '002_u1',
    'password' => 'password',
    'host' => 'localhost',
    'prefix' => '',
    'collation' => 'utf8_swedish_ci',
  );

$databases['lager_db']['default'] = array(
    'driver' => 'mysql',
    'database' => 'lager_db',
    'username' => 'username',
    'password' => 'password',
    'host' => '192.168.60.130',
    'prefix' => '',
    'collation' => 'utf8_swedish_ci',
  );

If I had to guess you called db_set_active() in some code and forgot to switch back to your master drupal database, so "drupal" execution continued after you intended it to with the current database set as your alternate.

The lager_db probably has no semaphore table, but drupal's trying to call it anyways. You should switch back to drupal at the end of your custom code (or as necessary) with db_set_active(); it passes the 'default' parameter if none is given.


How to upload media to S3 using entity browser and Flysystem S3 module My site is configured to upload media images to S3 using the flysystem module.

However when I want to use the entity browser it's default configuration is to upload images to the filesystem.

Is there a way to change the upload location to use the same S3 location?

What syntax should be used in the "Upload location" field below?


Some fields are not indexing in apache solr index I have taxonomy term and date type fields in content type. But they are not displaying in facets list in admin section.

While accessing this url http://localhost:8983/solr/select I noted that these fields are not indexing to the apache solr search index.

There is one other taxonomy term reference field and that field is indexing properly.

Any one who have some idea about this?

I had the search_index view mode was enabled and I have only enabled that one term reference field in search_index therefore only that field was indexing and not others.

So I enabled other fields search_index which I wanted to be indexed and it solve my problem.

So if you have enabled this search_index view mode for your content type then only those will be indexed which are enabled in this view mode.


D8 alter hook sequence I was wondering if using hook_module_implements_alter() is a good practice in D8 also to alter the order of execution of hooks?

I came to hear that it is suggested to do this with events that was introduced in D8 which will be a better way, but I could not find any reference that says not to use hook_module_implements_alter() in D8. One such ref.

If using events is advised, can someone put up a small example as to how to do that?

Thanks

I was wondering if using hook_module_implements_alter() is a good practice in D8 also to alter the order of execution of hooks?

Yes it is - in fact it's the only way to alter the order of hook execution.

Events are something different. Their execution order is set in the implementation of each handler, and can't be affected by any hook.