How to load a view's ajax when the view is programmatically loaded I am embedding a (calendar) view withing another view by using the following code (in a theme)..

        <div class="calendar-calendar">
          <?php echo views_embed_view('event_calendar', 'year_plan'); ?>
        </div>

The calendar itself is loading perfectly, however, it does have "Prev" and "Next" year links, which increment the year.  When you click on them, they navigate to a new page, with JUST this calendar view displayed.

I'd like them to navigate the years using the ajax it uses when I load the view without embedding.   Is it possible to load the ajax associated with these navigation links programmatically?

You have to enable ajax in the views. Probably you have to do it in both parent and child view.

To do so : go to Advanced -> Use Ajax


Subscribe/Unsubscribe link to a group's content type using Notifications & OG We're using the Notifications module with Organic Groups (in Drupal 6). We have been writing our own UI module for Notifications so that it is simpler to use and more tailored for our client's needs. One of the remaining tasks is to include a link in the groups that a user can click on to subscribe/unsubscribe to a group's content type.

Does anyone know what structure the subscribe URL needs to be to allow this?

I know for a normal thread it is: notifications/subscribe/[uid]/thread/nid/[nid] and notifications/unsubscribe/[sid].

OK, I eventually figured it out:-

notifications/subscribe/[uid]/grouptype/group,type/[gid],[type]


How to make a composite content type I would like to create a content type that has some unique fields but its other fields are references to other existing nodes (not a parent-child relationship but many to many relationship).

I have looked in entity reference module or field collection? Is there another way of doing this?

For example I have a synthesis report made up of smaller topics. I want this report to have a name and author but then it needs to reference multiple of these smaller topics (which are a content type of their own).

I could maybe make a Taxonomy term for every synthesis report?

The simplest way is to use the Entity Reference module. You can add fields to your content type which are a reference to other entities, like taxonomy terms, nodes, etc.

Note:  You can combine it with field collection, but you need to understand that a field collection is not the same thing. A field collection lets you group fields so you can re-used them. For instance if you have multiple addresses, you can create a field collection with street, zipcode, city, etc. But in itself, it's not an entity. Entity reference lets you point from one entity to another.


Views search to find users based on terms I want to have search inputs for users to search and find other users based on associated terms(I'm using term reference) of their user profile.  I'm using Search-API, Views-3, and Profile-2.  I created fields on the profile that have terms as check boxes.  But, I can't seem to figure out how to make a view with search inputs to find/search users by these terms.

~Then, this is probably a question for a different post.  But, could I filter the RESULTS to display only certain aspects of that users profile?  I would want the results to render a custom user-teaserprofile.tpl.php or something like that.  Thank you.

...the whole approach is somewhat related to a dating search or something like that.

With search API you create an index containing all the info that should be searchable. The easiest thing would probably be to create an index based on the Profile entity and add the reference to the User entity and add the fields you need, like the term reference.

If you only want to let users search on the term reference, you might want to exclude normal search altogether and use facets instead, that would allow users to select terms and get the users displayed. Alternatively you could just use Views alone since Search API in not needed if you don't do fuldtext search.

With or without Search API you can in Views select the fields you want to display, just like any view, and use the template options Views provide to customize the output of the search page.


Multi-page wizard webform that posts to external URL? I've got a multi-page wizard webform whose results I need to post to a specific URL. I see in the webform settings that you can set a Custom POST url. However, this appears to break the muti-page behavior. After setting this option the button that normally takes me from the first page of my webform to the second page instead posts to the given URL.

The option also appears to break the post-submission page that I've set in the webform settings. Any suggestions on how to remedy these issues?

It would appear that this needs to be done using a Remote Post handler (which can be added at site.com/admin/structure/webform/manage/form_id/handlers) instead of selecting the custom POST setting, as described at https://www.drupal.org/project/webform/issues/2961835


How do I set default product attribute? Simple Question here I hope.

I've got a Format taxonomy field on my product type Record that's defining an attribute (cd, vinyl, download etc.).

I'd like to have the same order and default value on the attribute dropdown on product displays. I've set the terms in the vocabulary in the order I want on product displays but it still seems the order is random when browsing the site...

any ideas?

According to Ryan, it's based on the weight of the terms you reference.

As far as the default product that is selected, it should be the first product referenced in the field. If you're wanting to set that dynamically, you can look at Commerce Product URLs which provides that functionality.


Single webform on multi-language site with different url aliases I have multi-language site with webform. I want to use the same (single) webform for each language so I used Webform Localization module to translate the webform via string translation. Everything works, but the urls now looks like /en/node/123 and /cs/node/123.

I'd like to have separate url aliases for each language, e.g. /en/my-form and /cs/muj-formular. How to achieve this?

You can achieve that using administration interface.

Firs, Go to admin/config/search/path and click "Add alias".

On "Add alias" page:

Select language.
Fill the field "Existing system path" with your webform node/{nid_number}
Fill the field "Path alias" with desired alias for that language.


Managing javascript / css dependancies? I know you can add css / js with the drupal_add_css() or drupal_add_js(). Is there a way to define dependancies ?

Use Case Example:

  I need a custom tabs/carousel jquery plugin working. I need jquery and
  jquery ui to load first. In order to ensure that i'd like it to load
  after jquery and jquery ui.

How would one do that?

Also, is there a way to declare if a script / library is already loaded? i.e. if i load two jquery (1.4 vs 1.8.1) libraries it'll conflict.

Or would this discussion be better suited for the drupal core issue queue?

This is pretty much what hook_library is for.  You define your library

function mymodule_library ()
{
    $path = drupal_get_path("module", "mymodule");

    $libraries = array();

    $libraries["mymodule_util"] = array(
        "title" => "MyModule Utilities",
        "version" => "0.0",
        "js" => array(
            $path . '/UTIL.js' => array(),
        ),

        'weight' => -10,
    );

    return $libraries;
}

You can add CSS and declare dependencies, if needed.

Then you say you want to use it

drupal_add_library("mymodule", "mymodule_util", TRUE);

This ensures all of the dependencies get loaded exactly once.

Check out drupal_add_library for more details.  The core jQuery UI components are loaded this way, too.  The module is system and the names all begin with ui., eg ui.scroller.

I would also check out jQuery Update to upgrade things so you stay in sync with that other jQuery plugins need.


solr search in multiple fields Now apachesolr search works only in content. It also have to work on other fields
for eg: on typing "test", It searches only in content.

My requirement is  to search on description,label also (which i have already indexed).
content:abcd OR description:sample_upload_document
Using  apachesolr.api.php,I tried hook_apachesolr_query_prepare($query)

function MYMODULE_apachesolr_query_prepare(DrupalSolrQueryInterface $query) {

     $query->addParam('qf','content description');
     watchdog('solr result',print_r($query,true));

}

refering to the sitehttp://knackforge.com/blog/selvam/drupal-7-filtering-solr-results.
After performing that, i found description is added to

SolrBaseQuery Object
    (
        [params:protected] => Array
            (
                 [qf] => Array
                    (
                        [0] => content^40
                        [1] => description
                    )

But still when i give the value for description, search results would not yield any value.

Am i correct in a way? why doesnt it return the result?

How to do that? default search,searches the given text only in content.How to make it to search on other fields like description,label?

You could use Search Api  Module

  This module provides a framework for easily creating searches on any
  entity known to Drupal, using any kind of search engine. For site
  administrators, it is a great alternative to other search solutions,
  since it already incorporates facetting support and the ability to use
  the Views module for displaying search results, filters, etc. Also,
  with the Apache Solr integration, a high-performance search engine is
  available for this module.

Using It you could create index for the field you choose!!


How do i mark html TRUE in l() In Drupal 7 we have option to mark HTML=>TRUE.

How can i do it in Drupal 8

my code is

    $create_icon_path = 'my_icon.png'; //my icon path
    $create_icon = '';
    $create_earlywarning_url = Url::fromUserInput('/node/5');
    $create_earlywarning = \Drupal::l($create_icon, $create_earlywarning_url);
    return $create_earlywarning;

But its printing the

"" in  tag.

Here is a way to do this:

$create_icon_path = 'my_icon.png'; //my icon path
$create_icon = '<img height=15 src = "/' . $create_icon_path . '">';
$create_earlywarning_url = Url::fromUserInput('/node/5');
$link_render_array = array(
  '#title' => array(
    '#markup' => $create_icon
  ),
  '#type' => 'link',
  '#url' => $create_earlywarning_url,
);
return \Drupal::service('renderer')->renderRoot($link_render_array);

Hope this solves it!


How To Force Search API To Reindex a Node / an Entity I'm working on Sear API. My entity has many items and data change by action of the user. I don't want to reindex all items of data. So I want to reindex an entity after user does the action. I found the topic but just for Drupal 7. So with search API for Drupal 8, how to I can implement force search API to reindex an entity? The way or snippet code I can use? Please help!

e.g. I have search index with some basic field like this:

I want to update the number of comment value after use add a new comment. Default search api doesn't not support that. And I don't want to wait for a cron to update value. Imagine one field very important not like the number of comment. That field needs to update immediately.

You can dive deep into the code of search_api to find solution for issue. See function search_api_entity_update() and search_api_search_api_index_update(). In case reindex number of comment, you can try this code:

// Example reindex after has new comment at node article id 1
$entity = Node::load(1);
$indexes = ContentEntity::getIndexesForEntity($entity);

foreach ($indexes as $index) {
    // Becarefull with indexes. Just for this case.
    // $datasource_id: entity:node (entity type)
    // $updated_item_ids: 1:en (node ID and Language)
    $index->trackItemsUpdated('entity:node', ['1:en']);
}

You can debug in search_api.module to more info.


Send mail to product owner only when the email adress is available As a follow up to previous questions asked by me:
Send mail to product owner with Rules and Fetch Customer Profile from Line Items. I have the following question.

I created a rule to send an e-mail to the product owner of a product in my commerce webshop. The email address is added to the product by hand in a custom field. The rule is working when the email address is available but when not available it sends out an error. How can I check to see if the e-mail address is there and only then send the e-mail.

This is my rule:

{ "rules_svds_send_mail_to_product_owner" : {
"LABEL" : "SVDS: Send mail to product owner",
"PLUGIN" : "reaction rule",
"ACTIVE" : false,
"OWNER" : "rules",
"TAGS" : [ "SVDS" ],
"REQUIRES" : [ "rules", "commerce_payment" ],
"ON" : { "commerce_payment_order_paid_in_full" : [] },
"DO" : [
  { "variable_add" : {
      "USING" : { "type" : "commerce_order", "value" : [ "commerce-order" ] },
      "PROVIDE" : { "variable_added" : { "commerce_order_value" : "Commerce Order" } }
    }
  },
  { "LOOP" : {
      "USING" : { "list" : [ "commerce-order:commerce-line-items" ] },
      "ITEM" : { "line_items" : "Commerce Line Items" },
      "DO" : [
        { "component_rules_perform_an_action_on_a_selected_line_item" : { "selected_line_item" : [ "line-items" ] } }
      ]
    }
  }
]
}
}

The component I use in the loop is like this:

{ "rules_perform_an_action_on_a_selected_line_item" : {
"LABEL" : "Perform an action on a selected line item",
"PLUGIN" : "rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules", "mimemail" ],
"USES VARIABLES" : {
  "selected_line_item" : { "label" : "Selected Line Item", "type" : "commerce_line_item" },
  "commerce_order" : { "label" : "Commerce Order", "type" : "commerce_order" }
},
"IF" : [
  { "entity_has_field" : { "entity" : [ "selected-line-item" ], "field" : "commerce_product" } }
],
"DO" : [
  { "entity_fetch" : {
      "USING" : {
        "type" : "commerce_product",
        "id" : [ "selected-line-item:commerce-product:product-id" ]
      },
      "PROVIDE" : { "entity_fetched" : { "product_fetched" : "Fetched Product" } }
    }
  },
  { "entity_fetch" : {
      "USING" : { "type" : "commerce_order", "id" : [ "commerce-order:order-id" ] },
      "PROVIDE" : { "entity_fetched" : { "fetched_customer" : "Fetched user" } }
    }
  },
  { "mimemail" : {
      "USING" : {
        "key" : "[commerce-order:order-id]",
        "to" : "[product-fetched:field-e-mailadres-product]",
        "subject" : "Product ordered",
        "body" : "E-mail body text",
        "language" : [ "" ]
      },
      "PROVIDE" : { "send_status" : { "send_status" : "Send status" } }
    }
  }
]
}}

Thanks in advance

The email address is added to the product by hand in a custom field

I supouse that the field for entering email, is an email field (must enter a 'valid email' in format: somename@someurl.something, avioding a 'blah blah email'), if so:
then in your rule add a condition: [your_email_field] is not empy, if that condition is far away to be implemented in rules area: condition, then use rules conditional module, when your a ready to implement 'send email' in your rule, before that accion, add condition: [your_email_field] is not empty, if user entered a 'fake email', drupal will send email, but it will not go anywhare, this way you can avoid your error, and only valid emails will be delivered.


Show map notes under map? Is it posible to show the selected data under the map also? When i enable "københavn" as show at the picture, then there should be a list of resturants downunder also?

Yes - this is possible with the great views support in the Leaflet module you are using:

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

I'm assuming that you are using Views to render the above map given the number of data points you are displaying (and if not you should consider it). If so, then the easiest way to do this would be to edit your view, and add an 'attachment' display based on the same arguments that you are using for the above view (including the contextual filters you are using) and then change the display format to whatever you want (ex. an html list, a table, etc.) Attach this to your map view (display below) and you're all set.

Another option would be to do the same but render it as a block display instead and then place this using context or block admin to place this right below your map view.


Why are only a few actions available on my triggers page? I'm customising the content publishing flow of my site using actions and triggers. Unfortunately I've got a problem that not all the actions are show on the triggers page.

For example on
I have: ["Choose an action", "Make content sticky", "Make content unsticky", "Promote content to front page", "Publish content", "Remove content from front page", "Unpublish content", "Change workflow state of post to next state", "Ban IP address of current user", "Block current user"]

Whereas on all other trigggers I only have these actions available:
["Choose an action", "Delete archived revisions", "Publish the most recent pending revision", "Change workflow state of post to next state", "Ban IP address of current user", "Block current user"]

Does anyone know why all actions are not shown for all available triggers?

Thanks

I had the same problem. The solution is to use the RULES module which is the successor of Triggers. If you want to use Triggers anyway (you shouldn't as my impression is it is being phased out and migrated to RULES) you would have to do code modifications (via drupal hooks).

With Rules, you can have all these options about publication of nodes and even more.


Override config per role I have implemented a service with the tag config.factory.override. In my class I check if the current user is logged in, and if so I change the system.site.page.front variable to a different page. This kind-of works, but I have a problem with cache. If the first user to visit my site is not logged in that frontpage will be used for everyone, and if a logged in user is first, that version is used for everyone.

This is my current attempt at the getCacheableMetadata:

/**
 * {@inheritdoc}
 */
public function getCacheableMetadata($name) {
  $metadata = new CacheableMetadata();

  $metadata->setCacheContexts([$this->isLoggedIn ? 'user.roles:authenticated' : 'user.roles:anonymous']);

  return $metadata;
}

As @4k4 commented, I don't think that works.

I'd suggest you either use Page Manager/Panels, which allows to create a page with multiple displays and conditions like based on the user role.

Alternatively, you could create your own controller and return the desired page.

I don't know what you want to do exactly, but yet another option would be to keep two separate pages and redirect authenticated users to the different frontpage. That's similar to how drupal.org works, where you can configure whether your front page should be the default or your dashboard as an authenticated user.


How to create custom module for admin area in drupal 8 Sorry if this question is so basic, I'm new about drupal.

So far which I know, we can create custom module or page in drupal 8 so we can access it with http://www.oursite.com/custompage.

What I need? Is possible to create custom module or page which can show in admin area? In this case, I want to sync a lot of accounts from another system/web app to my drupal site so I don't need to create manually using "people menu" in admin area. Or is there any best way to do that?

Can anyone provide a helpful articles to accomplish this? Help would so appreciated.

Main question is "how to have a module show up in admin area".

Create your custom module
Create your custom route in the "your_module.routing.yml" - file

Example:

your_module.admin_settings:
  path: '/admin/config/your_module/import'
  defaults:
    _form: '\Drupal\your_module\Form\ImportForm'
    _title: 'Import XYZ'
  requirements:
    _permission: 'administer site configuration'

Define the link in the "your_module.links.menu.yml" - file

Example:

entity.your_module.admin:
  title: 'Import XYZ'
  route_name: your_module.admin_settings
  description: 'Import XYZ'
  parent: system.admin_config_system
  weight: 100

... thats it!
In step 3 this line is the important part:

parent: system.admin_config_system

If you need a menu entry in "structure" you can use:

parent: system.admin_structure

Just read other xyz.links.menu.yml - files to find different parent-path.


Theming Block Contents in Drupal 7 I can change the overall layout of a block editing the block.tpl.php file. I can modify the way subject looks, but what I want to take control over contents of the block which is accessible by single line of code:

<?php print $content ?>

Now, How can I theme contents of the block, i.e. list items etc?

If I've failed to clarify myself, please mention it in your comments. Thanks :)

Before blocks get to the theme layer, they can be altered. Blocks are represented as "render arrays", which means you can manipulate them with the Render API.

You can use hook_block_view_alter() to change the contents of a block.

Any module or theme can implement this hook. For example, a theme named YOURTHEME would have code like this:

function YOURTHEME_block_view_alter(&$data, $block) {
  // Remove the contextual links on all blocks that provide them.
  if (is_array($data['content']) && isset($data['content']['#contextual_links'])) {
    unset($data['content']['#contextual_links']);
  }
  // Add a theme wrapper function defined by the current module to all blocks
  // provided by the "somemodule" module.
  if (is_array($data['content']) && $block->module == 'somemodule') {
    $data['content']['#theme_wrappers'][] = 'mymodule_special_block';
  }
}

Or, if you know in advance the module and delta you'd like to alter, you can use hook_block_view_MODULE_DELTA_alter() like this:

function YOURTHEME_block_view_MODULE_DELTA_alter(&$data, $block) {
  // This code will only run for a specific block. For example, if MODULE_DELTA
  // in the function definition above is set to "mymodule_somedelta", the code
  // will only run on the "somedelta" block provided by the "mymodule" module.

  // Change the title of the "somedelta" block provided by the "mymodule"
  // module.
  $data['subject'] = t('New title of the block');
}


Displaying the username of the user who created the node in the node template file I created file node--my_content_type.tpl.php, where I'd like to print the username as string. I tried the following code, but unfortunately it doesn't work. How can I do it?

<?php
  print $name;
?>

$node->name will get you the name of the author who submitted the node. It will return it as string, not as link to the user account.


Change published status directly in database I want to change published status of nodes according certain criteria. So I directly modified 'status' column of 'node' table. But it seems to be not reflected when nodes are viewed or edited (I want to avoid using node_lodad() and node_save())

That is, if I change 'status' column value of a row in 'node' table, it does not reflected in when corresponding node opened in browser.

So, from where it takes the 'status' (publihed/unpublihed) value other than 'node' table?

You also need to change the status column in the node_revision table:

foreach (array('node', 'node_revision') as $table) {
  db_update($table)
    ->fields(array('status' => 0))
    ->condition('nid', $nid)
    ->execute();
}

Notwithstanding any aggressive caching you might have in place, the effect should be immediate once you've run both those queries.

Drupal has plenty of these little nuances, which is why it's highly recommended to use the API functions rather than manipulating the database directly. Yes there's extra overhead, but you don't need to give things like the revisions table/caching a second thought as they're handled for you.


How to allow user of certain role to create user only of selected roles? I have few profiles. One profile per role. I've created few registration paths by Profile2 Registration Path module.

I have an issue with permissions, for example I want  allow user of role A, to create users of roles A or B, but because Profile2 Registration Path uses 'administer users' permission on it's registration paths, certain role can create users of all roles or none at all. Maybe I missed something, but I'm stuck.

Try Role Delegation

  This module allows site administrators to grant some roles the
  authority to assign selected roles to users, without them needing the
  administer permissions permission.


How to set transactional email api key for external app in drupal like mandrill Like mandril,I have app for routing system transactional mails through that.I got create account in that app and getting api key for my drupal site,But i dont know how to process it (where to add that api key to configure it)on drupal to send mail.please clarify.

Assuming you're using the Mandrill module, the API key can be configured at this path:

/admin/config/services/mandrill


Not able to log in to Drupal site as other user I am a site admin (Drupal 7 - all updates are current) and am able to log in with my own credentials.  I'm working an issue and need to log in as another non-admin user.  No matter what I try, I'm not able to log in as this particular other user though I have verified their user email address and password.  I have copied and pasted their email address directly from their user account.  I have also reset their password so I know it is correct.  I have tried turning off clean url's (as suggested by another forum), but that didn't help.  I have cleared the site cache.  I contacted the user and she is able to log in/out and back in with the exact same credentials I'm attempting to use.  We have had this problem with another non-admin user on this particular site but it hasn't happened in quite a while and never with this user.  I have logged in as this user prior to this happening but it has been a few months.

I saw another post on this site about the same thing but didn't really see a solution (Cannot log in to Drupal site).

Does anyone have any ideas?  This is quite an inconvenience.

Once I was able to get in touch with my other site admin and she was able to log in with the same credentials I knew the problem was local.  I had tried different browsers.  I flushed my DNS and rebooted my computer and was able to log in.


paging an array result in D7 I have a Query like this:

$query = db_select('nid_tid', 'nt')
->fields('nt')
->condition('terms', $name,'=');
$result=$query->execute();

$row=$result->fetchAssoc();
$nid =$row['nid'];
$ex=explode(',', $nid);
foreach ($ex as $tag_nid)
{
  $out .= $tag_nid;
}

return $out

I want paging this result .for example per 10 result in one page

thank you

You need to extend the query to a PagerDefault, and then use theme_pager() to output the pager links at the end of your content. The rest will be taken care of for you:

$limit = 10;
$query = db_select('nid_tid', 'nt')
  ->fields('nt')
  ->condition('terms', $name,'=');

$query = $query->extend('PagerDefault')->limit($limit);

$result = $query->execute();

$row = $result->fetchAssoc();
$nid = $row['nid'];
$ex = explode(',', $nid);
foreach ($ex as $tag_nid) {
  $out .= $tag_nid;
}

$out .= theme('pager');


How do I use a theme hook suggestion in template.php? How do I convert a theme hook suggestion into a function in template.php?

Here is an example I pulled using TEMPLATE_preprocess_field() with dpm().

What would I name my function in template.php to utilize field__field_video_virtual_tour__basic_drealty_listing, and where can I find the default theme function for a text field to use?

The default theme function for all fields is (wait for it), theme_field().  You can copy this function into your own theme, and rename it to MYTHEME_field(), either to alter or to refer to as reference.

You would then name your specific version MYTHEME_field__field_video_virtual_tour__basic_drealty_listing().  Note the two underscores separating the parts.

For reference, the standard suggestions are

MYTHEME_field__FIELDNAME__CONTENTTYPE()
MYTHEME_field__CONTENTTYPE()
MYTHEME_field__FIELDNAME()
MYTHEME_field()

Also remember, these are really just to wrap your elements with some HTML.  If you want to change the way the element itself gets rendered out, you should really make a field formatter.


How to log in a user and inspect their role in a functional test? I want to write a functional test that takes some test user credentials in a remote system, and posts them to Drupal login.

So far, I have

  /**
   * These users should authetnicate via Netforum.
   */
  public function testNetforumUsersCanAuthenticate() {
    $this->drupalGet('user/login');
    $edit = ['name' => [redacted], 'pass' => [redacted]];

    $this->drupalPostForm(NULL, $edit, t('Log in'));
  }

The authentication always goes through the external system even if the local account exists in Drupal. Therefore, I cannot just create these accounts beforehand.

The account should get created when authentication passes - and then I want to look at the users roles to check if they match what I expect for the different test accounts.

What can I use to see that this was successful and then look at the roles and check them?

You should be able to load the user object using user_load_by_name(), and then just make your assertions:

$account = user_load_by_name('foo');
$expected_roles = [
  'foo',
  'bar',
];
$this->assertEquals($expected_roles, $account->getRoles());

As an aside, it may be worth pursuing a mocked/testing authentication service for your tests. This way they don't rely on an external service, and will be more stable and reliable.


Token to get the last component of [node:url] I'm using [node:url:relative] but my path has multiple parts /content-type/node-title . I would like to get only the node-title part.

Alternatively, a token that give me the node title transliterate would be fine.

[node:title] will give you the node title.


Embed unique custom form in all rows of a view I want to create a custom form that will be embedded on each row for visitor to submit an email for that specific row.

I suppose I have to create a custom form (which I have done before) but how do I embed it on each row ?  hook_views_data_alter(array &$data) is the right way ?

Other questions (but not that important) are how do I make it unique (know which row the user has submitted) ? Another requirement is to be submitted without reload of whole page (ajaxy form).

That's a lot questions in one post. Two things may help you:

First, if you have more than one instance of a form on one page, you need different formIds. So implement the getFormId with a variable, like so:

public function getFormId() {
    return "mysuper_form-".$this->whatEverCounter;
}

Then, you will need to create your form yourself with the constructor (cause you need your state to be set from outside) and pass that instance to the formBuilder, for example like so

$idForm = new myForm($whatEverCounter);
$form = \Drupal::formBuilder()->getForm($idForm);

Second, for the "each row" topic:
If you really have one form per row, you will have one submit per row also - no problem. Or, you have one form with one element per row. Then just enumerate your elements like so:

public function buildForm(array $form, FormStateInterface $form_state) {
    foreach ($ems as $e) {
       $form['toggle'.$e] = []
    ]

If you need an ajax submit callback, use the '#ajax' attribute, like so:

'#ajax' => array(
        // Function to call when event on form element triggered.
        'callback' => [$this, 'toggleButtonPress'],
        // Effect when replacing content. Options: 'none' (default), 'slide', 'fade'.
        'effect' => 'fade',
        // Javascript event to trigger Ajax.
        'event' => 'click',
        'progress' => array(
        // Graphic shown to indicate ajax. Options: 'throbber' (default), 'bar'.
        'type' => 'throbber',
        // Message to show along progress graphic. Default: 'Please wait...'.
        'message' => NULL,
        ),


How to show comments for an unpublished node this is my problem,

A node is in unpublished state
The "View own unpublished content" permission is set
The node author posted a comment on the node, but the comment is not getting rendered in the node page
The super admin user though can see the comment.

Is this normal in Drupal 7? If so, how can I make those comments visible for the node author?

Hope I can explain my problem, thanks...

I vaguely remember I had once an issue with viewing unpublished content and the view_unpublished module offered me a better granularity that solved my issue.

Otherwise I would say creating a view showing comments in relation with the node, using a contextual filter nid, and without the filter "content: published" might help.


Using view result as an input filter for another view Let me explain my scenario at first.

I have two content types in my site.

First is products and second is producer.

Each product has only one producer and each producer has one or more products.

Now in every product page, I want to show the producer information. I made a view block for this issue and it works well.

but in the product page, I also have a plan to show all products of the producer of current product in another block.

In order to show the product nodes of a specific producer I need the node ID of producer content type.

I tried to use Contextual filters --- Provide default value "When the filter value is NOT available" via Content ID from URL but this function returns node ID of current product not producer id. (because we are in a specific page of single product)

Now I am searching to find a solution for this issue.

thanks a lot for your guidance.

Say, the term reference field in the product content type is called "field_ref_producer". You need to have this block of code, and a view that accepts a contextual filter for "term reference producer ID" ready.Let this view be called "other_products_producer"

$node = menu_get_object();
$output = '';
if(is_object($node)) {
  $producer_id = $node->field_ref_producer['und'][0]['tid'];
  $output = views_embed_view('other_products_producer', 'default',$producer_id);
}
echo $output;

Basic idea is, grab the node object from URL, get the producer tid from it and then embed a view passing the producer nid as contextual filter to the view.

Update:

Code to put in views PHP (default value of contextual filter):

$node = menu_get_object();
if(is_object($node)) {
  $producer_id = $node->field_ref_producer['und'][0]['tid'];
  return $producer_id;
}

Please replace the name of the field to what you have in  your content type.


Adaptive Theme: give the option to user to switch between fluid and fixed layout in specific nodes I would like to give the option to my users to switch between fluid and fixed layout when viewing nodes of a specific type. There is an option in the adaptive theme where you set the maximum width. Is there a way for me to bypass this and give a button to my users that will allow them to switch between fluid and fixed layout?

Assuming that you did not heavily modify the base structure of Adaptive Theme, you can explore using a custom solution to do this.

For example you can add a button like this in a block's contents (using the Raw HTML input format):

<button id="toggle-width">Toggle Width</button>

then a new class in your CSS to override the max-width property in .container (this is where the max-width is set in Adaptive Theme):

.page-full-width { max-width: none !important; }

and then add some jQuery to your button:

$( "button#toggle-width" ).click(function() {
  $( "#page" ).toggleClass( "page-full-width" );
});


In Panels, how are the 2 given arguments in System's node_view created? In the Panel pages for System node_view (Node template) and term_view (Taxonomy term template), there is a variant that is already defined. This variant has 2 arguments, "Node being viewed" and "Depth". How are these arguments created?

thanks,

Eric J.

Panels has by default some operations on url arguments which can create variables used in Panels. The short explanation is that Panels for nodes does a node_load on the node id which is part of the url: node/[nid]. It does something similar for taxonomy terms, only depth isn't the term itself, but rather information about it.

You can do this yourself if you create a custom url with placeholders, like my-panels-url/%node and assign the variable to be a node or taxonomy term.


Changes made in hook_node_view() are not applied? I wanted to change the title of a node field on the node display page.

I have implemented hook_node_view() and changed the title in code using following code:

$node->content['my_field']['#title'] = t('Field Name');

When I dpm() the $node object I can see that above code has been successfully executed, but on node display page I still don't see the field name changed.

I also did a dpm() of $content from tpl file and found out that $content['my_field']['#title'] has been set to 'Field Name' as per above code. But it still displays the older title.

Whay may be causing this to happen?

Hi you have added extra fields in the content variable so you have to override the old title


Drupal commerce. How to show only products suitable for selected vehicle? Any ideas how to tackle following scenario with Drupal Commerce?

User selects his own vehicle from select drop-downs. Vehicle consists of following attributes: vehicle type, manufacturer, year, model. Then, by clicking any product category, user gets a view of products in that category that are suitable for the currently selected vehicle.

There are 50000 products in Excel file (with unique SKU), 8500 different vehicles as csv (with unique vehicle id and each vehicle attribute in their own columns), there are going to be 800+ product categories with many subcategories (snow mobiles, scooters, engine parts, exhaust pipe systems…) Many products may fit in many vehicles.

So where to start? How to match products with vehicles? How to match products with categories? Any help is appreciated. Thank you.

General solution is to use Entity reference.

You need two entity types:

Cars
Products

Products you have already, thanks to commerce. Cars can well be nodes so you can create content type for them using GUI. To products add entity reference pointing to cars. Then create a view with product to car relationship, filtered by car.

For categories, use regular taxonomy.


I need a advanced search block (by using views) on home page of site I'm beginner in drupal.
I'm developing a site contains products that are displayed some product blocks by using views module on front page like featured products and top rated products.
Now, I also need to add a advanced search block (by using views module) on front page like I've attached image below. This search will only search from the one type of content named product and show another page.

How to add input field name titled, dropdown list, radio buttons and Search button while creating views block?

For Drupal 7 you can create mentioned output via setting Filters and set the option "Expose this filter to the user"
Moreover, you can add checkbox using BEF(Better Exposed Filters).
I hope this helps. :)


How to list out Flag content User in event page in Drupal Commons I tried to create the equivalent of the RSVP module (for which no D7 version exists ...) in combination with Drupal commons. But I didn't succeed in that.

So I then decided to use the Flag module, and created a flag for Participant Flag (Participant/Maybe/No) using the answer to my question about "How to implement RSVP Functionality?".

The implementation of the Flag for this is OK, but my next question now is "How to get the exact list of Participants, with some User details?". Some of the User details I want to get included in the list are:

User Name
User Picture

Assume that user A will attended a "Sample event" and user C will not attended that event. Also assume that user B will maybe attended that event.

How to create these 3 lists, for each of the 3 flags I am using (1 flag for each of these lists):

Participant List
Not attended List
Maybe Attended list

Anybody any suggestions?

Create a head count for each flag

Refer to listing flagged content with Views for a tutorial about creating a view with flagged content.

Starting from around 6:55 (and up to around 12:05) it explains How to create a view showing flagged content. Before 6:55 it mostly shows how to create that "Sidebar" flag (skip that part if you know that already). Here are the relevant steps in it (that you want to pay special attention to):

Even though the video uses a "global flag", your case is NOT a global flag (i.e. each user can flag/unflag, not just a restricted list of users, such as those with "administrators" or "content editors" role).
The tutorial creates a view of type "block", but you probably want to create a view of type "page" (though a "block" might be sufficient also if you prefer).
Within the "Advanced" link of the Views UI, you must add a "relationship" (think of an SQL "join" if you're not familiar with Views). To add such relationship, enter "Flag" as the "filter" on the popup window (as shown in the video around 8:25). You'll then get a shortlist of about 7 possible relationships to select from. Your question doesn't say (yet) if the flags you use apply to "nodes" or to "users", but I'm about sure (and going to assume) you'll be using "nodes". So use Flags: node flag counter as relationship. You might possibly also be able to use the Flags: node flag relationship instead (which is NOT shown in the video here), because the Flags: node flag relationship brings in more data about the flagging event, such as "who flagged it, when, etc".
As shown/mentioned from around 10:20 in the video, this video is about a "global flag". If it would have been about a none-global flag, then it would count the people who have used the "flag". So with only that, you already have like a "head count" of people who have "set the flag". Something like "number of attendees" already?
After you finish the first view for (say) the first flag, then repeat what is above by cloning that first view into a 2nd (and 3rd) view, and then adapt the 2nd view to use the 2nd (and 3rd) flag, to build a similar list.
As shown/mentioned from around 11:00 in the video (up to around 12:05), if you've selected to create a view of type "block" (not a "page"), then you still have to position the block (created by the view(s)) in an appropriate theme region.

Add more details about the flagging user

Refer to Getting the flagging user into Views for a tutorial about how to add more details about the flagging user (starting from around 2:00, though the real "Views" related part starts from about 4:00). Here are the relevant steps in it (that you want to pay special attention to):

This is about creating a view op type "page" (not block), which is also what you probably want, in the format of a simple tabular display.
The "path" where this view will be shown (around 4:40), like user/%/friends, which in your case I'd suggest something to become like user/%/events.
The "menu tab" that will be created (around 5:10), like Friends, which in your case I'd suggest something to become like Events.
The 2 (not just one ...) relationships that get added here, i.e.: Flags: User Flag (around 5:40) and Flags: User, which is The user that flagged an item (around 6:55)
Note the "contextual filter" that gets added (around 7:40, up to around 9:00), i.e.: User: Uid. It's to answer questions like "what are the events that this user confirmed to be attending so far".
Starting from about 9:10, the actual user details (such as User: Name) get added.

Starting from around 9:45, you get like a summary of it all, i.e.:

Start from a user profile (such as user/1) and use the (new) tab Friends.
A recap of the "crucial part" of this view, i.e. the 2 relationships that this view is using.


How do I change value of a boolean field on a node when a user clicks a button? I am building a small site for a friend who is getting married and they have their gift list online. Each gift is a node which I am thinking will have a boolean field called something like "bought". The functionality I want to create is that visitors can look at a list of gifts and, if they want to buy something for them they just need to click a button next to it.

So my question is simple, can I change the value of a node field when a user clicks a button?

There is a ready contrib module: Wishlist.

  Other site users can indicate their interest in purchasing an item from a wishlist. When that happens, everybody can see that somebody purchased the item and duplicated gifts are eliminated (or reduced - the wishlist module does rely on people playing nicely together).

If you just want the job done, that's your way to go. If you want to learn, read about node_save() and Form API.


How to create and display user content submission form and display it in a block? I want to build a user feedback form to create a content type which can be outputted as a view page. What I discover is that, i can create a new content type in which anonymous user can add contents, but I need that form to be in a block on a sidebar.

You can make use of the form block module.

  Enables the presentation of user registration, site wide contact, or
  node creation forms in blocks. This is particularly useful for
  including forms on panels.

Since the drupal 7 version is still in development, make sure to test it on a development site before moving it to a live site.


Hook for node preload Is there any hook for when the node_load or node_load_multiple functions are called, but before they are actually loaded from the DB?

I need this because I want to cache my nodes before Drupal goes and queries the DB for them.

No there's no such hook I'm afraid (see the list of hooks for Drupal 7).

If you want caching that goes beyond the normal static page cache provided by node_load() then you might want to look at the Entity Cache module, which "puts core entities into Drupal's cache API.". Even if you don't end up using that module you can inspect the code to get some ideas for implementing your own caching system.


How to list Taxonomy Terms with Pictures in View? I want to create a View with the list of Taxonomy Terms in Drupal 7.
I edit the taxonomy content type so that it has 1 extra image field.

I want to show all Taxonomy terms with their image but I cant seem to find it anywhere in View options.

When you create the view, you need to create a view of taxonomy terms instead of of content/nodes like you have done in your SS above. Then you have all the fields etc available that you have on your terms.


What's a good way to prepopulate web form fields with data from an external database? What might be a sane approach to prepopulating web form fields using data from an external database on the fly? This is my scenario: there is a form that we need clients to fill out, but we already have a lot of the client's information in our database. So to make it easier on the client, we want to fill out the form as much as possible before sending it to them to fill out the rest. I'm using the webform module on our Drupal 7 site, but all the data needs to come from our other database.
Ideally, there would be either a page or just a field where I can select the client ID. After choosing the client ID, other fields would use that ID to pull information like contact name, address, etc.
Is there a reasonable way to do this?

You would need to expose an API from your external database. If the external database is also a Drupal 7 site, you could use the RestWS module to do this (https://www.drupal.org/project/restws).

Once you have your data exposed via api, you would then have to connect to the api on the client's site, and you could auto populate some hidden fields via an ajax call when they select the ID. You would want to do this in a custom module.


Download true file name instead of from drupal version changed filename i have some file upload fields which works great. the file is stored on public file system and will be able to get downloaded from the users (in a specific node).

the issue is when i update the file (pdf) with a new version in the same month, drupal renames the file and save a new instance instead of updating the file (i know the reasons, avoiding global file conflicts on the page).

the user will download the renamed file which is wrong (e.g. manual_1.pdf).
how can i change the filename into the name that is in its metadata (manual.pdf).

is there any hook, module or settings?

Is all depends on how your loading the file information. As the filename field in the file_managed table will always be whatever is uploaded. e.g.
filename = mypdf.pdf
uri = mypdf_1.pdf

So you can always use the filename value for the real file name. It sounds like whatever you're using to load the file/create the file link isn't using this correct value


Create a link to the fist item of a specific view block I have different view blocks on my front page and they contain number of contents such as images, articles, news etc.

I've managed to get the block list and the block object for each item in that list but how do I fetch the nodes of a view block and generate a link to it programmatically?

$blocks = \Drupal::entityTypeManager()->getStorage('block')->loadByProperties(['theme' => $theme->getname(), 'region' => 'content']);
$block_list = array_keys($blocks);

$firstblock = $block_list[0]; // views_block__latest_image_galleries_block_1
// fetch the node list and create the link for first node for $firstblock here.

Since this is a view block, you might be better of directly accessing the view:

$results = views_get_view_result('my_view', 'block1')

Where block1 is the Views display ID. Leave it blank to utilize the default display.

Then

$node = $results[0];
$url = $node->toUrl()->toString();
$link = \Drupal::l('My link', $node->toUrl());


how to have block show up on specific pages AND specific content types I want to be able to have a particular menu block show up on specific pages, as well as on specific content type pages. My content type pages don't start with /node, so I can't simply say

pagename
/node/*

in the block settings. (I am trying to do this from the UI. If thats not possible, then please tell me what the best way to do this in code is.)

The Context module makes advanced block placement very easy in the ui. In your case you would:

Download Context and enable Context and Context UI,
go to admin/structure/context,
click add,
give your context a Name in machine name format (no spaces, use lowercase and underscores) ie. my_context
Under "Conditions" add a condition of "Node Type"
Select your Content Types
Add another condition, of "Path"
Enter the specific paths that you would like the block to appear on, one path per line
Add a "Reaction" of type Block
Check your block or blocks off to the right and click the "+ Add" button in the region that you would like to place the block.


how to remove anonymous user role from list of profile members I want to remove anonymous role member from the public list of profile users because anonymous roles cannot join so it is confusing to see the anonymous user at top of public profile list.

Add a filter for user: UID and set to "not equal to" and enter 0 for the value.


finding a route to form mode and add it local tasks I have a content type named "film" and a form mode named "film_artistic"

in my_module.routing.yml, I have added this entry:

my_module.film.artistic:
  path: 'node/{node}/artistic/edit'
  defauts:
    _entity_form: node.film_artistic
    _title: 'Edit artistic info'
  requirements:
    _permission: 'access content'

But when I try to reach, let say "/node/6/artistic/edit" I got a "Page not found" result

I don't know what I am missing...

My ultimate goal is to have several form mode for my film content type (ex: Artistic, Technical,...) and for each of them, I would like to create a "Local Task" sharing the same base_route: "entity.node.edit_form".
For my first local task, I have to add the following in my_module.links.task.yml:

film.artist:
  route_name: my_module.film.artistic
  title: Edit artistic info
  base_route: entity.node.edit_form
  weight: 20

But of course I can't test it as my main route is not working (node/{node}/artistic/edit)

I could find a solution with an handy module: https://www.drupal.org/project/form_mode_control

After installation, you can reach any form by using :

 www.your-site.com/node/add/my_content_type?display=machine_name_of_your_form

or

www.your-site.com/node/{node}/edit?display=machine_name_of_your_form

More then this, this module allow you to set permission to access each form mode.

I am still looking for how to add those forms as local task... but the main thing is done

My objective is: if I go to node/add, or node/{node}/edit, I would like to have the default form displayed but also, all the form mode accessible as Tabs (local task)


How to set jquery datapicker options from within Drupal? I want to customize a jQuery datapicker in Drupal 7. I found code to set an event:

(function ($) {
Drupal.behaviors.only_monday = {
  attach: function (context, settings) {
   // $( ".selector" ).datepicker( "option", "showWeek", true );
   $.datepicker._defaults.beforeShowDay = onlyMonday;
    function onlyMonday ( date ) {
      if ( date.getDay() == 1 ) {
        return [true, 'ui-datepicker-days-cell'];
      }
      else {
        return [false, 'ui.datepicker-unselectable'];
      }
    }
  }
};
}(jQuery));

This works great, except for commented line. According to the jQuery docs that line (added by myself) should make visible the numbers of the weeks:

$( ".selector" ).datepicker( "option", "showWeek", true );

The context from within Drupal is probably different. But I have no knowledge of js :-(

In what way does this code for setting an option has to be adjusted ?

Your are working within a Drupal behavior that could be reapplied several times on the DOM tree, in order to avoid processing the same element several times you should limit the $($selector) call to the passed-ind `context and use a marker CSS class for already processed class. Something like

$('.selector:not(.only-monday-processed)').addClass('only-monday-processe').doSomethingwithTheElements();

To defines then set the datepicker options from Drupal server-side PHP, you need to store the selector(s) and options in the settings object received by your behavior attach function using the drupal_add_js() function or the #attached property of your form/render array element. Then your function can use the selector to apply the option to the element. Something like

In your module code, store the selector and options in settings:

drupal_add_js(array('myModule' => array('.selector' => array('showWeek' => TRUE))), 'setting');

In your JavaScript, for each stored selector, apply the datepicker options:

(function ($) {
  Drupal.behaviors.only_monday = {
    attach: function (context, settings) {
      var selector;
      if (typeof settings.myModule === 'object') {
        for (selector in settings.myModule) {
          if (settings.myModule.hasOwnProperty(selector)) {
            $(selector, context).filter(':not(.only-monday-processed)')
              .addClass('only-monday-processe')
              .datepicker('option', settings.myModule[selector]);
          }
        }
      }
    }
    // ...
  };
}(jQuery));


jQuery post data to the database? I'm creating a system on D7 that tracks how much progress users have made watching various videos on the site. I've set up the jQuery that stores the percentage progress in an array with a modified version of the process at https://www.urbaninsight.com/2014/10/06/tracking-progress-embedded-vimeo-videos. Where I'm lost is where I actually post the data using:

$.post('/callback', {
   progress: myProgressVariable
});

I realized that '/callback' is just a placeholder, but I don't know what to sub in there. Should I designate a callback() function in a custom module that does something with the progress data and just place the function name into the javascript -- and what might that look like? Or do I need to do something something else entirely?

Ended up just using a custom hidden form as suggested by 4k4 and am populating/submitting it via jquery/ajax.


How to handle multiple stores and multiple store admin users Is it possible to create a restaurant(multi-store) online delivery system using Drupal commerce and OG? It has multiple stores(restaurants) in different locations which can be manageable by individual restaurant admins. The super-admin also have full control over all restaurants- can create products for each restaurants.

We have up to 40 restaurants and each restaurants have different products(food items). Each restaurant admin need to add/update  own products and own store addresses, delevery time, etc

I have checked with Commerce Marketplace and seems difficult to implement.

Please share your valuable thoughts.

I am currently working on a similar project and I am using commerce marketplace. Had faced some issues, but overall it was a smooth journey using marketplace. Also, it is not difficult to implement.


Trouble accessing twig variables passed from custom block I've looked through many similar questions and can't figure out what I'm missing. I have a custom module with a block...
/**
 * Provides the 'Four Words' block
 *
 * @Block(
 *   id = "na_fourwords",
 *   admin_label = @Translation("Four Words Hero"),
 *   category = @Translation("Custom"),
 * )
 */
class NAFourWordsBlock extends BlockBase {

  public function build() {
    return [
      '#theme' => 'block__na_fourwords',
      '#myvar' => 'TESTING',
      '#attached' => ['library' => ['na_fourwords/na_fourwords']],
    ];
  }
}

In my .module file:
function na_fourwords_theme($existing, $type, $theme, $path){
  return [
    'block__na_fourwords' => [
      'variables' => [
        'myvar' => NULL,
      ],
    ],
  ];
}

In my twig, {{ myvar }} doesn't render. If I call {{ kint(elements.content) }}, I get ...
elements.content => Array
(
    [#theme] => block__na_fourwords
    [#myvar] => TESTING
    [#attached] => Array
        (
            [library] => Array
                (
                    [0] => na_fourwords/na_fourwords
                )

        )

)

It looks like the data is getting passed through ... why am I unable to access it? I feel like there's something simple I'm overlooking.
Drupal 9.1.7
PHP 7.4.16
Thanks!

So, block--na-fourwords.html.twig is an existing Drupal suggestion for a template name for a block with id na_fourwords. I was able to override the template file, but my theme function that was trying to talk to that file was being ignored because it already existed. It would be nice if Drupal had some kind of feedback to let you know of conflicting theme hooks like that.
Anyway, hopefully this saves someone similar frustration.


Show new Flag's with views is it possible to get the amount of "new flags" in views? Like the "new comments" field. For example a user's article was flagged 2 times. After his login he should see in a view: "2 new flaggs on your article".

Drupal 7;
Views 3; Flag 7.x-3.2

thanks for ur help!
lolhonk

So add relationship "your_flag"

and in Sort criteria delete default Content: Post date (desc)

and add Flags: Flagged time

PS maybe i don't understand you, why you need in views this show? not in teaser node?


What modules are required to make a seating chart website? I'm currently working on a site that wants to sell theater seating by section by clicking on a map overview of the seats like the one below. What drupal 7 modules are there or recipes that can be done to create this similar functionality?

Closest things I was able to find are Wysiwyg Image Map and jQuery Map Hilight modules.

Wysiwyg Image Map is image Map editor for tinymce provided by the Wysiwyg module.

jQuery Map Hilight enables the simple addition of mouseover highlighting of hotspots to HTML image maps without requiring the editing of theme files or knowledge of javascript/jquery.

Together they should give you roughly what you need - but if I were in your situation, I would prefer to code this myself.


Clickable preview of a youtube video in a Lightbox? So I have been trying for a month now to get a nice gallery view working. It's a view displaying items of a custom "Gallery element" content type, that can contain either an image or a youtube video.

I want to have my gallery displayed as a 4x3 grid of thumbnails, that you can click on and get a lightbox output of the media file, wether it is an image or a video.

I managed to get the images working using the Lightbox2 module, but somehow the youtube videos need a little bit more working... So far I haven't managed to even see these videos in a lightbox. Either only an unclickable thumbnail appears in the gallery, or the full sized video if I remove the "Youtube Preview Image" display from the manage file display panel of File types in the configuration.

I do have checked the "Enable video support" checkbox in the Lightbox2 configuration, yet I cannot seem to find a way to display a video in those! One thing I wonder, is why don't I get the same field format "Lightbox2" options as for images?

Well! Thanks to this answer, I just found a workaround. I had to install the Video Embed Field module, and now I can display YouTube videos in a Colorbox popup window perfeclty fine. And Colorbox only, because Lightbox2 is still not supported by Video Embed Field.


Why don't menu tabs show for a view generated page? Why don't menu tabs show for a view generated page?
Viewing my site as an administrator I see menu tabs above content pages for view, edit, and Devel (I have the developers module turned on).  When I generate a view page, the menu tabs are not displayed.  I have viewed video tutorials and they are present on a view page.  The view is working and generating the correct page. Is there a setting somewhere?

Added Question:
OK hansag answered my initial question below, so let me rephrase the question. The problem is I have created 3 pages in the view each with menu tabs assigned. The paths for each are:

default tab page= materials/%
page 2 = materials/%/general
page 3 = materials/%/scope

There is a contextual filter that takes the % value and finds articles with an attached taxonomy term.  The view page works since the placing a URL such as materials/termname finds the correct articles and displays them.

Why don't the menu tabs show?

Those tabs are used for node editing. When you create a "page" from the views module it is general collecting a series of nodes on the page, so it is not displaying the single node tabs.

You might consider using this module. Block Edit

It generates view/edit tabs for blocks and views.

Hope this helps!


How do I check the value of a Boolean field in a template file? I have a paragraph with a boolean field.

content type
-paragraph entity reference
left hand side paragraph
checkbox
image
title

All the other fields have their own field-paragraph-field-checkbox.html.twig files and there's nothing to be checked, just adding a class around the image and title {{ item.content }} value.

However, I need to check if the checkbox field value is 1 or 0 in field-paragraph-field-checkbox.html.twig, and add a class if it's 1, or do nothing if it's 0.

When I tried printing the value with {{ content.field_checkbox.value }} nothing prints. I also tried with {{ node.field_checkbox.value }}, but I don't get any value.

How do I check the value of a Boolean field in a template file?

I don't know how you debug but I think from question contest that trying  node.field_checkbox.0.value might work. Or if you are working with views and use views_get_view_results function, try content._entity.field_checkbox.value or content._entity.field_checkbox.0.value 0 used if field is untranslated

Update for comment:

function TEMPLATE_theme_suggestions_page_alter(&$suggestions, $variables) {

  // Check it's a node page.
  if (($node = \Drupal::routeMatch()->getParameter('node')) && $node instanceof \Drupal\node\NodeInterface) {
    array_splice($suggestions, count($suggestions) - 1, 0, 'page__node__' . $node->getType());
  }
}

with this code in your TEMPLATE.theme file drupal 8 suggest page--node--CONTENT-TYPE-MACHINE-NAME.html.twig (Undersores to dushes). and thats it, You might have {{ kint(node) }} or {{ dump(node) }} in your twig.


Menu sort by year field I'm created a content type and have got field_year. I want, sort my contents by field_year on my sidebar. How can I do this?

I see you have added views tag views-filters, so, I think, you don't mind to list your content with Views.
If your field field_year is integer it is really easy to sort your content:

Some notes:

If you need block, just create Block display in Views. New block will be available on admin/structure/block page.
Add fields you want. Here I'm showing only title as a link to the original piece of content.
Remove all sorts and add your own by clicking on the Add button. It's very easy to find your field by it's name or machine name.

Result:

Yes, active class is added automatically.
Views module has tons of settings. To learn more please take a look at “Taming the Beast: Learn Views with NodeOne” series.


How to attach profile type to specific user role? I have multiple profile types and multiple user roles.  I want to combine specific profile types with users of specific roles.  For example, customer roles have their own profiles, content authors have their own profiles, etc.

Is there a way to assign them together?


Using GET parameters with clean urls I have module where I'm creating a custom path in hook_menu. When the user visits this page, they are supposed to be redirected to another site, with GET query parameters attached to the redirect URL. So for instance, if they visit http://mysite.com/site-search?query=blah, we are supposed to redirect them to http://othersite.com/different-path?query=blah.

However, we have clean URLs enabled; while I can hit the page http://mysite.com/site-search, it gives a page not found when I try to hit http://mysite.com/site-search?query=blah.

  The requested page "/site-search?query=blah" could not be found.

I tried adding another path for site-search/%, just to get that extra part of the URL, but that didn't work either.

Am I able to get the URL parameters while using clean URLs?

Edit: Here's the code:

function my_redirect_menu() {
  $items['site_search'] = array(
    'page callback' => 'my_redirect_redirect',
    'access callback' => TRUE,
  );

  // testing to see if this will allow me to capture get parameters
  // in the form http://site.com/site_search/q=blah
  $items['site_search/%'] = array(
    'page callback' => 'my_redirect_redirect',
    'access callback' => TRUE,
  );

  return $items;
}

function my_redirect_redirect() {
  // see if we can get the get paramters
  return "<pre>" . print_r($_SERVER,1) . "</pre>";
}

Edit 2 In my example, I transcribed the query string in correctly. It looks like it's a conflict between drupal wanting to use ?q= for its menu routing, and our search host URLs also using ?q= for their queries. If I do query=blah, I am able to hit the page.

I use $_GET variables as needed in my clean-url installs without issue. Views uses $_GET variables, too. Drupal uses $_GET['q'] so you don't want to use that ID, but you should be able to do something like:

function my_redirect_menu() {
  $items['site_search'] = array(
    'page callback' => 'my_redirect_redirect',
    'access callback' => TRUE,
    'type' => MENU_CALLBACK,
  );
  return $items;
}

function my_redirect_redirect() {
  return $_GET['query'];
}

This is working for me locally. The 2nd item you present in hook_menu only matches for /site_search/foo?query=bar so you only want the first. Be sure to set the 'type' property as well.


Node taxonomy now appears vertically in Drupal 7 After migration to Drupal 7 the taxonomy terms now appear vertically with the vocabulary names, and it seems to be the result of Drupal 7 converting taxonomies into fields.

Is there a way to revert to Drupal 6 behaviour, ie just display the taxonomy terms horizontally as before?

If you mean you want display terms in node view horizontally, then:

if your node-type is xxxx and you vocabulary name is yyyy, add this to your CSS files:

.node-xxxx .field-name-field-yyyy .field-item {
  display: inline;
}


Disable select option I have a select list in my registration form here. The user can select 3 options to register for the event. For now the user has the ability to choose an early bird registration. After the periode they shouldn't be able to select that option. Is there a way to disable that option?

I have the following options:

EARLY BIRD REGISTRATION (now - Nov 1)
REGULAR REGISTRATION (Nov 1 - Mar 1)
LATE REGISTRATION Mar (1 - to conference)
SPEAKERS REGISTRATION ( now to Apr 2)
STUDENT REGISTRATION (breaks only)

After the 1nov I should be able to disable the early bird registration in the select list.

Disabling single options from select lists is currently not that easy in Drupal. There are some open issues regarding the topic and a couple of suggested patches, but so far neither made it into core:

Allow FAPI select, radios, and checkboxes to specify some options as disabled
Introduce proper Form API #types for 'option' and 'optgroup', and make #options consistent
Using form_alter to disable ONE option of a select field

That said, there is a tutorial on Exove which works around the issue, by implementing the THEME_select() hook to enable theming of individual select options using a #options_attributes key: Drupal 7 Form API select element option attributes

Using the code for your theme's template.php from the tutorial, you can disable options in your form using hook_form_FORM_ID_alter().

function hook_form_FORM_ID_alter() {
  $today = date("Y-m-d H:i:s");
  $date = "2016-11-01 00:00:00";

  if ($date > $today) {
    //replace 0 with the actual index for Early Bird
    $form['your_select_field']['#option_attributes'][0] = array('disabled' => 'true');

    //set the other fields based on dates here
  }
}

There is also a module which seems to offer the same functionality as the theme code from the tutorial, but I have not yet tested it: Form Options Attributes. It seems to work in a similar fashion however and might be even a little easier to set up (since you don't need to write that theme function).


What is wrong with this drupal 7 preprocess function to output a fields value into the body classes? I have the following preprocess function and was wondering what I have wrong here as its not working.

This is just to grab a fields value and insert it into the body classes.

/**
 * Implements hook_preprocess_html().
 */
function cotyhouse_preprocess_html(&$vars){
  $node = menu_get_object('node');

  // Check if on an article node page
  if ($node->type == 'article') {
    // Get field values
    if (field_get_items('node', $node, 'field_title_color') == 'black') {
      $vars['classes_array'][] = drupal_html_class('tblk');
    }
    if (field_get_items('node', $node, 'field_title_color') == 'white') {
      $vars['classes_array'][] = drupal_html_class('twhi');
    }
    if (field_get_items('node', $node, 'field_title_color') == 'white_shadow') {
      $vars['classes_array'][] = drupal_html_class('tsha');
    }
  }
}

field_get_items return an array of field item so you need to do something like :

/**
 * Implements hook_preprocess_html().
 */
function cotyhouse_preprocess_html(&$vars){
  $node = menu_get_object('node');

  // Check if on an article node page
  if ($node->type == 'article') {

    // get field_title_color value
    $color = NULL;
    $field_items = field_get_items('node', $node, 'field_title_color');
    if ($field_items) {
      $first_item = reset($field_items);
      $color = $first_item['value'];
    }

    // Set class corresponding to color
    if ($color == 'black') {
      $vars['classes_array'][] = drupal_html_class('tblk');
    }
    if ($color == 'white') {
      $vars['classes_array'][] = drupal_html_class('twhi');
    }
    if ($color == 'white_shadow') {
      $vars['classes_array'][] = drupal_html_class('tsha');
    }
  }
}


How to get the current version of a node? I programmaly want to set the current version of a node to a status in workbench "needs_review" however the current version of the node is not the published version of the node.

$vid
5000 = Published
4999 = Current revision

How to get the versionid of a node which contains the current version?

I tried several and I guess:

$vid = revisioning_get_latest_revision_id ($nodeid)
$node = node_load ($nodeid, $vid)

but this is of course giving an error as a answer as I'm using D7, the function revisioning_get_latest_revision_id cannot be found.

I also saw https://api.drupal.org/api/drupal/modules%21node%21node.module/function/node_revision_list/7.x
But do not understand how the get the current revision of the node.

Any suggestions?

For those who need it. It is included in the node structure under value:

$node->workbench_moderation['current']->vid


Translating interface - same word duplication I have "problem" i want to do one word translation e.g. 'Location' (same case) I use that word with t() function in (menu, module, template tpl, taxonomy) when I go to translate interface it show me same string: 4x"Built-in interface", 2x"taxonomy", 1x"fields". I have 4 languages and I have repeat everything for same word. Is it possible to do one translation and Drupal apply on all exact strings.

Thanks

You need to translate each of these strings individually. It is not enough to do it only once.


Multisite drupal bootstrap Is it possible to bootstrap a particular drupal 'settings.php' ?

I've gotten bootstrap to work with the default site only.

I ended up using this code:

chdir('/path/to/drupal/sites/example.com/');
define('DRUPAL_ROOT', '/path/to/drupal/core');
require_once('/path/to/drupal/includes/bootstrap.inc');
drupal_override_server_variables(array('url' => 'http://example.com/'));
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

It could perhaps be more efficient but it works from crontab.


Categorizing and Sorting Webform Submissions I'm trying to find an effective way to categorize and sort webform submissions. I already have them displaying in views, but would like to take it a bit further. Here's the goal:

Anonymous users can fill out an employment application on our site (via a webform). Our recruiter would like to be able to sort through these applications and do things such as categorize them (accepted, denied, etc.) by selecting multiple at once, and send batch emails to applicants.

I already have Views Bulk Operations installed, but it doesn't seem to play well with webform submissions, if at all. Does anyone know of a good way to accomplish this?

I'm on Drupal 7, using Views 7.x-3.6 and Webform 7.x-4.0-alpha6.

Webform Report module allows users to create simple, dynamic reports based on data collected by the webform module. It adds a new node type that contains the report criteria, and the data displayed is updated automatically as webforms are submitted. The data can be sorted according to the viewer's preference without altering the report criteria.


Create users on the frontend, without 'administer users' permission As you may know, there's one single permission that controls user's access to other user's creation - permission is called 'administer users'. It either gives access to full user's administration or to nothing.

On my system I have tiered users who are supposed to have some permissions in relation to user administration. But not all permissions. I basically need to be able to create user accounts (based on profile2) on the frontend url (not /admin/people/p2rp-create/user but eg. /add-user.

I know there's a way of rendering an existing Drupal registration form, not sure how to
a) render profile2 form, or, to be precise, render profile2 form that includes forms for few created profile (I have 3 at the moment)
b) make it create a user even tho user doesn't have 'administer user'

I played with the following for starters

function module_menu(){
  $items['add-user'] = array(
  'title' => 'Add user',
  'page callback' => 'module_reg_form',
  'access arguments' => array('access create customer'),
 );

function module_reg_form(){
  $user_register_form = drupal_get_form('user_register_form');
  $form_state = array('profiles' => array('contact_details'));
  $registration_with_profile_fields_form = profile2_attach_form($user_register_form, $form_state);
  print(drupal_render($user_register_form));
}

This throws an error

EntityMalformedException: Missing bundle property on entity of type profile2. in entity_extract_ids() (line 7721 of /home/dreamweddings/www/dreamweddings.eu/public/includes/common.inc).

Can you not simply give user permissions to create users of specific roles (via the administerusersbyrole module) and then use the existing user creation form at /admin/people/create? If you do go with administerusersbyrole, make sure you follow the two steps on the project page for assigning the configuration.

If you must have a custom form via another page, you probably want to do it via a proper form definition function by setting the menu 'page callback' to 'drupal_get_form', and then passing the function that provides the form definition in 'page arguments'. See this particular comment for a code example. This way you'll be able to do proper form validation and a for submit handler too. Even if you get your current snippet working, the form still needs to submit somewhere to work.


How can I add a Dismiss Button to a Webform Modal Conformation? I added an extra close button to my webform confirmation modal in a Bootstrap 4 theme:
<button class="btn btn-primary" data-dismiss="modal" id="button-close-modal" type="button">OK</button>

Then I added a script to act on that button, but it doesn't seem to do anything:
(function($) {
  Drupal.behaviors.hideModal = {
    attach: function(context, settings) {
        $('#button-close-modal', context).on('click', function(e){
            $('.webform-confirmation-modal', context).modal('hide');
        });
    }
  };
})(jQuery);

Nothing in the console to give me a clue as to what may be happening. I tried .modal('toggle') and that didn't work either (although at least I could visually see a change).
I also tried $('.ui-dialog-titlebar-close', context).click();, but that didn't work either.
Note: I have the "Webform Bootstrap" module enabled.

Here is how I got it working:
(function($) {
  Drupal.behaviors.hideModal = {
    attach: function(context, settings) {
        $('body', context).on('click', '#button-close-modal', function(e){
            $('.webform-confirmation-modal--content', context).dialog('close');
        });
    }
  };
})(jQuery);


How to do file downloading in a controller function? I asked the question about downloading of files upon submitting a form.

Now I want to clarify how to do it in the case of controller function.
That is, some controller is called and its function is being executed.

In the form submit function file downloading starts upon executing the $form_state->setResponse($response);

How to start it in the controller function ?

I tried to use $response->send(); but it sends a file with wrong data and another size.

Never send the response with $response->send(). Instead return the response:

use Symfony\Component\HttpFoundation\Response;

public function myController() {
    $response = new Response();
    // prepare $response
    return $response;
  }

BTW, this is a standard Symfony Controller. The fact that you also can return the main content in a render array is because Drupal has added an event subscriber, which converts the main content to a response with the themed html page.

This works for all responses, in your case for example for a binary file response:

Drupal\system\FileDownloadController::download():

  public function download(Request $request, $scheme = 'private') {
    $target = $request->query->get('file');
    // Merge remaining path arguments into relative file path.
    $uri = $scheme . '://' . $target;

    if (file_stream_wrapper_valid_scheme($scheme) && file_exists($uri)) {
      // Let other modules provide headers and controls access to the file.
      $headers = $this->moduleHandler()->invokeAll('file_download', [$uri]);

      foreach ($headers as $result) {
        if ($result == -1) {
          throw new AccessDeniedHttpException();
        }
      }

      if (count($headers)) {
        // \Drupal\Core\EventSubscriber\FinishResponseSubscriber::onRespond()
        // sets response as not cacheable if the Cache-Control header is not
        // already modified. We pass in FALSE for non-private schemes for the
        // $public parameter to make sure we don't change the headers.
        return new BinaryFileResponse($uri, 200, $headers, $scheme !== 'private');
      }

      throw new AccessDeniedHttpException();
    }

    throw new NotFoundHttpException();
  }


showing an image field from solr index on custom solr search page I use the Apache Solr Views module to create a View that displays only items from a specific content type.

I would like to include an image as well on the view. I managed to get the images on my site indexed in solr using a custom module (field is called ss_field_image_uri). They show up in the solr index and I can add the image field in my custom solr view. So far so good.

The problem is that the field outputs as "public://folder/imagename.jpg". My question is how how I could I get the view to output not the link but the image itself?

Should I somehow rewrite the output of the image field in the view? Or use a custom php field and add some code? I cannot figure out how to do it. I am not a programmer but any pointers as to how to proceed would be very much appreciated.

Best,
Gerben

We managed to solve this with help from user Gaele Strootman.

There are three steps to solve this:
1) add the image to the solr index using a custom module
2) add the image field to your apache solr view
3) add a template file for the image field that displays the actual image

ad 1) create a custom module to add images to the solr index.

You only need two files, my_module.info and my_module.module. We name the image field ss_field_image_uri.

my.module.info:

name = Apache Solr Image
description = Add image field to the solr index so we can display images in search results
package = Apache Solr
core = 7.x

dependencies[] = apachesolr_search

my_module.module:

<?php
/**
 * Add field_image uri to apache solr index, so that we can later display image in search results or custom apache solr views page.
 * @see apachesolr.api.php
 */

function apachesolr_image_apachesolr_index_document_build($document, $node, $namespace) {
  if (isset($node->field_image['und']['0']['uri'])) $document->addField('ss_field_image_uri', $node->field_image['und']['0']['uri']);
}
?>

ad 2) add the image field to your apache solr view

First re-index solr so the images actually get indexed and show up. Then add the image field to your view.

ad 3)  add a template file for the image field that displays the actual image

This is the template we added. Since the field is called ss_field_image_uri the template name is: views-view-field--ss-field-image-uri.tpl.php. This is the code:

<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
?>
<?php
/**
 * For additional parameters see
 * http://api.drupal.org/api/drupal/modules!image!image.field.inc/function/theme_image_formatter/7
 */
?>
<?php $variables = array('item' => array('uri' => $row->{$field->field_alias})); ?>
<?php $variables['image_style'] = 'thumbnail'; ?>
<?php print theme_image_formatter($variables); ?>

Now clean your caches and the images should show up in your apache solr view. Note that you can change the image style in the code from 'thumbnail' to whatever image style you like.

Hope this helps anyone!


Big pipe and behaviors context I have problem with drupal behaviors and context in combination with big pipe. It seems like context variable sometimes contains same part of page. I have tried:

(function ($, Drupal) {
  Drupal.behaviors.myCustomBehavior = {
    attach: function (context, settings) {
      console.log(context);
    }
  };
})(jQuery, Drupal);

When I load page and watch browser console contexts there is div with main menu block but there is also whole #document element which contain menu block also (see screen).

This behaviour is for me real problem because I use zurb foundation and I have to initialize all components and I do it:

(function ($, Drupal) {
  Drupal.behaviors.myCustomBehavior = {
    attach: function (context, settings) {
      $(context).foundation();
    }
  };
})(jQuery, Drupal);

I think this is correct way how to initialize foundation for all elements and it should be compatible with big pipe. But if I get same html part in context twice (some sub elements in context are same) I initialize some zurb foundation plugin twice (see next image).

This breaks zurb foundation plugins. I'm not sure what to do. I read lot of Drupal documentation about js, behaviours and big pipe and according to documentation there should not be problem.

When I disable big pipe everything works as expected but that's not solution.

Do anybody knows what am I doing wrong?

Alternately, using once:

(function ($, Drupal) {
  Drupal.behaviors.foundationInit = {
    attach: function (context, settings) {
      $(body, context).once('foundation-init').each(function() {
        $(document).foundation();
      });
    }
  };
})(jQuery, Drupal);


Entity Field Query - Type of the Field How do I determine the individual field type using an EntityFieldQuery?

Here is the sample code for extracting the fields of a content type named 'digital_iq_test_2012', which contains many fields. How do I determine the type of each field?

$query = new EntityFieldQuery;
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'digital_iq_test_2012')
  ->propertyCondition('status', 1);
$result = $query->execute();

Any help?

EntityFieldQuery essentially just prepares an SQL query and gives you the results, it doesn't return any meta information about the fields themselves.

To get that you can use the Field Info API, e.g.

// Get all fields attached to your bundle.
$fields = field_info_instances('node', 'digital_iq_test_2012');

// Loop through
foreach ($fields as $field_name => $instance) {
  // Load up field info for this field.
  $field_info = field_info_field($field_name);

  // Get the type
  $type = $field_info['type'];
}


Passing Timestamp in the SQL Query to filter results I've a query where I want to filter query results based on today, yesterday and week. I've written queries within Drupal 7 and it is as follows:-

$result = db_query("
    SELECT
  n.title, n.nid,
  COUNT(*) AS times
FROM
  {node_view_count} a, {node} n where a.nid = n.nid AND a.uid = :uid AND n.nid <> 2120 AND DATE(from_unixtime(:mydate)) = CURRENT_DATE
GROUP BY
  n.title
ORDER BY
  times desc",
array(':uid'=>$_GET['uid'], ':mydate'=> date('Y-m-d H:i:s', "a.timestamp") )) -> fetchAll();

My question is, that could I pass two variables in the array as a parameter? Also if I could why is this query not working when I pass two parameters in it. The problem is that I need to convert the timestamp to date before using it and I am using a query Variable in the parameters.

Do you think you could assist in this?

Thanks.

I don't have a copy of D7 handy, but this seems to work on D6 for me. There's at least two problems with your code. I'm going to pare your query into a short bit of SQL, then transform it into drupal code.

Use JOINs

Whenever you're using multiple tables in SQL, you'll almost always have to use the JOIN ... ON ... syntax. Using JOIN tells MySQL that you want to connect certain rows on the two tables if a given field from those tables matches. This is a very basic SQL concept, so you'll need to master this if you want to write your own SQL or troubleshoot it. Try W3Schools tutorial for a better explanation.

Here's a simplified, pure SQL query that works for me using a JOIN:

SELECT
  n.title, n.nid, COUNT(*) as times
FROM
  node n
JOIN
  node_view_count a
ON
    a.nid = n.nid
GROUP BY
    n.title
ORDER BY times DESC;

In my D6 installation, I have a table called node_counter, but you probably have node_view_count instead on D7. JOIN node_view_count tells MySQl that we're connecting the node table to the node_view_count table. The ON a.nid = n.nid tells MySQL to only connect rows from these two tables when the nid field matches.

WHERE Clause

Next, let's add in a simplified WHERE clause. On my D6 database, the node_counter table's timestamp field is an unix timestamp (an integer). We can do the conversion from unix timestamp to datetime using pure SQL as well (no need to use a parameter to db_query()):

...
ON
    a.nid = n.nid
WHERE
    DATE(from_unixtime(a.timestamp)) = "2012-12-21"
GROUP BY
...

Add a Paramater to db_query()

We can change "2012-12-21" to whatever date we want to search on. So, next let's make this changeable part of our query into a parameter that gets passed to db_query():

<?php
$query = <<<SQL
SELECT
  n.title, n.nid, COUNT(*) as times
FROM
  {node} n
JOIN
  {node_view_count} a
ON
    a.nid = n.nid
WHERE
    DATE(from_unixtime(a.timestamp)) = :mydate
GROUP BY
    n.title
ORDER BY times DESC
SQL;

I've put { and } around the table names so that you use this query inside db_query(). By adding :mydate, you can now add in parameter called ':mydate' with a date string to your db_query() call:

$result = db_query($query, array(':mydate' => '2012-12-21'));

Hopefully, this gets you 90% of the way there.


Remove node edit form field validation I am working on the node edit form, and I want to remove all field validation when users click on Save as unpublished.

Is it possible?

I didn't write any code right now, so I don't have any code to show.

You could do this approach in HOOK_form_alter. Depending on validation that you want to remove... I provide you a simple example of required fields: Suppose you have an Image field that it's required, you could make it unrequired using the following:

$form['field_image']['widget']['0']['#required'] =  TRUE;

Also if you want to remove the "Alt field" for a image you could use:

$form['field_image']['widget']['0']['#alt_field'] =  FALSE;


Can I export token through features Can I export token through features from one environment to another

No - at this point it is not possible to export tokens using the custom tokens module. There is an open issue here on Drupal.org referring to this that has been waiting for a while without response and its unlikely the module maintainers will add this functionality as this is meant as a simple solution for developers who don't want to create their own tokens in PHP.

Depending on the complexity of your token operation, the best option might be to either manually sync up the two environments or to create your own custom token function following the instructions here (or other guides on the web). I would encourage you to try writing your own export functionality, its easier than it would seem and will open up more possibilities for you on future projects.


How to protect thumbnail and library images from media browser from being deleted? I have a Drupal 7 site where authenticated users can create a webpage to raise money for a charity. They can add a picture from the media library using the media browser. However, if they delete their page, this deletes the thumbnail and the library image from the db and site.

I've tried the File Lock module, but that doesn't work. I've set the user permissions to where the images cannot be deleted; that doesn't work. The images are used in other places as well as the need to keep them library for future users.

Any suggestions?

You could try this module:

Soft delete

  This module allows selected users, based on a permission, to soft
  delete nodes. To users the operation looks like delete but the node is
  unpublished. It's useful if you want to prevent accidental deletes or
  bring back content that wasn't supposed to be deleted.

  Note that this is a very simple module, adding just a tab called
  Delete next to View and Edit on nodes that the user can unpublish. A
  more advanced and customizable alternative is the Content
  unpublish module.


Select all nodes, where date is greater then current date and repeat event option is empty I have content type "event". In this content type I have a date field, provided by the Date Recur module. At the result I have range of the dates: Event start and end date. Also Date Recur provides an option to repeat event. I need to select all event nodes where date field is greater then current date and repeat event option is empty or select all nodes, where repeat event option is not empty.

My code:

$current_time = \Drupal::service('date.formatter')->format(time(), 'custom', 'Y-m-d\TH:i:s');

$query = $this->db_connection->select('node__field_type', 'n_f_type');
$query->join('node_field_data', 'n_f_data',
  'n_f_data.nid = n_f_type.entity_id AND n_f_data.type = n_f_type.bundle');

$query->join('node__field_event_dates', 'n_event_dates',
  'n_event_dates.bundle = n_f_type.bundle AND n_event_dates.entity_id = n_f_type.entity_id');
$query->fields('n_f_data', ['nid']);
$query->condition('n_f_type.bundle', 'event');
$query->condition('n_f_data.status', 1);
$group_and = $query->andConditionGroup();
$group_and->condition('n_event_dates.field_event_dates_value', $current_time, '>=');
$group_and->condition('n_event_dates.field_event_dates_rrule', '', '<>');
$query->condition($group_and);
$group_or = $query->orConditionGroup();
$group_or->condition('n_event_dates.field_event_dates_rrule', '%RRULE%', 'LIKE');
$query->condition($group_or);
$query->range(0, 500);
$events = $query->execute()->fetchAll();

Please, can anybody help me to build the correct query, because current query returns empty array.

SELECT * FROM table_name.node__field_event_dates where
((field_event_dates_value >= '2019-07-17T10:00:00') and
(field_event_dates_rrule is null or field_event_dates_rrule not like
'%RRULE%')) or (field_event_dates_rrule like '%RRULE%');

Last query works fine;

I need some help to transform the last query via using Drupal and/or conditions.

Right now your rrule condition is a singleton of its "OR" group. You need to add all the other conditions to an "AND" group and place that group as a sibling to the rrule condition in the "OR" group.


node_load not show taxonomy terms i dont know why

the script node_load(7) output is :

public 'field_tags' =>
    array (size=1)
      'und' =>
        array (size=2)
          0 =>
            array (size=1)
              'tid' => string '2' (length=1)
          1 =>
            array (size=1)
              'tid' => string '3' (length=1)

why the field tags not filled with tag title ! it only shows tid's

does this is a normal behavior of Drupal node_laod that it only load's primary id's of relational contents like taxonomy terms
?

Yes, that is the correct and expected behaviour. Loading every entity referenced by a node every time it loads, could potentially get very heavy on the server very quickly. That's why referenced entities are lazy-loaded (albeit manually as far as core is concerned).

To load taxonomy term entities from the tid, you can use taxonomy_term_load(). If you want an (arguably) slightly more pleasant experience when working with entities/fields on code, check out the EntityMetadataWrapper class, which is part of the Entity API module.


Disable language code in URL for default language I'm using drupal 7 and i18n module.

I select the user language with the language code in the URL like this:
mysite.com/fr/node/1
mysite.com/en/node/1
etc

The default language is French.

How could I manage to get only "mysite.com/node/1" when selected language is French?
For now, I only get "mysite.com/fr/node/1".
If I go to the root of my website "mysite.com", and I overlay the links, they're all pointing to "mysite.com/fr/...".

Is there anyway I could disable the /fr/ as the default language?

I tried playing around with the selection's rule weight, without success.

Under "admin/config/regional/language" you will see the list of languages. Click the edit link to edit the languages. In the edit screen, change the "Path prefix language code". If French is your default language, then keep this value blank for French.


View button that links to current node I'm trying to create this button in my views with a custom text, that needs to link to the current node.

I know you can use links and that works, but.. i need something like a variable that makes the link always go to the current node.

The field Content: Link allows you to enter Text to display.

Add a new Field Content: Link
Under Text to display enter Bestel nu

Easy :)

For more complex changes you can use the "Rewrite the output of this field" option on the "Content: Link" field. It's more reliable to use this field than Path.

You can use "Global: Custom text" field to construct some output (also "Rewrite the output of this field") using the tokens for the fields listed above it, but it isn't necessary in this case.