texts: Is db_set_active a global or local setting?

texts:
I need to run a new query on another database.

I configured the settings.php

 $databases = array (
      'default' =>
      array (
        'default' =>
        array (
          'database' => 'db_name',
          'username' => 'db_usr',
          'password' => '',
          'host' => 'localhost',
          'port' => '',
          'driver' => 'mysql',
          'prefix' => '',
        ),
      ),
      'slave' =>
      array (
        'default' =>
        array (
          'database' => 'db_name',
          'username' => 'db_usr',
          'password' => '',
          'host' => 'localhost',
          'port' => '',
          'driver' => 'mysql',
          'prefix' => '',
        ),
      ),
    );

and this is my custom function:

    function myModule_test()
{

    db_set_active('slave');

    sleep(90);

    $view = views_get_view('test_view');
    $view->set_display('page');
    $view->pre_execute();
    $view->execute();

    print $view->render();
    db_set_active();

    }

the query is performed on the second database, what I do not understand is if the database change is local or global, because during the sleep (90) I tried to insert a new 'article' content and it has been inserted into the 'default' database.


texts: Insert data into entity programmatically

texts:
I've installed contact storage module, it's provide storage for Contact messages which are fully-fledged entities in Drupal 8.
What I want to do, is to insert data programmatically from my custom module into the entity of the contact storage


texts: Customizing a drupal webform for Drupal 6

texts: I am working on a system that would require users to register online by filling out a membership application form. There used to be a PDF form that used to be filled out and sent for processing. The client wants the online form to be as close in appearance to this PDF form. Is it possible to customize a form created using webforms such that it can have some of these elements such as logos, images, etc.?


texts: Is it possible to hide the code of the theme that I have created for my client? In other words, when I open the page with firebug I dont want to see the HTML and all the CSS of my theme, also when I click with the right mouse button.


texts: How to create a view of all recent activity on a site?

texts:
I want to create either a view or a module (preferably view) to display all recent activity on the site such as a new user joined in, a user read some article or blog, a user gained some points and so on...the display should be as:

User x just joined in
User y just got 30 points for creating a blog
User Z just read Some Article

I tried doing so using the Message, Views and Rules modules, but I was able to do so (only for one specific event such as User x created a blog ...).

Note: I want to create new events in Rules. I wonder how to use a message type to get different messages to be displayed. I am following this tutorial, but I wonder how to add more messages such as "[user] gained [user-points]", etc and be sure that it is displayed when that event triggers. Also what data selector should I choose in Rules?


texts: How to create a sort features In Drupal?

texts:
I'm new to Drupal and want to create a sort option (to sort some Forum topics) so that a user can select any topic and apply it.

Here is an image to better illustrate this:

How to make such sort option?


texts: How to create a Contextual Filter using an Entity Reference field in user's profile?

texts:
My site's users have an entity reference field in their profile called "Club" where they select which Club they are a member of. Similarly, when creating a Project (a content type) you can select which club created it. I am trying to create a view called "My Club's Projects" which only shows the Projects created by the club the user has selected in their profile.

I am frustrated because when I try to create a Contextual Filter, my only options are to get parameters from the URL or use the ID of the logged in user. There is no option to use a field from the current user's profile as the contextual filter, which is what I want. No matter how many relationships I add, these options do not change. How do I add a contextual filter based on the current user's club, rather than their ID?

EDIT: I've seen many answers that reference a relationship called "Taxonomy term referenced from field_[mytaxonomy]". In my case, I am not using a taxonomy term, but an entity reference; the only available relationship using this field is "Users using field_club_entity_reference". I was hoping to find something like "Content referenced from field_club_entity_reference", but no such relationship exists.

EDIT 2: I've implemented @prkos' suggestions, details of the View setup as follows. It's a View that displays content with type Project.

Relationships:

field_club: Content (the Club entity reference from the Project content type)
(field_club: Content) field_club_entity_reference (the Club entity reference from the User account, using the first relationship)

Contextual Filters:

(field_club_entity_reference) User: Club:target_id with default value set to User ID from logged-in user.

No other filters other than the standard Content: Published (= Yes) and Content: Content type (= Project).

Unfortunately the view still displays no results. It should be displaying two projects for my account since there are two projects that have the same club selected as my account does.


texts: How do I test that a text field in $form_state has been populated by the user?

texts:
At the moment I am using the following code.

if (!empty($form_state['values']['my-field']) {
  // ...
}

If the user has entered 0 (a valid input in my case) my test will return FALSE. My guess is that I need to test for an empty string '', but I'm not sure.


texts: How to execute javascript from within an ajax request

texts:
OK, I'm doing some basic validation inside of an ajax form callback. I'd like to use the result to execute some javascript. What I've tried looks something like this:

inside my form alter:

if (isset($form_state['values']['field_temp_age'])) {
  if (validate())
  {
    //...return product information
  } else {
    drupal_add_js('alert("Validation fails!");', 'inline');
  }
}

This doesn't work. In this case, nothing is returned.

Also, tried this from inside the ajax callback:

function my_ajax_callback(&$form, &$form_state) {
  if (!validate()) drupal_add_js('alert("Foo!");', 'inline');
}

Not sure what's the approach here. How can I execute arbitrary javascript based on information returned from an ajax request?

Thanks.


texts: Any idea why view->field is empty when executing a view returning user emails?

texts:
We are using Business Rules to execute a view (users) that returns a list of email addresses. It works fine when rule is triggered by admin, but does not work when triggered by other users. In debugging it I found the following:

as both users the view returns the correct result rows, ie. $view->result is identical for both users.
as admin the view object contains a list of the fields which business_rules uses, ie. $fields = $view->field is an array keyed on 'mail';
as any other user $view->field is empty UNLESS I turn on administer users permissions for that user's role!

I am thinking that in views a permission to view the mail field is being checked when the 'fields' are populated into the view object. But, oddly enough that permission does not effect the view result as mentioned in #1.
Any thoughts on how to debug this further?


texts: Installed base them NineSixty - where is it?

texts:
I've installed the base theme NineSixty using the URL method without any errors.
When I then look for the files I can't find them anywhere.
I've looked in the themes directory as well as the sites/all/themes directories. In fact i've looked everywhere.

Where do the base theme's files end up?


texts:
I am relatively new to Drupal, and I am thinking of posting a feature request on Drupal.org for one of the Drupal modules that I'm using.  Before I do it, I wonder if there is any convention or etiquette that I should know about.

What is the convention for asking a feature request to the module developer? Is it bad to ask for the feature if it's a small thing that I might be able to write myself after some tinkering?


texts: Printing raw field value to use in path to files

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

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

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

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

The output for $path comes out like this:

/home/site/library/files/1/

Where am i going wrong? When I run

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

The output is for example "10201"


texts:
I am using Entity Translation module.

My Basic Page content type is using field translation, and I create a node (mysite.com/node/1 for English, mysite.com/de/node/1 for German).

Now in the body field of another node, I hyperlink some text to 'node/1'. But if I am viewing the site in German and I click that link, it reverts back to English.

Is the answer to provide a translation for the body field, hyperlinking to 'de/node/1' instead? I guess this would work, but seems like a lot of extra work for content editors?

Or am I missing something easy? I tried using Path Translation module (part of i18n package), but it doesn't recognise 'de/node/1' as a valid path.


texts: Set default value for taxonomy list using form_alter

texts:
how do I Set default value for taxonomy list?
I have tried altering form with the following line included, but it didn't work:

$form['taxonomy'][3]['#default_value'] = 6;

3 is my VOC ID and 6 TID that I want to select as default


texts: Check Current Environment of Drupal Instance

texts:
Is there a built-in way to check what environment Drupal is running in?

I'm coming from an environment where you would do something like

if Rails.env.production?
  render partial: "shared/google_analytics"
end


texts: Custom css is not applying to bootstrap subtheme

texts:
I followed the step by step to create a subtheme of bootstrap theme. Now, I am not able to apply my custom css to my page.

I took the below steps:

A) Downloaded  Bootstrap project (7.x-3.0). Placed the bootstrap folder in sites/all/themes/.

B) Downloaded jQuery Update project, which is required by Bootstrap. In ../admin/config/development/jquery_update and set the default jQuery version to 1.10.

C) From bootstrap folder, moved the bootstrap_subtheme folder to sites/all/themes/ and name it bootsub

D) In bootsub directory, renamed the bootstrap_subtheme.info.starterkit file to bootsub.info. I edited the content and it looks as below:

name = bootsub
description = A Bootstrap Sub-theme.
core = 7.x
base theme = bootstrap
;;;;;;;;;;;;;;;;;;;;;
;; Regions
;;;;;;;;;;;;;;;;;;;;;

regions[navigation]     = 'Navigation'
regions[header]         = 'Top Bar'
regions[highlighted]    = 'Highlighted'
regions[help]           = 'Help'
regions[content]        = 'Content'
regions[sidebar_first]  = 'Primary'
regions[sidebar_second] = 'Secondary'
regions[footer]         = 'Footer'
regions[page_top]       = 'Page top'
regions[page_bottom]    = 'Page bottom'

;;;;;;;;;;;;;;;;;;;;;
;; Stylesheets
;;;;;;;;;;;;;;;;;;;;;

stylesheets[all][] = css/bootsub.css

; For information on choosing the desired method, please read the Drupal
; Bootstrap sub-theme "how-to" documentation:
; https://drupal.org/node/1978010

; ;----------------------------------
; ; METHOD 1: Bootstrap Source Files
; ;----------------------------------
;
; ;;;;;;;;;;;;;;;;;;;;;
; ;; Scripts
; ;;;;;;;;;;;;;;;;;;;;;
;
; scripts[] = 'bootstrap/css/style.css'
; scripts[] = 'bootstrap/js/affix.js'
; scripts[] = 'bootstrap/js/alert.js'
; scripts[] = 'bootstrap/js/button.js'
; scripts[] = 'bootstrap/js/carousel.js'
; scripts[] = 'bootstrap/js/collapse.js'
; scripts[] = 'bootstrap/js/dropdown.js'
; scripts[] = 'bootstrap/js/modal.js'
; scripts[] = 'bootstrap/js/tooltip.js'
; scripts[] = 'bootstrap/js/popover.js'
; scripts[] = 'bootstrap/js/scrollspy.js'
; scripts[] = 'bootstrap/js/tab.js'
; scripts[] = 'bootstrap/js/transition.js'
;
; ; Disable BootstrapCDN if using Bootstrap source files in your sub-theme.
; settings[bootstrap_cdn] = ''

; ;-------------------------
; ; METHOD 2: Bootstrap CDN
; ;-------------------------
;
; Method 2 uses BootstrapCDN, the only thing you might need to provide here
; is overrides to Bootstrap theme settings. Copy them here from the base theme
; to override.

E) I enabled the bootsub subtheme.

F) Sites/all/themes/bootsub/css, I added bootsub.css file. I added some styling in the css file.

G) I inspected my page using chrome and I see that styling is not coming from bootsub.css file and instead it is coming from

"netdna.bootstrapcdn.com.......bootstrap.min.css.."

Do you know why custom css file is not applying the styling on my page?

Further Notes

Using CDN method
Cache has been cleared
Aggregation is OFF
"View source" in browser does not show bootsub.css had been loaded
Using shared hosting

link

I found the link which does not allow me to comment. Link says:

  I had the same issue few days ago and I fixed with the template
  preprocess function. Just put the following function inside your
  template.php

function YOUR_THEME_preprocess_html(&$variables) {
 drupal_add_css('/PATH_TO_THEME/custom-style.css'); }

I tried to follow the above steps and did not work. I have the subtheme in sites>all>themes. In sites>all>themes>subtheme, I have template.php. I added the below code in template.php:

<?php
function subtheme_preprocess_html(&$variables) {
  drupal_add_css('/sites/all/themes/subtheme/css/subtheme.css');
}

?>

Do you know if i followed the steps correctly or anything else you would like to recommend to resolve this issue?

site


texts:
Everytime I update a module the (linux) file permissions are changed. I use 755 permissions for my directories and 644 for files inside the modules directory.
Is there anyway I can tell drupal the default file permissions for every module update ?


texts:
I created a views to show all my products, in each product have a field named "Color", so now I want to group all product has same color.
So now how can I get all grouping values,

For exam we have 6 results but just only has 2 colors : Red and Blue without Black one.

My question is how can I get grouping values in this views (Red, Blue)

$view->some_thing->some_how ?

I want to put those values in View footer for my personal purpose

My View should displayed like this

--- View Content ----
[RED]
Product 1
Produc 2
[Blue]
Product 3
Product 4

--- View footer
[RED] - [BLUE]

Thanks


texts:
I wrote my own module that builds 4 forms with many features. Everything work great, but now i have reached 1000 lines of code and it's starting to get complicated to have all the forms on the same file.
I would like to make some .inc files, maybe one for each form (the biggest form has 9 functions related to it) to make more order to my code and make it easier to maintain it, but I have no clue on how to split the code in a way it will work.
How can i solve my issue?


texts: Webforms - modify certian components to export into one column, in Excel format

texts:
I am using webforms and downloading the submissions with an Excel format.

I have four check-boxes at the end of the webform asking the user if they agree on the terms and conditions of the form.

When I download the submissions those four check-boxes are outputted, but the client only need to know if the submission is True for all those fields.

this is whats being displayed now:

SID |  col1 | col2 | col3 | col4
--------------------------------
 1     T      F      T      F
 2     T      T      T      T

I am looking for this type of download:

SID |  agreeCol
---------------
 1       F
 2       T

The logic and rewriting I can handle but I am just curious if there is a way of achieving this with webforms out of the box? and if not, what are my options?


texts: How do I link a thumbnail image to its content programatically?

texts:
I have the following php code in a rule. It displays a picture that was uploaded by a user.

How do I link the thumbnail to the content?

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


texts: Add float or align selector for CCK image fields

texts:
I'd like to add a float/align drop-down selector for each CCK image field in my content items. Then, that image would float/align itself on either side of the content (left or right), depending on whether "left" or "right" was selected from the drop-down. Ideally, this drop-down would be in the same general area as the ALT and Title fields are in the admin view of the content item.

Does anyone know if this is possible without custom programming?


texts: Adding a variable to a menu twig template

texts:
Im trying to use bootstrap for an accordion menu. My issue is that I need unique ID's for each accordion item. I found some similar topics here: Add Unique ID to Menu Item and here: How to add a custom variable that can be accessed on bootstrap's menu--account.html.twig?
Id like to know how I can get a unique ID for each item. Preferably an ID I can store within a variable which I can then pass to the data target attribute. As you can see in my code below, I'm trying to achieve something like that. The issue is that I cannot use the variable in a twig template that I declared within the preprocess function. Help me understand what I'm doing wrong.
Here is my code in my .theme file:
function my_theme_preprocess_menu__main(array &$variables) {
    $id = 0;
    foreach ($variables['items'] as $key => $item) {
      $variables['items'][$key]['accordionNav']=[];
      $key_hash = hash('crc32b', $key);
      $variables['items'][$key]['accordionNav'] = $key_hash ;
}
}

Here is my twig file menu--main.html.twig:
{% import _self as menus %}

{#
  We call a macro which calls itself to render the full tree.
  @see http://twig.sensiolabs.org/doc/tags/macro.html
#}
{{ menus.menu_links(items, attributes, 0) }}
{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}

    {% if menu_level == 0 %}

    {% else %}

    {% endif %}

    {% for item in items %}

      {%
        set classes = [
          menu_level ? 'sub-item' : 'nav-item',
          item.in_active_trail ? 'active',
          item.below ? 'card',
        ]
      %}

        {%
          set link_classes = [
            not menu_level ? 'nav-link',
            item.in_active_trail ? 'active',
            item.url.getOption('attributes').class ? item.url.getOption('attributes').class | join(' '),
            'nav-link-' ~ item.url.toString() | clean_class,
          ]
        %}
        {% if item.below %}
        {% if item.in_active_trail %}

        <button class="btn btn-link" data-toggle="collapse" data-target="{{accordionNav}}" aria-expanded="true" aria-controls="collapse{{ip}}">

          {{ item.title }}
         </button>

          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
          {% else %}

        <button class="btn btn-link" data-toggle="collapse" data-target="{{accordionNav}}" aria-expanded="false" aria-controls="collapse{{ip}}">

          {{ item.title }}
         </button>

          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
         {% endif %}

        {% else %}
          {{ link(item.title, item.url, {'class': link_classes}) }}

        {% endif %}

    {% endfor %}

  {% endif %}
{% endmacro %}


texts: How to filter views results by value of profile field of currently logged in user?

texts: When I create a user a 'supplier' must be selected. When a user creates a product a 'supplier' must also be selected. Now I would like to show all the products with supplier = supplier logged in user. I now have a table with all my products listed, but now I need to add the filter. Is there a module for this or can this be done in another way? Because when I now want to add a filter only the product fields are shown.


texts: assigning a role to a user programatically

texts:
I have been looking around for how to assign a role to a user programatically and there is some discussion. Basing my code a little off of https://drupal.org/node/28379, will this work?

    global $user;
    $myuser = user_load($user->uid);
    $myuser->$role[4] = 'Member';
    user_save($myuser);

where I already know that the Member role is stored at key 4 (I did a print_r on user who is assigned that role and I see

 [roles] => Array ( [2] => authenticated user [4] => Member )


texts:
I try to set a new variable in rules. I try to get nid of a node selected by efq like this:

<?php
$termid = $node->field_terms['und'][0]['tid'];
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
->entityCondition('bundle', 'mybundle')
->fieldCondition('field_terms', 'tid', $termid)

$result = $query->execute();
$nid = array_keys($result['node'])->nid;
print $nid;
?>

The problem is that no matter I do, I am not getting nid output. Can anybody help? Thank you.


texts: Boosted Varnish for Drupal - what to do with "Control: no-cache" headers?

texts:
Per the following article http://www.trellon.com/content/blog/boosted-varnish-high-performance-caching-made-easy#comment-8150 we're attempting to use Boost and Varnish on our Drupal 7 site.

As for why we want to use Boost and Varnish, it is to limit the impact of restarting/clearing the Varnish cache.

Anyway, when we install Boost and go to the status report page (/admin/reports/status), there is a message which states:

  Boost will not function properly while Drupal core cache is enabled. Disable Boost or the core cache.

So we disable the core cache. When we do that the following HTTP header gets set:

  Cache Control: no-cache, must-revalidate, post-check=0, pre-check=0

We re-enable the core cache and the headers read as:

  Cache Control: public, max-age=900

As I understand, a cache control header of no-cache tells upstream proxies like varnish "you aren't allowed to cache this."

So essentially we have a dilemma: Boost requires core cache to be disabled, but disabling core cache makes the site un-cacheable by Varnish.
Leave core-cache enabled and Boost won't work.

How do we get them to play nice together? In other words, how can we disable the core cache to make Boost happy but not have the no-cache header set?


texts:
I would like to know how to correct a view query, when Drupal goes nuts ?
I'm using a view that should list media by categories (taxonomy term).
This view is called by a node, that held a reference to the same categories (same taxonomy term) that the medias I wish to display.
I need to order thos categories according to the delta field on my node object.
So in my views I did a join from the media taxonomy field to the taxonomy terms.
Then, I have a join on my any node that hold the taxonomy field.
I filter on the nid through contextual filters.
Until then all is good.
However, if I add the sort Critera on the delta value of categorie, the views module add another (unnecessaray) join on the table holding data for my taxonomy field on my node. This confuses my database and then I get a scalar product as results (every media is sent back, for each existing delta line).
Exemple of the query (I get two joins on node__field_categorie) :
    SELECT DISTINCT field_categorie_taxonomy_term_field_data__node__field_categorie.delta AS field_categorie_taxonomy_term_field_data__node__field_catego, media_field_data.mid AS mid, taxonomy_term_field_data_media__field_standard_termref_1.tid AS taxonomy_term_field_data_media__field_standard_termref_1_tid, field_categorie_taxonomy_term_field_data.nid AS field_categorie_taxonomy_term_field_data_nid
FROM
{media_field_data} media_field_data
LEFT JOIN {media__field_standard_termref_1} media__field_standard_termref_1 ON media_field_data.mid = media__field_standard_termref_1.entity_id AND media__field_standard_termref_1.deleted = '0'
INNER JOIN {taxonomy_term_field_data} taxonomy_term_field_data_media__field_standard_termref_1 ON media__field_standard_termref_1.field_standard_termref_1_target_id = taxonomy_term_field_data_media__field_standard_termref_1.tid
INNER JOIN {**node__field_categorie**} taxonomy_term_field_data_media__field_standard_termref_1__node__field_categorie ON taxonomy_term_field_data_media__field_standard_termref_1.tid = taxonomy_term_field_data_media__field_standard_termref_1__node__field_categorie.field_categorie_target_id AND taxonomy_term_field_data_media__field_standard_termref_1__node__field_categorie.deleted = '0'
INNER JOIN {node_field_data} field_categorie_taxonomy_term_field_data ON taxonomy_term_field_data_media__field_standard_termref_1__node__field_categorie.entity_id = field_categorie_taxonomy_term_field_data.nid
LEFT JOIN {media__field_domain} media__field_domain ON media_field_data.mid = media__field_domain.entity_id AND media__field_domain.deleted = '0' AND (media__field_domain.langcode = media_field_data.langcode OR media__field_domain.bundle = 'useful_document')
LEFT JOIN {**node__field_categorie**} field_categorie_taxonomy_term_field_data__node__field_categorie ON field_categorie_taxonomy_term_field_data.nid = field_categorie_taxonomy_term_field_data__node__field_categorie.entity_id AND field_categorie_taxonomy_term_field_data__node__field_categorie.deleted = '0'
WHERE ((media_field_data.status = '1') AND (media_field_data.bundle IN ('useful_document'))) AND (media__field_domain.field_domain_target_id LIKE 'intranet_adapei69' ESCAPE '\\')
ORDER BY field_categorie_taxonomy_term_field_data__node__field_catego ASC

Exemple of my view, so you can better understand.

How can I correct such a query ?
I'm using Drupal 8.7.12 and can't upgrade for the moment.
I guess the easier way around this would be to be able to add an order by clause using the column made available by my first join on : node__field_categorie
I looked into query_alter and views_query_alter hooks, but it seems it is no longer possible to add an order by clause there (or I tried the wrong way). Any ideas ?


texts: How to open video from a video link in an overlay on the same page?

texts:
How to open a video from a video link in an overlay on the same page? For example, If you go to google news you would have seen the video attached on the link, open as an OVERLAY, and play on the same page. My question is related to external video links.

Suppose a user shares a video link in a textarea any where on my website, I want it to open and play in a popup. It can be an input filter which I can enable from one of the text formats.

I have tried opengraph filter module, which is generating a thumbnail preview, but I want it to play that video on-site when a user clicks on that thumbnail.

Please do not suggest drupal overlay as it is known to create problems.


texts: Why, while developing a module, do I get an error for not specifying a handler when one exists?

texts:
Receiving the error "entity type did not specify a access handler", even though the entity type definitely does specify an access handler, like so:

/**
 * @ConfigEntityType(
 *   handlers = {
 *     "access" = "Drupal\give\GiveFormAccessControlHandler",
 *   },
 * )
 */

And the file src/GiveFormAccessControlHandler.php is in place and ready to handle access.

Why won't Drupal 8 see it?


texts:
The node has about 200 photos in an image field. Clicking remove on the image doesn't do anything, it gives image that it was removed, but it wasn't, on second try it gives error.

  The content on this page has either been modified by another user, or
  you have already submitted modifications using this form. As a result,
  your changes cannot be saved.

What I've tried:

Logged out all users, so nobody is editing any content drush sql-query 'TRUNCATE TABLE sessions;'
Tried sql-query 'TRUNCATE TABLE cache_form;'
Edited php.ini and increased max_input_vars to 3000 as per How can you remove the edit lock on a node?
And tried the rest from that thread.
I did rebuild the permissions and cleared caches.
No errors in log.

It doesn't matter if you try to create new content, it saves on first save and you can't edit it. It also gets saved as unpublished, even if ticked published.

The only way to make the publishing work is via admin/content with some views module that gives some bulk operations.

Preview:


texts: how do I get the parent node of an entity reference node

texts:
I have two content types - A and B.  For content type A, there are 5 content items - Aa, Ab, Ac, Ad, Ae.  For content type B, I have two items Ba, Bb.  Content type B has a field that is an entity reference of  content type A.  In a single page I have the following setup:

Ba -> Aa, Ab, Ac, Ad, Ae
Bb -> Aa, Ab, Ac, Ad, Ae

I have a twig template for B and a separate one for A.  When rendering Aa - Ae, I need to know if the container node is Ba or Bb because it is rendered differently.  Ba and Bb know about the referenced entities (Aa - Ae), but the referenced entities don't know who their parent is.

I've tried using the preprocessor but I can't seem to find a way to get the parent (containter) node.

Any suggestions?

TIA.


texts: Paragraph how to get content level wise?

texts:
Using module https://www.drupal.org/project/paragraphs.

On Admin side I have made content as a 3 level categories. Main Category, Sub Category, Sub Category.

Each category have their content as well.

On twig file when i print

{{ content }}

It display all data. Which is correct.

I need to fetch individual category & their content & do the styling for each.

How can i retrieve that each field in loop?


texts: How to get rid of 'security updates available' warnings?

texts:
I am using the ShareThis module on my website. Unfortunately, recent release 2.3 is flagged as a security update, but it is has a major bug (settings can't be saved). I have reverted to release 2.2.

The consequence is that 'security updates available' warnings are displayed all the time in administration screens. Is it possible to get rid of them? I tried to find an option, but could not find any.


texts: how to apply two themes for an element in custom module?

texts:
In the custom field module that i have written, i am trying to use two themes for same element. One is pager theme and another one is item_list theme ..

I want to make both of these themes work for this element. Do i have to add them in array one item after another ?

Thank you very much :)

Edit: I have modified my code as per patmacs suggestion. I will put that code below, since my page is not displaying anything with change in code.

function event_webpages_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {

// Retrieve documents from Solr function using query
foreach($items as $delta => $item) {
$records = solr_get_results($item['query']);

// iterate through the documents and put them in the array $items in which every record is passed over a theme defined in hook_theme()
foreach($records as $record) {
  $items[] = array(
    'data' => array(
    '#theme' => 'event_webpages_field_list',
    '#node' => $record,
    ),
  );
}

// Number of items per page
$per_page = 10;
// Initialise the pager
$current_page = pager_default_initialize(count($items),$per_page);
// Split your list in to page sized chunks
$chunks = array_chunk($items, $per_page, TRUE);

// The pager theme element
$element1 = theme('pager', array('quantity',count($items)));

// The item_list theme element
$element2 = array(
  '#theme' => 'item_list',
  '#items' => $items,
  '#pre_render' => array('event_webpages_item_list_child_render'),
  );

// the final element passed along with the theme defined in hook_theme()
$output = array(
  '#theme' => 'event-webpages-theme-list',
  '#element1' => $element1,
  '#element2' => $element2,
 );
drupal_add_css(drupal_get_path('module', 'event_webpages') . '/event-webpages.css');
return $output;
 }

The above one is my formatter_view function and my hook_theme function looks like this

/**
 * Implements hook_theme()
 */
function event_webpages_theme($existing, $type, $theme, $path) {
  return array(
    // The theme applied for each item in the item_list
    'event_webpages_field_list' => array(
    'variables' => array(
    'node' => NULL,
    ),
    'template' => 'event-webpages-field-list',
    ),
    // The theme applied to the final output and each variable is theme element
    'event_webpages_theme_list' => array(
    'variables' => array(
      'element1' => NULL,
      'element2' => NULL,
    ),
    'template' => 'event-webpages-theme-list',
    ),
  );
}

The code in event-webpages-theme-list is

<?php
// $Id$
?>
<div class="<?php print $classes; ?>">
<?php print $element1; ?>
<?php print $element2; ?>
</div>

Sorry if it made it more confusing but i thought this will give a overall view of what i have done. Should i use a preprocessor function for 'event-webpages-theme-list' before passing the variables ?

Many Thanks


texts: Mailchimp programatic subscription and updates of existing users

texts:
I'm using Mailchimp module for user registration and at this page I found a function for registering users programatically:

mailchimp_subscribe (
    $list_id,
    $email,
    array (
        'EMAIL' => $email,
        'FNAME' => $first_name, // fields in your mailchimp list
        'LNAME' => $last_name,
    ),
    false,
    false
)

In my mailchimp account I have defined new field of radio buttons type (field name 'type' with options 'client' and 'expert').

I have 2 questions:

How should be the 'type' column in mailchimp_subscribe() function specified?
How could be an existing user in mailchimp programatically updated?


texts: FBOauth: how to pass arguments to the callback function?

texts:
I am trying to create a facebook event through a drupal content type "event". I call the hook_node_insert() to make a POST on Facebook.

function fb_event_create_node_insert($node){
    if ($node->type == "event"){
        // get field values submitted when a new content type "event" is saved
        $event_name = $node->field_event_name['und'][0]['value'];
        $event_start_date = $node->field_event_start_date['und'][0]['value'];

        // get facebook app_id & secret from fboauth variables
        $app_id = isset($app_id) ? $app_id : variable_get('fboauth_id', '');
        $app_secret = isset($app_secret) ? $app_secret : variable_get('fboauth_secret', '');

        // Get the link to get the facebook code (generated by fboauth module)
        $link = fboauth_action_link_properties('fb_event_create');

        print l(t('Create event'), $link['href'], array('query' => $link['query']));
        // output a link to https://www.facebook.com/dialog/oauth?client_id=CLIENT_ID&redirect_uri=http%3A//localhost%3A8888/cs/%3Fq%3Dfboauth%252Ffb_event_create&scope=manage_pages%2Ccreate_event
        // parameters are created by the fb_oauth action (scope=permission) and some settings of the module (client_id & redirect uri).

    }
}

So I then have a link after having saved the node: when I click on it, it connects to facebook and gives me back a code as a parameter in my redirect uri (code has been modified):

http://localhost:8888/cs/?q=fboauth%2Ffb_event_create&code=AQDEvaeupRO-FE6lWaKXZFqvoSRnSuKlIdVjMDeGoy5su-hXpgCcGnBsyCzcPDl5YGGc3hj1yPAXheBjmFtGuivmM-lm5jlm5QG2UeFLPg3gQfnWM3UvB10Y-yrYPyr176dyuMI2Q3vvHGM8z-YVKpYkzPPgYUEifEDIbvADokgniNFiiwpyWZCS72GD32zWLxWCBkCThRk8o3MnO2vWXAmc#_=_

It goes to the callback function defined earlier:

function fb_event_create_fboauth_actions() {
  $actions['fb_event_create'] = array(
    'title' => t('Create events on behalf of CS'),
    'callback' => 'fb_event_create_fboauth_action_event_create',
    'permissions' => array(
      'manage_pages,create_event'),
  );
  return $actions;
}

And here is the callback function:

function fb_event_create_fboauth_action_event_create($app_id, $access_token) {
    $result = fboauth_graph_query("EVENT_ID/events", $access_token, array("name" => "test", "start_time" => "2013-04-04T19:00:00-0700"), 'POST');
}

WHAT I WANT:

Insert parameters to this callback function to be able to insert the $event_name and $event_start_date (that we find from the node_insert() hook above) to have the callback function like :

function fb_event_create_fboauth_action_event_create($app_id, $access_token, $name_fb_ev, $start_fb_ev) {
    $result = fboauth_graph_query("EVENT_ID/events", $access_token, array("name" => $name_fb_ev, "start_time" => $start_fb_ev), 'POST');
}

Thank you for any help guys!


texts: How do do "Facebook style" image tagging?

texts:
I couldn't find a module that would allow "Facebook style" image tagging (select an area of an image and tag it with a username, for example).

Any good starting points to build such a feature?


texts:
I am using Logintoboggan module but by chance by playing around with Wireshark packet sniffing tools I can see all login details and passwords when users login/register on my site!

Is there a way to encrypt login details and/ or add extra security to this module - Are there better secure modules out there?


texts:
I'm new to drupal and coding so I'll try and explain best I can the issue I'm having.

I'm on Drupal 7, using Zen Sub Theme

I have a site which is essentially a database of gadgets.  'gadget' is a custom content type with custom fields such as 'year of manufacture', 'manufacturer', 'image' and 'description'.

I work out of 'page.tpl.php' to control the look of my homepage. I find this to be very easy to use, as far as creating/formatting regions.  Essentially formatting the building blocks of my template.  On the homepage I have list of links (created via views) to the most recent gadgets.  When I click on a gadget it takes me to the 'Gadget' page displaying all the fields I mentioned above.

Now to the issue I'm having:

I can't figure out for the sake of me how I can have a tpl file for the custom content type (ie. the gadget).  I have so far formatted the page with CSS but it would be nice if I can have (I prefer to work through editing the tpl files) a TPL file for the page elements (ie. header, footer) and a TPL file for the region its showing my gadget node.

I've attached a picture of what I'm trying to do:

The home page templating

http://imageshack.us/photo/my-images/402/homepagem.png/

The gadget page templating

http://imageshack.us/photo/my-images/560/pageinside.png/

What I've tried:

1) Formatting the gadget page with CSS : This works fine, but I would prefer to have control over tpl file.

2) In the templates folder I added node--gadget.tpl.php and cleared cache (doesnt work).  node.tpl.php on the other hand does get pulled up by static pages in the site (like the 'about us' page) but not on custom content type (gadget).

3) I added the code below to confirm that content '[type] => gadget':

    <?php
function gadgettheme_preprocess_page(&$vars) {
  if (arg(0) == 'taxonomy' && arg(1) == 'term' && is_numeric(arg(2))) {
    $tid = arg(2);
    $vid = db_query("SELECT vid FROM {taxonomy_term_data} WHERE tid = :tid", array(':tid' => $tid))->fetchField();
    $vars['theme_hook_suggestions'][] = 'page__vocabulary__' . $vid;
  }
}
?>

4) Finally I put in the code below and create a page--gadget.tpl.php.  This worked but the problem is its page--gadget controls the whole content which means I would need to copy over the template from the page.tpl.php to control the header and footer.  I want these elements to be controlled solely from page.tpl.php and have another node--gadget.tpl.php.

function gadgettheme_preprocess_page(&$vars) {
  if (isset($vars['node']->type)) {
    $vars['theme_hook_suggestions'][] = 'page__' . $vars['node']->type;
  }
}

?>

Your help is appreciated in advance,

Cheers,


texts: Is drupal_mail() adequate for 500 emails sent once per month?

texts: I need to send a short, customized-per-user email to approximately 500 users once each month (via a custom module). Are there compelling reasons not to just use drupal_mail for this volume and frequency?


texts:
Could anyone please tell me that how to control RSS feed in D7, because even without my knowledge D7 has created a RSS feed for my site.eg http://wwww.mysite.com/rss.xml

Even though in that feed my page contents are not selected but some un-nessaary items are selected like News letter, Poll and image jCarousel details. I'm 100% sure that I didn't select these items to generate feed but I don't understand how get it involved.

Also if I want to select the required page content link to display on the RSS feed how can I do that ?


texts: How to limit/throttle speed of Views feed?

texts:
I have a Views feed that includes all recent content on my website. I run this through an IFTTT applet to auto-post to Twitter.

Is there a way to throttle how many feed items are added to the feed at once, in order to limit the number of tweets that come out of the IFTTT applet?

For example, if I add 10 pieces of content, I'd like the feed to reflect the first five now, and the next five after fifteen minutes.

ETA: I'm not limiting myself to using only Feeds, other modules or suggestions for a custom module are welcome.


texts: Compress Images that are already uploaded

texts:
I working on a website which has a content type. The content type contains an image field. Thousands of images uploaded already. Because image size is very big, there is requirement to compress the size of images.

I found a module Image API Optimize, but this module works only when a new image is uploaded. But my requirement is that I want to compress the images which are already uploaded.

Can anybody help me solve this problem?


texts:
I created a view that displays all the products of my website's database.

First of all, my view looks like this. As you can see I am using Responsive Grid as my layout format.

Because of the fact that I chose to work with Responsive Grid, I implemented some code to identify the content selectors to Infinite Scroll.

  case 'responsive_grid':
    $content_selector = '.view-content > div';
    $items_selector = '.views-row';
    break;

I am overriding the output of this view using a template file. The reason is that for every 12 blocks of content I have to display a banner for a product category. You can see the snippet bellow.

<?php if (!empty($title)) : ?>

<?php print $title; ?>

<?php endif; ?>
  <div class="<?php print $classes; ?>">
<?php if ($options['alignment'] == 'vertical') : ?>
<?php foreach ($columns as $column_id => $column) : ?>
  <div class="<?php print trim($column_classes[$column_id]); ?>">
  <?php foreach ($column as $item_id => $item) : ?>
    <div class="<?php print trim($item['classes']); ?>">
      <?php print $item['content']; ?>

  <?php endforeach; ?>

<?php endforeach; ?>
<?php else : ?>
  <?php foreach ($rows as $row_id => $row) : ?>
    <div class="<?php print trim($row_classes[$row_id]); ?>">
  <?php foreach ($row as $item_id => $item) : ?>
    <div class="<?php print trim($item['classes']); ?>">
      <?php print $item['content']; ?>

  <?php endforeach; ?>

  <?php endforeach; ?>
<?php endif; ?>

<?php if ($row_id % 1 == 0 && $row_id !=0): ?>

        <?php print views_embed_view('display_random_snippet_home_1', 'block'); ?>

<?php endif; ?>

Although everything appears to be working as designed I have an issue when the Infinite Scroll module loads the first page (always counting from 0.) As you are able to see bellow, when the pager is initiated it loads 12 products pushing down the category block and creating a mess. Also, you can notice that after the first initiation everything works as planned.

You can see the issue reproduced here: http://giphy.com/gifs/l0Ex99XrcsBjynBcY

Or you can reproduce it yourself: mygadgeto.com/infinite

Hope we find a way out of this.


texts: What can I do to improve the size of csv file that can successfully be imported via Feeds and Commerce Feeds

texts:
I am using Feeds and Commerce Feeds to import product lists into my Drupal Commerce store.
I'm finding I have to keep the csv files really small for the import to succeed? As soon as the file is too big (the exact threshold size does not seem to be consistent) the system generates a 403 error as follows:

An AJAX HTTP error occurred. HTTP Result Code: 403 Debugging information follows. Path: /batch?id=260&op=do StatusText: Forbidden ResponseText: Access denied

The file that resulted in this error was 577kB.

The only way around the problem is to have multiple csv files. These all have to be maintained and updated individually, which is very inefficient.

What can I do to improve this state of affairs?


texts:
How would you think if a designer extends the database of Drupal for a desired system? (for example adding field to some tables)

Would it be really PRACTICAL?


texts: How can I disable a user that should still be visible on the site?

texts:
It seems that User name on blocked user account not visible in view for anonymous users is basically the same question I'm asking, but it doesn't have an accepted answer or one that works for me.  This is a different take on the question than the one I'm making.

I am migrating a site from another CMS.  I am bringing over staff members, both past and current as users of the site.  As part of the migration, users who are no longer with the organization are being marked as blocked to prevent them from logging into the site.

These users are then associated with nodes on the site via various entity reference fields.  The problem I run into is that for anonymous users, indeed for anyone that doesn't have bypass access controls on their account, these user accounts are not visible.

What is the proper way to keep an account visible, while not allowing users to log-in to it?  For me, the answer will need to be something that will work with the Migrate Module.

Obviously blocking the user seemed like the obvious way to do it for me, but I can't find any permission that will allow access to blocked user info.  Is there another way of doing this, or is there a way of making blocked account info visible?

My Solution

Based on the accepted answer from @kiamlaluno, I created a solution that works for me:

I already have an end_date field for each user (field_user_end_date), so most of the time, that would suffice as a limiting factor for the login, but based on discussions with the stakeholders, I added an additional admin only boolean field named field_user_account_locked.

I implement hook_form_alter to add my validation function to the form:

function mymodule_form_alter(&$form, &$form_state, $form_id)
{
    if ($form_id == 'user_login' || $form_id == 'user_login_block') {
        $form['#validate'][] = 'mymodule_user_login_validate';
    }
}

And here is my validation module:

function mymodule_user_login_validate($form, &$form_state)
{
    if (!empty($form_state['uid'])) {
        // The user trying to login is not limited by flood control;
        // user_login_authenticate_validate() found a user with the username and password entered in the login form.
        $user = user_load($form_state['uid']);
        $end_date = (isset($user->field_user_end_date[LANGUAGE_NONE][0]['value'])) ? strtotime($user->field_user_end_date[LANGUAGE_NONE][0]['value']) : time() + 300000;
        if ($end_date < time() || $user->field_user_account_locked[LANGUAGE_NONE][0]['value'] == 1) {
            form_set_error('name', t('The username %name cannot be used to login.', array('%name' => $form_state['values']['name'])));
        }
    }
}

I'd love some constructive criticism on it, if you have some.


texts: Drupal 8 - How to Reference Flags Twig Template without showing full content?

texts:
I'm using Drupal 8 to construct a page, where flags are required for Adding Videos to Favorites. I am using the Flags Module, but it's a custom template, so I didn't use the {{content}} reference directly. Instead I'm using the machine names of each field in displaying and styling the node. I reference them using {{content.field_fieldname}}

The problem is that I'm unable to reference the flags that I have created using the Flags Module. They are appearing on other basic pages and articles (when I turn on those areas while editing the flags), but they fail to appear in the custom template that I have created for a node.

Could anyone please help me with this? Any sort of help is highly appreciated. Thank you.


texts: how to count the number of node a taxonomy term has?

texts:
Possible Duplicate:
  Views and node count for taxonomy terms

I want to count the number of node taxonomy term has in views. I want to display it in content:taxonomy term(exposed). that same as http://www.path.org/blog/ http://wiwisol.com/images/term.png
I remove print $exposed; in views--views--xx.tpl.php and add some code. it work http://vnfetp.wiwisol.com/blog but not good.

  <?php //if ($exposed): ?>

<?php

$vid = 5;  // number of vocablurary
$total_tid = 0;
$pole = array();
$tid = array();
$terms = taxonomy_get_tree($vid);
foreach ( $terms as $term ) {
    $count = db_query("SELECT COUNT(nid) FROM {taxonomy_index} WHERE tid = :aid", array(':aid' => $term->tid) )->fetchField();
    $pole[]=l($term->name."(".$count.")", 'taxonomy/term/'.$term->tid.'');
    $tid[] = $term->tid;
    $total_tid++;
}
$item = 0;
$selected = "selected";

if(empty($_GET['tid']))
    $tid1 = "All";
else
    $tid1 = $_GET['tid'];
?>
<form class="ctools-auto-submit-full-form" action="fetp/blog" method="get" id="views-exposed-form-blog-block" accept-charset="UTF-8">

CONTINUE CODE:

        Categories

CONTINUE CODE:

 <select id="edit-tid" name="tid" class="form-select"><option value="All" selected="<?php echo $selected;;?>">- Any -</option>

CONTINUE CODE:

<?php

foreach ($pole as $list)
    {
        if($item < $total_tid)
        {
            if($tid[$item]== $tid1)
            {
                echo ''.$list.'';
            }
            else
            {
                $selected = "";
                echo ''.$list.'';
            }
        }
        else
        {
            echo '- Any -';
            $item = 0;
        }
        $item++;
    }
    ?>

CONTINUE CODE:

</select>

CONTINUE CODE:

  <input class="ctools-use-ajax ctools-auto-submit-click js-hide form-submit" type="submit" id="edit-submit-blog" name="" value="Search" />

  <?php //dsm($exposed); //print $exposed; //var_dump($exposed); ?>

It work, but not fine when more than two exposed filter. How to count the number of node a Taxonomy term has? help me please,
Thank you very much.


texts: How would I clear values in ajax loaded select options?

texts:
http://pastebin.com/TX2UiJGZ

I have 3 select drop-downs, selecting a value in the first populates the second using ajax, selecting the second populates the third. However when I change the value of the first select it doesn't reset the second (If I already chose the first and the second drop down initially).

Method

Choose an option from the first
This populates the second select with options A, B and C
If I change the first one it won't reset the value if that value existed on the first option
So if our first option called A, B and C and we change the first drop-down to something else but it calls C, D and E; if C was selected in the second drop-down it doesn't reset since it existed in both ajax calls, this then doesn't load in the third select unless you select a different option in the second select.

Basically what I need is to reset the second and third select whenever the first changes.


texts: Any easy way of implementing a mega menu?

texts:
Im wondering if there is a easy way to implement the following dropdown menu(ive added a before hovering on a list item, and after):

If i had to do it right now, i would use a bootstrap dropdown, and basically have to create an entire module around making the paths to point in the right directions.

Do you guys know of any existing menus or any easier way of doing this?

thanks


texts: Pre-Populate Dropdown in WebForm from link

texts:
I have a Drupal 7 webform with a dropdown list of Products
 - Product A
 - Product B
 - Product C
 - etc...

I want to place a button link on another page "How to Buy Product A" that will bring up the webform with Product A selected in the dropdown.

The Field Key in the Webform for the dropdown is: railing_system_model

Do I just add something to the link URL??

I have no idea where to begin, is there a module that will do this?

Regards,

John


texts: Anyone have any luck exposing Ubercart's "enter your VAT" part of the form?

texts:
I am using http://drupal.org/project/uc_vat and http://drupal.org/project/uc_vat_number and am able to enter different VAT rates, but a the moment it seems that it simply applies whatever is the last item in the list as VAT. I need to find where in the interface (I may be being blind as well as ignorant) it will allow me to enable the part of the form where the user can select that they have a VAT number to enter to avoid paying VAT. I am pretty sure it is part of the interface, I just don't know where to find it.

If I find it, I will post and/or close the question. Many thanks for any and all support!


texts: How do I speed up `drush test-run` (compared to the SimpleTest UI)?

texts:
I have a number of Feature modules for which I've written tests to assure they work as expected. For performance reasons, I've overridden the parent's setUp() method in each test case so that it doesn't create a brand new database each time.

When I run my tests in the SimpleTest admin UI, all of my Feature modules' tests take about 15-20 seconds total to complete. When I run them via drush test-run [feature-group-name], they take about 75 seconds total. I noticed that drush seems to pause in between test cases to output something like the following:

Contact page 7 passes, 0 fails, and 0 exceptions  [ok]
No leftover tables to remove.                     [status]
No temporary directories to remove.               [status]
Removed 1 test result.                            [status]
 Group  Class  Name

If you're curious, my setUp() function looks like this:

public function setUp() {
  $this->setup = TRUE;
  // Prevent PHP warnings about a missing public_files_directory variable:
  $this->public_files_directory = variable_get('file_public_path');
}

Any ideas why drush is so much slower than the admin UI? I'd really like to get drush more performant, as I want to integrate these tests into a continuous integration environment.

Thanks!


texts: How to have parent taxonomy terms include their children terms' nodes?

texts:
I have a hierarchical taxonomy, and I'm currently using the Taxonomy Menu module to display navigation links. E.g.

+ Dairy
  * Milk
  * Cream
+ Fruit n Veges
  + Citrus
    * Lemon
    * Lime
  * Pumpkin
  * Tomato

Each of the links refers to a taxonomy page, which is nice, but the page for "Dairy" only includes nodes that have the term "Dairy". It doesn't include "Milk" and "Cream" nodes, for example, which is what I want.

What's the best way to implement this? And "what's the point" of sub-terms, if they don't seem to have any semantic meaning?


texts: How can I list all of the pages that display a certain view?

texts: In Drupal 7, is there a way either programmatically or through the UI to generate a list of all of the pages that display a particular view?


texts: How to create a View that shows flag fields and the number of times flagged per field

texts:
The idea is as follows:
I have a site where articles are evaluated with 7 labels. Authenticated users (not only the author) must be able to select a number of labels they want to apply to the article.

On the article page, there should be a views pane or block that lists the labels that have been applied to the article by everyone, and the number of times it has been applied.

I currently have the approach that I created 7 flags, and the views block needs 7 relations and 7 contextual filters which is a very inefficient way to display the flag count per flag.

Help is much appreciated


texts:
Which property should I set to save the last imported time in the migration map (SQL)?

I've seen that adding:

source:
  track_changes: true

https://www.drupal.org/docs/8/api/migrate-api/migrate-source

The hash is been calculated but no idea how to set the calculation of the time.

Thanks!


texts: How to use admin table theme with multistep form?

texts:
I have 1000 records of users with name and checkbox. I want to show the list of users in table theme. I have use

theme('table', array('header' => $header, 'rows' => $rows));

But how to use it with multistep form. Please find the below code.

function getForm() {
$form = array();
$step1 = array();

drupal_add_js("
function checkUncheckAll(theElement){
  var theForm = theElement.form, z = 0;
  for(z=0; z<theForm.length;z++){
    if(theForm[z].type == 'checkbox' && theForm[z].name != 'checkall'){
      theForm[z].checked = theElement.checked;
    }
  }
}", 'inline');

$step1['user'] = array(
   '#type' => 'container',
   '#tree' => TRUE,
   '#prefix' => '
',
   '#suffix' => '
',
);
$results = db_query("SELECT* FROM {user_token} ut LEFT JOIN {users} u ON u.uid= ut.uid where u.status=1 and u.uid!=0 group by ut.uid ")->fetchAll();

foreach($results as $k=>$result)
{
  $user[$result->uid] = $result->name;
    $defaults = array_keys($user);
}

 $step1['checkall'] = array(
 '#type' => 'checkbox',
 '#title' => t('Select / Unselect all'),
 '#attributes' => array('onclick' => 'checkUncheckAll(this);'),
 '#weight' => -1,
 );

 $step1['user'] = array(
 '#type' => 'checkboxes',
 '#title' => t('Send message to listed users'),
 '#options' => $user,
 //'#default_value' => $defaults,
 '#attributes' => array('class' => array('check_notify_user'))
 );

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

$form[] = $step1;

$step2['message'] = array(
  '#type' => 'textarea',
  '#title' => 'Message',
  '#description' => t('No more than 250 words please!'),
  '#wysiwyg' => false,
  '#attributes' => array('maxlength' => 250),
);

$step2['prev'] = array(
  '#type' => 'submit',
  '#value' => t('Previous'),
  '#name' => 'prev',
  '#submit' => array('custom_previous_submit'),
);

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

$form[] = $step2;

return $form;

}


texts: create double view with same url alias for different theme

texts: In my drupal. I created a two theme one for desktop and another for mobile using Mobile switch I change the theme. Now I Created a View as a page for desktop with alias "xxx/yyy" and for mobile also I created a view as a page with same alias "xxx/yyy"(some modification Done). While switching the theme from desktop to mobile, the desktop view is appear. How to differentiate?


texts: How I could put a block of text after my comment form (kinda like politics), I put comments separated from the content (different pages).


texts:
I'm trying to make a view that builds a drop-down select out of a taxonomy. I need to theme the fields as so:

<option value="{{ tid }}">{{ name }}</option>

where {{ tid }} and {{ name }} are my view's taxonomy fields.

I'm using a custom views-view-fields.html.twig template to provide the rest of the code for the select list.

How can I add the view's fields as theme suggestions? Something like this, but actually, you know, working.

function THEME_theme_suggestions_views_view_field_alter(array &$suggestions, array $variables) {

  $field_name = \Drupal::request()->attributes->get('field_name'); {# I have no idea what to use here :-) #}

  if (!empty($field_name)) {
    $suggestions[] = 'views_view_field__' . $field_name;
  }
}

I have no idea what to use to retrieve the field names to add them to the theme suggestions. I've stared at Kint output until my eyes were bleeding. Any help at this point would be greatly appreciated.


texts: Using OG to create custom user profile - need to share content with selected group members. Does anyone know of a module that does this?

texts:
I'm creating a site using D7 with OG to create a custom user profile where the user's group is auto created upon registration.  Everything is working just as I want it to, but now I'm hitting a wall with a required feature.  I need to have a method of allowing a user to post an "update" and share it with all or select "followers" (I'm using the OG member feature as a user's followers) and have it show their updates on their "home" page (which is really their group's main page).  I was thinking of using private message for this, but it is giving me fits getting it to do what I want.  I was thinking an alternative method might be to create a content type for Update and allow the user to post these into their group - but then I need to add an additional layer on top of the inherent public/private filter.  What I'd really like to do is allow the user to select from a list of group members and have the specific update only visible to those members.

Does anyone know of a module that exists that would allow this?  I'm trying to avoid writing a custom module if at all possible.

Thanks!


texts: Caching issue with View and anonymous users

texts:
Our site uses Views heavily and unfortunately we've got a caching problem.

On our front page we've got a View that only shows content whose publishing date is more recent than the current date. So if we post an article whose publishing date is 2 hours from now, it should be visible in two hours from now on.

This works fine for logged in users. But the majority of our visitors doesn't have an account. And when not logged in the article gets published seemingly at random. It could be visible 20 minutes or 1 hour past the desired date.

The View has got no caching enabled. Site wide we've got the following options enabled:

Caching mode: normal
Page compression
Block caching
CSS caching
JavaScript caching

Do you have some hints regarding our problem? I'm using Drupal 6.


texts:
I'm trying to fix a form that was created using a twig template. The form was not working because there was no action, nor was the form created using FormStateInterface. It's just a block that is rendering a template.

In this module there is a controller and in this controller a method that handles the form submission using \Drupal::request()->request->all() which should be the same as using $_POST[''], correct?

Could I not just do something like this:

<form method="POST" action="/route/to/controller/method">

if I'm wanting to use a custom form template?

I would really just like to know if this is an acceptable practice in the Drupal universe.


texts:
I want to remove the "My Account" and "Log out" menu links, as I've incorporated those into other parts of the page.

Now, I'm a Drupal novice so if I'm making rookie mistakes here go easy!

What I've tried is something like this in my module.install file

function mymodule_enable()
{
    menu_link_delete(null, 'user');
    menu_link_delete(null, 'user/logout');
}

Now - that doesn't work as those two menu links are 'system' links. I tried to brute force this by creating a variant of menu_link_delete which forces deletion, by passing "true" to the $force parameter of _menu_delete_item...

function force_menu_link_delete($mlid, $path = NULL) {
    if (isset($mlid)) {
        _menu_delete_item(db_query("SELECT * FROM {menu_links} WHERE mlid = :mlid", array(':mlid' => $mlid))->fetchAssoc(), true);
    } else {
        $result = db_query("SELECT * FROM {menu_links} WHERE link_path = :link_path", array(':link_path' => $path));
        foreach ($result as $link) {
            _menu_delete_item($link, true);
        }
    }
}

When my module is enabled, that does successfully delete the relevant rows of the menu_link table, but by the time the Drupal has finished working its magic they have reappeared in the table!

The reason of course is that the user_menu() hook goes and reestablishes them. I wondered if removing them with a menu_alter hook would work...

function mymodule_menu_alter(&$items) {
    unset($items['user']);
    unset($items['user/logout']);
}

Sure enough, they disappear, but so does the actual capability to logout!

So - I'm going about this the wrong way. I'm guessing I shouldn't try to delete the menu links themselves, but somehow prevent my theme from displaying them.

Pointers are very welcome....


texts: Multi-index search solution idea with autocomplete

texts:
For sometime I have been looking for a complete solution for search capabilities in drupal 7, but there is always some problem. With all the greatness and flexibility of drupal, I have to say that there are some limitations, which are obviously irritating.

For example, if I use multi-index search or any other similar module, the autocomplete feature does not work. I have also tried custom search module. Idea is to have a drop down with the search box and when someone selects an option and types something in the search bar/box, it should only search the selected option and also have auto-complete feature.

Secondly, I would like to know how to show any search bar/box anywhere on the website. For example, currently I am using following code, I read on this website, to show the search bar on the top of my website. I pasted this in my theme's page.tpl file. This code I am using for the default search provided by drupal. Obviously, when I modify search or use a module, it will have its separate search box and I would want to show it on the top instead of the default search box.

<?php
  $block = module_invoke('search', 'block_view', 'search');
  print render($block);
                ?>


texts: Delete references to files on nodes without saving the node

texts:
I have an image field (unlimited values) with his default button "delete", when i click it the image disappear but, as Drupal works, it will not be actually deleted from the node until the node is saved. If I reload the page without saving, the images are still there.

How can I save the node at the image delete? I was thinking about using hook_form_alter() but this is an ajax request done by the "delete" button so it's a different matter.

If I catch the right hook and save the node in ajax, could this create problems?

I only find info about how to delete images physically from the folders after they have been removed from the node.


texts: Entity reference item list with preview images?

texts:
In a node type 'album' I have an entity reference field 'photo' that can be used to reference nodes of the type 'single_photo'. This works fine – using the module Entityreference view widget lets the editor choose nodes from a lst view with a preview image and optional additional fields:

The actual list of referenced nodes however does only show the node title:

I now would like to have a similar preview in the actual item list – or maybe even also use other fields of the referenced nodes. Is there a similar module or a combination of views and code or the like, that would provide such a functionality? Any pointers, suggestions, links would be appreciated.


texts: Views callback work only once with advanced form block

texts:
this code work but the views is callback only once (reload only once), any idea to reload more than one time ?

see in detail on drupal.org

function modulename_form_alter (&$form, &$form_state, $form_id) {
    switch ($form_id) {
        case 'form_id_of_your_afb_form':
            $form['#validate'] = array();
            $form['ajax-submit']['#ajax']['callback'] = 'modulename_create_callback';
    }
}
function modulename_create_callback($form, &$form_state) {
    // load view
    $view1 = views_embed_view('view_name','view_display_name',$view_arguments_as_required);

    // replace the afb form with a clean form
    $newform = afb_ajax_handler($form, $form_state);
    $commands = array(
      ajax_command_replace('#target_div_id_of_view_to_update .view',$view1),
      ajax_command_replace('#target_div_id_of_afb_form_to_replace',render($newform)),
    );
    $form['#type'] = 'ajax';
    $form['#commands'] = $commands;
    return $form;
}


texts: Unable save/update any content after migrating from local to production

texts:
This is the first time I have made my Drupal site live on a production server (Ubuntu ls 10.04).

These are the steps I did:

Zip the entire webroot folder
Upload to the production server
Extract the contents into the webroot
Take db dump from local server
Dump into the production server
Update the production's Drupal admin password

I do not have a problem viewing the contents, but I am unable to save any content including the configuration settings such as Site information. It doesn't throw any error message or update the content.

What other steps might I have missed?


texts:
Friends -

Please help with this... to some of you, this is really easy. But, I have been struggling with this issue since two weeks:  I need to create categories structures such as Creating Categories/Subcategories/Subsubcategories/Products and have it appear on the menu of a newly install drupal commerce. this is what I have done so far:

I created the taxonomies necessary
I created the categories and subcategories: i.e.: Products Categories\Air Conditioners\
I created the product "Samsung Air Conditioner Unit" and inserted it into the correct categories
I clicked on All Products and observed that Samsung Air Conditioner is properly inserted into the correct subcategories
However, when I clicked on the root category "Product Category" on the main menu, which is generated by Taxonomy, I do not see the product listed.

I just need to know how to configure the content type to allow the product to display in the correct category\subcategory group.


texts:
I am testing my module, using a custom SQLite database. It has minimal amount of tables, necessary for the module. I run this function.

function test_header(&$modules, &$path_var = null) {
  $file_path = dirname(__FILE__);
  $path = preg_replace('/sites.*/', "", $file_path);
  $path = substr_replace($path ,"",-1);
  $_SERVER['DOCUMENT_ROOT'] = $path;

  define('DRUPAL_ROOT', $path);

  if (!is_null($path_var)) {
    $path_var = $path;
  }

  error_reporting(E_ALL ^ E_NOTICE);
  $path .= DIRECTORY_SEPARATOR . 'includes'.  DIRECTORY_SEPARATOR . 'bootstrap.inc';
  require_once($path);
  drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);

  foreach($modules as $value) {
    drupal_load('module', $value);
  }

  return $file_path;
}

I run it with modules that need to be loaded.

$modules = array("members");
$file_path = test_header($modules);

Then I load the SQLite database, using this function.

function set_db($db_name, $db_alias, $driver = 'sqlite') {
  $test_database = array(
    'database' => $db_name,
    'username' => 'user',
    'password' => '',
    'host' => 'localhost',
    'driver' => $driver,
  );

  Database::addConnectionInfo($db_alias, 'default', $test_database);
  db_set_active($db_alias);
}

For one of the modules it works correctly. But for another one it gives an error, when I change DRUPAL_BOOTSTRAP_DATABASE to DRUPAL_BOOTSTRAP_FULL.

  General error: 1 no such table: semaphore: DELETE FROM {semaphore} WHERE (value = :db_condition_placeholder_0) ; Array([:db_condition_placeholder_0] => 8994220325229a65a473108.08075181)
  in lock_release_all()

Without DRUPAL_BOOTSTRAP_FULL it gives some cryptic error.

It seems that it runs this function in the end, and it doesn't find the semaphore table in the SQLite database.

How can I turn off this function and everything else unnecessary?


texts: How to execute VBO list of nodes in Rules on After updating an existing user account event?

texts:
I have a VBO of all the unpublished nodes of the user, and I want to publish all of them based on user role change that happens via Rules.

I created a component of rule to list the nodes of that user but since my Event is After updating an existing user account in my actions section, when I add the component, there's no Node related parameters to pass so I can publish those nodes.

Update: Pierre's answer actually defines the steps that I've already taken, the last part that puzzles me is that how can I add the component to be triggered to an After updating an existing user account event where there's no node defined in it.


texts: How to set the value of a date field via Rules?

texts:
One content type in my Drupal page has a date field. After importing start hour, start minute and duration (Integer values) from an XML file, I want to set date field of the node via Rules. It seems that I cannot access the start date and duration of the date field.

Is there a solution to set the start date, end date, repeating, etc. ?


texts: Drush on production server without Composer

texts:
I want Drush 9 on a Drupal 8 production server without having to install Composer. Is there any way to do this?

And if that is not possible, can anyone suggest an alternative to Drush especially for maintenance, updating and syncing the site with dev and staging?


texts: Is there any way to import/export the panelizeers?

texts: I have some panelizer pages created on Drupal 7 sites. Now i want to migrate them on other instance. So is there any way to export the panelized pages in Drupal 7 like panel pages?


texts:
I have installed and activated basic cart module.
then I went to admin/config/basic-cart
their I selected my content type.
Then in view I added a field content:Add to cart
When I viewed my view result their I wasn't able to see button for add to cart.
How to use that module so that it show me that button
Basic Cart
I an using Drupal 7


texts: How to query only specific id's in a custom source plugin

texts:
I have 40/1040 source product_id's I need to ignore in one migration, so that I can put them in their own separate migration. I can exclude and include them in the yaml files, but it's a bit ugly and I would rather do so in the custom source plugin because doing this in the yaml is not performant as they are all queried in both.
I can exclude the 40 from their own yaml this way:
process:
  variation_id:
    -
      plugin: skip_on_value
      source: product_id
      method: row
      value:
        - 1
        - 2
        - all the way to 40

I can include only the 40 in another yaml this way:
process:
  variation_id:
    -
      plugin: skip_on_value
      not_equals: true
      source: product_id
      method: row
      value:
        - 1
        - 2
        - all the way to 40

But I would rather set a string of product_id's to include/exclude (I'm guessing in the public function query()??) because when I run the smaller migration (the 40) there is no need to query and ignore the other 1000 variations.
I created a copy of the source plugin so that I could use a distinct plugin for each of the 2 migrations. Here is the plugin that I am currently using for both:
use CommerceGuys\Intl\Currency\CurrencyRepository;
use Drupal\migrate\Row;
use Drupal\migrate_drupal\Plugin\migrate\source\d7\FieldableEntity;

/**
 * Gets Commerce 1 commerce_product data from database.
 *
 * @MigrateSource(
 *   id = "commerce1_product_bundle",
 *   source_module = "commerce_product"
 * )
 */
class CommerceProduct extends FieldableEntity {

  /**
   * {@inheritdoc}
   */
  public function fields() {
    return [
      'product_id' => t('Product variation ID'),
      'sku' => t('SKU'),
      'title' => t('Title'),
      'type' => t('Type'),
      'language' => t('Language'),
      'status' => t('Status'),
      'created' => t('Created'),
      'changed' => t('Changes'),
      'data' => t('Data'),
      'commerce_price' => t('Price with amount, currency_code and fraction_digits'),
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function getIds() {
    $ids['product_id']['type'] = 'integer';
    $ids['product_id']['alias'] = 'p';
    return $ids;
  }

  /**
   * {@inheritdoc}
   */
  public function query() {
    $query = $this->select('commerce_product', 'p')->fields('p');
    if (isset($this->configuration['product_variation_type'])) {
      $query->condition('p.type', $this->configuration['product_variation_type']);
    }
    return $query;
  }

  /**
   * {@inheritdoc}
   */
  public function prepareRow(Row $row) {
    $product_id = $row->getSourceProperty('product_id');
    $revision_id = $row->getSourceProperty('revision_id');
    foreach (array_keys($this->getFields('commerce_product', $row->getSourceProperty('type'))) as $field) {
      $row->setSourceProperty($field, $this->getFieldValues('commerce_product', $field, $product_id, $revision_id));
    }

So I'm asking how to exclude an array of 40 product_id's in one plugin, and then only include an array of 40 product_id's in the other plugin.
Should I do this in the public function getIds(), the public function query(), or the public function prepareRow(Row $row)?
My guess would be in the public function query() But I would like to know the best way, and why.


texts: Views block to list all terms in homepage and list child terms in taxonomy page

texts:
I have a views block of taxonomy terms.

I want the block to display all terms when it is on homepage, and to list child terms when it is on a taxonomy page (contextual filter: Taxonomy term: Parent term:Taxonomy term id from URL).

example: I want to create a block to list news categories(first level only) when it is on home page (I can do this by using contextual filter Taxonomy term: Parent term-> fixed value=0).
and when the block is in a taxonomy page I want it to list the child terms of the current taxonomy (can be done using contextual filter Parent term:Taxonomy term id from URL).

can I have a single views block to do both, without having to create two blocks, one for home page and another for taxonomy pages.

A similar block that I want to create (I don't know if I need to create a separate question or it is just related to the previous one).

I have a views block of content with taxonomy term.

I'm trying to create a slider(views block) that displays the latest 5 news of each taxonomy term from url, I can do this using a contextual filter: Content: Has taxonomy term ID (with depth) then provide default value: Taxonomy term id from URL, this works fine in taxonomy pages.

what I need is, when the block is on front(home) page I want it to display the news from all taxonomy terms (neglecting the contextual filter).
I can do this by creating another views block without the contextual filter, but can I achieve this with a single views block?

sorry if this sounds confusing, and thanks for help.

UPDATE:

An example for the taxonomy view:

I have a taxonomy vocabulary "Categories" consists of parents and children

Politics:

Local
International

Sports:

Local
International

I have a views block that lists the terms of a vocabulary "Categories" (only the first level)

Politics
Sports

I need the block to list the top level terms when it is showed in Front page(Homepage)
and to list the child terms when it is showed in Taxonomy term pages

Ex: when it is in Politics page I need it to list only the children of Politics

Local
International

I want to achieve this with the same views block


texts: How to Make field required depending on other field?

texts:
I have 2 fields in my content type "blog"

1)promote to front page(boolen field with yes or no option)

2)Hero Image(image field)

If user selects "yes" option in promote to front page field ,the Hero image field should become required.

How it can be possible?


texts: Views exposed filters set per content type in same view

texts:
Sorry for my fuzzy title. The problem I have is that I have a view that lists 2 different content types. Now I want to use a filter that will only filter on ONE of the content types that is listed.

Say I have one content type named "Album", and one content type named "Songs" that gets listed in the same view. Now I still need to have them both listed in the same view, but I want to add the filter "First letter is A" to the songs ONLY.
So the Albums gets listed as before, but the songs that doesn't start with the letter A is removed.

Is there any way to accomplish this?


texts: Can entity IDs (node, taxonomy, etc.) be synchronized across environments?

texts:
It seems the content synchronization module syncs entities UUIDs, but not their entity IDs (like TID, NID, etc). Since it only does UUID, this can result in environments with mismatched IDs for the same entity.

Views filters based on entities filter based on the entity ID and not the UUID.

If your deployment target ends up having different TID than your view is filtered on, it will result in it being broken or showing wrong results.

I assume we can't be the only organization using the combination of the core config sync and the content synchronization module and so I'm curious how others are dealing with this issue.

Right now we're considering just copying the database over or maybe writing a script to update the IDs in the DB.


texts: How do other modules update elements using AJAX callbacks?

texts:
I have a block, of which I want to update the contents via AJAX. So the block is:

$block['subject'] = t('My Block');
$block['content'] = '

';

And the form element AJAX part:

$form['select_element']['#ajax'] = array(
  'callback' => 'ajax_callback',
  'wrapper' => 'block_wrapper',
  'method' => 'replace',
);

The callback:

function ajax_callback($form, $form_state) {
  return views_embed_view('view_name', 'default', $form_state['values']['select_element']);
}

However when I change the form element the whole block content is replaced and the wrapper is replaced by a empty div, so subsequent alterations of the select element fail to update the block.

The wrapper documentation explains the entire div is replaced, not just it contents. But many modules (like for example Views) have dynamically updating form elements where changing a select element toggles other parts of a form, which keeps working no matter how often you change it. Do they insert the wrapper div again in the response? And how should I alter the response of views_embed_view to put the contents in a wrapper div?


texts: batch importing node data -- via database?

texts:
I'm looking to migrate an existing site to Drupal. I have a a content type on the new Drupal site that will eventually hold some 1500 nodes. Of course, I don't want to enter each one in the form on the admin side; I'd like to input them programmatically, from a script.

What I'm wondering is if I can do plain old SQL INSERTS into the node and related tables, and have my nodes ready to use. Assuming I do the inserts correctly, will the nodes just be there when I fire up Drupal? Or will I need to touch some other parts of the site?

Or is there another way, like a module for batch importing?

This is for Drupal 7.


texts: How to update role name progammatically in Drupal 8

texts:
I am new to Drupal 8. I want to save & update role programmatically in database. I am using below code

    //your data array
$data = array('id' => 'client', 'label' => 'Client');
//creating your role
$role = \Drupal\user\Entity\Role::create($data);
//saving your role
$role->save();

It works fine. Now I want update role name. How to proceed it?

Please anyone suggest to me?


texts: What is the best practice to update our internal code from Dev to Prod for multiple sites?

texts:
Details:
We are not sure of the best practice to use for updating internal code, such as custom modules and theme. There seems to be two main processes to take and both look like the correct answer. Can you please help guide me into the correct workflow?

hook_update_N() - We have been writing hook updates in our custom modules and then running drush updb.
Config import/export - We also export the config changes so that we can build new sites with the same config files. However, we don't use config import on our live sites. This is where I am not sure what we should be doing.

Setup: We have a multi-site setup where all sites are using the same core code, this includes custom modules, main theme, and a admin theme (along with contrib modules, core, and libraries).
Question: If we were to update a couple of the config files inside our custom module (let's say a form display). Then we wanted to push this to our live site. Would we:
A) Write a hook_update_N() function to update the DB, save to git, run composer update (grabbing the new .install file) and then run drush updb.
B) Export the config changes (drush cex), save to git, run composer update (grabbing new config files) and then run drush cim to import the new config files to update the DB?


texts: Are 'safe_value' values generated dynamically from the 'value' value?

texts:
I'm changing the content of an HTML field using entity_metadata_wrapper, and I see 3 values, like value, format, and safe_value.

My question is if I have to also edit safe_value or it will be generated dynamically. Thanks

PS: I edited and saved only value then in next load, the other were empty. I went to the node and clicked Save and the safe value was regenerated. Maybe I should call a hook after editing value?
Currently I'm using the check_markup function to generate the safe_value from the modified value


texts:
I am trying to write files and read from them.  The following code works great on my local Kalabox server, but when I push to Pantheon, the files don't get written.

Could it be because all files are under sub versioning on Pantheon?

$csv_text = array2csv($db_result);
save_csv_file($csv_text);

if($_GET[save_to_email] == 'true'){
    save_defaults();
}

function save_csv_file( $csv_text){
    //$file = './inventory.csv';
    $file = 'public://inventory.csv';
    file_put_contents($file, $csv_text);
}

function save_defaults(){
    $default_vals = get_inventory_defaults();
    $default_vals[sort_direction] = $_GET[sort_direction];
    $default_vals[threshold] = $_GET[threshold];
    $default_vals[hide_zero_inventory] = $_GET[hide_zero_inventory];
    $default_vals[email] = $_GET[email];

    save_inventory_defaults($default_vals);
}

function get_inventory_defaults(){
    $file = './inventory_defaults.txt';
    //$file = 'public://inventory_defaults.txt';
    $content = unserialize(file_get_contents($file));
    return $content;
}

function save_inventory_defaults($my_variable){
    //$file = './inventory_defaults.txt';
    $file = 'public://inventory_defaults.txt';
    $content = serialize($my_variable);
    file_put_contents($file, $content);
    //file_save_data($content, $file, FILE_EXISTS_RENAME );
}

function array2csv(array &$array)
{
   if (count($array) == 0) {
     return null;
   }
   ob_start();
   $df = fopen("php://output", 'w');
   fputcsv($df, array_keys(reset($array)));
   foreach ($array as $row) {
      fputcsv($df, $row);
   }
   fclose($df);
   return ob_get_clean();
}

I am not sure when to go from here... A million thanks!!


texts: how to get the values of entity reference fields of a content type in a node page?

texts:
There is a content type in my website called singer and every singer may have name and some other information. there is another content type called songs and every song has two fields: (1) File (2) name. I also created an Entity Reference field in songs which links the song to a singer. obviously every singer may have any number of linked songs.

I listed the singers in a page and it must display every singer information and songs when the user click on any of the singers. this is my template.tpl.php

function MyThere_preprocess_page(&$variables)
{
    if (isset($variables['node']))
   {
        switch ($variables['node']->type)
        {
        case "singer":
            $suggest = "page__node__singers";
            $variables['theme_hook_suggestions'][] = $suggest;
            $variables['name'] = t($variables['node']->field_singer_name['und'][0]['value']);
            break;
        }
    }
}

I can get value of singer fields (using kpr()) but I don't know how to get the value of songs fields that are linked to a singer.

thanks


texts:
I'm looking for the right tool to develop a peer to peer trading website that would include E-Commerce. The site would need to allow registered sellers to enter details about their products this information would then need to be stored in a database that would allow buyers to search based on a set of parameters.

Would all this be achievable with current Drupal modules and how much additional coding would be required to knit it all together?


texts: Field contains list and values of it are shown in one symbol

texts:
I'm developing a drupal module and there's a problem. I need to make a content type with some fields and one of them should have list with string values. But when I try to create content and choose new content type I created, I see list and there are values contains first symbol of the string that I need.

coursebook.info.yml

name: Course Book
description: Course book
type: module
core: 8.x
package: Course book module

field.storage.node.field_disciplines.yml

langcode: en
dependencies:
  enforced:
    module:
    - coursebook
  module:
  - node
id: node.field_disciplines
field_name: field_disciplines
entity_type: node
type: list_string
settings:
  allowed_values: { "1":'A', "2":'Bb', "3":'Cccc'}
  max_length: 1000
module: core
locked: false
cardinality: 100

field.field.node.coursebook.field_disciplines.yml

langcode: en
dependencies:
  config:
  - field.storage.node.field_disciplines
  - node.type.coursebook
id: node.coursebook.field_disciplines
field_name: field_disciplines
entity_type: node
bundle: coursebook
label: 'disciplines'
description: 'Type disciplines here'
required: false
default_value: 'example'
settings: { }
field_type: list_string

core.entity_view_display.node.coursebook.default.yml

langcode: en
status: true
dependencies:
  config:
  - field.field.node.coursebook.field_year
  - field.field.node.coursebook.field_semester
  - node.type.coursebook
id: node.coursebook.default
targetEntityType: node
bundle: coursebook
mode: default
content:
  field_year:
    label: hidden
    type: string
    weight: 0
    settings: {  }
    third_party_settings: {  }
  field_semester:
    label: hidden
    type: string
    weight: 1
    settings: {  }
    third_party_settings: {  }
  field_disciplines:
    label: hidden
    type: string
    weight: 2
    settings: {  }
    third_party_settings: {  }

core.entity_form_display.node.coursebook.default.yml

langcode: en
status: true
dependencies:
  config:
  - field.field.node.coursebook.field_year
  - field.field.node.coursebook.field_semester
  - node.type.coursebook
id: node.coursebook.default
targetEntityType: node
bundle: coursebook
mode: default
content:
  field_year:
    type: string_textfield
    weight: 0
    settings:
      size: 30
      placeholder: 'example'
    third_party_settings: {  }
  field_semester:
    type: string_textfield
    weight: 1
    settings:
      size: 30
      placeholder: 'example'
    third_party_settings: {  }
  field_disciplines:
    type: string_textfield
    weight: 2
    settings:
      size: 30
      placeholder: 'example'
    third_party_settings: {  }
hidden: { }

And what I see -
But i shuold see this list:

allowed_values: { "1":'A', "2":'Bb', "3":'Cccc'}

There are only files that describe problem field. I hope you understand my problem. I develop my module using this manual: https://medium.com/touch4it/custom-content-type-with-custom-fields-for-your-drupal-8-module-9478fd018f76


texts: Images loading from server on every page load

texts:
I am using the views flexslider with same images on every page but when ever we go from one page to another or come back to the previously browse page it take a time to load images.

It seems like views always loads the images from the server. Is there a way those images could appear instantly on every page. May be loading the images through browser cache ??

EDIT

The problem was actually because of Adaptive Image module I have turned that off and the images are loading normally now.


texts: Sort view items by field collection's field value

texts:
I added a field collection to Basic page that contains:

box title
box image
box position on page

You can add 0 or more field collection's items to every basic page. Every node may contain 0 or more boxes. They will be used instead of default teasers. Here is an example:

Node 1:

field collection item: [Title 1, image1.png, 3]
field collection item: [Title 2, image2.png, 1]

Node 2:

field collection item: [Title 3, image3.png, 2]

Taxonomy Term View is configured as below:

Format: unformatted list
Show: Fields

FIELDS

Field: The field collection

FILTER CRITERIA

Content: Published or admin

SORT CRITERIA

Field: box position on page (asc)
Content: Post date (desc)

CONTEXTUAL FILTERS

Content: Has taxonomy term ID (with depth)
Content: Has taxonomy term ID depth modifier

However, items are sorted only by post date and "box position on page" field has no impact on sorting. I expect boxes to be sorted in this order:

field collection item: [Title 2, image2.png, 1]
field collection item: [Title 3, image3.png, 2]
field collection item: [Title 1, image1.png, 3]

Note that 2nd box leads to Node 2 and the remaining to Node 1.

How to sort boxes by "box position on page" field that is part of field collection?


texts: Programmatically setting an image field from hook_node_insert (drupal 7)

texts:
I have a content type that has a file field (which accepts only .zip file) and a screenshot which is an image field and is not displayed on the content submission form.  Instead I have a module that unzips the .zip file from hook_node_insert.  At this point I would also like to set the screenshot to be a .png extracted from the .zip file.  So far I have had no success and I always seem to get an error like this:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '463' for key 'PRIMARY': INSERT INTO {node} (nid, vid, type, language, title, uid, status, created, changed, comment, promote, sticky, tnid, translate, uuid) VALUES (:db_insert_placeholder_0,

Since I was having trouble getting this to work, I tried what I thought might be simpler, I.E. trying to set the node to some image from the web using code like this:

  $image = file_get_contents('http://drupal.org/files/druplicon.large_.png');
  $file  = file_save_data($image, 'public://drupalicon.png',FILE_EXISTS_REPLACE);
  $node->field_screenshot[LANGUAGE_NONE]['0']['fid'] = $file->fid;
  node_save($node);

but I always get the integrity constraint problem listed above.  Could my problem be related to trying to do this from hook_node_insert?


texts: Is there an easy way of achieving a multirow&multicolumn views carousel?

texts:
In my website I'm trying to do something like the carousel set under the portrait image in this web: http://www.maersk.com/en (I'm not affiliated to Maersk in any way). I don't want to do the animation done with the mouseover in the tiles.

What I have seen here is that this is done in some way that there is a flexslider with some gridlayouts that are cycling with the links attached.

I would want to do something similar to show my recent articles/pages posted in my web, being nodes of different type(some could be image, and others, text, so I thougt of creating a field in all my node types being a richtextfield, and show that on the View -I don't know if this is possible, but if it fails, I will use an image and whatever-).

I'm not asking anybody to do this for me. What I would ask is some advice about modules that could help me to achieve this in a more or less easy way, or any quick hints that could pass per your head.

Would be very, very appreciated. Thanks :)


texts: My Status report shows that my Drupal version is 7.32 but my Available Updates page says 7.30. Can you tell me why they would be different? No recent updates have been made.


texts: Adding a CSS, JS and HTML code to a block

texts:
Using Drupal 7.2 I've successfully added a Google Adsense banner to my website by creating a new block with admin/structure/block/add and puting Google's code as "raw HTML" (added that "raw HTML" format first in admin/config/content/formats/add) there:

Now I'm trying to add another block containg a Like-button by the russian social network Odnoklassniki.ru:

My problem is - they want me to add:

Head:

<link href="http://stg.odnoklassniki.ru/share/odkl_share.css" rel="stylesheet">

Body:

0

And call:

How could I do it the best way please? (it would be good not to have it updated every time I update the Drupal version)

When I just try to put all 3 pieces listed above into a block (as I did for Google banner) - the button doesn't work.


texts: Entity reference with ddf, dynamic dependent fields

texts:
I'm not able to configure ddf module, I followed the instructions but still nothing.

I'm sure is the best module for my necessity.

I have a content type "house" with a field "rooms" with cardinality +1.

In another content type I have a field "house", an entity reference of the "house" c. type and a dependent select list of rooms that should be updated by the value chosen on the precedent field.

I installed the ddf module, I created the view with the contextual filter and configured the dependent value with dynamic argument.

Unfortunately I'm missing something and the dependent value doesn't reload with the correct values.

Any tip will be much appreciated !


texts: What happens when you delete a field from an existing Content Type?

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


texts: How can I get a block to display only on node view in Drupal 6

texts:
I have a block that I need displayed only on the main page of a node.

I can get it to display on node/1/view by putting node//view in the conditions, but that only works if view is in the URL. I want it to show whether I go to node/1/view or node/1, but NOTHING else. If I try node/ it shows it for every node page, not just node/1. I also tried node/*/ but that didn't work at all as it appears the ending slash is being removed.