cannot get custom Omega stylesheets to load responsively I have an HTML5 Omega 3 subtheme. I'm using the responsive grids, and Omega's (Alpha's) -wide -normal etc. css files are working.

But I can't get mine to. I have read the handbook and the wiki to no avail.

In mytheme/css I have

global.css
mytheme-alpha-default-normal.css
mytheme-alpha-default-wide.css

In my mytheme.info file I have

css[global.css][name] = my global stuff
css[global.css][description] = blah
css[global.css.less][options][weight] = 10

css[mytheme-alpha-default-normal.css][name] = my normal stuff
css[mytheme-alpha-default-normal.css][description] = blah
css[mytheme-alpha-default-normal.css][options][weight] = 10

css[mytheme-alpha-default-wide.css.less][name] = my wide stuff
css[mytheme-alpha-default-wide.css.less][description] = blah
css[mytheme-alpha-default-wide.css.less][options][weight] = 10

And I've enabled these in the Omega settings for the theme.

What happens is that all these stylesheets are loaded like the global one -- without any media query conditions at all, just like they were all global styles.

I've tried un-checking them. This just removes them. I've tried removing them from the .info file; this just removes them entirely too.

Can anyone help?

There's something odd about what you wrote in your question, because you mention *.less files. I'd expect to see just .css. Are they really .less?

But more importantly, you should not add css[] lines in the .info file for your width-specific css files. That makes them regular CSS files that will always be loaded. They will be listed in the list of CSS files, and can be turned on and off, as you see.

Take a look at the starter-theme .info file (e.g., starterkit_omega_html5.info), and you'll see that there are css[] lines there only for global.css, and not for any of the width-specific files.

Take those lines out. Omega will automatically generate loads for the width-specific files. It looks for the files based on the name pattern, and loads them with the appropriate media queries.

If the width-specific files do not appear at all in your page output with media queries, then there may be something wrong with your naming of the files. One common problem is that if your theme name has an underscore (e.g. "my_theme"), then the filenames must have dashes ("my-theme").

One other oddity to know is that the width-specific files for all the widths narrower than the browser width are loaded. So, for instance, if your browser is at "normal" width, the global, narrow, and normal width CSS files will all be loaded, in that order.

MORE:

Don't forget to check the box "Enable the responsive grid" in the theme settings, and also check the box "Use this layout with the responsive grid" for each width you want to include

You should see something like this in every page that's output:

....
@import url("http://yoursite.com/sites/all/themes/mytheme/css/global.css?lxt4yy");</style>

<!--[if (lt IE 9)&(!IEMobile)]>
<style type="text/css" media="all">@import url("http://yoursite.com/sites/all/themes/mytheme/css/mytheme-alpha-default.css?lxt4yy");
@import url("http://yoursite.com/sites/all/themes/mytheme/css/mytheme-alpha-default-normal.css?lxt4yy");
@import url("http://yoursite.com/sites/all/themes/omega/alpha/css/grid/alpha_default/normal/alpha-default-normal-12.css?lxt4yy");</style>
<![endif]-->

<!--[if gte IE 9]><!-->
<style type="text/css" media="all and (min-width: 740px) and (min-device-width: 740px), (max-device-width: 800px) and (min-width: 740px) and (orientation:landscape)">@import url("http://yoursite.com/sites/all/themes/mytheme/css/mytheme-alpha-default.css?lxt4yy");
@import url("http://yoursite.com/sites/all/themes/mytheme/css/mytheme-alpha-default-narrow.css?lxt4yy");
@import url("http://yoursite.com/sites/all/themes/omega/alpha/css/grid/alpha_default/narrow/alpha-default-narrow-12.css?lxt4yy");</style>
<!--<![endif]-->

<!--[if gte IE 9]><!-->
<style type="text/css" media="all and (min-width: 980px) and (min-device-width: 980px), all and (max-device-width: 1024px) and (min-width: 1024px) and (orientation:landscape)">@import url("http://yoursite.com/sites/all/themes/mytheme/css/mytheme-alpha-default.css?lxt4yy");
@import url("http://yoursite.com/sites/all/themes/mytheme/css/mytheme-alpha-default-normal.css?lxt4yy");
@import url("http://yoursite.com/sites/all/themes/omega/alpha/css/grid/alpha_default/normal/alpha-default-normal-12.css?lxt4yy");</style>

<!--<![endif]-->

<!--[if gte IE 9]><!-->
<style type="text/css" media="all and (min-width: 1220px)">@import url("http://yoursite.com/sites/all/themes/mytheme/css/mytheme-alpha-default.css?lxt4yy");
@import url("http://yoursite.com/sites/all/themes/mytheme/css/mytheme-alpha-default-wide.css?lxt4yy");
@import url("http://yoursite.com/sites/all/themes/omega/alpha/css/grid/alpha_default/wide/alpha-default-wide-12.css?lxt4yy");</style>
<!--<![endif]-->


Getting errors trying to upgrade Commerce Kickstart 1.24 to 1.34 I’m trying to upgrade my install of Drupal Commerce version 7.x-1.24 to 7.x-1.34 but am getting an update failed notice that reads:

Commerce_kickstart-7.x-1.34-core.tar.gz does not contain any .info files.

but when opening that package i see there is indeed an info file, Commerce_Kickstart.info

I’ve been Googling this message to see if other’s are having the same issue but curiously i’m not finding anything.

Is doing this manually an option? if so, do i just replace what is in the profiles folder?

I always did this manually.
You don't need to replace whole profiles folder. Replace commerce_kickstart folder inside profiles only if you have not hacked or changed any file within. If you have changed any module or theme file. First move the folder to sites/all/modules or sites/all/themes folder, then replace that and run update.php.


Form With Inline Input Boexes I am trying to create a form that will have the input boxes inline and next to one another. I have created the following module but nothing seems to help. Can anyone help to solve this issue? Also the form doesn't seem to be reacting to changes in the size parameters.

function name_search_block_info() {
    $blocks['name_search'] = array(
        'info' => t('Name Search Block'),
    );
    return $blocks;
}

function name_search_block_view($delta='')
{
     $block = array();
     switch($delta)
     {
        case 'name_search':
          $block['subject'] = t("Search Form");
          $block['content'] = "
".drupal_render(drupal_get_form('name_search_custom_search_form'))."
";
          break;
     }
     return $block;
 }

function name_search_custom_search_form($form_state) {
  $form = array();

  $form['keyword'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#attributes' =>array('placeholder' => t('Search')),
    '#maxlength' => 64,
    '#size' => 32,
    '#required' => TRUE,
    '#id' => 'searchfield',
    '#prefix' => '
',
    '#suffix' => '
',
  );
  $form['location'] = array(
    '#type' => 'textfield',
    '#required' => TRUE,
    '#attributes' =>array('placeholder' => t('Zip')),
    '#maxlength' => 5,
    '#size' => 7,
    '#required' => TRUE,
    '#id' => 'locationfield',
    '#prefix' => '
',
    '#suffix' => '
',
  );

  $form['#submit'] = array('name_search_custom_search_form_submit');

  return $form;
}

function name_search_custom_search_form_submit($form, &$form_state) {
  $redirect_url = 'search/node/';
  $redirect_url .= 'type:' . $form_state['values']['type'];
  $redirect_url .= ' category:' . $form_state['values']['category'];
  $redirect_url .= ' %' . $form_state['values']['keyword'] . '%';

  $form_state['redirect'] = $redirect_url;
}

No need to add prefix/suffix markup, just add a container or fieldset and use CSS to float them inside.


Multipage form progress indicator How would I go about adding a progress indicator to my multi page form?

So for example, I would like to have a Heading at the top of each of the form pages/stages. I would like them all to be displayed at all times, but with a "status box" or something similar next to each status, which changes once a certain stage has been completed (all the mandatory fields have been populated).

Any advice on how to achieve this?

Taken from Bala's answer.  I had to do a great deal of work on the code before it worked so I thought I'd paste my corrected code here:

Copy sites/all/modules/webform/templates/webform-form.tpl.php to your sites/all/themes/ folder so that you don't hack the original tpl.

In the sites/all/themes//webform-form.tpl.php copy add the code:

<?php
    if($form['details']['page_count']['#value'] > 1){
        $output_pagenum = '
Page '
            . '' . $form['details']['page_num']['#value'] . '' . ' of '
            . '' . $form['details']['page_count']['#value'] . '';
        echo $output_pagenum . '
';
        // End of custom code
    }

  // Print out the main part of the form.
  // Feel free to break this up and move the pieces within the array.
  print drupal_render($form['submitted']);

  // Always print out the entire $form. This renders the remaining pieces of the
  // form that haven't yet been rendered above.
  print drupal_render($form);

Then in your js file:

//Progress bar for webforms.
    var actual = $('.actual').text(); //Get the value of the actual page.
    var total = $('.total').text(); //Get the value of the total of pages.

    if(total > 1) { // check if is a single page form and the webform has no breaks
        var percentage = (actual/total)*100; //Divides the actual value between all the pages.
        percentage = percentage + '%';
        var progressbar = '
'
         + '

';

        $('.page-count').append(progressbar);
        $('#progressbar').css('width', percentage); //Depending on which page break youre on modifies the width of the progress bar.
    }

    //End of Progress Bar


How to build a field list in a node? I have two content types: 'artist' and 'venue'.

When an artist node is viewed, it needs to display a list of venues and dates. Venue name will link to the venue node eg:

Artist
--------------------
Venue1 | 1-Jan 20:00
Venue2 | 2-Jan 17:00
Venue3 | 4-Jan 20:00

The possible solutions are:

Create a 'performance' content type that links (using the References module) to artist and venue, and has a date field. Then attach the list using Views. This seems like a lot of extra work for the editor.
Add two unlimited value fields to artist node: reference to venue and date field. It is difficult to keep them in sync and clunky.
Would this be a good use of the entity API? I don't know enough about entities yet, but have a feeling that would be overkill for something so simple?

Are you looking for Field Collection?
You can create collection with Node Reference field and Date field. Then Field Collection Table will help you with outputting.
This exactly works with Entity API.


Upgrading and creating entity references I have a Drupal 6 site which I plan to upgrade to Drupal 7, but I would like to do some alterations to one of the content types on the upgrade.

When I built the site I did not use D6 Node References on a content type when I probably should have; for example, instead of referencing a company content type containing fields for its name and website, I just have two plain fields, company name and URL.  I would like to find a way to fix this on the 'new' site.

Do I try to fix this on the Drupal 6 site then do the Drupal 7 upgrade, do the upgrade and then create the D7 entity references, or can I, as part of the upgrade, build the entity references automatically?

I'm not planning on doing a Drupal 7 or Drupal 8 data migration, so that option is out.

If you attempting a Drupal 6 to Drupal 7 update without migration, you want to keep the structures as simple as possible since minimizing rough edges. Therefore, I would wait until after the update.

Once the site is upgraded, I would update the content types involved, and then write a simple custom module that creates a batch job for the conversion.


Call $created variable in content type node template How can I call the $created variable in my content type node template? I tried the following but it just produces what seems to be a random string of numbers:

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

The $created variable is just a number, but it's not random it is a unix timestamp of the node created date.

Since it is not a render array you do not print it using the render() function, you would just print it like this:

<?php print $created; ?>

However that is also probably not what you want because you probably want a human readable date/time, not a unix time stamp.

As you can see in the main variable preprocess function for the node template (template_preprocess_node()), there is also a variable $date, which is a formatted date based on the $created variable.
That will default to using your website's medium date format.

You can use it like this:

<?php print $date; ?>

If that is not the format you want you can also manually use the format_date() function to format it to your requirements like this:

<?php print format_date($created, 'short'); ?>

or like this for something more custom:

<?php print format_date($created, 'custom', 'd/m/Y'); ?>

See the php date() documentation for more information on custom date format options.


Loading content alone for each page from drupal to other site? How to load only content in a page (exclude header & footer) from once specific drupal site to another non-drupal site page.

Like, if I click on link on non-drupal site it should open up drupal content of respective link page without header and footer in a new popup.

I know Iframe and webservice are options to do.

Is there any other way to load content for specific page in drupal to non-drupal site ? Thanks in advance.

You could create a custom HTML template that would remove the HTML tags but that would render on a certain URL. However, that would make that URL every time it rendered. Web services are your best bet rendering the information an XML format. Below is the services module for Drupal 7

https://www.drupal.org/project/services


Organic Groups - Group members list (with content profile) with views http://ruh.kz/groups/ruhkz under the title - Участники группы - is placed a view block that displays members of this group. I've used a default view → og_recent_members, but it doesn't works for content profile. I need to display a CCK field from content_profile module.

Tried to set in filters - content type:profile, and in fields selected Content:field_photo, but it doesn't works. Displays nothing.

How to display CCK imagefield (Profile Photo) instead of usernames in og_recent_members views block?

In the view add a new relationship
1.) Select node and then content profile->corresponding content type, which creates a relationship.
2.)Now in the fields add your content profile fields u want to display. here select the relationship content profile.
Now you should have your profile fields coming from content profile.


How to create main links like home ,services programatically? I am creating a new website in Drupal 7,but from my past efforts I tried adding main menu links(home,services,clients,blog etc)but all in vain!!

Can anyone tell me how to create main menu links programmatically or through admin interface?

// You can use the following code to create a menu.

// Path.
$path = 'admin/structure/menu/manage/';
// Title of your menu.
$menu['title'] = 'My Another Menu';
// Description.
$menu['description'] = 'My Another Menu';

// Manu name like navigation, management which we have in drupal.
$menu_name = 'custommenu';
$menu['menu_name'] = $menu_name;

// Link title.
$link['link_title'] = 'My Another Menu';
// Link path.
$link['link_path'] = $path . $menu_name;
// Router path.
$link['router_path'] = $path;
// Module name.
$link['module'] = 'menu';
$link['plid'] = 0;

// Saves a menu link.
menu_link_save($link);
// Saves a custom menu.
menu_save($menu);

// After creating main menu. You can create links under it.
// Use the below code to create custom links.

$item_link = array(
  'link_path' => '<front>',
  'link_title' => 'Test link',
  'menu_name' => 'custommenu',
  'weight' => 0,
  'expanded' => 1,
);
// Creates custom link under main menu.
menu_link_save($item_link);


Setting text formats programatically I have defined a new content type, that just has a body field, which I define in my install file:

$type = array(
        'type' => 'status_update',
        'name' => t('Status Update'),
        'module' => 'socmed',
        'base' => 'node_content',
        'description' => t('A Facebook-like status update.'),
        'has_title' => FALSE,
        'custom' => TRUE
        );

    // Turn off comments.
    variable_set('comment_status_update', 0);

    // Fill in remaining defaults, add a body field and save the node type.
    $type = node_type_set_defaults($type);
    node_add_body_field($type);
    node_type_save($type);

I would now like to

a) Create a new text format.

b) Assign that text format to be the default for this content type's body.

c) Set permissions on the text format for normal authenticated users, so that this text format is the only option.

I want to package this up as a module, so I would like to do so programatically, but I'm not sure how to go about it. Any pointers on any of these steps? Thanks!

You're going to want to create your new input format separately (probably in a module), assign it to the fields in your content type, then export the fields again and bundle in your module.

Not knowing how complex your new input format is, best advice is to grab the examples module and check out the filter_example module for a good test case of how to create a new input format.

Once you have the input format created, go back to your content type and under "Structure > Content Types > Manage Fields" set the default input format for these fields to your new input format and export your fields to your module.


Replace default words in exposed filters I created an exposed view that allows users to sort content based on content type or date. In my content type drop down menu, the default choice is - Any -, I tried to replace it in the settings file's string override section, but while this works for numerous other defaults, it doesn't seem to be taking for exposed views. Any help would be much appreciated!

I have tried to resolve from backend/server side, but without success, so I have reviewed a way using Jquery (client side), while an backend alternative is achieved:

<script>
$("#here-field-name option[value='All']").html("Anytext");
</script>

Also, here is alternatives from backend perspective, maybe are useful for you how to default value to select list CCK with form_alter

I hope information be useful.


Commerce First Data Module I am working with Drupal Commerce to create an e-Commerce store. However, I am having some trouble with my client's gateway of choice, First Data.

I have everything set up as directed (I believe) but when I try to submit an order the page times out and I am given this error message. (This happens if I am testing a transaction live, test authorized, or test denied)

PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone away:

INSERT INTO {watchdog} (uid, type, message, variables, severity, link, location,
referer, hostname, timestamp) 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, :db_insert_placeholder_6,
:db_insert_placeholder_7, :db_insert_placeholder_8, :db_insert_placeholder_9);
Array ( [:db_insert_placeholder_0] => 0 [:db_insert_placeholder_1] => php
[:db_insert_placeholder_2] => %type: !message in %function (line %line of %file).
[:db_insert_placeholder_3] => a:6
{s:5:"%type";s:6:"Notice";s:8:"!message";s:27:"Undefined index:
order_num";s:9:"%function";s:33:"firstdata_cc_submit_form_submit()";s:5:"%file";s
87:"/home/betads/public_html/sites/all/modules/commerce_firstdata/commerce_firstd
ta.module";s:5:"%line";i:380;s:14:"severity_level";i:5;}
[:db_insert_placeholder_4] => 5 [:db_insert_placeholder_5] =>
[:db_insert_placeholder_6] => https://beta.designsenseinc.net/checkout/7/review
[:db_insert_placeholder_7] => https://beta.designsenseinc.net/checkout/7/review
[:db_insert_placeholder_8] => 166.147.79.6 [:db_insert_placeholder_9] =>
1330630525 ) in dblog_watchdog() (line 157 of
/home/betads/public_html/modules/dblog/dblog.module).

Any idea what could be the issue? To test for yourself, you can visit http://beta.designsenseinc.net/product/853 and add the product to cart.

Any help appreciated.

watchdog is trying to save an error log and database fails (probably too many error logs ?).
you might try to select showing errors on screen or sending them to syslog - you would probably get rid of the rying database and could diagnose the original problem :).

the original error seems to be undefined index on line 380 of commerce_firstd
ta.module


What is the best way to add my custom PHP functionality to a Drupal homepage? I have a custom PHP application I've written that accesses an API via SOAP, processes some data from the web service, and outputs an HTML table with the results. I'm an experienced WordPress developer and have been able to add my application's functionality into WP sites by creating A custom theme and adding the PHP/HTML code directly into the homepage template.

I now have someone asking me to add this to a Drupal site (v 7.34) - the end goal is to have the HTML table that the application outputs display on the Drupal site's homepage. The site is running the Porto 2.0.3 theme if that makes a difference.

I am pretty new to Drupal and I'd like to know what the best way to accomplish this is. I looked into adding PHP directly into a block, but my application consists of 2 files (an API class and the actual code that produces the output) so I'm not sure that's a good option.

My searching leads me to believe that creating a custom module is the best path (especially since I don't want future updates to the Porto theme to break the functionality) but I'd like to confirm that before I wander down that path. Or is is better/easier to override the homepage template to add my code?

I'd really appreciate some advice from experienced devs - not looking to be spoon fed and perfectly willing to do my own research, but a helping hand from people familiar with this system would be a huge help.

The best way forward is to go ahead and create a new module. You can find the steps from this link .It also shows you how to create a block from code.

You can add your files in the module and then make a function call which returns the table and add it as your block content. You can then include your block in the home page from admin interface in any region that you want it to be.

Hope it helps.


Switching to mobile theme while cache is enabled I have a Drupal7 website using a modified Zen subtheme that looks ugly on mobile devices and i want some kind of utility to create a separate mobile theme .
I tried to use differents modules like Mobile Switch,Mobile Detect ,Mobile Tools & Theme Key but unfortunatley they don't support Drupal Default Cache .
Is there any way or method or another module to resolve this problem.
Thank you very much

ThemeKey does support the Drupal cache.

However, the Drupal cache cannot perform device specific cacheing on a single domain since page caches are organized by absolute URLs. See this discussion for an explanation: https://www.drupal.org/node/2242303

The solution is to have a device redirect at the server level to a mobile subdomain (ie. m.mysite.com) which shares the same docroot and switches the theme there. The Boost module is recommended and the process is outlined here:

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


How can I display the of result count of a view in its header? Without writing using any Drupal db functions, how can I display the total/count/number of results of a view in its Header?

Do you not mean these predefined value(s) in the Header area ?

Return a view's total_rows in Drupal 7 without php filter?

You could count the number of rows using PHP in views_pre_render() ... but I bet this is what the above is doing already ....


How can I remove self-closing source tags when rendering HTML markup? I use this markup in a node body.
<video>
  <source src="myvideo.mp4" type="video/mp4" />
  my title
</video>

The following markup is instead rendered in the node view.
<video>
  <source src="myvideo.mp4" type="video/mp4" />
    my title
  </source>
</video>

</ source> is added to the markup, and renders the full HTML not valid.
How can I avoid </ source> is added?

I use this code for replace < /source> in theme
  $content_this =  render($content['body']);
  print str_replace("</source>","",$content_this);

in node.tpl.php


How to add field in field I have a content type with text field (unlimited). Text field is limited to 250 chars and will be used to put names inside
User can choose as many fields as they want depending on how many names they have for this node.

What i would like to do is to let users upload image next to text field.. if they chose 15 text fields, then they can also upload 15 images, but each image connected to its text field.

I think you're looking for the Double field module.

  Double field is a small module written to provide extensions to Drupal's core Fields. By this module you can divide your fields into two seporate parts. For the moment it includes the following sub-widget types:

  Textfield
  Select list
  Single checkbox
  Textarea Consequently, in all there are 4 x 4 = 16 widget types.

Currently it is not supporting file upload. However, you can make this as support request in that module's issue queue.


Run a boolean test function on form submit Is there a way to run a function when a user submits a form in Drupal that returns a true or false. If it is true, run the submission handler. If false, return an error.

Application:

I am using Drupal to run a product booking system. If a product is reserved during a certain period of time, it is not available to others. The client wants the customer to be able to change the dates of the their order. This is fine. The order creates a reservation node and with permissions and hook_form_alter, I set it up so that they can edit the reservation dates.

However, I don't want them to be able to change the dates to whatever they want without first checking to see if it is already reserved. I have already written the code to run a query and return a boolean based on whether or not there is a booking conflict. Now I just need to be able to use that on the form submission handler.

You should do this in validation handler. In hook_form_alter (or in your form definition function), add $form['#validation'][] = 'mymodule_form_validate';. Then, add this code:

function mymodule_form_validate($form, &$form_state) {
  if (!mymodule_dates_valid($form_state)) { // Return boolean here.
    form_set_error('date_field', t('Invalid dates'));
  }
}


Open Atrium 2: comment forms not appearing on pages Situation:

Recently created a fresh Open Atrium 2 installation to replace an old AO1.
No content from the old OA1 database has been migrated, we're making a fresh start. Some content (a few pages) will be recreated by copy-pasting the content.
No anonymous access allowed, only authenticated users have acces to any content. Only admins can create user accounts.
As of yet, no groups and teams have been made -- there's only a handful of users. The actual userbase will be small enough that it can be managed simply by giving individuals access to certain spaces; groups and teams may be made later if the need arises. (I'm still partially in OA1 mode, really :) )

Problem: Comment forms do not appear anywhere in the site, for any user level (authenticated, editor, admin).

I have:

checked whether the required comment modules are enabled (they are)
checked permissions; authenticated users can view & post comments, skip approval & edit their own comments
made sure commenting is enabled for that content type (it is by default, no settings changed there)
made sure it's not simply a matter of permissions not being retroactive. Newly created content still has the same problem, though.
checked individual nodes (in this case, calendar events) to make sure comments are open
spent several hours googling, but found nothing beyond the things I've already tried.

Most likely I'm simply overlooking one little setting somewhere, but right now this has me stumped... Any pointers would be highly appreciated.

I believe you need to add the comment box via panels. Admin > Configuration > Content Authoring > Panelizer > Content [link to the right of Your Content Type]


Last articles in front page I'm using Drupal 8 and I created a global layout with a custom theme I coded myself, and I added a custom content type for the home page. I have almost exactly what I want except for the following points.

I should have a block somewhere in the home page containing the last 3 articles posted on the website, and of course, a link to each of these articles. How am I supposed to do that? All answers I found were talking about Drupal 7.
I'm supposed to do the same as the last articles but for photos albums. I guess I have to use a module,  do I?

You can use thw Views module, which is a Drupal 8 core module.
On admin/structure/views you can create a new view, even a block view. You can select which content type you want to display, the fields that should appear, and add all your limitations. After you save the view, on /admin/structure/block you can place the block on your preferred region.
If you have a content type for the photo albums, you can do exactly the same.


How to achieve triggered redirect after log in so that administration interface will be available on the redirected url? I would like to ask for an advice. Recently, I was developing a conference site with Drupal 7. The site is hosted at domain1.com. However, the conference is covered by another organization and they require that conference page will be accessible from their own domain something like.: organization.com/conference2014 Fortunately, Drupal has base_url parameter and the site is accessible from organization.com/conference2014 domain. BUt, my problem is when I want to access administration interface of Drupal through organization.com/conference2014?q=user/login I get redirected to organization.com site which is administrated by the organization admin. Moreover, when I access again organization.com/conference2014 - it still asks me for the password.

I got adviced to introduce trigger after the user successfully logs in to the site organization.com/conference2014. It does redirect me but the administration interface/overlays is not there. Any ideas how to tackle this problem?

Martin

Try Login Destination , it will redirect you to the destination

  module allows you to customize the destination that a user is
  redirected to after logging in, registering to the site (7.x), using a
  one-time login link or logging out (7.x).

  The destination can be an internal page or an external URL.

  It is possible to specify certain
  conditions like referring pages or user roles and make the destination
  depend upon them. You may use PHP snippets to provide custom
  conditions and destinations.

  It is also possible to keep users on the
  currently visited page after logging in or out.

also take a look at Login Redirect module


How do allow an exposed filter to override another filter in Views? I have a view that display content on the site. I have the following hidden filters on it:

Published: Yes
Posted Date: Relative 'today'

Then I want to add a second Posted Date filter but expose it for a user to enter their own custom dates Is between Start date and End date. I then want the view to ignore the hidden exposed filter that is set to 'today' and use the user defined dates.

EDIT:

The default one is a relative date format and the exposed one is to be a jquery date popup.

Thoughts?

You can modify the view paramteres implementing hooks_views_pre_build. There you can examine received data (for example, checking $_GET) and modify view filters, deleting the "Posted Date: Relative 'today'"filter.

function mymodule_views_pre_build(&$view) {
  if ($view->name == 'my-view') {
    if (must_delete_filter()) {
      unset($view->filter['posted_date_relative_filter_name']);
    }
  }
}

So Views is executed without that filter. In example code must_delete_filter is the function that decides if filter must be deleted or no.


Complex form - merge of two with single callback I have a complex form of two logical parts, which I have placed in different  functions (my_module_partner_form & my_module_fields_form). Both forms have submit handlers (my_module_partner_form - 1 submit, my_module_fields_form - 2 different submits). I would like to display those on one page.

So my solution was the following:

Create a menu item like the following:

$items['complex-form/%/%/%'] = array(
    'title'         => 'Complex Form',
    'page callback'     => 'drupal_get_form',
    'page arguments'    => array('my_module_complex_form', 1, 2, 3),
    'access callback'   => 'my_module_complex_form_custom_access',
    'access arguments'  => array(1, 2, 3),
    'type'          => MENU_NORMAL_ITEM,
    'file'          => 'includes/some_file.inc',
);

Create a callback function to handle it

function my_module_complex_form($form, &$form_state, $param1, $param2, $param3)
{
    // ... some irrelevant code here ...

    $form = array();
    $form = drupal_get_form('my_module_partner_form', $someParam);
    $form += drupal_get_form('my_module_fields_form', $someParam);

    return $form;
}

Here are the forms itself (code obfuscated)

function my_module_fields_form($form, &$form_state, $param1)
{
    // ... some irrelevant code here ...

    $form['save_all'] = array(
        '#type'     => 'submit',
        '#value'    => 'Update',
    );
    $form['save_with_no_changes'] = array(
        '#type'     => 'submit',
        '#value'    => 'Save with no changes',
    );

    return $form;
}

function my_module_partner_form($form, &$form_state, $param1)
{
    // ... some irrelevant code here ...

    $form['save_profile'] = array(
        '#type'     => 'submit',
        '#value'    => 'Save contact details',
    );

    return $form;
}

SO, the question is: what am I missing, as the submit function for each of the functions (except for the my_module_complex_form_submit - why?) is being called, but I can not identify which button was clicked.

What I have already tried, not to waist your time:

reading $form_state['clicked_button']['#value'] - always the same - "Update".
creating custom #submit elements for each button - this will not work as I only need one handler to work each time. Please correct me if I missed smth in the workflow.

Any ideas welcome.

When you submit a form, either by clicking a button or pressing enter, the first (by default) submit button is assumed clicked, that's why the value is always "Update".

When you submit a form, every enabled element of the form is submitted, so the #submit parameter doesn't do for you.

The complex_form_submit is not executed because you are building it using two forms with their own _submit. This way, the drupal_get_form() call doesn't link the complex form submit to the complex form.

ok, because of the reasons above, you can't proceed like that, but you still have several options:

option 1

I'm assuming that when you save, you're looking for the #value of some select/textfield/etc of your field_form, but when you save without changes, you use the #default_value of said elements for example.

If this is the case, can you consider the option to turn the save_without_change button from a submit to a reset button?

This way, the user will revert all changes to the form elements, then click on save, and you will only need one _submit callback that just save the #value.
You should still split field and partner forms like shown at the bottom of page anyway.

Drupal wont let you create reset buttons, but you can specify one like this:

$['reset'] = array( '#markup'=>'<button type="reset">Revert changes</button>');

if #markup doesn't work, use #prefix instead.

option 2

Split the field form into two forms.

The save form will be exactly like the field one, but with a button less.

The save without changes form instead, will only have the missing button, and will store the form parameters or default values you need into elements like:

$['#val1'] = $val1;

that wont be rendered, but that you can use inside its submit for its logic.

option 3

if you really want to keep the field form like that, the only workaround i can think of is adding a hidden checkbox to your field form, and adding an onclick event to one of the two save buttons.

The event will call a JavaScript function that change the checkbox value.

Later on, inside your field_form_submit, you can use the checkbox value to evaluate which button was clicked and execute the correct logic.

downside: JavaScript have to be enabled.
you still split partner and field forms.

split

The problem here is that the two "sub" forms don't really exist anymore, they are rendered as one, which you should be able to confirm inspecting the resulting html.

If you need that only one submit is sent, don't mix them up.

Use my_module_complex_form as page callback, fix arguments accordingly, and inside render each form with drupal_render():

function my_module_complex_form(.....)
{
  // ... some irrelevant code here ...

  $f1 = drupal_get_form('my_module_partner_form', $someParam);
  $f2 = drupal_get_form('my_module_fields_form', $someOtherParam);

  $page = drupal_render($f1);
  $page .= drupal_render($f2);

  return $page;
}


Entity reference count in a parent node I have two content types

For example say X and Y

Every Y should refer any one of the X . I want to display how many number of Y is refering a particular X while viewing the X node. Please suggest some module which direclty achieve this requirement.

You can either use Views and Aggregation to Sum the number of references to show on a list.

But, I recommend using the Computed Field module to write some PHP code that is run on save to store an integer value that is the count of references. This value can be cached by drupal and used within Views and other modules.

  Computed Field is a very powerful field module that lets you add a
  custom "computed fields" to your content types. These computed fields
  are populated with values that you define via PHP code. You may draw
  on anything available to Drupal, including other fields, the current
  user, database tables, you name it. (Feeling the power yet? :) ) You
  can also choose whether to store your computed field values in the
  database with other content fields, or have them "calculated" on the
  fly during node views. (Although you should note that Views use
  requires database stored values.) This field is literally the Swiss
  Army knife of fields. So start cooking up your PHP based values!


How do I display the attachment's file size of a node? Is there any way in Drupal 7 to display the attachment's file size of a node through the manage file / display of the file field, or is this programmatically achieved?

You can do this hardcoded with the $node object by doing so (preferably in theme_preprocess_node in template.php) :

If you field field_my_field as a single value :

$file = field_get_items('node', $node, 'field_my_file');
if ($file) {
    $file_size = $file[0]['filesize'];
    $file_size_formated = format_size($file_size);
}

If you field field_my_field as a multiple value :

$files = field_get_items('node', $node, 'field_my_file');
if ($files) {
    $files_size_formated = array();
    foreach ($files as $key => $file) {
        $file_size = $file['filesize'];
        $files_size_formated[] = format_size($file_size);
    }
}

In template.php you should have something like this :

// This function allow one preprocess_node function per content type
function mytheme_preprocess_node(&$vars) {
  $node = &$vars['node'];
  // Preprocess function for each node type
  $function = __FUNCTION__ . '_' . $node->type;
  if (function_exists($function)) {
    $function($vars);
  }
}

function mytheme_preprocess_node_my_content_type(&$vars) {
  $node = &$vars['node'];
  $file = field_get_items('node', $node, 'field_my_file');
  if ($file) {
      $file_size = $file[0]['filesize'];
      $vars['file_size_formated'] = format_size($file_size);
  }
}

Then in you node--my-content-type.tpl.php you can print your var $file_size_formated where you want like this for example :

<?php print $file_size_formated; ?>


Validate and submit function for my fom aren't working So I'm trying to create a form with a validate and submit function, here is my code :

the form :

    function custom_form() {
      $form = array();
      $form['field1'] = array(
        '#type' => 'textfield',
        '#title' => t('Field1'),
        '#required' => TRUE
      );
      $form['field2'] = array(
        '#type' => 'textfield',
        '#title' => t('Field2'),
        '#required' => TRUE
      );
      $form['field3'] = array(
        '#type' => 'textfield',
        '#title' => t('Field3'),
        '#required' => TRUE
      );
      $form['submit'] = array(
        '#type'=>'submit',
        '#value'=>t('Submit')
      );
      return $form;
    }

the validate function :

    function custom_form_validate($form, &$form_state) {
      if(empty($form_state['values']['field1']))
        form_set_error('field1','field1 is empty.');
      else if(empty($form_state['values']['field2']))
        form_set_error('field2','field2 is empty.');
      else if(empty($form_state['values']['field3']))
         form_set_error('field3','field3 is empty.');
    }

and the submit function :

    function custom_form_submit($form, &$form_state) {
       drupal_set_message("Form has been submitted");
    }

But when I click on submit nothing appends, do I forget something ?

EDIT :
Here is all my code (I'm using shortcode module to create a custom shortcode in order to show my form)

    function custom_form_info() {
      $shortcodes['form'] = array(
        'title' => t('Link form'),
        'description' => t('A simple form.'),
        'process callback' => 'custom_shortcode_form',
      );
      return $shortcodes;
    }

    function custom_shortcode_form($attrs, $text) {
      $form = drupal_get_form('custom_form');
      $attrs = drupal_render_children($form);
      return $attrs;
    }

Add the following lines to your custom_form function:

$form['#validate'][] = 'custom_form_validate';
$form['#submit'][] = 'custom_form_submit';

Clear the cache afterwards and you will be good


How can I get my RSS feed to be Auto Discovered? Created an RSS feed in Drupal 8 using Views.  The feed is fine, but yet I don't have the discoverability icon show up in browsers.  Looking at the HTML source I don't see anything like this at all

I found this answer for Drupal 7 but doing "Feed Settings > Attach To > Master" had no affect.

Attach the Feed display to a valid Page display. The "Master" display may not be a valid page display.

An example of this can be seen in the default "Front Page" view. In this view, the feed display is attached to page_1, which is the page at the URL /node.

See the YAML export snippet from views.view.frontpage.yml below:

  feed_1:
    display_plugin: feed
    id: feed_1
    display_title: Feed
    position: 2
    display_options:
      sitename_title: true
      path: rss.xml
      displays:
        page_1: page_1
        default: ''


drush/drush dev-master requires codegyre/robo ~1.0.0-beta1 I'm transitioning a Drupal 6 site to Drupal 8.1 so following the official instructions, I set up a new install in its own directory. Since this is only one site, I followed the instructions to put my database credentials in sites/default/default.settings.php after the declaration of the $databases array.

Running drush --status returns the following.

Drush version          :  8.1-dev
Drush temp directory   :  /tmp
Drush configuration    :
Drush alias files      :
Drupal root            :  /media/psf/Home/apps/newp
Drupal Settings File   :  MISSING

Since this Drupal is 8.1-dev that must mean I need to upgrade it. Since this is a global install using Composer, I run composer global update.

  Your requirements could not be resolved to an installable set of
  packages drush/drush dev-master requires codegyre/robo ~1.0.0-beta1

Checking the drush-ops page on github doesn't show any anomalies like this nor my Google search.

What am I overlooking?

The dev/master branch of Drush is a development release, so it depends on non-stable components such as Robo 1.0.0-beta1. Composer will reject this component unless you have "minimum-stability": "beta" in your composer.json file.  Note that Drush itself has this setting, but if you include Drush from some other project (e.g. your Drupal site), then you will also need to set your minimum-stability in your project's top-level composer.json file.

Perhaps a more reasonable solution would be to run composer require drush/drush:~8, and use the stable release of Drush.

UPDATE

Drush master is now using the stable release of Robo ~1, so it should be easier to install Drush via composer require, at least for the time being. It is always possible that at some point in the future, though, the dev version of Drush may become dependent on features only available in some non-stable release of one of its dependencies, so you should always be prepared to set your minimum stability when requiring a dev version of Drush -- or any other Composer project.


Theme specific Drupal modules? Possible? Anyone know if it is possible to have Drupal modules enabled/active only when a current theme is present?

Working on a feature where I only need one module to be enabled when the site is accessed via a specific theme controlled by the ThemeKey module in Drupal 7.

Themes are enabled/disabled in Drupal by altering the flag in the database table system. And these settings are common for all the users irrespective of which device/ how they are accessing your page.

So in your case it is about making sure that only the files from necessary modules are loaded based on the current theme.

You can use $theme global variable to find out the current theme, and then based on that you can fetch the files from the necessary modules only. You can check the code from js module how the second part can be implemented. You need to have patience though ;)


Wildcard link for user menu I have a dropping menu links for the user menu:

My account

Profile edit
My posts (track)
Exit

Here's an example of my code:

<?php echo l(t("Profile edit"), "user/%/edit"); ?>

<?php echo l(t("My posts"), "user/%/track"); ?>

<?php echo l(t("Exit"), "user/logout"); ?>

I've tried with wildcard %. With a Views module was very easy, but in this case (without views) it's not working.
Is any other way so when user clicks on "My posts" will link to user/user_id/track or profile edit that will lead to user/user_id/edit?

You cannot use menu wildcards like that. You need to use the following code.

<?php echo l(t("Profile edit"), 'user/' . $GLOBALS['user']->uid . '/edit'); ?>

<?php echo l(t("My posts"), 'user/' . $GLOBALS['user']->uid . '/track'); ?>

<?php echo l(t("Exit"), "user/logout"); ?>

The global $user is the user object for the currently logged-in user. Be careful: It is not a fully-loaded user object. If you need that, you should use the value returned from user_uid_optional_load().


Display the day of the week I have a date field (field_date) and on the right of this field I have to display the day of the week

You can change how dates from date fields are displayed by changing it on the Manage display (/admin/structure/types/manage/[my_CT]/display) page for that Content type.

Custom date format for individual field

The quick and dirty way of doing it is by choosing Custom for Formatter and entering the code for the date, for example:

Y-m-d\TH:i:s, l

will give you "2019-09-09T17:30:19, Monday".

You can lookup the various date and time codes in the PHP manual:  https://www.php.net/manual/en/function.date.php

Overriding individual fields displays with custom date formats isn't the best way to go because you can't reuse it throughout the site, for other fields, or translate into other languages (different countries have different conventions about how to write dates).

Reusable Custom date format

The best way is to first add the new Date format to your site. This way you will be able to use anywhere where you can format Date output.

Go to Configuration > Regional and language > Date and time formats and Add a new format.

Name it so it makes sense to your case, enter the PHP date code you want into the Format string, select Language and add the format.

Now visit your Content type's Manage display page and change the Formatter of the Date field you want to affect to Default, and the Date format to the one you have just created.


How do you add custom help text to content entry/edit screens unrelated to field? I use field groups to break my fields into "tabbed" areas for my content editors. I would like to be able to put some kind of help text at the beginning of each of those blocks to explain the entire section of entry. Each of the fields already have their own help text, this would be above all the fields.

I usually do this with a form_alter myself in PHP code or I use the help entry for a Field.

Recently I found out about the Markup module. I recommend you try it out. I have no added it to any of my projects yet, but it's on my todo list.

  This module adds the ability for site admins to add "Markup" widgets
  to the form. These essentially let designers of cck content-types
  insert additional markup into the node/edit form to display to
  content-authors. This is the equivalent of adding additional elements
  to $form of the type '#markup'.

  The module does not add anything to the $node object for the content
  being created, and utilizes form_alter to remove unnecessary fields
  from the '_content_admin_field' form when this widget is being
  created.


Make a separate list of selected content Hi I am very new to Drupal. I want to make a restricted list of contents to show in a view. By default a view of certain content type brings all of the contents in it which I don't want. How can I accomplish this?

You can use Nodequeues to accomplish this really effectively.


Update same table using dynamic query in drupal 7 HiAll,

I want to execute below sql query using Drupal 7 PDO, But could not find a way to do,

SQL:

"UPDATE  `books`  AS a
  JOIN  `books` b  ON a.pid = b.pid
  SET  a. `status` = 'INACTIVE'
  WHERE   b.`pdays` * (36400) + b.`ptime_from` > 6546"

Drupal 7:

 $query = db_update('books','pb');
    $query->fields($update_values);
    $query->join('books', 'pc', 'pc.pid = pb.pid');
    //$query->condition("pc.pdays" * (36400) + "pc.ptime_from",$today ,'>');
   /* $query->expression('pc.pdays', 'pdays * :daytime + pc.ptime_from', array(':daytime' => '36400'),'>')*/
    $isbn_reds = $query->execute();

How can we write above SQL in D7 PDO?

To execute clauses like that you would use a where funtion. so your code would be something like

$query = db_update('books','pb');
$query->fields($update_values);
$query->where("b.pdays * (36400) + b.ptime_from > 6546");
$isbn_reds = $query->execute();


Error : No eligible views were found. Create a view with an Entity Reference display, or add such a display to an existing view I cannot work out some basic stuff ... what do I not correct?
Using D8, distribution varbase.

I  would like to create a reference from one content type to antoher in D8 so a user is able to use a select box by module chosen (https://www.drupal.org/project/chosen)

I looked up different post but cannot find the problem. The latest QA is followed is: How to create a select box field to select from a filtered list of articles?
or also this post How to create a view type of Entity reference display?

So I did I create a view

- Add Display Entity Reference
- Format:Entity Reference list | Settings with content: title
- Show:Entity Reference inline fields | Settings with content title.

Then I add some fields as well. The result is a list of education
Clear cache, did drush CR.

I goto to the content type I would like to have the reference (e.g. student).
Add a field and would like to add this view a a selectbox to object student.

I should be entity reference the in the reference field I select Views with a filter reference. But every time I get the message here...

No eligible views were found. Create a view with an Entity Reference display, or add such a display to an existing view.

The view list displays:
Nascholingsactiviteit voor leden  - Entity Reference Source

I made another view for testing purposes but no result of that as well.

I tried other fields but i cannot get it working. I though this is all in D8 core now... Any suggestions?

I solved it by chosing content as a reference. After that the options are the same but then it is displaying the view and it works.


Making a view with a node reference argument I have two content types, Contributor and Articles.  The Articles content type has a node reference field linked to the Contributor, so when someone creates an Article they can select a Contributor to reference.

On the Contributor nodes, I'd like to have a block view that shows Articles linked to that Contributor.  When I make the block view, how do I set up the argument, or is there a better way to do this?

you are almost there. Create a view with display type block for content type articles. Then add a contextual filter (called arguments in Drupal 6) and select the node reference field that links articles and contributors.
Select "Provide default value" and "node ID from URL". You can also validate it to make sure it's of the type "contributor".

Give the block a name and then go to "structure/blocks" and assign that block to a region and have it show up for all content type "article".


How to remove the webform title field on add/edit form? I am using bartik responsive theme. I made a sub theme of the theme. I enabled the sub theme as the default theme. I have given access to anonymous users to add webform content at xxx.com/node/add/webform. Users see the title field as required. I like to remove the title field of web form so users dont need to enter the title.

I found this link but I could not follow it all the way:

link.

"You need to have both node.tpl.php and node-webform.tpl.php in your theme directory for this to work. Also make sure you clear your Drupal caches after copying the files in."

I went to theme directory(theme/xx/templates) and I see bartik, engines, garland, stark, seven. I dont see my sub theme and bartik responsive there. What would be my theme directory in my case?

I simply went to theme/bartik/template> copied node.tpl.php to node-webform.tpl.php and then added

<?php if ($page == 0): ?>

<a href="<?php print $node_url ?>" title="<?php print $title ?>"><?php print $title ?>

<?php endif; ?>

I still see the web form title field for public users at xxx.com/node/add/webform.

Do you know how I can remove the title field for web form module?

If you don't mind installing another module:

Install Automatic Nodetitles
Go to admin/structure/types/manage/webform/auto_label
Select a default title and check "Automatically generate the label and hide the label field"
Profit!


How to clone any standard webform element I've been able to copy the example webform element, as detailed at Create webform element.

Although I've not tested submission yet, I think it's all looking good.

What would be great is if I could clone any of the standard webform elements.

I've made a copy of src/WeformElement/Email.php - and it appears in the list of webform elements available to be inserted into the webform - but when viewing the actual webform, it is not rendered.

It may be that I have to use the example webform element to create a new copy, and then change stuff in there to render an email field instead, but as mentioned I'd appreciate any pointers towards being able to clone any of the elements.

(The reason we need to clone them is due to styling. One text field might be used for a name, and another for a completely different purpose which will be styled differently, and as the cloned element has a new id then we can use the module Themable forms to provide more template suggestions.)

The WebformElement plugin acts as a wrapper around a Drupal Form element plugin.  Therefore to actually create a webform element you need to define a Form element plugin with a corresponding Webform element plugin.

If you want to extend the Email element you need to extend the below classes

\Drupal\Core\Render\Element\Email
\Drupal\webform\Plugin\WebformElement\Email

All you might missing is a \Drupal\custom_module\Element\CustomModuleEmail class which probably will look something like...

<?php

namespace Drupal\custom_module\Element;

use Drupal\Core\Render\Element\Email;

/**
 * @FormElement("custom_moduel_email")
 */
class CustomModuleEmail extends Email { }


How to manage video content including chapter markers and CC I'm building a site that has 46+ videos associated with it. I'm using Mediaelement.js. Each video has at least two language .srt files, a .vtt chapter marker file and two video sources, mp4 and WebM.

My project mananger says, "do it how ever is easier for you."

Part of me is tempted to upload all the files, then just copy-pasta the mediaelement code and change the file names. But this is laborous, time-consumming and prone to error.

As I'm writing this I think that I need to have a content type that has 5 or more "file upload" fields. How do I use the media module to my advantage?

Here's the solution I'm working on:

new Content Type: Video.

This content type has file fields for each file, two video type, up to 10 closed caption files, and chapter markers.

Then I add a node--video.tpl.php
Within the node template I'm then doing this:

 $mp4 = ltrim ($node->field_mp4_video[und][0][uri], 'public:/');
 $webm = ltrim ($node->field_webm_video[und][0][uri], 'public:/');
 $vtt = ltrim ($node->field_chapter_markers[und][0][uri], 'public:/');
 $encc = ltrim($node ->field_closed_captions[und][0][uri], 'public:/');
 $escc = ltrim($node ->field_closed_captions[und][1][uri], 'public:/');

ltrim trims the public:/ from the front of the string and printing that inside the video element:

<video width="100%" height="100%" style="width:100%; height=100%;" id="player2" controls="controls" >
  <source src="../sites/default/files/<?php print $mp4 ?>" type="video/mp4">
  <source src="../sites/default/files/<?php print $webm ?>" type="video/webm">
  <track kind="subtitles" src="../sites/default/files/<?php print $encc ?>"  srclang="en" />
  <track kind="subtitles" src="../sites/default/files/<?php print $escc ?>"  srclang="es" />
  <track kind="chapters" src="../sites/default/files/<?php print $vtt ?>"  />

Unsupported in this browser.

</video>

The un-solved issue is if there's more than the English and Spanish closed-captions. Certainly solvable, but probably outside of the scope of the project as currently budgeted.

Also, Drupal is throwing an error Notice: Use of undefined constant.... I'll tackle that in a separate question.


Displaying multiple fields in referenced webform option? First I have a content type Quiz option which represents one option (answer) for a webform question (field).

Then I have a (entity reference) view which is collecting specific number of nodes in this type. I got one argument to that view, which represents question id and when passed I'm getting all possible answers for that question.

And then I got a webform, where I have field of entity checkbox type where all options are referenced with that view. So webform field options are set like:

Type of item to reference: Content
Reference method: Views: Filter by an entity reference view
View used to select the entities: my view
View arguments: that question id

And all this works well - I'm getting the possible options from that view and as option titles node titles are displayed.

Basically if I create new node in "Quiz option" and select for it question id i.e. 1 then view referencing those node will also display it when question id 1 is passed and since question in my webform is using that view new option will appear as a new option under that option.

Now what I need is to display another field (image field) beside that title as part of an webform option. I've added image field to my content type. Then I adjusted my view so it also displays the image. But problem is that webform is still displaying only node title. New image field is ignored. Checked on "Display options" of my content type, but image field is not hidden there. So must be that webform module is responsible - it's displaying only referenced node title no matter what used view is returning.

Is there a way do configure my webform field to display this extra field for field options instead of only node titles?

The issue is coming from Drupal core and is fixed in Drupal 8.8.

@see Issue #2174633: View output is not used for entityreference options


How to use the value element to pass values internally from $form to $form_state['value'] I have a form and i want to pass some values without user see them.

At the beginning i was using the default values:

$form['field_devis_lien_fiche']['und'][0]['value']["#default_value"] = t("@path",array("@path" => $path));

It was working fine but it's not the behavior i wanted because all the user could see the value.

So i buy "pro drupal 7 developpment" and at page 283, he describe the element value and i think this is what i have to use.

$form['title'] = array(
 "#type" => 'value',
 "#value" => $titre,
);
$form['field_devis_lien_fiche'] = array(
 "#type" => 'value',
 "#value" => $path,
);

The $form['title'] works fine but all my other fields trigger an error.

Warning: array_values() [function.array-values]: The argument should be an array in _field_filter_items() (line 517 of ***/modules/field/field.module).
Warning: Invalid argument supplied for foreach() in text_field_validate() (line 119 of ***/modules/field/modules/text/text.module).
Notice: Undefined index: #language in locale_field_node_form_submit() (line 405 of ***/modules/locale/locale.module).

When i want to edit my content type, my value doesn't exist.

So i tried another solution with the hidden element:

$form['title'] = array(
 "#type" => 'hidden',
 "#value" => $titre,
);
$form['field_devis_lien_fiche'] = array(
 "#type" => 'hidden',
 "#value" => $path,
);

In spit of the fact that my hidden fields are created when i inspect the form, i have the same error again (with array_value problem)

i don't understand why it's works for the title field and why it's not working for my other field. And i don't understand too, why i have an error with the hidden field as they appears well when i inspect element with firefox.

Do i have to create a validation function because of my element value? Maybe i have forgotten a step...

Thanks for the help.

The problem is that you'll need to set the type of the correct element to value, and that isn't what you've got at the moment. Notice how you use:

$form['field_devis_lien_fiche']['und'][0]['value']["#default_value"]

To access the field the first time round (which you've confirmed to be working). Logically then, if you want to change the same field to a value type, you need to do so on the same element:

$form['field_devis_lien_fiche']['und'][0]['value'] = array(
  "#type" => 'value',
  "#value" => $path,
);


How to do a URL redirect to the latest content? This should be pretty simple, but what would be the best way to set up a 301 redirect to the latest post of a node type, for example.

For example: example.com/blog/latest -> example.com/node/*

Ehat I was originally was doing was using views, getting the path of the latest post (+ random, also in views) and rewrite the results with a simple Latest.

But, since I need to include this in email message, a URL is desired (as well as adding Google Analytics UTM Parameters).

What would be the simplest, site builder way to do this?

There seems to be a module for that.
Smart Node Links


Search API Attachments Facet returning part words I’m using these modules for the search :  Search API attachments; Search API Attachments Field Collections; Solr search; Search Facets

One of the Fields I’m searching is from attachments and I’m using type ‘Fulltext’ .

Then when setting up a Facet for this field it return a whole heap of the most common keywords.  The only problem being that in some cases it's returning part words.  For example in the attachments the words 'manage' 'management' 'manager' would exist, and the Facet is returning 'manag' as my keyword.  Has anyone else come across this; and do you know how I can make it so that only whole words are returned.

Thanks

Before I go into to how I solved this; its worth repeating what feed back of this from our hosts.
'This will happen if you attempt to create a facet for a Solr field of type "text" (which might be the case here), because Solr stems and further processes all words before storing them on the index. There is no direct way to get around this.

Also, faceting on text is not really recommended:

UX-wise, searchers get too much noise, because words come from all over the place--your top facets could be just common words like 'the', 'with', 'you', 'they', etc.

Performance-wise, calculating the facets to show for large fields takes a long time. '

I have got things looking like how I want them though and that was to use 'Facet API BONUS' module.

Install and Enable Module
Configuration > Search and metadata > Exclude specified items > Add to Exclude items

  Save Configuration

You only get a limited amount of words with this module .  If needed this can be changed by extending the Form in

Facetapi>filter_exclude_specified_items .
class FacetapiFilterExcludeItems::settingsForm

And adding a '#maxlength'

This is a pretty good blog on adding how to other extended functionality changes to the Facet API module  http://www.trellon.com/content/blog/apachesolr-and-facetapi


Username Token in block doesn't work I'm  using Drupal 7 and installed the Token filter module.

I want to display a welcome message in block; I used <h2>Welcome [user:name]! </h2> as token, but the token is not recognized.

Why isn't the token recognized? Which token should I use?

Try this token instead:

[current-user:name]


panelizer content not displaying I have installed and enabled the panelizer module and enabled the node_view template system page on the Page Manager administer pages page. I enabled panelizer for the Basic Page content type and created a new page. I clicked the panelizer tab and used the builder layout to create a new row below my body content. I added a region to the row and used the menu to add an existing node to that region.

It looked fine it preview so I saved it and went checked out the actual page where I saw the node content but not any of the panelizer content. The content in my added rows and regions did not display.

I tried uninstalling panelizer and re-installing but it still isn't working. Did I forget something?

Make sure you enable panels node template at admin/structure/pages.


Is Drupal doing something to JQuery delegate or click() that causes the binding to fail? I am trying to implement a simple mobile menu, but using Nice Menus as my base. So to get things the way the snippet's CSS is set up, I'm using JQuery to dynamically add a <button> element that can be clicked.

Problem is, nothing happens when I click the button. I've checked that my code works fine when the user clicks a <p> element. And I have also confirmed with code that the element to which I'm attaching the click function exists. (But it wasn't working with a $(document) scope either.)

Doesn't work:

$('.nice-menu-main-menu').before('<button class="nav-button">Toggle Navigation</button>');

if ( $('.nav-button').length > 0 ) {
    console.log("nav-button element exists"); // console shows this message
    $('.nav-button').click( function() {
        console.log("menu button clicked"); // never see this message
    });
}

Doesn't work:

$( document ).delegate('.nav-button', 'click', function() {
    console.log("button clicked"); // never see this message
});

Does work:

$( document ).delegate('p', 'click', function() {
    console.log("button clicked"); // console shows this, no problem
});

What magic am I missing? I figure the issue must be with the dynamic aspect of the  element, but everything I'm finding in the documentation of JQuery and similar code online suggests this should be working.

Drupal.behaviors ensures that the JavaScript code is executed again whenever there are any changes in DOM Elements.

Most JavaScript works by manipulating elements in the HTML DOM. As Such, JavaScript code generally does some extra work to ensure that DOM is fully loaded and elements we want to interact with are available.

The most common way to do this in jQuery is using the $(document).ready() syntax. Placing our code inside this statement will ensure that it is not executed until the DOM has finished loading.

Drupal takes this a step further by using Drupal.behaviors. Along with ensuring that code is not executed until the dom has finished loading, It also ensures that the code is executed again whenever there are any changes in DOM Elements.

So, the Drupal way of handling the click event of a newly added element with a class of nav-button looks like this:

Drupal.behaviors.exampleBehavior = {
  attach: function (context, settings) {
    $('.nav-button',context).click(function(){
      console.log("button clicked");
    });
  }
}


How to stop using Hindi number in Arabic translation of products When using English version of website, price is shown in Arabic number (common one). But when using Arabic version of website, price is shown in Hindi number.

I don't want price to be shown in Hindi Numbers.

English view of products (Arabic Numbers)

Arabic view of products (Hindi Numbers)

How to force using Arabic Numbers in both versions.

Subscribe to the NumberFormatDefinitionEvent ("commerce_price.number_format") and change $definition['numbering_system'] to 'latn' for your locale.


Get the nid from current URL after the ? for views argument I am adding a post to an Organic Group and I want to display a list of all posts to that group below the node add form. The url looks like this:

    node/add/group_post?gids[]=23

I want to add argument that filters the view using the group's id. How can I use the PHP to get that gid?

This is what I have so far, but it's not working.

    $gid = htmlspecialchars($_GET["gids[]"]);
    return $gid;

Just put $_GET['gids'] this will return you an array in PHP.
Then if there's only one nid you can make:

$gids = $_GET['gids'];
return $gids[0];

Source: How to get PHP $_GET array?


getting URL from Route: breaks in localhost subdirectory I just had a Drupal 8 site break when moving it from a top-level domain on a server to a subdirectory on my desktop machine: apparently that subdirectory wants to be included in the URL as converted from routes.  This threatens to ruin my sandbox environment so I would like to figure out 1) why this is happening and/or 2) what isn't portable about my code fragment below.  I've been using

Url::fromRouteMatch($route_match)->toString()

to get the URL Alias of the current page: e.g., the RouteMatch passed as argument to the breadcrumb service.  On the server, this returns a proper pathname relative to the top-level domain, for instance:

/dir1/dir2/dir3/myAlias

... but running the same code in my sandbox (http://localhost/mySite) includes the subdirectory name, as if Drupal is returning the URL relative my local web server's document root, instead of the root of my Drupal site:

/mySite/dir1/dir2/dir3/myAlias

I realise there may be better ways to get the current URL Alias (e.g., \Drupal::service('path.current')->getPath() and then passing it to \Drupal::service('path.alias_manager')->getAliasByPath, but I'd really like to convert the route itself since that's the argument to the breadcrumb builder in Drupal 8.

p.s., clarification, tentative answer: it is clear from comments below that the variable $base_path is expected to be used here, and that "base path" is how one refers to the name of the site subdirectory (if there is one). Neither of these were known to me when I submitted my question above and I can safely say they're not detailed in the Drupal 8 documentation either. Therefore the question becomes trivial: "How do I strip out that string from the provided URL?" and the answer is a matter of text processing:

global $base_path;
$route_url = Url::fromRouteMatch($route_match)->toString();
$alias_url = substr($route_url, strlen($base_path) - 1);

p.p.s., maybe a better answer: I think I know why comments suggest that finding the URL Alias from the request is the wrong approach, since the path.current service factors out any base path beautifully, without the gross string processing as above, and works fine in a breadcrumb builder:

$current_path = \Drupal::service('path.current')->getPath();
$alias_from_path = \Drupal::service('path.alias_manager')->getAliasByPath($current_path);

Sorry for all the fuss here: from my not knowing about the global variable $base_path or about how the Drupal services already deal with subdirectory installations.  Looking forward to the answer as expressed by other contributors with an eye on the big picture.

Drupal 8 is very smart to detect in which environment it is running. If you have this path

/mySite/dir1/dir2/dir3/myAlias

then Drupal is installed in /mySite, but the root of the webserver is still in /.

If you want to get rid of /mySite you have to point your webserver at this directory. Usually you define a vhost with this path and choose a local sub domain, which is configured in the nameserver or your local host file.

With a correct configured vhost there shouldn't be any problems.

See https://httpd.apache.org/docs/current/vhosts/


How do I stop the page refresh on pressing "enter" in a form's text field? How do I stop the page refresh on pressing "enter" in a form's text field?

You need JS/JQuery assistance in this regard.

var stopSubmission = false;
jQuery('#q').keydown(function(e){
   if(e.keyCode == 13){
       stopSubmission = true;
   }else{
       stopSubmission = false;
   }
});

jQuery('form[action="/help/search"]').submit(function(){
    if(stopSubmission){
        return false;
    }
});


link next to field to add referenced entity for site editor EDIT: I want link button in an edit form of a content type like 'store' that says 'add store section'. This link/button should directly go to  the edit form that adds a new 'store section' which is pre-configure by me as entity reference.
This link would be next to a drop-down list of already available 'store sections'.

First step would be that the link needs to go to the node/add form of contenttypeB.
I've heard as a hint that hook_field() functions are what I need.
Something would have to get the form id somehow and this is where I'm confused, I'm wondering if I need to address the contenttypeB nodeforms hardcoded into my .module file? Or do I just need to start doing this by looping through all the fields of the content types and checking whether those fields are an entity reference and then apply it?

I'm still very scared of module development and php as I can stare at code for too long. I'm sort of getting the hook concept a little bit now. Things like hook_men() and then how it goes to the callback function I sortof get. Or when it can go to drup_get_form() and you fill in the function to build a form, I can dig that.

Just to say what level I'm at.

This could be done without a custom module, by using the Markup module.

However, if you are looking for the ability to add a new ContentTypeB that is immediately referenced, the References Dialog module can do this.


How to add css class to a table created using views I want to add a css class to a table which is created using views. I tried to override "views-view-table.php" in my custom theme but that doesn't seems to work. In "views-view-table.php" I replaced the line "<table <?php if ($classes) { print 'class="'. $classes . '" '; } ?><?php print $attributes; ?>>" with "<table class="responsive">" and then cleared the cache, yet it didn't work. Can any one help. Thanks in advance.

This is an old post, but I'd like to chime in with a couple of solutions.

First, and this may not answer your question directly, but you can change the CSS selectors you are using to target the table.

So, rather than using table.yourclass you could use .yourclass table. This can be accomplished by setting a custom class for the entire view under the advanced section.

Of course, this won't work if you are trying to add classes directly to the element as you might need to do with Bootstrap, i.e. table.table.table-striped.

The second solution will allow you to add the same classes to all your tables. In your template.php file, add the following:

function THEME_preprocess_views_view_table(&$vars)
{
    $vars['classes_array'][] = 'table table-striped';
}

If you need to target a specific table, you can also check the $vars variable first to find the name of the view and display being called and only apply your classes to the ones you want to target. I haven't checked, but it's probably found in something like $vars['view']->current_display.

Finally, it's worth noting that Views does actually support custom classes on the table. The variables are called in the template files, there just isn't an option for it in the views GUI. This is an oversight in my opinion, but the module's devs don't seem to plan on fixing it. That said, a patch for it does exist (direct link).


Search API display message when match not found I had an issue before (Search API with views -> Apply filters) that has been solved already.

I have a website where i manage to create a database, display it with the views module and add a Search box with Search API.

The search module works great but i would like to know how can I make it to display a message when there's no match found. Something like "Your search didn't match any documents. Please try again."

Does anyone know how do I do that?

Thanks in advance!!

In Views, under the Advanced Tab, click on NO RESULTS BEHAVIOUR. There you can include a general statement (global text) when it returns nothing.


Is it possible to define a hook_preprocess function based on entity type such as profile2? I walked through the possible hooks by using function hook_preprocess(&$vars, $hook) and only entity was available to use. Is it possible to do something like hook_preprocess_profile2_entity(), or do I have to write an if condition to check the entity type in hook_preprocess_entity()?

This adapts the Zen theme pattern for node preprocess functions to entities:

<?php

/**
 * Implements template_preprocess_entity().
 *
 * Runs a entity specific preprocess function, if it exists.
 */
function MYTHEME_preprocess_entity(&$variables, $hook) {
  $function = __FUNCTION__ . '_' . $variables['entity_type'];
  if (function_exists($function)) {
    $function($variables, $hook);
  }
}

/**
 * Profile2 specific implementation of template_preprocess_entity().
 */
function MYTHEME_preprocess_entity_profile2(&$variables, $hook) {
}

/**
 * Field Collection specific implementation of template_preprocess_entity().
 */
function MYTHEME_preprocess_entity_field_collection_item(&$variables, $hook) {
}


How do I query entities to get all fields values - including referenced ones (INNER JOIN) I have custom content types in my Drupal 8 module and want to query nodes of those content types programmatically.

Querying through entityQuery is easy. However, I have also entity reference fields (so a node of one content type has a relation to a node of another content type).

Is there a way how to make a query that will return 'rows' of field values, exactly as when I use raw SQL INNER JOIN? I want to have an associative array of all field values, not only the specific node, but also the referenced nodes/entities.

Right now I have an own class to handle this, but it's way too much complicated and, I believe, unnecessary, so I guess I'm missing something.

Thank you.

No, there is not.

Entity query only returns IDs, you need to load those and then from there access the referenced entities.


What is the equivalent of sess_count in Drupal 7 As Converting 6.x modules to 7.x explained:

  All session functions starting with sess_*, as well as session_save_session(), are now renamed to drupal_session_* or _drupal_session_*

I have to use sess_count() in my D7 module and naturally I used drupal_session_count() but I ended up having Call to undefined function drupal_session_count() fatal error. I also tried _drupal_session_count() with no luck. User session handling functions page for Drupal 7 didn't mention about this function neither.
Which function should I use in order to count how many users have sessions?

drupal_session_count() was removed from Drupal 7. I'm not sure what an equivalent would be other than writing your own function.

Looks like the user block has it's own query. And admin menu had to replace it too.


Redirect when translation of node is unavailable I have installed pathauto and i18n and I would like to create a node which is only available in one language. Lets say I have a Basic Page with the URL:

www.example.de/test-page-in-german

so I dont want this page to be available from

www.example.pl/test-page-in-german

because I am afraid google is gonna ban my site for double content.
Ive already selected "Require language (Do not allow Language Neutral)" for my content type and for "test-page-in-german" I have selected german and their is no translation but the node is still visible from other language domains.

I finally got it working with the Global Redirect Module

I had to enable the option Language Path Checking.

Then I got another problem with the redirects which was fixed by this patch:

https://www.drupal.org/node/1514166#comment-11657665


CKEditor configured MediaEmbed button doesn't appear in toolbar I have updated my CKEditor profiles to display the MediaEmbed button. The profile is saved, but when editing content, the button doesn't appear in my toolbar.
I'm using CKEditor 4.4, oEmbed plugin 1.17, jQuery 1.10 and the latest version of the CKEditor module.

Here's a screenshot of the config:

And another screenshot of the actual toolbar:

Any idea why?

I managed to resolve my problem but didn't have time to post it in here. It was simply misconfiguration...

First you need to install Widget, Lineutils and oEmbed plugins in CKEditor's plugin folder.
Then you need to specify the path to the plugins folder in CKEditor's module configuration.
Finally, in each of CKEditor's profile, you need to enable the plugins and move the oEmbed icon to the profile's toolbar.
Clear Drupal and browser cache and it should be working.

That's it!


Change templates based on path alias What is the easiest way to select a template based on path alias. For example, if I have the following URLs:

http://www.example.com/mydirectory/page1
http://www.example.com/mydirectory/page2
http://www.example.com/mydirectory/page3

How would I go about creating a template for all of the pages in mydirectory? I should also add that using content type to theme these pages is not an option.

You can add some logic in a hook_preprocess_page() implementation that checks the alias, and adds theme hook suggestions if the path matches, e.g.

function MYTHEME_preprocess_page(&$vars) {
  $alias_parts = explode('/', drupal_get_path_alias());

  if (count($alias_parts) && $alias_parts[0] == 'mydirectory') {
    $vars['theme_hook_suggestions'][] = 'page__mycustomtemplate';
  }
}

Then if you create a page--mycustomtemplate.tpl.php file in your theme, and clear the cache, any pages with an alias beginning mydirectory/ will use that new file instead of the standard page.tpl.php.


Undefined index: und on search-result.tpl.php for Taxonomy Terms I want to show the node title and related taxonomy terms in a table and modifying the search-result.tpl.php to do this.

What I use to for taxonomy terms is that:

<td class="field-item">
<?php
    $str = '';
    foreach($result['node']->field_my_taxonomy_term['und'] as $obj)
        $str .= l($obj['taxonomy_term']->name, 'taxonomy/term/' . $obj['tid']) . ',&nbsp;';
    print trim($str, ',&nbsp;');
?>
</td>

This code works in one of my Drupal website and doesn't work on another one and gives this error:

Notice: include() (.../search-result.tpl.php  line 20) Undefined index: und.
Warning: include() (.../search-result.tpl.php  line 20) Invalid argument supplied for foreach().

How can I show the taxonomy terms related to the node in search-result.tpl.php?

It's either that your field has a set language (not 'und' which stands as 'undefined') or that you have no value for field_my_taxonomy_term.

Either way you should add this control before your foreach (I also rewrite it to fit Drupal best practices) :

<td class="field-item">
  <?php $str = ''; ?>
  <?php if (isset($result['node']->field_my_taxonomy_term[LANGUAGE_NONE]) && $result['node']->field_my_taxonomy_term[LANGUAGE_NONE]): ?>
    <?php foreach ($result['node']->field_my_taxonomy_term[LANGUAGE_NONE] as $obj): ?>
      <?php $str .= l($obj['taxonomy_term']->name, 'taxonomy/term/' . $obj['tid']) . ',&nbsp;'; ?>
    <?php endforeach ?>
    <?php print trim($str, ',&nbsp;'); ?>
  <?php endif ?>
</td>


How do I add the "- Any -" option for the published status on exposed filters? I need to add the - Any - option for the published status, on exposed filters.

I can't use it, as when I try to add it, I get the following error.

  You must select a value unless this is an non-required exposed filter.

How can I add - Any - as option?

As the screenshot shows, the filter is set as Required. This means the users need to select a value for that filter that, being a filter for the published status, can only get Yes and No as values.

If you want to allow users to select - Any - as value for that filter (which isn't really a value for the published status, but a value that tells the view not to filter the nodes basing on their published status), you need to deselect the checkbox that is shown to the left of Required.


OG how to contrain a group to a maximum number of users I would like to restrict groups to a certain amount of members. Is there any ways to do so?

Organic Groups join limit
This module allows to set a join limit on a specific group.


JSON returned from Memcache is invalid I have Drupal 7 site. I am using Memcache for caching.

This is how I am storing the JSON into it

    //creating an object of Memcache
    $cache = new Memcache();
    $cache ->addServer('localhost', 11211);
    //adding a key
    $cacheKey = 'mobile';
    //delete old cache
    $cache ->delete($cacheKey);
    //refresh cache
    $cache ->set($cacheKey, serialize($jsonData));

No issue till here. But when fetching the JSON from this cache.

returned JSON fails to validate

I am using http://jsonlint.com/ to validate my JSON.

Please note the however the JSON has correct data but issue is validation.

$Records = $cache->get($cacheKey);

echo '<pre>';
print_r(Records);
exit();

JSON

{
"defaults": [{
    "nid": "213",
    "public_url": "http:\/\/www.mywebsite.com",
    "HTMLStr": "layout and user interface.\
    r\ n\ t
    http: \ /\/mywebsite.com<\/a><\/p>\r\n"
}]

}

Any help highly appreciated.

This is not really related to Drupal since you are not using the Drupal Memcache module API.

But based on your example. Here is my test code.

  // Creating an object of Memcache
  $cache = new Memcache();
  $cache->addServer('localhost', 11211);
  // Adding a key.
  $cacheKey = 'mobile';
  // Delete old cache.
  $cache ->delete($cacheKey);
  // Create a temp json data.
  $jsonData = "{
    'glossary': {
        'title': 'example glossary',
                'GlossDiv': {
            'title': 'S',
                        'GlossList': {
                'GlossEntry': {
                    'ID': 'SGML',
                                        'SortAs': 'SGML',
                                        'GlossTerm': 'Standard Generalized Markup Language',
                                        'Acronym': 'SGML',
                                        'Abbrev': 'ISO 8879:1986',
                                        'GlossDef': {
                        'para': 'A meta-markup language, used to create markup languages such as DocBook.',
                                                'GlossSeeAlso': ['GML', 'XML']
                      },
                                        'GlossSee': 'markup'
                  }
              }
          }
      }
  }";
  // Set the cache.
  $cache ->set($cacheKey, serialize($jsonData));
  // Fetch the cache.
  $Records = $cache->get($cacheKey);

  // Dump the cache.
  echo '<pre>';
  print_r($Records);
  echo '</pre>';

and here is the result

s:881:"{
    'glossary': {
        'title': 'example glossary',
                'GlossDiv': {
            'title': 'S',
                        'GlossList': {
                'GlossEntry': {
                    'ID': 'SGML',
                                        'SortAs': 'SGML',
                                        'GlossTerm': 'Standard Generalized Markup Language',
                                        'Acronym': 'SGML',
                                        'Abbrev': 'ISO 8879:1986',
                                        'GlossDef': {
                        'para': 'A meta-markup language, used to create markup languages such as DocBook.',
                                                'GlossSeeAlso': ['GML', 'XML']
                      },
                                        'GlossSee': 'markup'
                  }
              }
          }
      }
  }";

with $Records = unserialize($cache->get($cacheKey)); here is the result.

{
    'glossary': {
        'title': 'example glossary',
                'GlossDiv': {
            'title': 'S',
                        'GlossList': {
                'GlossEntry': {
                    'ID': 'SGML',
                                        'SortAs': 'SGML',
                                        'GlossTerm': 'Standard Generalized Markup Language',
                                        'Acronym': 'SGML',
                                        'Abbrev': 'ISO 8879:1986',
                                        'GlossDef': {
                        'para': 'A meta-markup language, used to create markup languages such as DocBook.',
                                                'GlossSeeAlso': ['GML', 'XML']
                      },
                                        'GlossSee': 'markup'
                  }
              }
          }
      }
  }

The only reason why you are not able to see the result is because of this.

print_r(Records);

which is it should be

print_r($Records);

Record is a variable and therefore it must have a dollar sign before it.

Test your connection to Memcache

  $cache = new Memcache();
  $cache->addServer('localhost', 11211);
  $stats = @$cache->getExtendedStats();
  $available = (bool) $stats["localhost:11211"];
  var_dump($available);

If the result is true then you are connected to Memcache if false then you are not connected.

UPDATE 1:

I tested with your json.

  $arr = array(
    "nid" => "213",
    "public_url" => "http:\/\/www.mywebsite.com",
    "HTMLStr" => "layout and user interface.\ r\ n\ t http: \ /\/mywebsite.com<\/a><\/p>\r\n",
  );
  $jsonData = json_encode($arr, JSON_HEX_QUOT | JSON_HEX_APOS);

and here is the result

s:157:"{"nid":"213","public_url":"http:\\\/\\\/www.mywebsite.com","HTMLStr":"layout and user interface.\\ r\\ n\\ t http: \\ \/\\\/mywebsite.com<\\\/a><\\\/p>\r\n"}";


How to create conditional checkboxes that hide each other? I have 2 check-boxes.

Checkbox 1: Attend event for 1 day
Checkbox 2: Attend event for 2 days

If a checkbox is selected, I want to hide the other one. I don't want the user to be able to select both. If I create 2 rules, I get a circular reference error which breaks the form.

How do I achieve what I described?

Simple solution: Don't use 2 fields with checkboxes, use one field with radio buttons.


Search api excerpt are empty in the result I have installed search api module in drupal 8 and included excerpt in the search result.

But excerpt are always empty in the search result. (HTML div element is there but no content inside)

I searched in the forum and enabled the 'highlights' from settings as suggested.
But no changes in the result (I cleared the cache)

Am i missing anything?

First go to this path
admin/config/search/search-api/index/default_index/processors#edit-processors-highlight-settings
make sure this settings are enabled

Next i created a view Global search which has search Excerpt field.

Finally i was able to see the highlighted text word after searching

Actually this is not default search form that comes in drupal8 it is exposed form in block if you see in view exposed form setting i have enabled it.
once this is done, exposed form comes in block just place that in which ever regions you want.


Taxonomy View - show only terms with children I have a view of terms where I show in a grid terms form the highest level (those with parent = 0). I have to limit this view to only show those terms that contain at least one child term. I can't figure out how to do this. Anyone?
Thanks!

I would do quite as Arthur did, but I don't think double relationship is necessary  :

Set a relationship "parent term"
Make it mandatory
Display "term" with the relationship

You then will have only parent terms with children displaying.

Of course, you'll then have to aggregate or group to avoid duplications of parents with multiple children.


How to display another message instead of 403 when trying to open a display of an unpublished product? When somebody tries to open the product display page for the product which is unpublished, it results in the access denied 403 page being shown.

I want to display a message ("This product is not available as of now, check other products.") instead of showing 403 page.

You could add a view as the error page.

Add the view with page (with appropriate path) and attachment as your error page. Filter it on your Product display, pass in the nid as contextual filter and be as creative as you want. The attachment can show the details for the Product that is no longer available, the actual page view can show similar products as alternatives etc. The not found for the contextual filter can be the generic 403 for anything other than products.

Then add the path of the view to the 403 error page setting at admin/config/system/site-information


installed memcache, no noticeable improvements I just installed varnish and memcache on my server. Varnish works great but I don't really know how memcache should perform. I can't see any improvements for authenticated users.

I turned on memcache statistics and saw that it is working but I can't see a noticeable improvements in the page loading time.

Any ideas on how I can improve performance for authenticated users for an existing website?

Thanks, M.

I recommend you to try/use Authcache module

http://drupal.org/project/authcache

Make sure to configure it with memcache by adding the following line in your settings file

$conf['cache_inc'] = './modules/authcache/api/authcache.inc';


Accidentally changed the path of an RSS feed page in Views to refer to a menu link item and cannot access Views menu anymore I cannot access views from the Structure Menu in Drupal 8 anymore. I accidentally changed the path of an RSS feed page in Views to refer to a menu link item and cannot access the Views menu anymore.

How does one fix this? I get an error that says "The website encountered an unexpected error. Please try again later when trying to access View Menu."

The report log says the following:

"InvalidArgumentException: The internal path component 'http://localhost/drupal/News-Press' is external. You are not allowed to specify an external URL together with internal:/. in Drupal\Core\Url::fromInternalUri() (line 409 of C:\xampp\htdocs\drupal\core\lib\Drupal\Core\Url.php)."

You can export your configuration to files, then edit the file that holds wour faulty view, edit the URL, save it and import the configuiratin again.

To do this:

Go to /admin/config/development/configuration/full/export and click 'Export'. Your browser should donwload tar.gz file.
Uncompress the file to see all your site configuration splitted in multiple files.
The file that holds your faulty view file should be views.view.NAME_OF_THE_VIEW. Edit it and look for a line with the view path. It should be:

  path: {wrong path}

Change to the right path and save the file.
Compress again all files to get again a tar.gz file. Is the same that you downloaded but with the file you have just updated.
Go to /admin/config/development/configuration/full/import and upload your tar.gz file with the new configuration.

Drupal should update the configuration and change that view url.

Udpate

Unfortunately it seems there's a bug with views that can arise when editing file in Windows (an probably Mac):
Importing tar file causes Archive_Tar error

  I had the same problem and I found that I could not open the tar
  neither. So I tryed other exports. I found that when I don't export
  views settings, the tar is good. It's only when I put some specific
  views in the export that the tar does not work.

Second update
As @user3531869 says, it's possible to update one single file of configuration to avoid the mentioned bug. To do this go to /admin/config/development/configuration/single/export and select the element you want to export (in this case select View as configuration type, Aggregator RSS Feed as configuration name), copy the the code that Drupal returns, edit to fix the path and the go to /admin/config/development/configuration/single/import, select View as configuration type, paste the edited code in the text area and clicj Import.


Wrapping div around form function gng_unsubscribe_form($form,&$form_state) {
 $form['email'] = array(
 '#title' => 'Email',

'#type' => 'textfield',
 );
 $form['submit']=array(
 '#type'=>'submit',
 '#value'=>t('Unsubscribe'),
 '#prefix' => '
',
 '#suffix' => '
'
 );
 return $form;
 }

For a particular field I can add custom class using #prefix and #suffix, is there a way to add wrapping div around whole form?

According to the Form API Reference, #prefix & #suffix are valid properties of the form element, so you should be able to:

$form['#prefix'] = '
';
$form['#suffix'] = '
';