Fetch product data from commerce order on rules check-out completention This is the scenario :

Designing a automation website, user buys a product of type "EditOption", an EditOption consist of an editor and a task. When a user buy one of these products a new content of type "Project" should be created automatically, containing Editor and the task which must be assigned to him/her. So what I want is to fetch EditOption's Data from commerce order so these can be used later creating the new content.

I'm looking for a solution based on rules events.

The problem I faced is I can't get through commerce-line-items to fetch it's data. this is the result I get :

The solution I found:

First of all we need to create a Component which takes commerce-line-item as input,there we add some conditions to check if the item we are processing is of our desired type or not,this is how it configured :

Note that the way conditions are sorted is important.

Now after setting these conditions rules know that the item is definitely of type 'EditOption' so now all fields related to these type is accessible like below :

to create a content of type project I created another component which takes editor and 'EditOption' as inputs and the created my desired entity.(it is called in first component using data fetched from order)

the final step was to add an action of my first component in loop for each commerce-line-item of order.

here is the image :

Everything works fine now.


For external data, should I create custom table or new entity type? I have a database that exists outside of Drupal. I wish to show the summarized data from that database on Drupal.

At a high level, you can see the structure of the data below.

| Seller's ID | Product Category | Date      | Total Sales |
| 1           | Widgets          | 5/1/2018  | 20000       |
| 2           | Widgets          | 5/1/2018  | 40000       |
| 3           | Widgets          | 5/1/2018  | 50000       |

In the past, I simply have made a custom table in Drupal and then performed SQL queries on that table using a custom module.

Within this table, I likely have hundreds of thousands of rows.  As far as I can tell, I have two viable options:

Entity Type - Create an entity type with fields that mirrors the columns that I expressed above.

Potential benefits:    I should be able to use the full power of views to create different reports.  I could also make new reports from data without having to touch the custom module.
Potential Disadvantages:  I have concerns about site performance. On a prior site, I had hundreds of thousands of nodes and it seemed like it substantially slowed down the site.

Custom Table:

Potential Benefits:  1) This would be easy to implement on the front end  2) I would not be adding lots of nodes that MIGHT negatively affect performance.
Weaknesses:  1) I won't be able to use the data without leveraging a custom module to query the SQL.   2) Only developers with knowledge of creating custom modules would be able to create new representations of data.

Overall, I would prefer to create an entity type to hold the data so I can deal with the data in the front end of Drupal.  With that said, I don't want to set myself up for disaster in terms of performance down the road.

Should I be worried about the database having hundreds of thousands of entities in the entity table?

Are there other options I am not aware of?

It's really up to HOW you are going to use it. Just listing it? Will you extend it with new fields? How likely will be problem be more complex in the future?

Custom entity is a definitely good thing: it's not just about views, but lot more (entity hooks/events for example). Don't worry about performance yet, since you didn't mention anything that could be dangerous.
Still regarding simplicity the table solution would be still a winner.


google analytics are killed after "cookie control" instalation I'm new in drupal so I will write as simple as possible. I have installed the "google analytics" (GA) module. I have configured it and it worked. I was able to see live statistics on the GA web-page. Then I had quite stupid idea and I have installed "cookie control" (CC) module. After some time I have recognize that on the GA web-page I get no results... - no live-stats. So first I had disabled the CC module. But again there were no GA-live-stats :( so I have removed the CC module from the sites/all/modules, but that does not change anything. GA does not show any new stats since I have installed the CC module. How to proceed now?

Best regards,
kami

That's pretty much what Cookie Control is for.

On May 26th 2011 a new EU originated law came into effect that requires website owners to make significant changes to their sites and may fundamentally change the whole web browsing and shopping experience for everybody.This Cookie Law is amended privacy legislation that requires websites to obtain informed consent from visitors before they can store or retrieve any information on a computer or any other web connected device.
Cookie Control does just that, presenting users with clear information on whether cookies are present, linking to your privacy policy (where you should have specific information about what cookies are in use), and advising users on how to adjust browser settings and what cookies mean for them.
Features

Compact pop-up with dark and light colour themes.
Prevent users logging in until cookie consented.
Other modules can integrate with cookie callbacks (see below).
Configurable message and read more message.
Link to an admin defined privacy policy node.
Only apply cookie consent restrictions to specified countries or whole world.

3rd Party Module Support
A sub-module is bundled with Cookie Control which will disable Google Analytics from tracking a visitor until they give consent. Upon accepting cookies their first visit will be logged, along with any further page loads.

Emphasis mine.
So if you want to track people who do not consent for being tracked, you need to stop obeying the law - by disabling or modifying modules that makes your site law compliant.
If you in fact disabled CC module
and GA is silent, then if you have no (or not much) new users, or you haven't cleared your caches, or ISP caches, then yes, it can last up to a week (usually a day or two). Try uninstalling this module, not only disabling, too. If it lasts longer than about a week, and GA can't even detect you when you browse from a browser you are sure never seen CC-enabled version on your site, then you are in trouble and it might be worth to compare your site (especially HTML, JS and headers output) with a backup from before first CC installation. But it would be a bug in Cookie Control, and you should report them in issue queue, not here.


How to get each db result value count How to get values count in db_select
My query is:

$last_item = '2015-07-19';
$query = db_select('field_data_appointment_date','ap');
$query->join('field_data_appointment_slot','aps','aps.entity_id = ap.entity_id');
$query->fields('aps',array('appointment_slot_value '));
$query->condition('ap.appointment_date_value', '%' . db_like($last_item) . '%', 'LIKE');
$result = $query->execute()->fetchAll(PDO::FETCH_ASSOC);
dsm($result);

and my result is:

... (Array, 4 elements)
0 (Array, 1 element)
appointment_slot_value (String, 11 characters ) 10.00-11.00
1 (Array, 1 element)
appointment_slot_value (String, 11 characters ) 10.00-11.00
2 (Array, 1 element)
appointment_slot_value (String, 11 characters ) 10.00-11.00
3 (Array, 1 element)
appointment_slot_value (String, 11 characters ) 11.00-12.00

I need result like count of

:10.00-11.00 is 3
:11.00-12:00 is 1

Anyone help me out

Not fully understanding the output you really want to achieve, but here's examples on how to count the results coming from the database

get count with db_select

OR

rowCount

Let me know if any of those work for you.


Rewriting Views results with tokens on multi field I need to write a paragraph laced with field values from a result from a view.  For example, "Our camera case works with model ABC, 123, and XYZ", where ABC, 123, and XYZ are 3 out of multiple results values for that field.

Can I use tokens to achieve this?

yes using field_fieldnamename:delta

"Our camera case works with model [field_fieldnamename:0], [field_fieldnamename:1], and [field_fieldnamename:2]"


Webform to add row to specific sql table I have drupal running and have enabled a few modules including the webform module. I have opened phpmyadmin and added a new table with specific rows.

Now I want to link the two so that a user can log in to the site, fill out the webform with some data each day and I can insert a new row in the table and send each field to a specific column in that row. Later I will build a page for the user to view his inputs, maybe with graphs etc.

Am I on the right track? Is a webform the correct way to do this? And how do I make that link between the two?

Sorry, but no, you are on the wrong track.

Webform module is nice and easy, but it uses it's own storage. And whilst you can indeed use hooks to store a copy in your own table, it would take a pretty huge amount of work to do it properly.

It will be easier if you simply write your own module for that. If you don't know where to start, see Examples for Developers.


Creating a view of content that is filtered by the email of the current user How can you create a view of content in a specific node type where there is an email address that will correspond with the email address of currently logged in user's email address? The content is not owned by user. This view will be used to assign relations to the user and other content with rules.

Here is the approach to provide a relationship between content and logged in user:

Create a user view.
Add a contextual filter on User: E-mail.
Add a relationship on User: Content authored.

Now you can do rest of you functionality.


Drupal 7 site display unexpected symbols My site working very effectively on my localhost, but when I move the working site's all folders and files to Live Server i.e to cPanel, Its only display unexpected symbols that are given below.

‹Ý0M™å‘/ðë¥R!ŒH6L¨½¯Tl³/)4-/`4A‹.iÌ$³·†1‚š–b·Ê¹¢jZ-"¯i!¶=Ç¡Wô¶Ö¢c.kžu›pW:W_R–ÚF½¶™Õj!jWÒj5ƒ°µöÃb‚¹hB:=ú…4Íçÿ Ÿ>ÿ’ubK-NeýS¥#™Ú÷<‘FªR%•ûöËÝÍÍ—õm{£òùÅ<CR€u"Ôµ±/”hŒJ¨w}F{¼”Zï¦‘‡oýùZ,Oä¿G{ð&i:¯y`ðŠkë#o¥ F`xMû&©Lh¥26ˆÊaäÁ(•¤l¬æ š×+8]r¯Bš%êðÐ¸¢Zœ%<_I6Ðq¤*dÏÔ¡zssSyAþƒT²É¶iDƒ¡âž™r t%K,¡¨²,i©LLùzxI{¨å‘ÀŸêŸG°²ƒ#ˆÔ    ¬Ë$KÔk¾„÷À;ÈB;ß^¬gå‘%éZÀ£kÒOX·™sß—“fêIùk—†<6©{[õzuÃüçà5¸W} µ—Em«(½‚öWEm·^¯„ÍŠv²Ï˜ªS6“„*°iY2qh·HÈ|NÁõÕúG§¤HšëÖHñµ’):àR âÈ¡–}j.•¬†E»êv×µ@1G³”Êb“–ÈêÂ¶N€Ê]™’q'”±P‹ØM¹ø‘¦1Ãº‰+n;Øûxm%ø}ð0úG,_VŒ6q;zVLsÌ½k–Ô6j¯1ç]Îß`5å•pˆl›Â½ÆkàUÏÜ'¬00Ø½~öY‰¬©Ëœ”“z´XRVŽ6?õÊÅ•“€È&aEaµè!Î‹c¹}ËìóˆÉL%j[®HÓ]Htd¦ôÜ®/wI†,qÖ¥i F®*kèèþÕøDqºÙW3ß`þ©êˆ.Úw=Y.½fž2ëÌKZÖñ¦GÉ<Ÿˆ9$Ø¡pù#gk> W%!:Žçèt©#ÆÔ"ƒƒU~–¸’¿šµÚVù<±"ä"òXNas•øý$i€¨3Õ¬·>i¦_Õ6WÅõrQËªåQ‡C%œÙyÙ)…lÒòºmŽ™OÅÉ”s¼•Ÿ“ìý|ò÷ÑC'ÔÚwùõ'Ygçô8Ú<áZ›í_¯ò´J- .xwø„*¾‹…œ€õ‘â;°`Ð|Ê£íí» ‡ƒþmÛql»ÕøñÓÁáþåþ'ÇiaãÚÕ_õ´‹üõC³OI¦”I„~µ0ÑpFUßÚ³ÚŽUµb(Ÿ%¬Ëo¡ê¸ý`FìBUX{_--ô#uGG‰kA÷ÎÇƒóð ÷ã«wÿ•þ>è½ ¶w½_Þ~<Œ/6?ü1ŒÞ}8í¥ÁÕ[  °WQã:l"ko£:Þ–mà¥Žbç-µe;¦nÑúoã´s÷ÒßÝÚS›Ý`±KÆ–K³7ª»Éd©vO³?´ó ¢=‡X–Ü»Ï‡›ðÃíŽ¹4 %‡:…Ò,†öÄj0üL;Ã‡€—ÙRà…Z ªì@XXÍ·ª…\¹âM¢¬=™4Êž3¨HúÝ1j”Ì[8°HÒÍ7Q=‘S{àR\‰“Û.ò`í"v/âÍÌt’k\:_• o²WóI%¢ÚÓy©qôFö1‘GJÕù£v)´`}fùv‘j¥ˆî   ™e|ÚÙŸ{BëtN{,±sÈ}KÞŸÌƒ˜9?È>÷ðU Ó!”Ù&lýDK¿\Ù‹DÄòÉrŒ¼wjÿžÊï#:£|R¿[ý\hD¼§ùö Ûs]èŒæeŽ`s‹À¶4tŠ<ì¾6:òÉQwä‰~€ÿ²ž¿áyQKÅpümÓfLå'Ù7x†¬¼¨yœf«á+Ûp#%ºÙ%Ä [·@ÿ /¡ôØoY!ûŽ¿ð)Ià¦øÚŽp¿iåXD?‹lZƒµ(ˆG4°Ç›•&«uÐ"¶¬9seN   UP’Cú¸§Ë˜FÅÞ Vk#\ë÷£“äŸÿìC7î³†ß‰i79ó—S#%Æ Ê––r¬nÊ”Œ",–Ð J5)ÓViavy"a· ’Ï|â'"öÅY§ÙR„¹ˆ;" 8.Ï,—©ob ,ãÓð“Õº\ãú…•É”ŽíP«zmŽ$*ÈÌábÈîZÑ—}FD4‡Ï äßÓ4!X¼×"(´š0†úÄÏR€×È‚f…ûOhŒc«u†Ÿ»&o¶ô¿ø,åÐÎq!‚²&£ÂÖkhÏÜ½¬CŸ7=e§_‡Õ*McÑ¢AÌÚ5˜Âl}cqáæ–5¬ÍPÚû¤dó` ¢žQü37öqëâòã#²rHÞì_¼{zBÞœž“w§¿5œx;S•¢˜LÞó ivtà`AŒ(f[zI–IxžLÃßÌ+õ9ÆªsYF=›£;%ý¬«´d   §5¼µ¡a  Má˜Ð!   „ˆg…ý ~Çc;/³Pã-+‹guƒƒ Ï@ë8]lxº7Ì Ç  ë–™”…{–«ÝÈÊTm~¯Éz¹Y‡c˜Îm6Íúœcgƒ….øÇÉ.oºh8šØLM8F3¬ÖÑ¨§Ì}F„¾8hÏVÔÏ¥Õ×ÎÊ¥Q„âåÔ¬ˆõ§ýó÷ót]J&¤¡-K%þ.Üá!œÓî“NÌ_u9>·É!í3ù€Î†9$Ï?Ò—·§¾¸PÍ7¨ùP%…¸B¹â@ïÈf”Ev]ˆ   ÈduYYÃ!^gø¾ß©ß%å´=˜fúcšÌ&Ü{“Êö&Ø_‹mj´/¹ø«iáÿÑÍéUi) Ì-LpüÂò‹i´–fÇyk‹ñéãRZ`RùË¡¤=]éB›g°K»©·¼t1œå6Æáf³ùÀe5Ó°vfÖtÙ¬&Oókw»¸g6ª3Œõ¹wžöì×‚ª•ûð9æõ×¾#ƒùHô\,s.ÇKÛÚ]æ¶5Ó=(0ö8ÓË/’¦.Ë²_áÖW0w;¼ïnŸû‘×É1lI×Ççwïÿ¼&ºí¦RD]æê© ôóÜ~o8K`UàwüîŸÑüâÄ÷”„ åÿ¹c¼IÂb&žÍðVÝv…POðšcc³dÿ†FÄsB[¼…Û|l3ÚÆß>7f2ÏiD'-ñí‚¥SH‚ÂaÊüÜšÁq!ÓÌ¾,16S¦9I7)‰S®Ìºb”Kç §¯ŠÜ`œðõ†¶ÄgßxYˆ9YÝD.ò¦±Äé\ ÄPÚPó¹¾ˆ±Z—ØBþ†ñ/ä h¿/¾¬+ÀÎ_ ‚kPiÙ±¸7Ä+&ÓžÑ8×½äL÷N¤9—°Ò¼_Ö§–Y‹mÏ0õÙ¶¸1f‹*b7šÈ4ô»güS+x;Añíû(NÕQHy°’¥.ÞœºŒ(ADš|c0|cB!lëN‹,oÖ£‡½ööŸÂ¶Iþ'uÀƒ$a‘g±)sY„j9ñ  ™ê*RùJ FTÄB”Çbe{}šHŒ±>\¾±w,æ1]ëñà’C¢K˜Ã³ñ^¿&E¯3i_žkXYÏ‘þŽïD:Á?ö’0¿¸¿ìs<1#z(äÝ5«õïÅu1   °YŽVTz`„‘ÍþŠ)hê›uÉÿ_ÌÅ…ô´ÓÃÜÜÆæŽ5Æâ##î\4fí”©ÂDÀ!ªD7o0”E\Ð½MY™L>ÞiáísßgQŽGvÜ”~ö‹£†?<¦    lÀ'[gþßøûm/¾Ýýø×ôìXþöúUxö·íŸÅîéÉka„¸ƒJ  ÿÈx:Úx:zÀvI ›ZÚ\×™µY>ÜóLÄ-žˆ‡ÙMÊ?ÿ›Œÿ‰©r ³v¶!7|ªïKðdý/oþŽ¿;K

I also change the permissions of index.php but nothing works for me.
Also my index.php works, when I write die('test') in index.php it displays "test" on the page. I think the problem is in these two lines of code in index.php,

drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
menu_execute_active_handler();

If any one know how to fix this error, Please let me know I'll be very thankful to all of you.
Thanks in Advance...

Every time I have encountered this problem, it has been because I have

page level caching enabled on admin/config/development/performance
page compression enabled on admin/config/development/performance
output compression enabled in .htaccess or httpd.conf (eg, mod_deflate)

The cause is that pages are being compressed twice on the server side, but only decompressed once on the client side.  The solution is to disable page compression in Drupal.

You can add an override to your settings.php

$conf['page_compression'] = FALSE;

and alter the performance page

function MYMODULE_form_system_performance_settings_alter(&$form, $form_state) {
  $form['bandwidth_optimization']['page_compression']['#default_value'] = 0;
  $form['bandwidth_optimization']['page_compression']['#disabled'] = TRUE;
  $form['bandwidth_optimization']['page_compression']['#description'] = t('Handled by Apache.');
}


Behaviour of display links in views I have defined a new content type with comments. When I create a new view (page) consisting of the x most recent posts of this content type I see this:

I choose: Show content | Teasers + display links. I get an overview page consisting of teasers and each teaser has the Add new comment link (as well as the Read More link). This I understand.
I choose: Show content | Full content + display links. I get an overview page consisting of full content and only nodes with comments have the Add new comment link. This I do not understand. Why is the Add new comment link not visible for each node? And how can I make it visible (in node.tpl.php?)

Any help would be greatly appreciated!

Adding comments in Full content view mode happens, not through a link, but in the comment form that is displayed below the node (assuming it is set to be displayed in the content type's comment settings), but you need to switch on the Display comments checkbox in the Page: Row style options dialog.

You're right, Display links will print the add comment link in Teaser mode. If you have Full content mode and have both Display links and Display comments on, then you get both the link AND the form, which is akward. I don't know why it is that way.


Where are the Views located? This is related to this question I asked.

Bottom line is that for some reason some junk view is stuck under the Views list and when accessing the List I get a WSOD.

I confirmed that is a view issue after uninstalling and reinstalling Views the problem went away.

An easier fix might be to take a look on the saved Views. But the major question here is where are the created Views located? (in a folder? in the DB?).

I just want to see that malformed View and delete it.

EDIT: A screenshot of the output of drush vl. Note the enabled view on the top that has no name or machine name.

Active views are stored in the config table of the db. For example the view that produces the "recently added" block is stored in config table as name=views.view.content_recent.

The view's config itself is in the data (blob) column of that config-row.

Views that get installed by contrib modules at install time are located in the config/install/views.view.* file of the module's folder.

Try

mysql> select * from config where name='views.view.content_recent';


Trying to add an html head tag in Drupal 8, beta 2 With Drupal 8.0 beta2, drupal_add_html_head() has been deprecated in favor of #attached. So the old way was:

function MYTHEME_page_build(&$page) {
    $viewport = array(
          '#type' => 'html_tag',
          '#tag' => 'meta',
          '#attributes' => array(
            'name' => 'viewport',
            'content' => 'width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=0.55, user-scalable=yes',
          ),
        );
        drupal_add_html_head($viewport, 'viewport');
}

Based on the change notice you now use #attached. So the code above is essentially the same with the last part changing to:

$build['#attached']['html_head'][] = [$viewport, 'viewport'];

This does not work though and no error messages in watchdog. I've also tried putting this in a page alter as well as swapping $build with $variables and $output but it still does not work. In addtion, I tried the entire thing as an array:

  $build['#attached']['html_head'][] = array(
    '#type' => 'html_tag',
    '#tag' => 'meta',
    '#attributes' => array(
      'name' => 'viewport',
      'content' => 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no',
    ),
  );

... but that did not work either. I am not sure what I am doing wrong, seems like it should be working.

Update

Here is working code which uses hook_page_attachments_alter which is not in D8 Beta 2 as it was just committed to dev.

function MYTHEME_page_attachments_alter(array &$page) {
    $viewport = array(
      '#type' => 'html_tag',
      '#tag' => 'meta',
      '#attributes' => array(
        'name' => 'viewport',
        'content' => 'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no',
      ),
    );
    $page['#attached']['html_head'][] = [$viewport, 'viewport'];
  }

The only issue now is that core's viewport tag does not get overwritten so I am stuck with my custom tag and core's. Not sure how to handle that one or should my tag be overwriting core's?

You don't have $build in preprocess, so can't work like that. $build needs to be a render array that is rendered somewhere. I also don't see how this could have worked before, as this is already converted in template_preprocess_html() before your function runs.

Add hook_page_attachments(_alter)() and deprecate hook_page_build/alter() was just committed, and as a theme, you can implement hook_page_attachments_alter(), look for examples in the committed patch, like common_test_page_attachments_alter().

So, something like $page['#attached']['html_head'][] = [$viewport, 'viewport']; should work in there.


Using multiple AND/OR operators in contextual filters I'm trying to query my nodes by using a contextual filter in views, however, I am unable to use multiple AND (+) operators and OR (-) operators at the same time. For example:

This works:

mysite.com/json/20
mysite.com/json/19+20

This does NOT work:

mysite.com/json/21,19+20
mysite.com/json/21+27,19+20
mysite.com/json/21+27/19+20

Using the "/" causes the additional arguments to be ignored.
What I'm trying to tell the view is to return nodes that have a Term ID equal to either 21 or 27 AND also either have a Term ID equal to 19 or 20.

Here's my view:

Here's the contextual filter:

I have tried checking the "Allow multiple values" box, but it does not affect the filter at all. Does anyone have any suggestions?

As a workaround I have second contextual filter configured and arguments are separated with "/". In this case your /21+27/19+20 should work fine.

Still searching for the real solution.


Invoice module to run with commerce module? I'm looking for the right module to include invoicing capabilities with the Commerce module, but none of them fully fit my needs. Are there any other modules to help with invoicing?

Commerce Invoice
Commerce PDF Invoice
Commerce Invoice Receipt

The most up2date list of Drupal Commerce invoicing modules can be found at
http://drupal.org/node/1535498


Webform hours/time field How do you add a field where user can set hours when it's best to call for contacting. The Date field gives only days, months and years.

In this thread Webform: Time Field - Changing Variable Increments he states he has some time field for his Webform. But I can't track it down which module is that?

Webform module have time field by default.


Batch operation not called I am trying to write a Batch import to create nodes based on a uploaded file. The form works and I receive the file, and can read it in my submit callback which should initiate the Batch import. Here is the code:

function mymodule_import_submit(&$form, $form_state) {
  $xml = file_get_contents($form_state['values']['xml']->uri);

  $ads = xml2ary($xml);

  $batch = array(
    'title' => t('Importing Content ...'),
    'operations' => array(),
    'init_message' => t('Commencing'),
    'progress_message' => t('Processed @current out of @total.'),
    'error_message' => t('An error occurred during processing'),
    'finished' => 'mymodule_import_finished',
  );

  foreach ($nodes['nodes']['_c']['node'] as $new_node) {
    $batch['operations'][] = array('mymodule_import_create_node', array($new_node['_c']));
  }

  batch_set($batch);
}

While it seems to know the amount of operations needed (how many need to be created) my callback doesn't seem to get called. Here is its code:

function mymodule_import_create_node($new_node) {
  $clean_body = make_safe($new_node['CONTENT_BODY']['_v']);

  $node = new stdClass();
  $node->type = 'article';
  node_object_prepare($node);

  $node->title = substr(strip_tags($clean_body, 0, 20)) . '...';
  $node->body['und'][0]['value'] = $clean_body;
  $node->status = 1;
  $node->field_article_category = array();
  $node->field_article_location = '';
  $node->field_email_address = '';
  $node->uid = 1;

  node_save($node);

  $context['results']['articles_imported']++;
}

I put a few dumps at the start of the batch callback and it never exits. Watchdog indicates nothing, and no new nodes appear.

According to the Batch operations page on api.drupal.org, the processing function needs to have $context passed by reference.

Thus your import create node function should read function mymodule_import_create_node($node, &$context) and that should do it

Edit: sample code


Showing fields from different bundles that are related I'm trying to display the fields of one content type while searching on another content type. More specifically... here is my situation:

I have a view based on an index with fields in Organism and fields in mRNA.

Content type: Organism
Fields: order, common name, genus, species

Content type: mRNA
Fields: description, scientific name (Genus species)

I set up search filters for description, order, common name, scientific name. The result should look something like:
link to mRNA page
order | scientific name | common name
description

However, if I actually search by description, nothing shows up for order and common name. I feel like this is the result of an outer join of the two content types.

How would I "inner join" organism on scientific name? I've tried looking into EntityReference module but it seems like I would have to manually fill in the entity reference for every mRNA page I have... which isn't what I want.

Thanks

I figured it out using the Views Field View module. It basically gives you the ability make a subquery inside a view using a subview.

First I created a new index on organism with an aggregated field called Scientific Name that combines Genus and species. Then I made a view on that index with a contextual filter with Scientific Name (display empty text when filter value not in url; specify validation criteria).
Then I made the other view which uses the previously made view as a subview.

Well here's an intro tutorial for the module anyways: https://www.ostraining.com/blog/drupal/views-field-view/


Hiding menu items dynamically I am developing an application based on Drupal 7 and web services. Some application pages have a menu which should be customized (menu items should be removed) based on the response from the web service, but am not sure on how should implement it.

In general the logic is the following: I will get a parameter from the request and call the web service with PHP (I know how to do this). Then, based on the response, I should show or hide some menu items.

The problem is that the menu should be customized in every request, so hook_menu_alter does not help me, because it is only called once when the menu is created. Is there another hook that I should be looking into, or any other method I should be using?

use theme_menu_link() to modify your menu links on the fly:

style="display:none"
class="invisible"

e.g.

function mytheme_menu_link(array $variables)
{
   if ($variables['element']['#href']=='temp-menu-link') {
       $variables['element']['#attributes']['class'][] = 'invisible';
   }
   return theme_menu_link($variables);
}

Security note: It'll still be possible to access the URL, thus a "state check" must be implemented on the receiving end if temporarily invisible also means 'not permitted to call'.


Search autocomplete - what is the proper way to make it work for more that 13000 nodes? I use Search Autocomplete module, it works fine but only for small amount of nodes. I have more than 13000 nodes and this module just stacks. Is there a solution for this case?

I have not run into this directly with Search Autocomplete, but have run into similar issues with Views autocompletion with very large node sets.  There are two things that have helped me in the past.

One, is to make sure your database is truly optimized, to eliminate that from any speed problems.  mysqltuner will give you a good starting point.

The second thing requires monkey patching misc/autocomplete.js to use your own version of Drupal.ACDB.prototype.search which uses a minimum search needle length to lower the initial result set.  TBH, I have done this before, but it was so long ago that I forget the details.

Also keep in mind that single word searches will be against the index (which has a MySQL index), but multiword searches are against the dataset, which is essentially a LIKE query, which can be slow.  Enable query profiling to see what is going on there.

This should give you a starting point.


Drupal 7: Custom content types become un-editable and do not output correctly I've had the following problem a few times and can't find a satisfactory answer to it anywhere.

I create a new content type
add content for this new type
then, when the system displays the finished content after save, all of the new fields are missing (yes I made sure they were set to 'display' in the manage display tab)
on editing this new node, none of the fields display, all I get is the node title field and the tabbed options (eg comments, create version, menus etc)

I've read that this is caused by a permission problem. That sounded good, so I checked the permissions after creating the new content type and sure enough, there were no boxes checked for the new content type.

I checked all of the boxes for the admin role for the content type and still nothing. I've rebuilt the permissions and cleared the cache. Still nothing.

Dylan - have you looked here?  http://drupal.org/node/1029230


How do I create a custom rule action? I have drupal 8, and I want to create a custom rule action. I have created it in Drupal 7, and it's working fine. I have no idea how to do it in Drupal 8.

Can you please explain which code should I use for Drupal 8?

Drupal 7 Code

function custom_rules_action_info() {
    return array(
        'custom_action1' => array(
            'label' => t('custom_action1'),
            'group' => t('Custom'),
            'parameter' => array(
                'user_id' => array(
                    'type' => 'integer',
                    'label' => t('User ID'),
                    'description' => t('User ID.'),
                ),
            ),
            'provides' => array(
                'return_value' => array(
                    'type' => 'text',
                    'label' => t('User Created with return_value'),
                ),
            ),
        ),
    );
}

Check the actions of the Rules module:

http://cgit.drupalcode.org/rules/tree/src/Plugin/RulesAction?h=8.x-3.x

These are the actions provided out of the box by Rules.

Each action class has a @RulesAction annotation. Wire that up and you should see your Rules action appear. Think of the annotation here very similar to what you would have in hook_rules_action_info().

The only exception is instead of defining it in the .module file, it will live in mymodule/src/Rules/Plugin/RulesAction/NameOfYourAction.php.

Here is an example of what it might look like:

namespace Drupal\mymodule\Plugin\RulesAction;

use Drupal\user\UserInterface;
use Drupal\rules\Core\RulesActionBase;

/**
 * Provides a 'custom action' action.
 *
 * @RulesAction(
 *   id = "mymodule_custom_action",
 *   label = @Translation("Custom Action"),
 *   category = @Translation("Custom"),
 *   context = {
 *     "user" = @ContextDefinition("entity:user",
 *       label = @Translation("User"),
 *       description = @Translation("Specifies the user we are taking action on.")
 *     ),
 *   }
 * )
 *
 */
class NameOfYourAction extends RulesActionBase {

  /**
   * Flag that indicates if the entity should be auto-saved later.
   *
   * @var bool
   */
  protected $saveLater = FALSE;

  /**
   * Does something to the user entity.
   *
   * @param \Drupal\user\UserInterface $account
   *   The user to take action on.
   */
  protected function doExecute(UserInterface $account) {
    // execution code
    // you may want to set $this->saveLater based on your use case
  }

  /**
   * {@inheritdoc}
   */
  public function autoSaveContext() {
    if ($this->saveLater) {
      return ['user'];
    }
    return [];
  }

}

Please note that at the time of this writing, Rules is in alpha release state. It may change with subsequent releases.


Customize user profile page I want to fully customize the user profile page. I want to be able to show only the fields that I want, display views, blocks, etc...

Some users will be able to see others users pages so I really need to customize this my way.

Is this possible? Where should I code?

I found a user-profile.tpl.php and it only has this code:

Should I get rid of this code and write a new one?

Don't delete it, copy it into your theme with the other templates and adjust it there, your theme will override the one in core once you clear cache.


How to add google maps js without breaking jquery? So, I'm trying to implement a custom map using the Google Maps API in addition to a Google Map view. I'm working with an up-to-date D7 install. The reason for this is that I need to have multiple layers of content types, which isn't possible with the default views user interface. The view needs to show multiple entity types as individual layers, which I hope to implement as GeoJSON data layers from GeoJSON views through a custom map implementation.

The problem is my current approach is breaking my existing GMAP views and is interfering with jquery functionality.

I get a series of 'jquery is undefined' errors, as well as broken UI functionality, leading me to believe something is making variables collide.

I am approaching this by creating a block in a custom module and adding the markup and JS necessary through the module like so.

add js files $path = drupal_get_path('module', 'gmap_json');
drupal_add_js($path. '/gmap_json.js', 'file');

function gmap_json_block_info() {
    $blocks = array();
    $blocks['hello_world'] = array(
      'info' => t('Hello world'),
    );
    return $blocks;
  }

  function gmap_json_block_view($delta = '') {
    $block = array();
    if ($delta == 'hello_world') {
      $block['subject'] = t('Hello world');
      $block['content'] = t('This is the block content.');
      $block['content'] .= '

';
    }
    return $block;
  }

And my map js is here

function initMap() {
    map = new google.maps.Map(document.getElementById('json-map'), {
      zoom: 4,
      center: {lat: -28, lng: 137}
    });

    map.data.loadGeoJson(
        'https://storage.googleapis.com/mapsdevsite/json/google.json');
  }

The problem seem to be with how I'm adding my scripts, since leaving the drupal_add_js statement out of the module is what triggers the error.

So, how am I messing up in adding the js to the page? What's the right way to do this?

So, in this case the answer comes from one of the comments. I wasn't properly using the drupal_add_js call, which shouldn't be called globally. So I moved it into the function in my little module to side step this, but the better way to approach this is using the render arrays and the #attached property of the block's content array. This approach let's you more granularly choose which js is placed and called.


Trying to import existing Drupal site to a Linux Mint VM - getting redirected to install.php I have Apache/MySQL/PHP installed and working, I've imported the database and called it stove and have updated the settings.php file in sites/default/ to use my database's name, username, and password. The hosts and vhosts are all set up correctly as well, pointing to 127.0.0.1 and the proper directories.

Any ideas on why it keeps trying to re-direct me to the install.php

Here is the snippet of code from settings.php for the database:

/* Database configuration format:
 * @code
 *   $databases['default']['default'] = array(
 *     'driver' => 'mysql',
 *     'database' => 'databasename',
 *     'username' => 'username',
 *     'password' => 'password',
 *     'host' => 'localhost',
 *     'prefix' => '',
 *   );
 *   $databases['default']['default'] = array(
 *     'driver' => 'pgsql',
 *     'database' => 'databasename',
 *     'username' => 'username',
 *     'password' => 'password',
 *     'host' => 'localhost',
 *     'prefix' => '',
 *   );
 *   $databases['default']['default'] = array(
 *     'driver' => 'sqlite',
 *     'database' => '/path/to/databasefilename',
 *   );
 * @endcode
 */
$databases['default']['default'] = array(
    'driver' => 'mysql',
    'database' => 'stove',
    'username' => 'root',
    'password' => '',
    'host' => 'localhost',
    'prefix' => '',
);

Some of what was said was correct for this issue.  Going through the install process would have been correct, however the install.php page was not loading because when I had gone through the install process on the previous server, acquia dev desktop had deleted the install.php.

The fix was to take my sites folder and put it into a freshly extracted Drupal directory (so that the install pages were all there), update settings.php to correct database info, then go through the install process, and finally drop the tables and import the back up of the database with the information I needed.

Another note:
Acquia dev desktop will add the database settings to the BOTTOM of settings.php which can be easily missed.  If you're developing on Windows for whatever reason, I recommend using a virtual machine.  WAMP is wonky with some Drupal modules and Acquia Dev Desktop can be hassle when trying to migrate Drupal sites so having a *nix VM can be very useful.


Create RSS feed for content type = news? I created a content type called news items in drupal 7.  How do I tell D7 to create an RSS feed of ONLY news items?

When I go to /rss.xml, it displays all content types, which is too much.  I only need news items.

You can use the Views module to create feeds.  Simply add a new display of type "Feed" and customize the view to contain only the content you want.  Be sure to choose a path for your feed so that it can be accessed.

To add a "Feed" display:

Go to your views administration and select the view you want to edit. Towards the top of the page you will see the "Displays" heading with an "+ Add" button.  Click that and select "Feed" (See image below).  You will then have a Feed display that is using the Default Display's settings.


Create custom endpoints by extending the Resource Base class I created a custom endpoints by extending the core of Drupal. but I can not retrieve JSON data. I do not know what value to put in 'note: serialization_class

/** * Provides a resource to get bundles by entity.
*
* @RestResource(
*   id = "dna_custom_endpoint",
*   label = @Translation("DNA custom endpoint"),
*   serialization_class = ??????,
*   uri_paths = {
*     "canonical" = "/dnarest/{type}"
*   }
* )
*/

You know comprehensive guides that explain?

public function patch($type = 'type') {
    ???????
}

if you use what you said ( serialization_class = "Drupal\Core\Entity\Entity",) to me this generates fatal error PHP :

Drupal\Core\Entity\Exception\NoCorrespondingEntityClassException: The Drupal\Core\Entity\Entity class does not correspond to an entity type. in Drupal\Core\Entity\EntityTypeRepository->getEntityTypeFromClass() (line 103 of /Applications/MAMP/htdocs/dnaphone/core/lib/Drupal/Core/Entity/EntityTypeRepository.php).

The serialization class is the input or output of normalization and denormalization, or in other words, the object that you get when you denormalize data or the object that you normalize on the way out. Drupal 8 core provides one example of this \Drupal\rest\Plugin\rest\EntityResource. If the object is an entity you can use core:

  serialization_class = "Drupal\Core\Entity\Entity",

In order to use your arbitrary non-entity, you would also probably need to implement a Normalizer, but that is possible as well.

If your goal is to create a non-REST API with a custom endpoint that does not correspond to a REST operation (such as login or getProperty), then you should look at the Services module.


Configure a view to display nodes that match a term value of the container node I have two content types:

Programs
Events

I have a vocabulary:

Programs

I have a view that displays Events, and I place the view in my Programs nodes.

Both Programs and Events have a field_term_programs that references the Programs vocabulary. If I place the view in a Programs node, I want it to display any Events assigned to the same Programs term as that Programs node.  I have tried to set this up using contextual filters but have had no luck thus far.  The views block is displayed in the Programs node, but no nodes are displayed within the block.

The request to show sibling nodes through Taxonomy is one of the most common Views requests.

You case seems to be the simplest one, you can use the Has taxonomy term ID Contextual filter.

Create your Views listing Events
Add the Has taxonomy term ID Contextual filter and configure it:

When the filter value is NOT available
Provide default value
Taxonomy term ID from URL
Load default filter from node page, that's good for related taxonomy blocks
Filter to items that share any term
When the filter value IS available or a default is provided
Specify validation criteria
Taxonomy term ID
[your vocabulary]
Single ID
Place your Block Display on Programs nodes and configure Block settings for the contextual filter.


CKEditor: *During* WYSIWYG edit, how to show caption beneath image? When editing a body field with image and caption, the caption does not display during editing. Once saved it is visible - when the content is viewed.

Implementation-wise, I've added a caption field to the Image entity via the Entity View Mode config pages - admin/structure/file-types/manage/image/fields

Any thoughts on how to get the caption to show during edit?

CKEditor 4.3 supports captions but there would need to be support for the Drupal side of the implementation.

As of CKEditor 4.3, they now have widgets in the CKEditor side. They have introduced the Image2 plugin/widget, which supports image captions. The problem I've seen here is that Drupal has not caught up with this, so if you're using the media module for a file browser, it looks like that functionality is not yet ported to this newer version. However, if you just care about captions, it works.

See: http://ckeditor.com/addon/image2 for the plugin. I've been using it with the CKEditor Module, but it should work just as fine with WYSIWYG + Ckeditor Library.


How to create a template for a Views row style? I want to create a template file for a Views row style. I have created a template file for a field as views-view-fields--menu.tpl.php and output style file as views-view--menu.tpl.php.

How to create a template for a view row style?

In Advanced section in your view, there is a theme option in the last row. On clicking it you can get suggestions for possible template files in row style output sub heading. In this the last option is the most specific one.

Also on clicking the row style output heading you can get the code of default row style tpl which is getting called currently, which you can add in your tpl file and override it as per your requirement.


Why would a new user role have default permissions that are greyed out and cannot be changed? I recently installed a new role for the LoginToBoggan module for pre-authentication, aptly named 'pre-authenticated.'

However, this user has has all the default permissions of an authenticated user, and even one that is not (Edit own comments).

If I hit 'edit permissions' to the right of the user role name on the roles page, I get the single column and can set them as desired.

However, when I look at the permissions column when all roles are listed, none of my configuration settings I had saved are honored. Also, they are greyed out and cannot be changed, giving this user permission to add and edit content. Even more of a problem, this role can indeed add and edit at will before being authenticated.

Thoughts on why this is happening and how to fix it?

Under Drupal 7, assigning a permission to the authenticated user defaults that permission to all roles except the anonymous user. If you wish to have a lesser role (non-authenticated) you are going to have to remove the permissions from the authenticated user first. Then set up a post authentication role with the permissions you wish to add on authentication and set up a rule to assign that role when the user authenticates.

(I know! Not straight forward at all!) Remember that the permissions are additive. You do not have to repeat their assignment. Just specify the permissions that each role will add to the default. Then assign the roles to the users as required.


Drupal 8 Views filer results by logged in user association Hello Drupal Views Experts

First time Drupal site builder newbie to stack overflow and sounds like this is the smart place to ask a query.

I have a content type "Policies". This content type has a reference field to content type " Client". "Users" also have a reference to content type "Client".

What I am trying to display in views, either through filter criteria or contextual filter, is display a table of "Policies", but only display the results of which the logged in user has reference to.

I.E Logged in user is referenced to "Client A" of content type "Client". There are a few policies of content type "Policy" which also have a reference to "Client A" of content type "Client". I only want logged in user to be able to see content from views with the same reference to "client".

Is filter criteria the way to go, or contextual filters? As I said. I am a newbie site builder and guidance would be amazing if you have the know how.

Here's hoping.

You can find answers here with detailed steps about how to do that. Search for "sibling entity reference" or something longer.

Basically, you do do it with a couple of Relationships and a Contextual filter. You need Relationships to get the referenced Content into your Views, because when you create Products views you will only have Products fields available.

So you create a list of Products, add the ER Relationship for the Client info, add another Relationship that is using the first one for the users referencing the Client, then you can add the User ID contextual filter that is using the second Relationship and set it to provide default value from Logged in user.


Explain the N-rules in hook_update_N On hook_update_N() the documentation says:

  mymodule_update_7000(): This is the required update for mymodule to
  run with Drupal core API 7.x when upgrading from Drupal core API 6.x.

  mymodule_update_7200(): This is the first update to get the database
  ready to run mymodule 7.x-2.. Users can directly update from 6.x-2.
  to 7.x-2.* and they get all 70xx and 72xx updates, but not 71xx
  updates, because those reside in the 7.x-1.x branch only.

Is it really mandatory to define an 7000 update hook? I saw some contributed module updates that starts with 7300, when the module version for Drupal 7 is 7.x-3.x.

I am a bit confused, because I read before the UPGRADE.txt file for Drupal 7 core that says:

  MAJOR VERSION UPGRADE
  To upgrade from a previous major version of Drupal to Drupal 7.x, after following the instructions in the
  INTRODUCTION section at the top of this file:

  In addition to updating to the latest available version of Drupal 6.x core,    you must also upgrade all of your contributed modules for Drupal to their    latest Drupal 6.x versions.

For me, it means that users can't directly update from 6.x-2.x to 7.x-2.x unless  6.x-2.x module was the latest in the Drupal 6.x versions. Is this correct?

What about eventual database updates defined by 7.x-1.x branch? Do they have to be reported in the 70xx updates?

Can a module version 7.2.x keep any other updates (e.g. 60xx, 71xx) or it should be clean and defined only updates about 70xx and 72xx?

Basing on the documentation, 70xx updates are only necessary if there are updates from Drupal 6.x to Drupal 7.x that are necessary for any branch the Drupal 7 module has (e.g. 7.x-1.x, 7.x-2.x, 7.x-3.x). If that is not the case, then you don't need to use 70xx as update numbers.

As said in the documentation, updates numbered 72xx allows updating from the 6.x-2-x version of the module to the 7.x-2.x version, but not from the 6.x-3.x version. This is generally not a problem, since project maintainers normally create a version 7.x-3.x together a version 6.x-3.x.

As the documentation reports, updates numbered 71xx are for updated from version 6.x-1.x to 7.x-1.x; updates numbered 70xx are for updates from Drupal 6 to any branch of the module for Drupal 7.x. You don't copy the 70xx updates in 71xx updates, since those are already executed for the 7.x-1.x branch.

As for the updates to keep, the documentation says:

  A good rule of thumb is to remove updates older than two major releases of Drupal.

So, updates for a 7.x-1.x version should still be kept for a 7.x-2.x version.

Keep in mind that, as far as I recall, what described in the documentation about which updates are run when updating from Drupal 6 to Drupal 7 doesn't describe what the code actually does. For what I recall, Drupal code simply run any updates higher than the last executed update. For example, if a module last time ran its 6123 update, Drupal will run any update higher than that number, such as 7000, 7100, and 7200, if they are defined.


Are there existing modules to group nodes and give sequential access to them in Drupal 7 I want to be able to select a set of nodes, put those in a specific order (or make them dependent on each other) and give a group of users access to the set. However, I want the nodes to be read sequentially so users cannot start reading node 2 if they have not seen/read node 1.

I would very much like to use existing modules to accomplish this if possible. I have just spent an hour on the Drupal modules site and I'm a bit overwhelmed by the possibilities. I have not found one that does exactly what I want and although it seems possible by combining a few, most require a more in-depth understanding of the module to make a good assessment.

If you have a suggestion for one of my requirements, that would also be very welcome.

I would recommend the following modules:

Views: Views is a powerfull query and report generator. You can filter and sort your nodes or show individual nodes based on any criteria.
Rules: Rules allows you to take action on a lot of ocations. Let's say you can change data, roles or access rights on nodes when a user sees a node or confirms to have read the contents.
Fields (built in core): Is a little bit like Access: Create your data structures without coding.

It's very likely that you can do 90%-100% of you requirements with this (and may be some more helper) modules. Sometimes some glue code in a custom module is necessary.


Validation error, please try again. If this error persists, please contact the site administrator I've been searching google and I'm about to start surfing through the code, but we all know how useless searching through drupal code is.

People are running into this problem everywhere, including on my website today. So I figured it was worthy of stackexchange.

Basically, I run into this error when trying to send the contact form from my website. Others have run into it with a variety of forms.

I want to know what we're running into that is causing this error.

The form token associated to forms created with the form API is a value that is used to verify the data are submitted from a user who filled a module form, and not forged data.

The drupal_valid_token() function that validates the token is validating it using the user session; this means that, if the user session used when the data are being submitted is different from the session used when the form was created, the validation of the token fails.
This could happen also when a module calls session_destroy().


Link video (media_youtube) to node I have a content type called 'webtv' for adding videos from youtube with media, media_youtube modules. On the webtv page I want to add blocks with video preview image and node title.
My problem is that the video preview image is not linked to the node. I followed the instrunctions of the link but is not working as the field in not output to link
https://www.drupal.org/forum/support/post-installation/2011-12-25/making-preview-images-using-modules-media-and-media-for#comment-5644588
I also tried to use Content:Path and add it later but still not working.
PS. file_entity_link is not working because the field is a multimedia asset
Any ideas?
Using media youtube 7.x-3.9 version

The way it worked for me was by adding [path] at the end of the fields of the view and using css (position: absolute).
The best way would be to rewrite the image as link but never worked so I did it by css.


How do I create different landing pages? I am newbie to Drupal and I have deadline to make a website. So, I apologize if this question sounds silly to you..

I wanted to create a website that has one front page and 8 different landing pages. I have created front page. But I am not sure what is the best practice to create 8 different designed landing pages that are going to be use for the entire website.

For example:

"About" page uses 2 column layout.
"Contact Us" page uses 3 column layout.
"News" page has flexible layout and so on.
Also, News page has two image boxes with contents.

So, how do I create image box for one of my landing page?

So, can any one please guide me how do I create different landing pages?
I know there are several methods like, using panels, views and mini-panels we can create different landing pages. But, can any one suggest me good video tutorial and documentation for that?

Many Many Thanks!!

You have to check this link for theming of different different page.


url of each listed nodes in a view using the content format How can I display a node link for each node listed in a view with a content format parameter?

I have set a view with a content format teaser and the template is
 node--article--teaser.html.twig.

<a href="{{ url }}" rel="bookmark"> displays the page link where the view is displayed, not the content.link.

I cannot figure out why it does not work in my site and what could interfere with it.

The only way around I found was to get the node ID with   content.links['#lazy_builder'][1][0].

Do you have any idea?

Read the comments of the default node.html.twig under /core/modules/node/templates/. Any variable listed there should also work in node--article--teaser.html.twig.


In Drupal 7, what is the proper syntax to call the theme function for a node, passing an argument? I'm writing a Drupal 7 application that has many content types. Each of these content types has a custom template for display. For instance, I have node--event.tpl.php, node--person.tpl.php, node--feedback.tpl.php, and so on.

I'd like to be able to manually call a theme function on a node that should have an overriding template. i.e. something like the following:

<?php print theme('node', array('node' => $node)); ?>

The reason for this is that I've written a module called Content Inclusion which allows pieces of content to be manually included within one another. I'm trying to have this line of code in my node.tpl.php file to automatically display the included node along with the parent node.

I appreciate any and all suggestions, but I would be more interested in learning about ways to make this work - this module has some very specific requirements that existing modules were not able to address. Thanks.

The function you're looking for is node_view():

$view_mode = 'teaser'; // Or 'full'
print render(node_view($node, $view_mode));

It's the same function that Drupal internally calls to display the node page/teaser so your template files will be honoured as you'd expect.


How to run jquery codes before and after ajax call? I want to create a loading code while the ajax call is not yet complete, AND enable my jquery code after calling the ajax of drupal form. The ajax I'm referring to is the "Add new field/Add more" of unlimited field. I don't have a custom module for that. I'm just using what drupal already has.

This is the code that triggers the Ajax of the form:

$('input[name="field_collection_add_more"]').mousedown();

I can't use the $(document).ajaxComplete(function(){}); nor ajaxStart
function of the jquery because I only want my functions to run on that specific ajax call for that specific field.

How can I use the beforeSend: and success: when the ajax add new field is running?

Thank you in advance for the help!

/**
 * Special Effects AJAX framework command.
 */
Drupal.ajax.prototype.commands.nameOfCommand =  function(ajax, response, status) {
  alert("Hello I'm Maged Eladawy...")  ; // this will be executed after the ajax call
}

More details


How do I modify a custom entity delete form? I have a custom entity "Possession" that I created that has a non-standard edit form route to help facilitate a decending url structure. The routing for the edit form looks like this:

entity.possession.edit:
path: '/individual/{individual}/possession/{possession}/edit'
defaults:
  _entity_form: 'possession.edit'
  _title: 'Edit Possession'
requirements:
  _permission: 'access administration pages'
options:
  _admin_route: FALSE
  parameters:
    individual:
      type: entity:individual
    possession:
      type: entity:possession

That seems to be working fine, but now the Delete form isn't working properly. When I click on "delete" the page white screens with this error:

The website encountered an unexpected error. Please try again later.
Symfony\Component\Routing\ExceptionMissingMandatoryParametersException: Some mandatory
parameters are missing ("individual") to generate a URL for route "entity.possession.edit_form".
in Drupal\Core\Routing\UrlGenerator->doGenerate()
(line 182 of core/lib/Drupal/Core/Routing/UrlGenerator.php).

After a little bit of digging I noticed that the reason that the Delete form would be complaining about the edit form route is that the cancel link on the Delete form directs you to the edit form, so it needs those parameters form the link. I ran into this problem previously with the List Builder page for this entity, but I just fixed it in the code for that page.

For this I tried to edit the PossessionDeleteForm.php file that was generated when I created this entity through Drupal Console. I added a buildForm method to the empty class to a variation of this:

public function buildForm(array $form, FormStateInterface $form_state) {
  $form = parent::buildForm($form, $form_state);
  $entity = $this->entity;

  $form['actions']['cancel']['#url'] =  Url::fromRoute('entity.possession.edit_form', [
  'possession' => $entity->id(),
  'individual' => $entity->get('individual_id')->target_id,
  ]);
  return $form;
}

If I throw a ksm() in there to inspect that it seems like it's set up correctly, but it doesn't seem to have any change on the message that I'm recieving on the white screen. I also tried adding the getCancelURL() method to the class with a basic URL:

public function getCancelURL() {
  return new Url('system.admin_content');
}

Still nothing.

Next I tried the urlRouteParamters() method in the actual Entity class:

protected function urlRouteParameters($rel) {
  $uri_route_parameters = parent::urlRouteParameters($rel);

  if ($rel === 'edit_form') {
    $uri_route_parameters['individual'] = $this->get('individual_id')->target_id;

  }
  return $uri_route_parameters;
}

That also didn't work. I have no idea what else to do here. Does anyone have any suggestions?

The relationship is the key of the url relationships, aka edit-form, not edit_form. Try that in urlRouteParameters() and what you are doing should work.


Image Cache only clears when clearing my browser cache When I update my image style (for example adding a water mark overlay) the only way I can see the change is if I clear my browser cache. I am using the ImageCache Actions module.

I downloaded a fresh copy of Drupal and installed the Imagecahce Actions module and the problem doesn't happen on that site. It updates without requiring me to clear my browser cache.

Anyone have an idea what could be causing this issue?

Drupal some times uses cache in Images for better user performance.

if you want to view the image after the update or change you can use this code

<?php
 //get the image fiels
 if (isset($data->field_field_profile_pic) && !empty($data->field_field_profile_pic[0]['rendered']['#item']['uri'])) {
        $Logo = file_create_url($data->field_field_profile_pic[0]['rendered']['#item']['uri']);
 }

?>
//print the image tag
<img  src='<?php print $Logo.'?'.time();?>' alt=''>

Here the main code here is appending time stamp after your image as query string so time() will append the image tag with latest timestamp which will get the latest image from your server.

will reduce your burden from clearing your cache every time.

this is a quick fix we used in our project.


How to theme the Event content type node creation form in drupal 6? I have installed Event module which gave me an "Event" content type.

I want to theme the node edit/creation form for the Event content type that automatically comes once the Event module is enabled.

I have tried defining the custom tpl to handle but it's not working. Any help would be appreciated.

Thanks.

It all depends on what changes you want to make, but the standard way of altering forms in D6 (and D7) is invoking hook_form_alter() in a custom module. Do a switch on the form_id, and enter your edits, something like this:

YOUR_MODULE_form_alter(&$form, &$form_state, $form_id) {
  // print $form_id; exit;
  switch($form_id){
    case 'event_node_form':
      // change the form. The following will alter the text on the submit button:
      $form['submit']['#value'] = 'Go!';
      break;
  }
  return $form;
}

If you don't know what the form_id is of the form you want to edit, just uncomment the print $form_id line and visit the form in your browser. You can refer to the D6 form api guide to find what form elements go with which properties. Hope that helps!


How can I show only 3 countries in country list (select box)? I'm using SMS User module which validates users' mobile numbers. There's a select box and all countries in it. Users select country and write their mobile numbers.

I want to show only 3 countries in it, but there's no option in admin panel. I looked up the sms_user table. There is a gateway column and country codes writing. That's all.

How can I modify the country list? When I looked into the module code, I found nothing about countries.

I think you are trying to shorten the country select box in user registration form and user edit form. You should not hack the contributed modules. You could create your own module and override the forms using hook_form_alter().

I assume you have a custom module and you could implement hook_form_alter() to update the country list as you need. Here is the code in mymodule.module tested in my test site:

function mymodule_form_alter(&$form, &$form_state, $form_id) {
    if( $form_id == 'user_register_form' || $form_id == 'user_profile_form' ){
        $countries = array( // define the countries you want
            93  => 'Afghanistan',
            355 => 'Albania',
            213 => 'Algeria'
        );
        $form['sms_user']['gateway']['country']['#options'] = $countries; // update sms country select box.
    }
}

But, to access the field group sms_user, your module must have the heaviest weight, otherwise you won't be able to update $form['sms_user']['gateway']['country'].
You can make sure your module is heaviest by creating yourmodulename.install.

/**
 * Implementation of hook_install()
 */
function mymodule_install(){
    # Fetch max module weight from "system" table.
    $max_weight = db_query("SELECT MAX(weight) FROM {system} WHERE type = 'module'")->fetchField();
    # Make sure this module is the heaviest one in order to run last
    db_update('system')
        ->fields(array('weight' => $max_weight+1))
        ->condition('name', 'mymodule')
        ->execute();
}
/**
 * Implementation of hook_uninstall()
 */
function mymodule_uninstall(){
    db_delete('system')
        ->condition('name', 'mymodule')
        ->execute();
}

If you are expert, you can tweak the weight field of your module in the system table to make it heaviest without creating yourmodulename.install, but not recommended. You may need to flush all caches after you implemented this.


Node add form alter & submit custom field I have a content type "event" with a field called "field_pricelist". It's a dropdown with no values, I add the values when I alter the form. The values come from a custom table (install / schema) in my database. I want to save this custom value on insert/update. My code works but I don't think it's the best way to save/update a custom field.. Any suggestions?

function TableManager_form_alter(&$form, &$form_state, $form_id){
if ($form_id == 'event_node_form') {

global $user;
$query = db_select('pricelist', 'p');
$query->fields('p');
$query->condition('user_id', $user->uid,'=');
$results = $query->execute()->fetchAll();

$query2 = db_select('field_data_field_pricelist', 'd');
$query2->fields('d');
$query2->condition('entity_id', $form['nid']['#value'],'=');
$results2 = $query2->execute()->fetchAll();

$dropdown_array = array();
foreach ($results as $r) {
    $form['field_pricelist']['und']['#options'][$r->pricelist_id] = $r->pricelist_name;
}
$form['field_pricelist']['und']['#default_value']['0'] = $results2['0']->field_pricelist_value;
$form['#submit'][] = "TableManager_form_submit";
}

}

function TableManager_form_submit($form, &$form_state) {

global $user;

$nid = $form_state['values']['nid'];
$pricelist_id = $form_state['values']['field_pricelist']['und']['0']['value'];

$query = db_update('field_data_field_pricelist');// Table name no longer needs {}
$query->fields(array('field_pricelist_value' => $pricelist_id));
$query->condition('entity_id', $nid, '=');
$query->execute();
}

Try this...

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

  if ($form_id == 'event_node_form') {

    global $user;
    $query = db_select('pricelist', 'p');
    $query->fields('p', array('pricelist_id', 'pricelist_name'));
    $query->condition('user_id', $user->uid);
    $results = $query->execute()->FetchAllKeyed(0,1);

    $results['_none'] = "-Select-";

    $query2 = db_select('field_data_field_pricelist', 'd');
    $query2->fields('d', array('field_pricelist_value'));
    $query2->condition('entity_id', $form['nid']['#value']);
    $results2 = $query2->execute()->fetchField();

    if(empty($results2)) {
      $results2['_none']="-Select-";
    }

    $form['field_pricelist'][LANGUAGE_NONE]['#options'] = $results;
    $form['field_pricelist'][LANGUAGE_NONE]['#default_value'] = $results2;

   // $form['#submit'][] = "TableManager_form_submit";  // No longer need of this function

  }

}


Update title field in hook_ENTITY_TYPE_insert() I use hook_ENTITY_TYPE_presave() and hook_ENTITY_TYPE_insert() in order to update the node with a title using its ID.

function <module_name>_node_presave($node) {
  // ...
  if ($node->isNew() && $node->getType() == '<custom_content_type>') {
    $node->title = 'New entity ' . $node->id()->value;
  }
}

function <module_name>_node_insert($node) {
  if ($node->getType() == '<custom_content_type>') {
    $node->title = 'Submission #' . $node->id();
    // more code...
    $node->save();

  }
}

The first setting of title in hook_ENTITY_TYPE_presave() is only done because no entity can be saved without title. However, it seems like the setting of the title in hook_ENTITY_TYPE_insert() does not change anything.

I have already tried calling node->save(); in hook_ENTITY_TYPE_insert() but it gives me an exception stating that I try to store an entity using an already existing primary key. The exception message is

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

  Drupal\Core\Entity\EntityStorageException: SQLSTATE[23000]: Integrity
  constraint violation: 1062 Duplicate entry '48' for key 'PRIMARY':
  INSERT INTO {node_revision} (nid, vid, langcode, revision_timestamp,
  revision_uid, revision_log) VALUES (:db_insert_placeholder_0,
  :db_insert_placeholder_1, :db_insert_placeholder_2,
  :db_insert_placeholder_3, :db_insert_placeholder_4,
  :db_insert_placeholder_5); Array ( [:db_insert_placeholder_0] => 45
  [:db_insert_placeholder_1] => 48 [:db_insert_placeholder_2] => en
  [:db_insert_placeholder_3] => 1485011236 [:db_insert_placeholder_4] =>
  11 [:db_insert_placeholder_5] => ) in
  Drupal\Core\Entity\Sql\SqlContentEntityStorage->save() (line 770 of
  core/lib/Drupal/Core/Entity/Sql/SqlContentEntityStorage.php).

Can I change the title of the new entity (using the id)? Should I use another hook?

Since nodes have no id on insert, you should just save the node twice.

node_save() initiates a database transaction, in which the changes are not yet written, but the id is already reserved (explaining your issues with not being able to save). You will have to await the database transaction before attempting to save the node again. Unfortunately there is no hook for this.

However, there is a workaround: drupal_register_shutdown_function(). This can be used to call an additional function at the end of the request.

You'll end up with a code like this:

function your_module_node_insert($node){
  if($node->type == 'your_node'){
    drupal_register_shutdown_function('_your_module_post_insert',$node);
  }
}

function _your_module_post_insert($node) {
  if ($node) {
      $node->save();
  }
}

Code comes originally from here: https://drupal.stackexchange.com/a/102185/9921


How to show a content without creating node for it on Drupal site? I am creating a custom node page called node--mynode.tpl.php.
The code I'm putting in is <p> test</p>

Unfortunately nothing shows up on my Drupal site.
I have also added a node.tpl.php on the same folder as my node--mynode.tpl.php.
However I'm not sure if I have to add any code to the node.tpl.php?

Is it anything I need to add on my template.php?

Many thanks

While not at all suggested or encouraged, if you really want to create a static page in drupal, you can fake it out by creating a page--PATH.tpl.php template, but just realize that while it will show up, behind the scenes drupal will be throwing 404 / not found errors.

See Drupal 7 Template Suggestions for more information.

What I would suggest instead, though, is to look into Drupal's Menu System and create a callback for the page in question.


Allow user to select which registration type on Entity Registration module H, I am using the Entity Registration module, but I would like the user to be able to select what kind of registration type - e.g. registering as a participant, a facilitator or a resource-provider.
Is this possible? as it seems as though its only possible to enable one registration type on a registration field.

I haven't use the Entity Regisration module for registration but for my suggestion. You should use the Profile2 module for that purpose. It allows you to:
- Create many type of user profiles
- The link for registration of each kind of users (Must use the Profile2 Registration Path module)
- The custom fields for each kind of users


Is it possible to redirect user to another form depending on values entered in the first form I have 3 Webforms named A, AA and AB, In form A there are few question with Yes and No options.

I am looking for a way to direct user depending on the selected options, If user select all the options as Yes and press submit the form should direct the user to form AA else to form AB.

Is there any easy way/Module to check the Form A and direct user to either AA or AB depending on the selected options

I assume rules could be a choice, but i can't figure out.

Finally I Manage to redirect user to anther form base on entered values.

Install Rules module and Webform Rules
Create new rule
From React on event select After a submission draft has been submitted
Add a new condition, select Webform has name, Select form_id from Data selector, and select the form name from Weforms value
Add a new condition select Execute custom PHP code
Add the custom code

if ($data['components']['1_are_you_aged_18_to_50_years_of_age_']['value'][0]=='Yes')  {
return TRUE;
} else {
return FALSE;
}

Change the field name 1_are_you_aged_18_to_50_years_of_age_' and Yes value to your own field name and value
 7. Add an action, select Page redirect and add the URL.

Click save, And click save again.
Go to /people/permissions
Allow all the user type to Execute PHP code "Please note allowing users to execute PHP code is not recommended due to security risk".


Drupal CSV import and create nodes I am trying to accomplish the following through feeds and want to know if this is possible.

Setup a cron to pull a CSV file via ftp from another server daily
Create a bunch of nodes with custom fields based off the CSV file

I have the latest Feeds module setup, When I go to create a node it says I can upload my CSV file, however it seems the mapping could be wrong? I was a little confused at when I was setting up the mapping. My CSV file has no headers so for the source I put in the Column Name i.e A, B, C etc.

What am I doing wrong?

Link to CSV: http://markets.naptiveagency.com/diamondlot.csv

In order to do the mapping correctly, you have to instruct the feed importer how to do it. This is done through the configuration steps, shown in the following screenshots:

For sake of simplicity and time saving, I have created a content type called i.e. SimpleCar and added all the fields from the CSV file with the same name. Here is the screenshot of the content type:

Once you created a content type that closely correspond the screenshot shown above, then install/enable the following modules namely feed, feeds_ui,job_scheduler. And create a feed with the following configuration screens (closely watch how the feed is configured to read the CSV - Comma seperted file).

For simplicity, I have used the Standalone Form to directly upload the CSV. If you want this process to be triggered by CRON then you need to attach it to a content type - from the list).

You can also set the periodic import and tick the process in background option, you must have the CRON already configured.

Click on Fetcher and select either File Upload or HTTP, in this test case I have chosen File Upload, Save.

Once saved then you will see the File UPload Settings, Click it and see what is there. You can leave this settings intact. You can also tick the tick-mark to indicate where the feed importer should automatically pick up the CSV file and process it (should you have a way to automatically store the csv file in a directory then importer can pick it from there - that is advanced, you need to read about it).

Click on Parser and select CSV parser then SAVE. Once SAved then you will see the CSV Parser settings. By default it looks for Comma seperated, leave this intact and Save it. If you notice in this settings, there is a tick mark for Header, if you tick that then feed importer will start from top-most row, if you don't select it then first row will be skipped.

Click on Processor settings and choose Node Processor, Save. Once saved the Node Processor settings will appear and it has two sub-settings, Settings and Mapping.

The settings for this example, look as follow:

I have chosen Bundle as SimpleCar (which is the Drupal content type). This says that for every row of the CSV create one of the SimpleCar node. Save this screen.

The mapping settings of Node Processor should look as follow, to avoid mistakes, I recommend that you copy/paste fields directly from CSV and map them to their corresponding SimpleCar content type fields. Don't forget to map a unique value as VIN to GUID and Title and then Save.

Now go back to the basic settings and there is a link under the Standard Form drop down, you can use that link to upload your CSV and it should process and create your drupal nodes.

See my results:

and here is how the node looks like

In case you are lazy to follow the instructions, then at least create the content type and import the following code to Feeds using Import feed functionality and give it ago. You can then customize this to do it for you automatically either via HTTP download from server or pick up the CSV file from a location. You of course need to do some reading, google, there are a thousand tutorials on feeds module.

$feeds_importer = new stdClass();
$feeds_importer->disabled = FALSE; /* Edit this to true to make a default feeds_importer disabled initially */
$feeds_importer->api_version = 1;
$feeds_importer->id = 'csv_importer';
$feeds_importer->config = array(
  'name' => 'CSV Importer',
  'description' => 'Testing CSV Importer',
  'fetcher' => array(
    'plugin_key' => 'FeedsFileFetcher',
    'config' => array(
      'allowed_extensions' => 'txt csv tsv xml opml',
      'direct' => FALSE,
      'directory' => 'public://feeds',
      'allowed_schemes' => array(
        0 => 'public',
      ),
    ),
  ),
  'parser' => array(
    'plugin_key' => 'FeedsCSVParser',
    'config' => array(
      'delimiter' => ',',
      'no_headers' => 0,
    ),
  ),
  'processor' => array(
    'plugin_key' => 'FeedsNodeProcessor',
    'config' => array(
      'expire' => '-1',
      'author' => 0,
      'authorize' => 1,
      'mappings' => array(
        0 => array(
          'source' => 'DEALERSHIP_ID',
          'target' => 'field_dealership_id',
          'unique' => FALSE,
        ),
        1 => array(
          'source' => 'STOCKNUMBER',
          'target' => 'field_stocknumber',
          'unique' => FALSE,
        ),
        2 => array(
          'source' => 'new',
          'target' => 'field_new',
          'unique' => FALSE,
        ),
        3 => array(
          'source' => 'VIN',
          'target' => 'field_vin',
          'unique' => FALSE,
        ),
        4 => array(
          'source' => 'Year',
          'target' => 'field_year',
          'unique' => FALSE,
        ),
        5 => array(
          'source' => 'Make',
          'target' => 'field_make',
          'unique' => FALSE,
        ),
        6 => array(
          'source' => 'Model',
          'target' => 'field_model',
          'unique' => FALSE,
        ),
        7 => array(
          'source' => 'series',
          'target' => 'field_series',
          'unique' => FALSE,
        ),
        8 => array(
          'source' => 'Body',
          'target' => 'field_body',
          'unique' => FALSE,
        ),
        9 => array(
          'source' => 'Ext Color',
          'target' => 'field_ext_color',
          'unique' => FALSE,
        ),
        10 => array(
          'source' => 'Int Color',
          'target' => 'field_int_color',
          'unique' => FALSE,
        ),
        11 => array(
          'source' => 'Asking Price',
          'target' => 'field_asking_price',
          'unique' => FALSE,
        ),
        12 => array(
          'source' => 'MILEAGE',
          'target' => 'field_mileage',
          'unique' => FALSE,
        ),
        13 => array(
          'source' => 'Transmission',
          'target' => 'field_transmission',
          'unique' => FALSE,
        ),
        14 => array(
          'source' => 'Engine',
          'target' => 'field_engine',
          'unique' => FALSE,
        ),
        15 => array(
          'source' => 'restraint type',
          'target' => 'field_restraint_type',
          'unique' => FALSE,
        ),
        16 => array(
          'source' => 'image url',
          'target' => 'field_image_url:url',
          'unique' => FALSE,
        ),
        17 => array(
          'source' => 'Comments',
          'target' => 'field_comments',
          'unique' => FALSE,
        ),
        18 => array(
          'source' => 'options',
          'target' => 'field_options',
          'unique' => FALSE,
        ),
        19 => array(
          'source' => 'certified',
          'target' => 'field_certified',
          'unique' => FALSE,
        ),
        20 => array(
          'source' => 'VIN',
          'target' => 'guid',
          'unique' => 1,
        ),
        21 => array(
          'source' => 'VIN',
          'target' => 'title',
          'unique' => FALSE,
        ),
      ),
      'update_existing' => '2',
      'input_format' => 'plain_text',
      'skip_hash_check' => 0,
      'bundle' => 'samplecar',
    ),
  ),
  'content_type' => '',
  'update' => 0,
  'import_period' => 1800,
  'expire_period' => 3600,
  'import_on_create' => TRUE,
  'process_in_background' => FALSE,
);


How to preserve kint output upon form submit redirection? I've attached a custom submit handler to node add/edit form for the article content type:

$form['actions']['publish']['#submit'][] = 'my_module_node_edit_submit';

In the handler, I am trying to inspect the form state values with kint (via the devel module):

kint($form_state->getValues());

Upon submission of the form, I'm able to briefly see the kint output on the screen, but I am also presented with this message:

  Redirecting to http://localhost/example.com/node/123

The page then redirects back to view the node, and the kint output is gone. How can I preserve the kint output so it is available after the redirection?

Use ksm() instead of kint().

I ran into the same issue when I want to inspect the entity after saving, using drupal's hook_entity_presave and kint

I found this article on how to print variables using kint() which explains that ksm() prints the output inside the drupal page (not before as kint()) does.

So this example prints the entity without redirecting:

function mymodule_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  ksm($entity->toArray());
}


Modify instead of add a class in classes_array for theming purposes I am using the following preprocess in my template.php

function paddle_admin_preprocess_menu_block_wrapper(&$variables) {
  if ($variables['delta'] === 'management_level_2') {
    $variables['classes_array'][] = 'max-width';
  }
}

It works as intended, it adds a class when the delta equals this string..

I am trying to modify another other entry of the classes_array array in order to make the classname more semantic. How would I go for that? (so replace an entry instead of add)

ps: I figured it can be as easy as:

$variables['classes_array'][1] = $variables['delta'];

but I am wondering whether the array indexes can change (from the ones I see with devel themer)

Search for the key of the value you want to replace and then modify it. It's that simple.

function paddle_admin_preprocess_menu_block_wrapper(&$variables) {
  if ($variables['delta'] === 'management_level_2') {
    // Search for the key
    $key = array_search('class_to_be_replaced', $variables['classes_array']);

    // If class was found, replace it
    if ($key !== FALSE) {
        $variables['classes_array'][$key] = 'class_that_replaces';
    }
  }
}


How do I use the value of a webform_field as the default-value for a later webform_field? Is there a way with Drupal 8 Webform UI to set the default value of a text field as the value of an earlier text field in the same form, and update via Ajax?

example:

user_name:
     '#type': textfield
     '#title': 'User Name'

nick_name:
    '#type': textfield
    '#title': 'Nick Name'
    '#default_value': '[webform_submission:values:user_name]'
    '#ajax': true

But the default value does not render the token and just prints plain text.

Any help is much appreciated, thanks.

The short answer is 'No' to using tokens to sync two element values, unless the two elements are on different pages. The simplest solution is a write a little JavaScript to sync the nickname with the username.

You can search for examples of sync'ing two input fields.

The Webform module's Options admin widget uses a little JS to sync an option's value with the option's text. @see webform.element.options.admin.js


CSS reverted on cache clearing I am using D7 with Panels and Panels Everywhere enabled and using the Versatile Theme.  I have changed the default versatile.css file to have the page-content div be 960px instead of 1020px.  All of the regions are % that are created using the Builder Flexible layout since the site is still under development.

Every time I clear the cache the css at -- /sites/default/files/ctools/css/ad57ff1546b4e3e493a0d16eb09e3ad9.css
reverts back to 1020px.

Seeing if anyone knows how to keep this from happening?

/* found out what I was doing wrong.  1020 was the default width that was still being used at the General page of Variant even though I changed the default setting in the Panels Mod.*/


hook_form_alter function to make field visible and required? I'm trying to build a hook_form_alter function to  make field visible and required.

The form is the checkout form at http://example.com/en/checkout/33

The targeted field are Customer Profile Billing fields that I added at: http://example.com/en/admin/commerce/customer-profiles/types/billing/fields

I tried with:

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'commerce_checkout_form_checkout') {
    $form['field_cif_nif_id'] = array(
         // This #states rule says that the "field_cif_nif_id" fieldset should only
         // be shown if the "field_dispongo_de_" form element is set to "CIF/NIF/ID".
        '#states' => array(
           'visible' => array(
               ':input[name="field_dispongo_de_"]' => array('value' => 'CIF/NIF/ID'),
            ),
        ),
  );

 }
}

it simple doesn't work. No errors.

I need to make the 'field_cif_nif_id' visible and required only if 'field_dispongo_de_' has value 'CIF/NIF/ID'

UPDATE:
I forgot to mention that 'field_dispongo_de_' is a 'radio' type field and 'field_cif_nif_id' is a 'input text' type.

UPDATED CODE

It is closer but not working yet.

function MY_MODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'commerce_checkout_form_checkout') {
    $form['customer_profile_billing']['field_cif_nif_id'] = array(
       '#states' => array(
           'visible' => array(
               ':input[name="field_dispongo_de_"]' => array('value' => 'CIF/NIF/ID'),
            ),
       ),
    );
 }
}

Try changing the selector from ':input[name="field_dispongo_de_"]' to the id of the field (#edit-customer-profile-billing-field-dispongo-de-und) as below:

/**
 * Implements hook_form_alter().
 */
function MODULE-NAME_form_alter(&$form, &$form_state, $form_id) {
  // Check if the form is commerce checkout form.
  if ($form_id == 'commerce_checkout_form_checkout') {
    // Verify the field names are as per the form.
    $form['customer_profile_billing']['field_cif_nif_id']['#states'] = array(
      // This #states rule says that the "field_cif_nif_id" fieldset should only
      // be shown if the "field_dispongo_de_" form element is set to "CIF/NIF/ID".
      'visible' => array(
        '#edit-customer-profile-billing-field-dispongo-de-und' => array('value' => t('cif')),
      ),
    );
  }
}


What is the correct way of logging in through services from android? I currently have an app in development where I use services 3 on drupal 7 to login to my site. I do this by simply passing in the username and password parameters to a json object and use httppost to post them to service endpoint. Using the response I grab the cookie and store it in sharedpreferences on android which is used in all the following requests. I have this cookie set to be used for several days so the user wont require login again. Do I have any reason to be concerned about the security of this (I dont store any passwords) and if so what are the extra steps I can take and how to beef up the security but still allow for users to remain logged in? I have played around with the oauth module a bit but it seems rather complicated to implement on both drupal side and android. If oauth is my best option what are the steps to take to implement it with drupal and android?

You can use Android AccountManager over https to be more secure.
Like this Drupal 8 Android app at https://github.com/onedrupal/One-Drupal-Android.


Remove disabled menu links from menu settings I have a multilingual site, and when adding content theres an option to add a menu link. Both languages show up in the drop down selection, my goal is to hide/remove the links that are "disabled" (NOT in the current language).

So only the current language links should be visible in the dropdown.

Never solved this, finally i deleted the drupal site and rewrote the site with dogescript.


Where do I find the translation overview? I'm totally spooked about this. Last week I activated the contributed module Translation Overview. All worked great, a very usefull module for my project. Now, one week later, I'm totally unable to find this translation overview in Drupal. I have searched every corner, browsed the web to no avail, I have all permissions, the module is activated...

Where do I find the translation overview?

You can find the translation overview on:

admin/config/content/translation-overview-manage


nested xml views export I use drupal6 and views2. I need to create xml file using views. This can be done easily using any xml export module but I am not able to create deeper nested xml output like:

    <itemslist>
     <items>
      <item>
       <item_nbr></item_nbr>
       <item_pic></item_pic>
      </item>
     </items>
    </itemslist>

Can anybody point me to the right direction?
Thank you.

The best way for creating data output from Drupal is by relying on Services it will give you XML-RPC or REST server which will be capable of outputting data in precisely the way you want.
 I will lay out in steps:

Installing Services module
Creating an endpoint and firring up a server.Here is simple guide how to do that.
To format Service output you will need to create a simple module or rely on contributed modules.

Writing a module may seam bit tricky for a beginner so I suggest using modules like Services Views which will let you add a Service type view page or use Services Entity API or Services SearchAPI.


Search info_split is empty I need to customize the search results of a drupal 8 (8.7.0 currently) page a bit and need the node_type for this. According to search-result.html.twig, this should be stored in info_split.type, but the whole variable is empty.

How can I get the node type inside the search-result.html.twig file?

Alright, so I'm still not sure why the fields are empty, but they the keys are certainly there. Either it is a bug in the core, or some weird behaviour of my installations.

I fixed it now manually by implementing the preprocess_search_result hook in mytheme.theme:

function mytheme_preprocess_search_result(&$variables) {

    $variables['type'] = $variables['result']['node']->get('type')->getString();
    $variables['nid'] = $variables['result']['node']->get('nid')->getString();

    switch ($variables['type']) {
        // some other adjustments based on the node tpye
    }
}


How do I add a view mode to a simple custom entity? I have created a super-simple drupal 8 custom entity.  We now need a custom view mode for this entity.  What do I need to add to my definition to make my entity appear as an option on the 'Add View Mode' page: /admin/structure/display-modes/view/add ?

My super-simple entity definition is

 * @ContentEntityType(
 *   id = "schedulecal",
 *   label = @Translation("ScheduleCalendar"),
 *   base_table = "scheduler_entity_calendars",
 *   entity_keys = {
 *     "id" = "id",
 *     "uuid" = "uuid",
 *   },
 * )

I can't find this info anywhere in doc.

You need a view builder class in the handler section:

 *   handlers = {
 *     "view_builder" = "Drupal\Core\Entity\EntityViewBuilder",

and a field UI route:

 *   field_ui_base_route = "my_entity.settings",

pointing at the config form for the settings of your entity type. If you don't have settings return at least a #markup element:

  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['my_entity_settings']['#markup'] = 'Settings form for My Entity entities. Manage field settings here.';
    return $form;
  }


What is the URL to set the admin theme? The URL to change the admin theme isn't the same in Drupal 7 compared to 6.  What is the new URL?

Its at the bottom of the 'Appearance' page (admin/appearance), in the section labeled 'Administration Theme'.


cannot use some drush commands I am running into some trouble with drush I can't pm-enable the modules I just downloaded with it.
I did some research but none of the solution worked for me, most cases involved switching "localhost" to "127.0.0.1" in settings.php but my database is located on a docker container.
I am running drush from the root folder.

Here the output I get when running drush en module1, module2

    root@c4765ef094a2:/var/www/html# drush en pathauto, token,
    simple_gmap, addtoany, scheduler, devel, devel_generate
    Command pm-enable needs a higher bootstrap level to run - you will
    need to invoke drush from a more functional   [error]
    Drupal environment to run this command.
    The drush command 'en pathauto, token, simple_gmap, addtoany,
    scheduler, devel, devel_generate' could not be     [error]
    executed.
    Drush was not able to start (bootstrap) the Drupal database.
    [error]
    Hint: This may occur when Drush is trying to:
     * bootstrap a site that has not been installed or does not have a
    configured database. In this case you can
    select another site with a working database setup by specifying the
    URI to use with the --uri parameter on the
    command line. See `drush topic docs-aliases` for details.
     * connect the database through a socket. The socket file may be
    wrong or the php-cli may have no access to it in
    a jailed shell. See http://drupal.org/node/1428638 for details.

    Drush was attempting to connect to:
     Drupal version         :  8.4.0
     Site URI               :  http://default
     Database driver        :  mysql
     Database hostname      :  mariadb
     Database port          :  3306
     Database username      :  root
     Database name          :  drupal
     PHP executable         :  /usr/local/bin/php
     PHP configuration      :
     PHP OS                 :  Linux
     Drush script           :
     /var/www/html/vendor/drush/drush/drush.php
     Drush version          :  8.1.15
     Drush temp directory   :  /tmp
     Drush configuration    :
     Drush alias files      :
     Drupal root            :  /var/www/html
     Drupal Settings File   :  sites/default/settings.php
     Site path              :  sites/default
     Sync config path       :  sites/default/files/config_oL5MBo-
     2_ALSPTKnAwZb1o3WVs19lndEmQpb4zfSv42kL9A8F0bp4g_de
                       mvUvf96DBkH3qyYww/sync

Here's the output of drush sql-connect

mysql --user=root --password=root --database=drupal --host=mariadb --
port=3306

I have been stuck on this for 2 hours so any help would be greatly appreciated

I prefer to use drush from drush alias files, so that the magic of Drush figuring out everything from the document root isn't so magical and you can sometimes more easily debug issues from a proper drush alias file.

As others mention it's likely the database connection that's not working. In docker you can use the --add-host build option, or the extra_hosts docker-compose options to give a name to your database container (docker can use the container name to properly create the /etc/hosts entry at runtime).

See this stackexchange answer https://stackoverflow.com/a/38306666/1491507

By following the above directions in docker-compose an entry such as the following that creates a named hosted in /etc/hosts as my_resolved_db_service which is magically resolved to the mariadb container.

extra_hosts:
  - "my_resolved_db_service:mariadb"

Then in a drush alias file, or when installing drupal via drush you would use the /etc/host name created:
drush si --db-url=mysql://root:root@my_resolved_db_service/drupal as an example.


How to check if block is empty in page.html.twig In my page.html.twig I have

{{ 'Block title'|t }}

  {{ drupal_block('leftblock') }}
  {{ drupal_block('rightblock') }}

I want to display Block title only if my custom leftblock and rightblock are filled.

Thanks.

I tried

If I do in my my_module.module

function my_module_preprocess_page(&$variables) {
  $block = Block::load('leftblock');
  if ($block) {
    $variables['leftblock'] = \Drupal::entityTypeManager()
      ->getViewBuilder('block')
      ->view($block);
  }
  $block = Block::load('rightblock');
  if ($block) {
    $variables['rightblock'] = \Drupal::entityTypeManager()
      ->getViewBuilder('block')
      ->view($block);
  }
}

and in my page.html.twig

{% if leftblock or rightblock %}

{{ 'Block title'|t }}

{% endif %}

  {{ leftblock }}
  {{ rightblock }}

This {{ rightblock }} display the real content of the block in twig( when is filled ), but
It always display Block title because the block have always something

if I do  {{  dump(rightblock) }} i got this when the block is empty or filled.

array(3) { ["#cache"]=> array(4) { ["keys"]=> array(3) { [0]=> string(11) "entity_view" [1]=> string(5) "block" [2]=> string(22) "rightblock" } ["contexts"]=> array(2) { [0]=> string(28) "languages:language_interface" [1]=> string(8) "url.site" } ["tags"]=> array(2) { [0]=> string(10) "block_view" [1]=> string(41) "config:block.block.rightblock" } ["max-age"]=> int(-1) } ["#weight"]=> int(0) ["#lazy_builder"]=> array(2) { [0]=> string(42) "Drupal\block\BlockViewBuilder::lazyBuilder" [1]=> array(3) { [0]=> string(22) "rightblock" [1]=> string(4) "full" [2]=> NULL } } }

I have two themes :

block-myLeft.html.twig

block-myRight.html.twig

You could preprocess your template

function mytheme_preprocess_page(&$variables) {
  $block = \Drupal\block\Entity\Block::load('leftblock');
  if ($block) {
    $variables['leftblock'] = \Drupal::entityTypeManager()
      ->getViewBuilder('block')
      ->view($block);
  }
  $block = \Drupal\block\Entity\Block::load('rightblock');
  if ($block) {
    $variables['rightblock'] = \Drupal::entityTypeManager()
      ->getViewBuilder('block')
      ->view($block);
  }
}

Than you can do this in your template

{% if rightblock or leftblock %}

{{ 'Block title'|t }}

{% endif %}

  {{ leftblock }}
  {{ rightblock }}


How to create entity relation of counselor to client? I'm trying to create a relation in D8 between a counselor and clients.  The counselor would have to record counseling hours for each client.  I've looked at the group module, even building the relation using RedHen CRM.  Just curious, anyone have suggestions?

You seem to need two relations/references; one to connect clients with counselors, assuming that doesn't change for each new session, and then a session node (Session Content type) related to either the client or the councelor, depending on what makes more sense in your case.

Or you might orient it around sessions, where you have two user reference fields, one to the counselor and the other to the client. Although that seems less likely to make sense.

If the hours is the only thing that needs to be recorded maybe you can get away with only the reference between counselor and clients, with the added Hours field to the reference field, with unlimited values so with each new session another value is added. You can use Views to summ them up.

You haven't said anything about privacy and permissions requirements and how the data is maintained. There are modules that can control access through references made between entities. Maybe explore that to find the right combination for you.

Group module can also be used, although it may be an overkill depending on your requirements.

Which modules/structures to use and build becomes obvious once you have all your requirements clarified.