How do I validate form elements in a modal without closing? I'm using Drupal 8 and I have defined a custom entity type 'my_entity_type', with form handlers defined in the @ContentEntityType annotation:

 * @ContentEntityType(
 ...
 *   handlers = {
 *     "form" = {
 *       "add" = "Drupal\my_module\Form\MyEntityForm",
 *       "edit" = "Drupal\my_module\Form\MyEntityForm",
 *       "delete" = "Drupal\my_module\Form\MyEntityDeleteForm",
 ...

where:

MyEntityForm extends ContentEntityForm
MyEntityDeleteForm
extends ContentEntityConfirmFormBase

These are routed in my_module.routing.yml leveraging the _entity_form element:

_entity_form: my_entity_type.add

I am rendering the form from another form as a modal:

$form['add_my_entity_button'] = [
  '#type' => 'link',
  '#title' => t('Add NewEntity'),
  '#url' => Url::fromRoute(
    'my_module.add_entity',
    array(
      'node' => is_numeric($node) ? $node : NULL,
    )
  ),
  '#attributes' => [
    'class' => ['button', 'use-ajax'],
    'data-dialog-type' => 'modal',
  ],
  '#attached' => [
    'library' => ['core/drupal.dialog.ajax'],
  ],
];

All works as imagined. The '#required' type validator appears in the form in the modal.

Goal

To add custom validation to this form's elements ('live' validation that does not close the modal). I recognize that this type of problem isn't novel, and I've done it often in non-modal forms. The methods I would usually leverage are:

'#element_validate' form element callback
validateForm() type form callback

Both appear to require submission of the form, close the modal, and render the errors in a flat form display. I then combed through Core for ideas and embarked on a remarkably twisted yak-shaving journey:

Adding validation via BaseFieldDefinition::addConstraint in the
entity baseFieldDefinitions() : This still submitted the form and led to a flat (non modal) form with errors correctly thrown. Once I solve this problem, I will likely leave this in to serve as a gatekeeper at the storage level.
Extending the 'number' FieldType via Plugin, extending the widget, type or storage : This seemed overly complex for something as simple as adding a validator. I bailed on this before getting too far, since I considered:
Injecting a generic '#ajax' 'replace' callback to the element inside buildForm() in MyEntityForm : I could NOT get ajax inserted in this manner to fire here.
Injecting a generic '#ajax' 'replace' callback to the element in hook_form_alter : I could NOT get ajax callbacks inserted in this manner to fire either.

Questions

What have I missed? I feel this is simple. Is there something I've missed in Form that defines simple ajax validation?

Is there a standard way for validating form elements inside modals without closing the modal?

Can AJAX 'replace' callbacks be attached to forms defined and routed via the @ContentEntityType annotation? Is there a restriction here in the render pipeline?

This is a excellent article which you can read for "fixing" your issue:
http://www.mediacurrent.com/blog/loading-and-rendering-modal-forms-drupal-8

Keep in mind this lines:

First, we wrap our form with a div

public function buildForm(array $form, FormStateInterface $form_state, $options = NULL) {
  // It is important this id
  $form['#prefix'] = '
';
  $form['#suffix'] = '
';

  // The status messages that will contain any form errors.
  $form['status_messages'] = [
    '#type' => 'status_messages',
    '#weight' => -10,
  ];

  // more code

  $form['actions']['send'] = [
      '#type' => 'submit',
      '#value' => $this->t('Submit modal form'),
      '#attributes' => [
        'class' => [
          'use-ajax',
        ],
      ],
      // Function to call when the users click on submit button.
      '#ajax' => [
        'callback' => [$this, 'submitModalFormAjax'],
        'event' => 'click',
      ],
    ];

    // more code
}

Second, we show the errors:

/**
 * AJAX callback handler that displays any errors or a success message.
 */
public function submitModalFormAjax(array $form, FormStateInterface $form_state) {
  $response = new AjaxResponse();

  // If there are any form errors, re-display the form.
  if ($form_state->hasAnyErrors()) {
    // Remember the previous id ? Here it is
    $response->addCommand(new ReplaceCommand('#modal_example_form', $form));
  }
  else {
    $response->addCommand(new OpenModalDialogCommand("Success!", 'The modal form has been submitted.', ['width' => 800]));
  }

  return $response;
}


Drupal7: Private/Password Protected Section in a Drupal Website What would be the best way to do this In a Drupal7 Website:
I want to add to an already existing Public Drupal Website an 'Internal Section' that can be viewed only by Login (Password Protected).
This 'private/internal' Website will have 60+ info. pages, its own menu hierarchy, and any content that relates to it will also be private (private directory for images and files)
Thank you.

Boutros.

Drupal has only a very course access control structure for viewing content.  For the any user role, you can set permission to 'access content' (Drupal 6) or 'view published content' (Drupal 7), but that's about it.

Most inportant, out of the box, Drupal does not have any setting that let you set the permission "access content/view published content" for a particular content type.  It is all or nothing. I.e. if you untick "access content/view published content" for the anonymous user, no content on your site will be available to those that are not logged in.

Assuming that you're looking for more fine-grained access control, (where only a section of your website is private) you need to install a node access control module.  Many such modules exist. There is a page at the Drupal.org wiki giving an overview of node access modules.  You may start by reading that and try to find a suitable module.

To make a recommendation, I'll say that the one named Content Access seems to match your requirements.  It lets you control access per role and per content type.  I use this module to create premium or private content for logged in users on my sites.

To use it, install and enable it.  Create a new content type for the private pages - let's say you call it "Private page". Then (assuming Drupal 7) navigate to Administration » Structure » Content types and click "edit" for the "Private page". There is now a tab "Access control" that lets you control all types of access (Including "View") for this content type only.

As for menus, Drupal will usually manage this for you.  Any menu items that leads to content that is inaccessible, will not be visible for the roles that are not allowed to see it.


Is there any File Manager Module for drupal 7 I need a module as like as File manager. We need to view, edit, modify and delete the files and also with permission option.

There are many modules available for managing files.

Reference URL : https://drupal.org/module-categories/file-management

Try this module : https://drupal.org/project/elfinder i think it suits your requirement.


How do you add remote javascript script with custom parameters? There are many tutorials on adding js to themes in Drupal 7, but the examples for Omega Sub Themes seem to omit the part about remote scripts, scope and weight:

In the theme .info file:

scripts[] = js/map.js

So how do I specify remote URL, header or footer, and what weight to assign?

scripts[] = https://maps.googleapis.com/maps/api/js?key=XXX&sensor=false

results in <script src="&amp;muqqwd"></script> and even if it did work, I still need it to be in the header.

External javascript files can't be declared inside the theme.info file, unfortunately. Inside your template.php file, you'll have to add something like this:

<?php
  drupal_add_js('https://maps.googleapis.com/maps/api/js?key=XXX&sensor=false', 'external');


db_query with where clause not returning anything I ran following query on DB through PHPmyAdmin

SELECT * FROM field_data_field_country_feed WHERE entity_id=40848

And it worked and returned me the single row
But when I try to implement that in my custom services it is not returning anything.

$result1 = db_query("SELECT * FROM field_data_field_country_feed WHERE entity_id=40848")->fetchAll();
        var_dump($result1);

Please help

Try:

$taxonomy_term = taxonomy_term_load(40848); // the 40848 is the term id
$field_items = field_get_items('taxonomy', $taxonomy_term, 'field_data_field_country_feed');


How to implement bulk pricing/discounts with Drupal Commerce? I've been trying to find a way using Drupal Commerce to be able to give discounts on individual item prices based on quantity. For instance:

1-9 units of product A: $1.99 per unit

10-19 units of product A: $1.75 per unit

1-19 units of product B: $2.99 per unit

20-39 units of product B: $2.60 per unit

and so on and so forth. However, I haven't been able to find any documentation or modules to do this. Is there any way to do this with Rules, or any modules?

Maybe you should use the Commerce Discount module. Quote from its community documentation:

  The Discount UI (available under Admin → Commerce → Store → Discounts) allows creating and editing discounts. Each discount consists of two related entities: Commerce Discount and Commerce Discount Offer. The Discount allows you to choose what type of entity this discount this will apply to i.e. "Order Discount" or "Product Discount" (line item). The Commerce Discount Offer denotes the result the discount produces. The module provides 4 discount offers out of the box.


"Home" not changing in Breadcrumbs when switching languages (Locale) I am using Locale to translate content and menus.

Despite that, even when viewing a page in Spanish, the "Home" link in the breadcrumbs does not change to "Inicio".

What can I do to fix that?

I have attempted to create a node called "Home", translate it to be called "Inicio" and then changed the url to the homepage in the Configuration > Site Information but have still not had any success.

Is there a possibility to fix this without an additional module and a ton of re-configuring?

Thank you.

Navigate to "Translate strings" interface in "Regional and language" admin section (/admin/config/regional/translate/translate).

Search for "Home" and translate all untranslated instances of that string. This should fix the issue with translation of default breadcrumbs.

Useful tip: strings search is case sensitive, so make sure you enter your strings as they appear in html source (this condition gets easily overlooked).


automatically reference user to node by date field I'm totally stuck in this situation, can't find any solution, please help!

i have content profile date field "date of birth" (y-m-d) and node "horoscope" with multiple value date field (m-d). When new user registers his date of birth I need to auto-reference to the horoscope node with same date. Year is not important in that case.

For example:

I have "horoscope" nodes: (title - dates)

Horoscope A - 01.23, 03.11, 05.02
Horoscope B - 02.14, 07.01
Horoscope C - 11.11
Horoscope D - 02.10, 03.02, 05.07, 09.14
After new user registers his account with date of birth: 1977.07.01, I need "horoscope_reference" field to automatically assign him "Horoscope B" or if entered date of birth: 1234.03.02, "horoscope_reference" should be assigned to "Horoscope D" and so on...

any suggestions please? (drupal 7)

Thank You..

Use the computed field module for this. This lets you add your own conversion logic into the field (using PHP) that will be processed on entry. So download and enable the module, then add a field for your horoscope, then in the settings field, you want to add your PHP logic, ex (roughly):

$date = new DateTime($entity->field_profile_dob[LANGUAGE_NONE][0]['value']);
$month = $date->format('m');
$day = $date->format('d');
if (($month = 1) && ($day < 21)) {
    $answer = "some sign";
} else if .. etc.

That will take some time to write that logic. You might be better off putting this in a module then leaving it in the settings. There are dozens of examples in the documentation that should help you get started on this.


Display popup message when i hover on taxonomy link to display description I used Hierarchical Select module in my academic web site for student to select course from dropdown menu and it is works good but i have problem, for each course i  want to add course description as a popup message when we click on course link(Course link displayed as taxonomy link). Can you help me to solve this problem.
I really appreciate to you.

It can be easily done with Simple Dialog module. All instructions you can find at the module page


Limit access and editing menu by user I have created a new menu and I'm trying to limit the access to a particular user to edit instead of role with the following code but it's not working, I still can't see the menu and edit the menus items by logging in with the relevant user login (user id 3 in this case). Wondering what's the proper way of doing.

/**
 * Implements hook_menu().
 */

function menu_access_by_uid_menu(){
  $items = array();
  $items['admin/structure/menu/manage/new-menu'] = array(
    'title' => 'New Menu',
    'access callback' => 'menu_access_by_uid_validate',
  );

  return $items;
}

function menu_access_by_uid_validate() {

 global $user;

 if (user_is_logged_in() && ($user->uid == 1 || $user->uid == 3)){
   return TRUE;
 }

 return FALSE;
}

There is a nice module to handle visibility of menu items. You can use the module or see code in side the module.

May be It will help you. I am not sure :P

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


how to delete width and height attributes from image field for particular nodes I would like to strip width and height attributes from image fields for a few specific nodes.

I tried hook_preprocess_image($vars) but $vars don't have enough information. From the documentation, theme_image() won't have that information, either. I can't figure out the node from the path, because the node is used in a block. Using CSS width:auto !important; does not work, at least with Firefox 16 (and I've read IE 8 has problems with it, too). Any ideas?

You may be able to accomplish this with view modes.

Make some new image styles for these particular images.  Implement a theme_image_style(), which checks for this new style name and unsets width and height as needed.

If you install/enable Entity View Modes you can create new view modes for your nodes.  Clone what you have for node/teaser to your additional layouts.  For the images, change the display settings to use your new styles.

Next is the part I am not sure what the best solution is.  One way to use the view mode is to use a Panel page for each individual node.  When you add the content, you can set the view mode to one of your new ones.   Otherwise, I would try @PierreBuyle's solution at Using a different view mode with a node.  This essentially overrides the menu page for node/nid to add some additional intermediate logic to set the view mode.


How can I avoid wrapping my block into  tags? I have created a custom block

/**
 * @Block(
 *   id = "block_text",
 *   admin_label = @Translation("Text"),
 *   category = @Translation("Text"),
 * )
 */

And here is a build() function

/**
 * {@inheritdoc}
 */
public function build() {

  return [
    '#type' => 'markup',
    '#markup' => $render,
    '#cache' => [
      'max-age' => 0
    ],
  ];

}

On the page my block is wrapped into

<div id="block_text"> </div> tags

Could you please tell me, how can I avoid this wrapping?

I think you should copy block.html.twig (perhaps from /core/themes/classy/block/block.html.twig) in your custom module/theme and make it work for your specific block by naming it block--BLOCKID.html.twig and remove the outer <div> from this twig file.

Alternativelly you can create a custom template


Render values directly in a twig paragraph template I'm working with the paragraph module and I've created a paragraph type called Image Teaser Block wich is an entity reference to a content type (Image Teaser, multiple references possible). This content type has 5 fields (Image, list, 2x text + link) and I'd like to render the values directly in the paragraphs template (paragraph--image-teser-block.html.twig).

What I could do is using {{content}} or {{content.field_image_teaser}} to render the HTML in the paragraph template and then change the field templates. But because I have many different paragraph types and each has a lot fields I would end up with tons of templates (imagine 10 different paragraphs with 6 fields each -> 60 different template files) and that's not really efficient to work.

So how can get the values (not rendered HTML) in the paragraph--image-teser-block.html.twig file like that:

    {% for item in imageTeaserBlock %}

{{item.listLabel}}

{{item.title}}

{{item.subtitle}}

    {% endfor %}

I think the same issue applies also to content types wich are entity references to other content types.

I'm new to Drupal also and was trying to do the exact same thing. I simply put the machine name of the input I was trying to show in to the twig template i.e - {{ field_image_caption }} - flsuhed the cache and it magically appeared. Hope that helps.

                {{ field_image }}

                    PHOTO CREDIT: {{ field_image_caption }}


How to embed my webiste Header(logo, menu) for each of my panel variant I'am using Panel and I created several variant for many content type.

Is there a way to add my Top WebSite Header composed with (Logo, Main Menu, Second Menu, Search textbox, Language switcher and social network Icon) for each of my variant in a desired region.

Here is what I would like to do.

Create a kind of template called MyHeader where I would put any html element that I need for my Website Header(Logo, menu etc...).
If it's possible to create a template for MyHeader, how to do that ?

Use MyHeader into each variant panel, I would like to drag it into a specific Region , like dragging a simple widget.

Is it possible to do this.?

Note: I'm using Omega 4 as base theme for my subtheme

Sory for my english.

Thanks a lot.

Create a block with the required Header and then assign that to your content regions in panels. I think that should be it.

And yes, you can theme your block as required using block--block--[block-id].tpl.php templates.


what is the use of the migrate module UI in drupal 7 Guys do i still have to code object oriented coding when i use the migrate module in drupal 7? like this one example here.

http://miss-hana.com/migrate-contents-from-drupal-6-to-drupal-7-using-migrate-2/

if so, then what's the use of the UI for migrate module provided in drupal 7? i cant post a screenshot of the UI i nee 10 reputation for that. But it is in the 3rd tab in the content page.

if i still have to code, anyone can guide me to a very good tutorial or video on how to code this step by step. Because im not into object-oriented programming. :(

The UI just acts as a display for the mappings that you create, it also tells you how many nodes have been imported and how man haven't so you can manually do it.

There is lots of documentation on the drupal website here http://drupal.org/migrate and the example migrations are worth a look.

To migrate from drupal 6 to 7 I used created an xml view in drupal 6 and then created my mappings to use that in Drupal 7.

Cheers


How do I correctly add jQuery UI widgets? Im using Drupal 7, which ships with jQuery UI. I need to have  Accordion only on the homepage. jQuery will not just let me download Accordion and then use drupal_add_js().

Do you have any suggestion?

jQuery UI Accordion is included in core, use drupal_add_library('system', 'ui.accordion'); to add it.


How to change the language of a node and all its fields and all related data? On my multilingual site, I have a content type that is going to be user created. I want to keep it language neutral ('und').

But there already are a couple thousand nodes of that content type and they have English set as their language.

To make them language neutral, I want to write one time update function (hook_update_N) to change the language of the nodes and all their fields from 'en' to 'und'.

I am doing this by making changes directly to database (using db_update) to the language column of node & related field tables. But I am afraid that I may miss something. Can I do this some other way to not miss anything.

I read somewhere that I can user hook_node_presave & node_save to do this but I am not sure how.

Also, how can I make any future nodes' language to be set default as 'und'?

If this is just a one-time conversion, you should be able to do it with Views Bulk Operations (VBO).

Here's one way to do this that doesn't involve writing any code.

Install the VBO module.
Create a new view showing Content of whatever content types you need to convert.  Use the Fields display method.
Add a field Bulk operations: content.
Check Modify entity values and select Language.
Choose Apply.
Save the view (add any other filters if necessary to limit the selection) and go to the created view page.
From the view page, choose the option to select all items on all pages and execute the Modify entity values action.
Choose the language and click next.

If you have an extremely large number of nodes, you may need to play around with the queuing settings so that not everything is executed at once, but I would try doing it in one pass first because hey, if it works, you're done (note: always test on a backup first!)

Source: How can I set the language of nodes in bulk to existing content when making a site multilingual? - please upvote that one if you liked the solution above.

To force the default language to be undefined, in the setting.php file used by your site, add the following lines:

$conf['language_default'] = (object) array(
  'language' => 'und', 'name' => '', 'native' => '',
  'direction' => 0, 'enabled' => 1, 'plurals' => 0, 'formula' => '',
  'domain' => '', 'prefix' => '', 'weight' => 0, 'javascript' => ''
);

This will force Drupal to use 'und' as the default language for all new content.


How can I display an image within a node with an SRC value that incorporates a URL taken from another field? I'm creating a directory of useful (web based) resources for a community. I'd like to use Drupal 7, but can use Drupal 6 if absolutely necessary. I don't mind installing any additional useful modules.

I'd like to create a node with a link field that stores the URL of the useful resource.

I'd like to display a screenshot of this URL, using WordPress's mshots feature, as part of the node.

So, as an example, the value of the link field would be:

  http://mashable.com/guidebook/twitter/

Within my content type template, or as an image field, or however you suggest I do it, this URL would need to be encoded and inserted into an image SRC value to give:

  http://s.wordpress.com/mshots/v1/http%3A%2F%2Fmashable.com%2Fguidebook%2Ftwitter%2F?w=500

Which shows a 500px wide screenshot of that URL.

What do you think would be the best way of doing this? I could use 'rewrite the output of this field' in Views, but I'd like the screenshot to be shown in the node view too.

You could use a custom 'screenshot' formatter for the link field. Further info for D6 and D7.


Is it possible to abort sending of the e-mail somewhere in the middle of sending procedure? Mail sending is initiated in the depths of some third party module. There's a case when I need to intervenue and depending on some environment variables either let it through, or prevent it. How do I do that?

I've seen in the wild a weird technique of setting $message['to'] to + (what's logic behind this by the way?). But this generates an error in server logs.

Any ideas?

As reported in the documentation for hook_mail_alter(), you can avoid a message is sent by setting $message['send'] to FALSE.

  Parameters

  $message: An array containing the message data. Keys in this array include:

  'id': The drupal_mail() id of the message. Look at module source code or drupal_mail() for possible id values.
  'to': The address or addresses the message will be sent to. The formatting of this string will be validated with the PHP e-mail validation filter.
  'from': The address the message will be marked as being from, which is either a custom address or the site-wide default email address.
  'subject': Subject of the email to be sent. This must not contain any newline characters, or the email may not be sent properly.
  'body': An array of strings containing the message text. The message body is created by concatenating the individual array strings into a single text string using "\n\n" as a separator.
  'headers': Associative array containing mail headers, such as From, Sender, MIME-Version, Content-Type, etc.
  'params': An array of optional parameters supplied by the caller of drupal_mail() that is used to build the message before hook_mail_alter() is invoked.
  'language': The language object used to build the message before hook_mail_alter() is invoked.
  'send': Set to FALSE to abort sending this email message.

At least, your code should check the value of $message['id'] which is a concatenation of the short name of the module and the key assigned to the message from the module.

function mymodule_mail_alter(&$message) {
  if ($message['id'] == 'modulename_messagekey') {

    // Verify other conditions are true.

    $message['send'] = FALSE;
  }
}


How to remove duplicate results from views block? How to remove duplicate results from views block ?
I have tried aggregation method and query distint but none of them working.

As previously i did the same by using the below code, but how to use the same code in drupal 8 ?

  function bootstrap_views_pre_render(&$view) {
      $used_nids = array();
       $new_view_result = array();

   if ($view->name == 'view_name') {
foreach ($view->result as $row) {
    if (!in_array($row->nid, $used_nids)) {
      $new_view_result[] = $row;
      $used_nids[] = $row->nid;
    }
}

$view->result = $new_view_result;
 }
  }

Is there any other possible solution of my problem ?

For anyone else looking for a Drupal 8 solution for Views Distinct, I was able to get this to work by creating a custom module with MY_MODULE.views_execution.inc file with this code:

<?php

use Drupal\views\ViewExecutable;

/**
 * Implements hook_views_pre_render().
 */
function MY_MODULE_views_pre_render(Drupal\views\ViewExecutable $view) {
  $unique_uuids = $new_view_result = [];
  $new_row_index = 0;

  // Loop through results and filter out duplicate results.
  foreach ($view->result as $row) {
    // Use UUID so this works for all entities
    $uuid = $row->_entity->uuid();

    if (!in_array($uuid, $unique_uuids)) {
      $row->index = $new_row_index;
      $new_view_result[] = $row;
      $unique_uuids[] = $uuid;
      $new_row_index++;
    }
  }

  // Replace $view->result with new array. Apparently views requires sequentially keyed
  // array of results instead of skipping keys (e.g. 0, 2, 4, etc), so we can't just
  // unset the duplicates.
  $view->result = $new_view_result;

  // Update the view index to match the new number of rows.
  $view->total_rows = $new_row_index;
}


Render an image that is located inside a Paragraph that is inside an Entity Reference I'm working with Drupal 8.

I have a content type called Lawyer.

This content type has an Entity reference called Firm.

In Firm (which is another content type) I have a Paragraph with an image field in it.

I need to render this image inside node--lawyer.html.twig

I have tried several ways to do it but I can't make it work. Any help?

Assumming a firm content type has field_paragraph which holds field_image of 1 image

for comparison to get firm name in twig file you will use

{{node.field_firm.entity.title.value}}

for firm paragraph image field value

{{node.field_firm.entity.field_paragraph.entity.field_image.entity.uri.value}}

To get the rendered image

{%
  set firm_image = {
    '#theme':      'image_style',
    '#style_name': 'thumbnail',
    '#uri':        node.field_firm.entity.field_paragraph.entity.field_image.entity.uri.value,
    '#attributes': { class: 'yourclass' },
  }
%}
{{firm_image}}

Alternative way to get referenced entity fields


How to setup Advanced Content Filter to not remove drupal-entity tags? I use CKEditor to create content. And Media Plugin to upload and manage images.

Now I have a problem that as soon as I activate Advanced Content Filter in CKEditor settings, my images are removed. I think problem is, that they are implemented like this:

    <drupal-entity class="media-element" data-entity-embed-display="image:image"
        data-entity-id="2589" data-entity-type="file" data-fid="2589"
        data-media-element="1"></drupal-entity>

I tried to insert drupal-entity in extra allowed content, but it doesn't change anything.

As long as I do not save this node with activated ACF the images are shown on my website. This is because first I created nodes with deactivated ACF.

Try this :

admin/config/content/ckeditor/edit/Full->
Advanced Options ->
Custom JavaScript configuration ->
Paste in:  config.allowedContent = true;
Save


How do I programmatically render a view that has exposed filters? I can call a view with contextual filters without any problem, but when I add exposed filter value $view->setExposedInput to the call, I just does not work, the exposed value is not applied and being ignored. The filter 'price' field is set in the views filters options and i tried both exposing it and not exposing it to visitors without any luck.
I call this view from my controller class and I need to pass the arguments to both filters and I do not need exposed form to be displayed to the user.

$view = Views::getView($view_id);
if (is_object($view)) {
  $filters = [
       'price' => 500, //my exposed filter value
     ];
  $view->setExposedInput($filters);
  $view->setArguments($args);
  $view->setDisplay($display_id);
  $view->preExecute();
  $view->execute();
  $view->buildRenderable($display_id, $args);
  $content = $view->render();
}

You can use this code in custom block can also set permission.

 use Drupal\Core\Form\FormState;
 use Drupal\views\Views;
   $form = [];
   $view_id = 'blog_landing_page';
   $display_id = 'page_1';
   $view = Views::getView($view_id);
   if ($view) {
   $view->setDisplay($display_id);
   $view->initHandlers();
 $form_state = (new FormState())
  ->setStorage([
   'view' => $view,
   'display' => &$view->display_handler->display,
   'rerender' => TRUE,
   ])
   ->setMethod('get')
   ->setAlwaysProcess()
   ->disableRedirect();
   $form_state->set('rerender', NULL);
 $form = \Drupal::formBuilder()->buildForm('\Drupal\views\Form\ViewsExposedForm', $form_state);
    }


Only create taxonomy terms on node approval? Right now nodes on my site are unpublished by default because I want to manually approve user submitted content. How can I make it so that user submitted taxonomy terms are not created until I manually approve the corresponding node?

As far as I can see, this would require a custom module. You would have to do something like this (tailor to your needs; I don't know if you're using publishing status to represent approval status).

    <?php
      function mymodule_nodeapi(&$node, $op, $a3 = NULL, $a4 = NULL) {
        switch ($op) {
          case 'presave':
            if (!empty($node->taxonomy) && $node->status == 0) {
              // Write some logic to save the data to your module's DB table, e.g.
              // _mymodule_get_taxonomy_temp() would contain a database query or
              // something to get the record.
              $record = _mymodule_get_taxonomy_temp($node->nid);
              $record_exists = !empty($record);
              $taxonomy_temp = ($record ? $record : new stdClass());
              $taxonomy_temp->taxonomy = $node->taxonomy;
              $taxonomy_temp->nid = $node->nid;
              if ($record_exists === FALSE) {
                drupal_write_record('mymodule_taxonomy_temp', $taxonomy_temp),
              }
              else {
                drupal_write_record('mymodule_taxonomy_temp', $taxonomy_temp, 'nid'),
              }
              unset($node->taxonomy);
            }
            elseif (!empty($node->taxonomy_temp && $node->status == 1)) {
              // Retrieve the saved taxonomy and put it back into the node.
              $record = _mymodule_get_taxonomy_temp($node->nid);
              // We append it to any changes made during the approval process.
              $node->taxonomy = array_merge($node->taxonomy, $record->taxonomy);
              // Clean up the database record
              _mymodule_delete_taxonomy_temp($node->nid);
            }
            break;
        }
      }
    ?>

Note that this is strictly sample code. You might want to retrieve the terms using hook_form_alter instead and show them in the tags box as if they had been added. In any case, the key is not to have them in $node when taxonomy_nodeapi() runs and saves them.


Drupal module versioning and compatiblity. How to know what to use? Sorry if this is a really stupid question or if I should have been able to find it.

When it comes to module versions, how exactly does it work? Say for example the Openlayers module that has several other sub-modules, modules it integrates with, as well as modules/libraries it depends on.

Lets say open layers has the following available versions:

Reccomended:
 7.x-2.0-beta5

Other Releases:
 7.x-3.0-alpha0

Dev Releases:
 7.x-3.x-dev
 7.x-2.x-dev

Now it's time to install dependencies lets use "views module" for this case. Lets say it has these versions...

Recomended:
 7.x-3.6

Other:
 7.x-2.16

Dev
 7.x-3.x-dev

So my question is do module updates/versions have any correlation on dependency modules? So in this situation if I install the Recommended : 7.x-2.0-beta5  of OPENLAYERS, am I suppose to install the Recommended :  7.x-3.6  of views or should I alternately install the version that has the 7.x-2.16 since both modules would then be in the  same 2.x stage.

From what I've read patches are for minor releases like 7.x-2.{something) and only a major release would make a developer change to the next version 7.x-3.x. Also how does alpha, beta versions fit in with all this??? How is it that a alpha version of something is recomended over a non aplha or beta version?

The versions I've listed above are not real, but just an example. Hoverer, recently I do have issues with Openlayers and another module that required it. Both these modules had several stable versions and dev releases. Sine the sub-module is stable I'd assume it had a release that worked at one point in time with Openlayers. Is there a way to know this. Or is there a way to download using something like drush to chose dependency modules that are tested against openlayers version-whatever without problems.

Sorry for the long and horribly formatted question I hope someone can either answer or point me in the right direction to get some good documentation on this

Unfortunately, there are no rules.
"Recommended" is just a flag set by the maintainer meaning "I think this is my most stable branch".
Alpha and beta are also just labels, in the Drupal world beta often means "Works for me, but I don't want to create a full release yet."

You'd usually want to use a recommended release, if it's not too old (if it's a year old, yesterday's -dev will probably be better).
Sometimes the -dev release is the most stable version of the code, if the maintainer doesn't create releases regularly.

When I have a dilemma such as yours (which version of dependency X should I use for module Y), I open an issue in the Y issue queue and ask. The maintainer knows best which code he optimized for.


Migration data from Tridion to Drupal I've been tasked with migrating a Tridion based website to a Drupal installation. (It's more of a rebuild really)

I was wondering if any of you have any experience with migrating the data from Tridion in a such a form that I could use it in Drupal. I have never worked with Tridion and don't know the first thing about it (the documentation does not seem to be open?).

So my question to you is: What is the best/easiest/most reliable way to import the data from a Tridion driven application in to a Drupal application? (I would seriously prefer not to do it manually.)

Any general tips you might have are also much appreciated.

There are a number of api/integration points for SDL Tridion, depending on your version you have:

SDL Tridion 2009 and previous -> TOM (Tridion Object Model) a COM+ API you can use in a .NET project.

SDL Tridion 2011 -> TOM (as before) or the SDL Tridion Core Service (.NET web service)

I'd recommend using these APIs to extract the information you need from Tridion into XML data in the structure that makes it easy for you to work with.

You can then use something like the services module http://drupal.org/project/services to process and import your XML.

Also maybe of use... SDL Tridion is a component based CMS and content is based on a specific Schema items.   A schema is likely to translate to a drupal content type pretty well, but if you're trying to achieve the sort of flexible layout that you can get from SDL Tridion (page/component templates) you'll likely need to be using the Panels module.. or something similar.

Let me know if you need some more information.


How to save dynamic select list value into config table in Drupal 8? I wanted to show list of fields per content type in admin config form. After saving the form, selected list value should get save into config table.

public function buildForm(array $form, FormStateInterface $form_state) {
  foreach (node_type_get_types() as $content_type) {
    $entity_type_id = 'node';
    $fields = \Drupal::entityManager()->getFieldDefinitions('node', $content_type->get('type'));
    if ($fields) {
      $options = array();
      foreach ($fields as $field_name => $field_definition) {
        if (!empty($field_definition->getTargetBundle())) {
          $options[$field_name] = $field_definition->getLabel();
        }
      }
      $form['test']['test_' . $content_type->get('type') . '_field'] = array(
        '#type' => 'select',
        '#title' => $content_type->get('name'),
        '#options' => array_merge(array('0' => t('Auto')), $options),
        '#default_value' => $config->get('test_' . $content_type->get('type') . '_field') ? $config->get('test_' . $content_type->get('type') . '_field') : '',
      );
    }
  }
}

Here is submit handler

public function submitForm(array &$form, FormStateInterface $form_state) {

foreach (node_type_get_types() as $content_type) {
  $this->config('test.settings')
  ->set('test_' . $content_type->get('type') . '_field', $form_state->getValue('test', 'test_' . $content_type->get('type') . '_field'))
  ->save();
}
parent::submitForm($form, $form_state); }

After saving admin form, test_article_field and test_page_field  is getting saved instead of selected field.

Any help would be appreciated?

There is some problem in the submit handler.

Replace

$this->config('test.settings')
 ->set('test_' . $content_type->get('type') . '_field', $form_state->getValue('test', 'test_' . $content_type->get('type') . '_field'))
 ->save();

line with

$this->config('test.settings')
  ->set('test_' . $content_type->get('type') . '_field', $form_state->getValues('test_' . $content_type->get('type') . '_field'))
  ->save();

Hope that this helps you.


How do I force my nodes to all show up at a given path, without adding them to a menu? My site has a set of events, all with the content type "event". I don't want to have to add them to the main menu manually, because there's hundreds of them and they'll make the menu very cumbersome to manage. I'd like each event to show up with the same breadcrumb and secondary menu as the view that displays all events.

So I added a hook_node_view to try and force all event nodes to show up in the same place as the events listing:

function MYMODULE_node_view($node, $view_mode, $langcode) {
    $menu_name = variable_get('menu_secondary_links_source', 'main-menu');
    if ($view_mode == 'full' && $node->type == 'event') {
        menu_tree_set_path($menu_name, 'events'); // 'events' is the path to the view listing
    }

This only works when the nodes are already added to the main menu manually (i.e. it can be used to override the path, but won't do anything if the node isn't in the menu already).

Is there an easy way to force Drupal to always return my hardcoded path for a given content type?

There are two ways I know, and both are based on Menu block module.

Add all elements to the menu all right, but in the blocks that show menus, limit maximum depth so they are never shown to the end user in menu. Additional benefit is that you will have them properly placed in a tree for SEO modules like Site map or SiteMenu. And breadcrumbs will work out of the box.
Keep all nodes that should "appear" like they are in one menu in one path "directory", using Pathauto or similar solution. Add a Menu block set to show menu you need, and set it's display settings to only appear under the path you need and everywhere deeper. For breadcrumbs, you would need something like Breadcrumbs by path or Easy Breadcrumb - both claim to provide breadcrumbs based on URL aliases, so they are menu independent.

Personally, I would go with first way.


How to set the sizes for image thumbnails When I am editing "Image" content type there is an option:

Where can I changes sizes of these previews? And regenerate the corresponding pictures?

These are the same settings as for your normal image styles. You can manage them here: admin/config/media/image-styles. Klick on edit on the rhs, then "override defaults", then edit the effect.


How can I limit filter to child terms of selected parent in Views? I have a View that I am using to allow users to search for nodes on my site, all nodes have a category and a subcategory. I have two filters in the View, call these Parent Term filter & Child Term filter.

Example vocabulary:

-Categories
--Category A
---Item 1
---Item 2
---Item 3
--Category B
---Item 1
---Item 2
---Item 3

I want to implement the following functionality:

User selects Category A from list in Parent Term filter.
Child Term filter list populates with only Category A child terms.
User selects Category B from list in Parent Term filter.
Child Term filter list populates with only Category B child terms.

I've looked into Views Dependent modules, but none seem to do this properly. I'd prefer to have something in code (AJAX?) that does this much more efficiently.

At the moment I have the two filters manually limited to parent terms and child terms. However this means the child term filter shows all children irrespective of parent term selected.

I would take a look at Simple Hierarchical Select. From the module page:

  Simple hierarchical select defines a new form widget for taxonomy
  fields to select a term by "browsing" through the vocabularies
  hierarchy. The widget is available in node forms and as Views exposed
  filter.


How do I achieve 2 level tabs? Drupal 6 had an easy way to do this, but D7 doesn't.
I asked this question on the drupal.org forums, and I didn't get answer. Am I asking too much? I just want 2 level tabbed main menu where I can have full control over the link styling.

Bottom line, I want to extract each individual link (and sub link) from the main menu and theme them individually.

If you have a theme that supports the output of primary and secondary links in the way you describe (Bartik, the default theme for Drupal 7 does, but it doesn't have the secondary nav below the primary, but rather in the upper right of the header), you can accomplish this by setting the secondary menu to be the same as the main menu. Navigate to admin/build/menu/settings to make this selection.

You can further customize this behavior using the Menu Block module.


Adding drop down divs to content I have search and searched and have not found this question yet. Nor have I found a way to do it.

I want to have a page built where it has a few fields, Objectives, Audience, Credits, Location, etc. I want the user to be able to type in all content on one edit screen.

When you view the page I want a horizontal bar with the fields listed - Objectives, Audience, Credits, Location - and when you click on the name Objective, the information for objective pops down in a div. When you click on Audience - text for audience pops down. This would be below the main body copy of the page.

I was thinking maybe fields group or conditional fields for forms however I do not see how those would work.

Does anyone have any ideas? a tutorial to send me too? a module to review?

Thanks
Tim

It sounds like you could use something like Field Group and use Horizontal Tabs, seems like it would work the way you want.

Under Manage Display of the content type, add a Horizontal Tabs Group.
Then a Horizontal Tab Item for each field or section you want. The label you put in will be what shows up on the tab.
Nest the tabs underneath, and then put the fields you want underneath each tab.

The result will should look something like this. With a bit of CSS, you can make it look different.

Manage Display

Final Result


How to show files with lighbox/colorbox effect? My goal is to create a gallery of all media of the site. I created a views-page of type file with bootstrap grid format that displays all file type of my site (File: Mime type (has word jpeg jpg png gif YouTube)).

My first problem is to get lightbox or Colorbox to display the file on click on the page. Is there any way I can get lichtbox in code (css, function,...) or views showing only file.(Note I'm not using fields but file). That mean when I'm on the views-created page, I can click on any file(image or video) and it react with lightbox overlay.

The second one is to remove certain content type files from the views display. (I don't want user profile images to be displayed or private files).

Thirdly, i want to create a menu to sort the file per type(image, audio, images, and taxonomy terms.) Maybe there is a good tutorial for this on google. I couldn't find anyone, ;)

My first problem is to get lightbox or Colorbox to display the file on click on the page

For this you need to set either lightbox or colorbox module. Once you install and enable the site you will see the option in file field to show the file in lightbox.

    he second one is to remove certain content type files from the views display

Add a filter criteria File Usage: Entity type or File Usage: Entity Id and exclude user entity.

    Thirdly, i want to create a menu to sort the file per type

For this you need to add a sort criteria based on your File:Mime Type


How do I implement Ctools plugins from other modules? I have a module which defines a plugin. Using this code, I can easily load the plugin:

ctools_include('plugins');
ctools_get_plugins('mymodule','myplugin');

That works great, but I would like my module to use plugins from other modules of type 'myplugin'.

I can only seem to get it to load plugins defined by the module provided in the first argument whereas I want to get all modules that provide plugin "myplugin", is there any way to do this?

With the code you shown, you get all the plugins of that type implemented by any module, not just from one module. In fact, when I execute the following code, I get the plugins implemented also from the Views UI module.

ctools_include('plugins');
dpm(ctools_get_plugins('ctools', 'export_ui'));

The module name passed as first argument to ctools_get_plugins() is used to namespace the plugin type: There can be other modules that implement a "export_ui" plugin type, and that is the reason why the function requires the name of the module defining the plugin type.

See also the description given for hook_ctools_plugin_directory():

  This hook is used to inform the CTools plugin system about the location of a directory that should be searched for files containing plugins of a particular type. CTools invokes this same hook for all plugins, using the two passed parameters to indicate the specific type of plugin for which it is searching.


How to calculate the sum of the values of a multi value field without page reload For a content type with a decimal field with unlimited values
(rows), how can I have another field in that same content type that shows the sum of all of the decimal values from the multi value field?

The goal is to keep a tally of the decimal values as the user enters them so they know the total before hitting save on the node.

When the node is saved, the final sum should also be saved in the database.

Modules used are Entity Api and Field Collection.

I was going to recommend researching the AJAX in hook_form_alter function(), but when I read that you were using Field Collections I got a little nervous.

The problem with Field Collections is they can be little finicky when you try and do more complex field "stuff" like the scenario you're proposing. I have yet to try using AJAX in combination with Field Collections and I definitely would not want to be the developer who was tasked with it.

However, if you feel like you want to tackle such a problem you are most certainly going to have create a custom module specific to your situation.

Below is the basic layout for a Node Form Alter using AJAX. Ultimately you want to add an AJAX Event function on your select list, so when the value changes it will call a function that adds the values together.

That's even before you factor in the Field Collections module, which is going to add another layer of complexity to the whole operation.

https://api.drupal.org/api/examples/ajax_example!ajax_example_node_form_alter.inc/7

/**
 * Implements hook_form_FORM_ID_alter().
 *
 * Adds two fields to the node form, second only appears after first is enabled.
 */
function ajax_example_form_node_form_alter(&$form, &$form_state, $form_id) {
  $node = $form['#node'];
  $form['ajax_example_1'] = array(
    '#type' => 'checkbox',
    '#title' => t('AJAX Example 1'),
    '#description' => t('Enable to show second field.'),
    '#default_value' => $node->ajax_example['example_1'],
    '#ajax' => array(
      'callback' => 'ajax_example_form_node_callback',
      'wrapper' => 'ajax-example-form-node',
      'effect' => 'fade',
    ),
  );
  $form['container'] = array(
    '#prefix' => '
',
    '#suffix' => '
',
  );

  // If the state values exist and 'ajax_example_1' state value is 1 or
  // if the state values don't exist and 'example1' variable is 1 then
  // display the ajax_example_2 field.
  if (!empty($form_state['values']['ajax_example_1']) && $form_state['values']['ajax_example_1'] == 1
      || empty($form_state['values']) && $node->ajax_example['example_1']) {

    $form['container']['ajax_example_2'] = array(
      '#type' => 'textfield',
      '#title' => t('AJAX Example 2'),
      '#description' => t('AJAX Example 2'),
      '#default_value' => empty($form_state['values']['ajax_example_2']) ? $node->ajax_example['example_2'] : $form_state['values']['ajax_example_2'],
    );
  }
}

ajax['event']

Description: When this event occurs to this element, Drupal will perform an HTTP request in the background via Javascript.

Values: String. Possible values: Any valid jQuery event, including 'mousedown' (for submit, imagebutton, and button), 'blur' (for textfield and textarea), 'change' (for select). Note that #ajax['event'] does not need to be explicitly specified. Although it can be manually set, usually the default value will be sufficient.


Export fields properly with Features I want to improve the way I put my Drupal sites in production. For that I began to use 'Features' to export every single content type I created. (I'm doing it on the Drupal 6 websites).

But when I import those features on the production version of the website the only field I get is the title and other parameters. My field's from CCK are not exported.

I have the same module's (and version) on the local, staging and production website. All required modules are installed. During the generation of the 'Features' I added the custom fields I have created.

Has anyone experienced this behavior? Is there any solution? Did I forget something during the process?

Just because this comes up high on google when searching for the answer (and I just figured this out):

Run cron
Run update.php

Your fields will then appear. This is a Drupal 6 Features issue only. With Drupal 7 the fields should show instantly.


how to remove password confirmation field in user registration form? I want to remove password confirmation field. Its ok if user enters the password only once. There is no need to confirm it again.

I am using this code

<?php
function dp_form_alter(&$form, &$form_state, $form_id)  {
    switch ($form_id)  {
        case 'user-register-form':
        $form['account']['pass']['#type'] = "password";
            break;
     }
  }

Please tell me where am I wrong. Its not working. :(

The following code works for me in Drupal 7.

/**
 * Implements hook_form_FORM_ID_alter().
 */
function MODULE_form_user_register_form_alter(&$form, &$form_state, $form_id) {
    $form['account']['pass']['#type'] = 'password';
    $form['account']['pass']['#title'] = 'Password';
}

Please note that the user registration form and the user profile form both have password confirmation fields and are not the same form.  You will need to alter both forms if you wish to remove all password confirmation fields.


Building taxonomy Selector I'm building a classified website, on which users can create ads using the custom content type I've created. Each ad has a category field which a reference to a multilevel taxonomy, and uses the  hierarchical select field type.

When a user creates an ad/classified, I'd like the UI to first ask the user to choose from the the top-level terms of the taxonomy, then from the child terms of what is selected, then the child terms of that, so on so forth.

Here's an example of what I'm trying to achieve:

I've already tried using Conditional Fields with Hierarchical Select, and Simple Hierarchical Select but neither have worked out so far. I'm trying to create something that's user friendly.

Any help is appreciated.

You can try with Hierarchical Select module.

  This module defines the "hierarchical_select" form element, which is a greatly enhanced way for letting the user select items in a hierarchy.


Add Additional Submission Processing To "Create Node" forms Which hooks can I implement in Drupal 7 to add additional processing steps to the node creation process.  For example, to run a snippet of PHP code after the node has been successfully saved to the database.  I'm assuming hook_form_alter, but I only want to add to the process, not replace the default node save process.

Specifically, I'm looking to make an immediate external API call to SmugMug.com and then trigger an email upon a successful node save.

In Drupal 6, this was done in hook_nodeapi.

In Drupal 7, this is done in hook_node_update & hook_node_insert

hook_node_update($node)
This hook is invoked from node_save() after the node is updated in the node table in the database, after the type-specific hook_update() is invoked, and after field_attach_update() is called.

hook_node_insert($node)
This hook is invoked from node_save() after the node is inserted into the node table in the database, after the type-specific hook_insert() is invoked, and after field_attach_insert() is called.

there is also hook_node_presave($node) if you want to do something before its been save

More information on api.drupal.org & link to the D6 to D7 upgrade changes


Token to show all the comments including comment body for a node I am trying to set up a notification email using rules that will email a forum topic with all the comments including the comment titles and body.

The Message text I have so far is:

  A new forum comment has been posted by
  [comment:author:profile-main:field-name] with the following details

  [comment:node:title]

  [comment:node:body]

  Comments:

  [comment:node:comments]

However, the final token, [comment:node:comments], only shows the comment titles and not the comment body.

Is there a way that I can show the full list of comments including the comment body?

To solve your issue you can create custom token which contain needed info. Basically you create a module that implements hook_tokens and hook_token_info. For more details see the documentation: http://api.drupal.org/api/drupal/includes--token.inc/7.

Additional, where you can find examples:
https://www.drupal.org/node/1308488 and
How to programmatically create a custom token in a module


Why is my patch failing a test? When a patch fails testing because it doesn't apply, and the error reads "Ensure the patch applies to the tip of the chosen code-base." what does this mean?

Basically your patch have to be applyable with the command

patch -p1 < $filename.patch

http://drupal.org/node/707484 is a pretty good tutorial how to create patches so the testbot can use it.


Create bulk nodes - PDOException Problem

I'm trying to create multiple nodes at once using a CSV file for the data. However my script only creates the first 25 before it throws the following error. Any ideas what might be happening?

  PDOException: in drupal_write_record() (line 7166 of C:\XAMPP\htdocs\drupalie\includes\common.inc).

Set-Up

I have a custom form which creates the nodes on submit. The form just has a submit button.

This is the submit handler. I only have one column in my CSV sheet so I don't actually use the delimiter. First I generate an array with each node name.

  if (($handle = fopen("sites/all/modules/custom/generatenodes/nodes_database_import.csv", "r")) !== FALSE) {
    //open the CSV file
    $length = 1000;
    $delimiter = "|";
    //set the length and delimiter.
    while (!feof($handle)) {
      //$line is an array of the csv elements
      $node_name_array[] = fgetcsv($handle, $length, $delimiter);
    }

    fclose($handle);
  }

The array looks like this:

I then create the nodes:

global $user;
foreach ($node_name_array as $nodename) {
  if($nodename == FALSE) {
    return;
  }

    $values = array(
      'type' => 'school',
      'uid' => $user->uid,
      'status' => 1,
      'comment' => 0,
      'promote' => 0,
    );
    $entity = entity_create('node', $values);

    $ewrapper = entity_metadata_wrapper('node', $entity);

    $ewrapper->title->set($nodename['0']);
    $ewrapper->field_country->set($schoolname['0']);
     $ewrapper->save(true);
    entity_save('node', $entity);
}

But it breaks after the first 25 or so. What have I missed?

EDIT--

So I found the cause. It's to do with the values in my CSV file. Sometimes it likes them othertimes it doesn't. If I replace these values then it works up to the next broken value.

The first problem was a value with an accented e inside. Removing the accent fixed it.

Unfortunately the next two which broke it are not so obvious:

Putian Cambridge English
Zhangzhou Bilingual Middle School

Yet the following values work:

Quanzhou Foreign Language Middle School
International College of Xiamen University

I've only pasted in clean values, but something is breaking it. Any ideas?

Trying to navigate to the content page after causes MySQL to break. Here's the error log:

https://www.dropbox.com/s/jji3cw559filq03/mysqlcrash_log.txt

You should be using migrate for this: https://www.drupal.org/project/migrate, it covers many of the pitfalls you are currently encountering when creating or importing content from a CSV, database or XML file. Don't recreate the wheel when someone has already created it for you.

It's not like the feeds module or other "import" type modules, it's an entirely  code based OOP solution. You just extend the main migration class and map your data. It comes with a number of built in PHP functions to process the data further and it literally covers almost every scenario you could possibly encounter when mass creating or transferring content.

As someone who's been down this path many times, it will save you a lot of time and hair pulling. I recommend looking at the code examples migrate provides.


How to display users with same select list value to each currently logged in user In my site each 'User' as a profile (created using Profile 2). One of the fields in the profile is a 'Select list field' that allows the user to choose his/her State of origin.

Please how can I create a View which displays to each "currently logged in  user", the people who come from his/her State.

I have tried the following but it returned empty.

I created a User view.
I added some fields
I added the following relationship- "User:Profile"
I added the contextual filter on "(Profile) Profile:State" to provide default value from "User ID from logged in user" if filter value is not in the URL.
I added the contextual filter on "User:uid" to provide default value from "User ID from logged in user" if filter value is not in the URL.

You should set the contextual filter to have a default value provided by the UID.  Since you're trying to only display the list of users where they have the state in common, you'll need to set the default for the profile:state to be provided by the UID.


How to translate views infinite scroll Loading message I have an Arabic website and I have views infinite scroll module to allow ajax paging.

I want to translate Loading the next set of posts.... I have tried to search for it in the translate interface, but I could not find it. I tried to import its *.po file from this link but also I could not find it. I have tried to search among the module views_infinite_scroll files, for that string to change it from the source, but also I could not find.

I'm using webpal pinteros theme, and it has its own js/views_infinite_scroll.js file, in-which the message could be translated. However, this solution is not suitable for multiple languages sites.


Exclude taxonomy terms from search_excerpt in snippet In search-result.tpl.php or in preprocess_search_result function, I want to keep $snippet. It is a great view to display search results.

But Apache Solr results, or Search module results, are displayed with terms that matches the query. These terms are designed to be hidden to anonymous. They can't be displayed in the snippet.

  ex: Marguerite Duras … histoire " avec DURAS. Celle de deux personnes qui se reconnaissent avant de se connaître. Une … "Qui est Marguerite Duras ?" Il avait découvert l'écrivain, il allait rencontrer la …

The term Marguerite Duras is an admin tag. By the way, it is nice that the score relevancy depends on it.

How is created the snippet, or search_excerpt ?  I tried the Taxonomy Hide module, but it doesn't affect search results.

The search result is a node view and hence the hook_node_view_alter works for it.

So you would could create a custom module and write the following function

function custom_node_view_alter(&$build, $type)
{
    if (($build['#view_mode'] == 'search_result') && ($type = 'node'))
    {
        unset($build['field_tags']);
    }
}

change the field_tags to the name of your taxonomy field in the content type.

$build['#view_mode'] this variable defines the view we are on. In this case we are on the search_result view. And the $type defines the module in this case it is the node.

Use the following for Drupal 6

function custom_nodeapi(&$node, $op, $a3, $a4) {

  switch ($op) {
     case 'search result':
          $node = node_load($node->nid);
        $node->build_mode = NODE_BUILD_SEARCH_RESULT;
        $node = node_build_content($node, FALSE, FALSE);
        $node->body = drupal_render($node->content);
      break;
  }
}


Image uploading issue I have uploaded the drupal website on one of my domain and it is working well, then now I need to migrate it to another domain. Every thing was migrated but when I try to upload images from admin panel it is not uploading correct images. Means, if I try to upload let say cat.jpg then sometimes it display another random image from my directory. Strange issue, unable to figure out why?

I am trying to upload the following image:

And when it is uploaded it is displaying a random image:

I suggest you clear you cache and if not getting worked  I suggest install image style flush module and flush all your image styles.

Easiest way to flush image styles in Drupal 7.

  Image style flush Overview

  This module will allow Drupal to flush all image styles at once or
  flush each image style individually right from administrative
  interface. Features

Flush all image styles
Flush each image style individually

  Known problems

Private file image styles can't be flushed with this module.


How to restrict group node access to a user/member of an group? I am using the Group module and I have created a group called "Group-Y" and group type "Group-type-Y". I also defined a group role name "Admin". Added an member with role "Admin".

I have checked this module, which provided the access based on page,

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

Page access module does work with global user admin, like here:

I tried to achieve it for group admin. In the edit node, page access settings are not displayed.

I need to achieve to restrict node based on user/role in a group. Can anyone help me out?

It seems to me that, for what you're trying to achieve, you do not need the "Page access" module. Instead only using the Group module it should be possible to get it to work.

Some basics about the Group module to be aware of:

Make sure you enable gnode, a submodule of the Group module.
For each group type you need to define the appropriate permissions (view, edit, delete, etc) for the various Content Types.
Every group can have users, roles and permissions attached to it (refer to "What are the various roles supported by the Group module?" for more details about that).

It seems that you would want to grant access to what, in Group, is called "Members". But you woudn't allow access to "Anonymous" (site visitors that are not logged it). However, you also need to think about which access you want to give to "Outsiders" (=  logged in users who are not a member of a group).

With the above in place, it's just a matter of assigning a node to a Group. So if the gnode submodule is enabled, you should be able to do so via a group-related field that will be shown on the node edit form, via which you can then select the appropriate group

More info

Refer to "How to create collections of content that can be accessed by users with various access levels?" for more  info about all this.


Text formatting in the "Help Text" section I'm wondering where the formatting is set for the "Help Text" section. I was thinking that maybe it was plain text, but it does not appear to be so - I want to use the module Collapse Text to collapse the text and make the help text available to the user only if they want to view it, while filling out their registration form.

Is there a way to do this, or will I have to write a third party module?

This is the module I want to use with the help text.

https://drupal.org/project/collapse_text

The Advanced Help module will let you create help texts that can be tied to a help icon on any page, form or form item. Clicking the icon will pop-up a Ajax window with the text.


How do I change order of completion rules in checkout? How do I change the order in which completion rules fire?
There is a default Completition reaction rule. I wanted to add a second rule which executes some custom PHP but it's never executed.
I see no way to change the weight as in other rules. I also tried adding what I need as an action in that default rule, but it also doesn't seem to fire.
This is the reaction rule that fires on order completion.
{ "rules_completion" : {
    "LABEL" : "completion",
    "PLUGIN" : "reaction rule",
    "REQUIRES" : [ "php", "rules", "commerce_checkout" ],
    "ON" : [ "commerce_checkout_complete" ],
    "DO" : [
      { "php_eval" : { "code" : "jch_send_quote()" } },
      { "commerce_checkout_complete" : { "commerce_order" : [ "commerce_order" ] } }
    ]
  }

This is the code for jch_send_quote() which doesn't seem to fire.
function jch_send_quote(){
    global $user;
    watchdog('dev', 'jch_send_quote running here');
    drupal_set_message($user->uid);
        die('jch_send_quote running here')
}

What am I missing?

You should be able to edit the rule and set it's weight:

Screenshot, showing reaction rule with weight of "2"

Lastly, your rule should still fire, even with a different weight. If it's not firing, it's probably an issue with that rule itself.


server migration issue I've developed a website and deployed it in a server, I consider this server as a test server. Now, I'm in the final stage of development and I'm looking to move the website content to new server. In that process, I've moved my website contents from test server to the new server, updated the database details in settings.php file, created a database in the new server and imported the .sql file (from the test server). I anticipate all the cloning work is done.

Now, when I look into the new site, the home page appears in the old format - I mean most of the edits that I made have gone. When I click on the menu tabs, the corresponding pages are broken - there is no proper redirection to the pages.

What I've observed was, in the homepage the url was good but when I click on one of the links the url is pointing to something odd like - localhost/new_mywebsite/search. I feel that this is odd. I couldn't trace why it was showing in that way.

Moreover, when i compared the new database with old database(test server) the old one has around 130 tables and the new one has only 90 tables. Even it seems odd for me.

What might the real reason for this odd behaviour? Is it with database or links?

I had this same problem recently, and it took me forever to figure out. What you have to do is make sure the database at your new location is empty. You have to have a database, and it has to be an empty database. Of course, do still make sure your settings.php info is correct, as you did the first time around. Then run install.php and go through the normal steps. Once that is complete, then import all of the tables from the old database into the new database.

The reason for this is that Drupal caches the database connection information, so if you change that in settings.php, it will continue using the old information until you run install.php. And you can only run install.php if you’re pointing the site at a fresh database.

EDIT: Sorry, I missed part of your post. You need to also make sure that your base_url settings in settings.php are set up for the live domain.


Allow/restrict access based on privacy setting flags in profile I have privacy profile type and flags with checkbox like "Keep all my friends private" and "Keep all my videos and channels private".These are in my privacy settings profile.Now i want  to allow or restrict the access based on my flagging (on/off checkbox) for the users.Here i have two content types videos & channels.By default other users can watch my videos & channels and i want to make it private when i click my checkbox on for "Keep all my videos and channels private" and once i uncheck this,it should become public.The same need to be done for "Keep all my friends private".I have used user relationship module for friends.How can i do this? Is it possible using php coding or is there any other solution.Please help.
Thank you.

Implement hook_node_access($node, $op, $account) and check whether the user has flagged his content to be private, if so then deny access.

function MYMODULE_node_access($node, $op, $account){
  global $user;

  if($node->uid != $user->uid && $node->type=='video' && $op=='view'){
     $entity_type = 'profile2';
     $profile = profile2_load_by_user($node->uid,'main');

     $flagging_data = flag_get_user_flags($entity_type, $profile->pid ,$node->uid);

     /************ UPDATED ****************/
     if(isset($flagging_data['channels'])){
          return NODE_ACCESS_DENY;
     }
  }
}


How to add custom attributes to description meta tag? I need to add 'class' and 'data-type' attributes to meta tag containing description attribute. I was able to locate the core Metatag module, however I'm unable to find any documentation on how to customize output without altering the core.

function [your-theme]_page_attachments_alter(array &$attachments) {
  $attachments = SwiftypeMetaDescription::add($attachments);
}

 class SwiftypeMetaDescription{
      /**
       * @param array $attachments
       * @return array
       */
      public static function add(array $attachments): array
      {
        // check if $attachments contain html_head
        if (empty($attachments['#attached']['html_head'])) {
          return $attachments;
        }

        // loop through HTML head
        foreach ($attachments['#attached']['html_head'] as $key => $attachment) {
          // check if element name is defined
          if (empty($attachment[1])) {
            // if it's not, skip element
            continue;
          }
          // if the element name equals 'description'
          if ($attachment[1] == 'description') {
            // add 'class' attribute
            $attachments['#attached']['html_head'][$key][0]['#attributes']['class'] = 'swiftype';
            // add 'data-type' attribute
            $attachments['#attached']['html_head'][$key][0]['#attributes']['data-type'] = 'string';
          }
        }

        return $attachments;
      }

    }


How do I force Twig output from my custom module, instead of from the theme? I'm new to Drupal, I create a module including block and twig.
I want to call out my twig(modules/custom/footer_block/src/templates) and store data in there when execute build() in block.

However, it output a twig from theme folder(a templates folder inside the theme folder) that's is not created by me.

How can I force to output from my module folder?

The block is using the following code.

footerMenu_block.php.

public function build(){
    return [
        '#theme' => 'footer_menu',
        '#address_title' => $this->configuration['address_title'],
        '#address_content' => $this->configuration['address_content'],
    ];

footer-menu.twig.html

{{ address_title }}

{{ address_content }}

footer_block.module

<?php
function footer_block_theme($existing, $type, $theme, $path){
  return array(
    'footer_menu' =>
      array(
        'variables' => array(
          'address_title' => '',
          'address_content' => '',
        ),
      ),
  );
}

If I move the Twig to that output folder (inside theme folder), it will be unable to store my data.
If I make simple output '#markup' inside build() that will work fine. Therefore, other code in block should be working without problem.

I am using Drupal 8.6.x.

Try adding the template array key to your theme hook:

function footer_block_theme($existing, $type, $theme, $path){
  return [
    'footer_menu' => [
      'variables' => [
        'address_title' => '',
        'address_content' => '',
      ],
      'template' => 'footer-menu',
    ],
  ];
}

Or try adding the block twig template suggestion as:

function footer_block_theme($existing, $type, $theme, $path){
  return [
    'footer_menu' => [
      'template' => 'footer-menu',
      'base hook' => 'block',
    ],
  ];
}


Ajust the position of autocomplete fields I working with the theme base bootstrap and my problem is that in autocomplete fields it's a bit offside of position, see the screenshot.

How fix this ? I need this more to the left and below the textfield.

Greetings.

This should be a CSS positioning issue, whether it is caused by padding, margining, position, top, left, right, or bottom.

You should be able to use firebug or another developer tool like it to find what CSS is causing this and remove that CSS if it's your own CSS. Otherwise if the CSS is provided by contrib then you can use a more specific CSS selector and override the values.


How to change status and update account? How can i change status to 0 and update an existing user account?

Here is the code i tried:

$account = \Drupal::currentUser();
$account->status = 0;
$account->save();

It gives me error :  Call to undefined method Drupal\Core\Session\AccountProxy::save().

The account proxy class doesn't have a method called save. Refer to the API docs.

https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Session%21AccountProxy.php/class/AccountProxy/8.2.x

What you want is the block() method:

$account->block();

As $account should be an instance of UserInterface, returned front getAccount of AccountProxy. But without seeing the rest of the code its hard to see if this is the right approach for what you are trying to do.

If you could get the user account another way, then you could do:

$account = \Drupal\user\Entity\User::load('uid arg');
$account->block();
$account->save();


javascript code wrapper While using drupal 7, is it necessary for to wrap pure javascript code with jquery wrapper? (I understand that while working with jquery, I need to wrap my code inside beaviors.)

code

function openWin()
  {
    mycode
  }

od should I wrap it like this

(function () {

function openWin()
  {
mycode
  }

  })();

Or even use behaviors? Thank you.

You don't have to wrap your code with a behavior or jQuery at all. That depends:
If you want to use jQuery object with the $ as a shorthand:
Wrap your code like this:
(function($){
  //$('#something').show();
})(jQuery);

If you want to execute something after an Ajax DOM change and on document ready event
Use behaviors.
Drupal.behaviors.ysu_premium = {
  attach: function (context) {
    //jQuery('#something').show();
}}

You can wrap the behavior with the above jQuery wrapper if you want to use jQuery.
(function($){
  Drupal.behaviors.something_unique = {
    attach: function (context) {
      //$('#something').show();
    }}
})(jQuery);

When I'm working on Javascript, I always use the last snippet above.


Can Xdebug be triggered by Drush commands? I'm running into an issue with my Features modules and installation profile when installing the site with drush si. There are a number of probably related issues in the Features issue queue, but none with good solutions. The interesting part (mentioned in some of the issues) is that it works fine when installing the site through the browser, but fails when installing with drush si.

I have an idea of what's wrong, but need to confirm it. The only way I can think of confirming it is to step through the code with a debugger (Xdebug is what I have set up). So, is it possible to trigger Xdebug from a command run with Drush? Specifically, can I get Xdebug to kick in when I run drush si?

you have to remember that with drush you are (most supposedly) in cli, so this should help :

https://stackoverflow.com/questions/1947395/how-can-i-debug-a-php-cli-script-with-xdebug

also, try running the command with the option -d (--debug) - it should give you quite a lot of info about what is going wrong.


Is Drupal following W3C standards? How to change the DOCTYPE? I tested two of my sites in W3C validator. One site passed the test and other site gave me lot of errors. Site2 was having the doctype -//W3C//DTD HTML+RDFa 1.1//EN instead of HTML5. But site1 was having HTML5.

How to change the doctype to HTML5 for Site2?

This would completely depend on the theme you are using on the Drupal site, as the markup of the site is handled on the theme layer.
If you are using an HTML5 theme, then the it will show the appropriate DOCTYPE i.e. <!DOCTYPE html>. In short, your theme should support HTML5 in order to get the DOCTYPE.

To answer your question, you'll need to either make your theme compatible to HTML5, or use any other HTML5 theme.
There is a very good article for Converting Your Drupal 7 Theme Into HTML5 which could give you a good start.


Exposing Individual Fields on Output for Styling I've created a view which outputs a particular content type into a jCarousel.

One of my fields is a 'background colour' and I want to use this value for the actual background colour of the li element in my jCarousel. The next is an image and I want this image to be wrapped in a div that I can lay out correctly within the same li of the carousel.

So, this carousel will have a customisable image and background colour for each member of the content type.

The problem is, in jCarousel, the fields are just dumped into an array haphazardly, so I cannot output different fields in different ways. Ideally, what I'd like to happen is: in the jcarousel-view.tpl.php I'd like to output $rows[0]['background-color'] into my custom html div tags and then $rows[0]['image'] output into my own custom classed div tags also - obviously iterated within a loop to apply the individual settings to each element.
However, the current set up is that $rows[0] dumps both fields into their default styles and I can't access individual fields.

Now, is this something I can control in Views? Or do I need to do some custom hacking to get this to work?

This is a complex but ultimately pretty easy thing to do once you understand how this "haphazard" array is built :)

In Drupal 6....

If you go into views, look under Style Setting at Theme Information.  There, it will tell you all the templates it uses to create its output.  The one here you are interested in is Row Style Output, because it is the template that is building the $rows that are ultimately passed to jcarousel-view.tpl.php.

What you want to do is make a copy of this template in your theme directory that overrides the default one, and in this case, the easiest is the first one that incorporates your view name into it.  Doing a quick test here, with a view named jc-test, that would be views-view-fields--jc-test.tpl.php.

Rescan the templates files to make sure it's selected and edit that bad boy.  What you want to do now is change how it creates the individual row.  Normally, views just passes the information given to it along, but you want to work on it programatically, eg, turn the content of a field into some html based upon it.

So, if you don't have devel set up on your machine, a quick:

<?php drupal_set_message('
' . print_r('field id: ' . $id . ' field raw: ' . $field->raw,true) . '
'); ?>

right after the first foreach() will tell you want's inside here you have to work with.  Let's say for ease of discussion, the field you have that you want to use for the color is named field_color.  For ease, it should be the first field passed to the row, which is easily set up in views.

So, inside here, you'd do something like this:

<?php if ($id=='field_color'): ?>
  <?php print '
raw . '">'; ?>
<?php else: ?>

  -- ALL THE REST OF THE CODE BEFORE THE ENDFOREACH GOES IN HERE
  -- BECAUSE YOU DON'T WANT TO PRINT OUT THIS FIELD
  -- BUT YOU DO WANT TO PRINT EVERY OTHER FIELD

<?php endif; ?>

Now....that OPENS the DIV.  You need to close it at the end of the row, so just put:

<?php print '
'; ?>

after all the php in the template (after the last endforeach).

So, now, barring any typos of mine above, you've wrapped a row in a div classed with the content of the first field of the row :)  Use CSS to make it pretty.

You do have to make sure your data is sane, though,  $field->raw isn't friendly at all, so you may need/want to check_plain() it if it's user input etc etc.

Anyways, hope this helps out!


Contact recipient different than UID Is there any way to make that Drupal 7 built-in contact form sends the emails to a different address than the one of the UID 1?

Under admin/structure/contact/edit/1 you can add or remove any e-mail address(es) you want from the "recipients" box.


how to integrate libraries to load third party files in themes drupal? I just want to know how to integrate third party files with the drupal theme.

To use a CSS/JS library with the Libraries module in Drupal, there are a number of steps:

copy the library to sites/all/libraries/my-library;
Write a small custom module, which informs Drupal that the library is available;
Add the library where's its needed, e.g. with a MYTHEME_preprocess_html hook.

I found a very nice recent tutorial with code samples here.


Views Data Export: How can you include a raw database column? I'm running a data export (using Views Data Export) on some comments and I'd like to include the thread column in the result. The only thing I can see is a Depth field, which doesn't contain the detailed thread information needed to re-render the comments in the correct order. Is it possible to include the thread database column in the results?

Many thanks

Table column will not be automatically imported as available views field. Any extra field you want to use in views. You can define it with hook_views_data. Anyway, I can find pretty much fields are ready to use.


PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined: I get "PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined" using the below db_query() call.

db_query("SELECT image.:field1_fid as fid, image.:field2_data as file_data, image.:field3_list AS list FROM {content_:field4} AS image WHERE vid = :vid AND nid = :nid", array(':field1' => array_values($field), ':field2' => array_values($field), ':field3' => array_values($field), ':field4' => array_values($node_type), ':vid' => array_values($vid), ':nid' => array_values($nid)));

I also tried like this.

db_query("SELECT image.:field1_fid as fid, image.:field2_data as file_data, image.:field3_list AS list FROM {content_:field4} AS image WHERE vid = :vid AND nid = :nid", array(':field1' => $field, ':field2' => $field, ':field3' => $field, ':field4' => $node_type, ':vid' => $vid, ':nid' => $nid));

Wny idea what's wrong in my query?

A parameter to a query is something that will go in the WHERE/HAVING clause, it can't be used to substitute text into the SELECT or FROM (or any other part) part of the query. As you've only got two proper parameters in the query (those after the WHERE clause), and you're passing several more as the arguments, you get an error informing you of the count mismatch.

You're also trying to pass in arrays as single string parameter replacements to the SELECT and FROM parts of the query, which will just never work (even if you could use parameter replacement in those part of the query). When cast to a string, the array will simply be the string Array, which is pretty much definitely not what you're looking for.

If you want to build those parts of your query dynamically you'll need to use db_select() instead. This code isn't a complete representation of your example but should get you going:

$query = db_select('content_' . $table_name, 'image');

$query->addExpression('image.' . $field_name);
$query->addExpression('image.' . $field2_name);
// etc...

$query->condition('vid', $vid);

$results = $query->execute();


pass view result from one view to another I have a view that outputs field content, and outputs one result.  There are four additional views that I need to have this result passed to somehow so I can filter the nid of that result out of the possible results for the other four views.

It's the end of the day so I wrote this question in haste, if it is no clear, please ask for clarification.  I will review later and update if necessary.

You can use Views field view module ,https://drupal.org/project/views_field_view
with which you can have a view inside a view,and pass an argument from one view to another.


Views Display for a query that doesn't display view content to user I need a views display type that will not output content to the user.

Essentially, I've got a view that simply performs a query, and I get the results of the query with views_get_view_result() and then emails the results of the query to a user with a spreadsheet.

It's being run during cron, so I have to turn off access checks for access, or the query displays no results.

Though I could use an alternate access check that ensures the view is being run during cron. Any ideas, Drupalers?

Alright. So here's what I did. I installed Views Access Callback, then created a callback function that checks for the cron key.

The funny thing is, this disables the page URL access for me as user #1, even though I have "access all views" permission, and "Disable SQL rewriting" under Advanced -> Query Settings is turned on, which I would think bypassess access checks, but views_get_view_result() is getting results from the view even when my access function returns false. That's acceptable for me. I need to disable access via a URL.

Here's my implementation

/**
 * Implements hook_views_access_callbacks()
 */
function mycustommodule_rules_views_access_callbacks() {
  $callbacks['mycustommodule_rules_is_cron_view_access'] = t('Is function run from cron');
  return $callbacks;
}

function mycustommodule_rules_is_cron_view_access() {
  if (isset($_GET['cron_key']) && variable_get('cron_key', 'drupal') == $_GET['cron_key']) {
    return TRUE;
  }
  else {
    return FALSE;
  }
}


How to get all nodes of a content type as header menu item? I want to get all nodes of Article type added dynamically to header menu. Any module that can do it for me?

You can configure content type to create menu items. So look at content type configuration.
It will dynamically create menu items when new node is created.


Use form_alter to change description under reset password field for user_pass form I'd like to change the text below the reset password field. I took a look at this answer, and it talks about changing the button, but I need a bit of help to change the text.

Here is the debug output and it looks like I need to access #description

[name] => Array
        (
            [#type] => textfield
            [#title] => E-mail
            [#size] => 60
            [#maxlength] => 254
            [#required] => 1
            [#default_value] =>
            [#description] => A password reset message will be sent to your e-mail address.
            [#input] => 1
            [#autocomplete_path] =>
            [#process] => Array
                (
                    [0] => ajax_process_form
                )

This is how I would change the button:

function footheme_form_alter(&$form, &$form_state, $form_id) {
  if($form_id == 'user_pass') {
   $form['actions']['submit']['#value'] = t('reset password');
   print "boom";
 }
}

Got it!

if($form_id == 'user_pass') {
   $form['name']['#description'] = t('This is a test');
 }


Vimeo Video Browser While Creating New Page In Drupal I'm new to Drupal, learning it from past few days.

I want to create a vimeo video browser field widget while creating a page content type. Is there any module available which could help me achieve this?

I have installed various modules like vimeo media module, media embed field which enables me to add the vimeo video URL while creating the new page, I want to make an addition to this functionality like a vimeo video browser window to be opened and I could select the video from the same. Any idea as in how I could accomplish the same?

I can advice you this module
https://drupal.org/project/media
https://drupal.org/project/media_vimeo

I wish it helps you.


Wrong and ignored language to be translated My website is by default in French and I need to get an English version.

Prob n°1 : I've got this kind of Exposed filter (exported in a block), everything in it is translated excepted "Tri" (sort) and "Appliquer" (apply) which stay in french.

Here, you can see all modules about languages/i18n (add i18n, i18n_block)

In my exposed filter settings (in FR) :

In the view, translate view > English > traduire > and I wrote this

In Config > Regional > Translate I found what I wrote correctly

Answer n°1 : Why my exposed filter labels can't be translated ?

Answer n°2 : Another thing, it's maybe common but I found this strange, when I write a sentence in t() function, it must be in english and not in my site language else I get

Is it normal to write in english in t() function even if the site language is not ?

Thanks in advance for helps. I'm listening some tricks, advices and good practice about languages.

First, you need to select source/default language from admin/config/regional/language.

After you need to import .po file of English or your selected import other import languages (https://localize.drupal.org/translate/languages/en).

Now you will able to translate your term from Config > Regional > Translate. and those are visible according to your language.


Duplication of files when using Acquia Dev Desktop I am creating a Drupal site using Acquia Dev Desktop. I have noticed that there seems to be duplicate files located at

C:\Users\Sam\Sites\devdesktop\columbiablooms-dev\docroot\sites\all

and

C:\Users\Sam\Sites\devdesktop\openoutreach-7.x-1.19\sites

"Sam" is my Win 7 logon. Columbiablooms is the name of the site I'm building. Using Acquia Dev Desktop I pushed the site up to Acquia. What is the relationship between the two file paths?

Does the C:\Users\Sam\Sites\devdesktop\columbiablooms-dev folder have anything to do with multisite or is it necessary for Acquia Dev Desktop? Having stuff duplicated seems a waste and causes confusion for a newbie like myself.

C:\Users\Sam\Sites\devdesktop\columbiablooms-dev contains data for your Acquia site (e.g. hooks has scripts that can trigger upon deployment, private contains files that setup as private in Drupal's file system, etc.)

The C:\Users\Sam\Sites\devdesktop\columbiablooms-dev\docroot dir is the webroot of your site; this is the dir that is the base of your domain that is uploaded to Acquia (e.g. C:\Users\Sam\Sites\devdesktop\columbiablooms-dev\docroot\index.php -> http://www.example.com/index.php). See this post for an explanation of all the subdirectories.

C:\Users\Sam\Sites\devdesktop\openoutreach-7.x-1.19 is a copy of OpenOutreach 1.19 you downloaded. It contains the OpenOutreach installation profile, its needed modules/themes, and the version of Drupal it's bundled with.


How can I avoid clearing caches when CSS changes are made? Every time I make the slightest CSS change, I need to clear cache to see the changes.

What can be done about this?

Install AdvAgg, go to admin/config/development/performance/advagg and set "AdvAgg Cache Settings" to "Development"

If you don't want to do that, go to admin/config/development/performance and uncheck "Aggregate and compress CSS files" as well as "Aggregate JavaScript files"

Another option is to install the admin menu module. That has an option to just clear the css/js cache.


Equivelant of node_type_load() for entity bundles If I know the entity type and bundle, I want to load the bundle object with its settings. Drupal core has this for nodes, but is there any way to do it for entities?

See node_type_load() in core:
https://api.drupal.org/api/drupal/modules!node!node.module/function/node_type_load/7

EDIT: So to elaborate, I'm asking about a way to load up the data about the entity bundle, not a specific entity.

E.g.

var_dump(node_type_load('page'));

object(stdClass)[628]
  public 'type' => string 'page' (length=4)
  public 'name' => string 'Page' (length=4)
  public 'base' => string 'node_content' (length=12)
  public 'module' => string 'node' (length=4)
  public 'description' => string 'Use pages for your static content.' (length=43)
  public 'help' => string '' (length=0)
  public 'has_title' => string '1' (length=1)
  public 'title_label' => string 'Title' (length=5)
  public 'custom' => string '1' (length=1)
  public 'modified' => string '1' (length=1)
  public 'locked' => string '0' (length=1)
  public 'disabled' => string '0' (length=1)
  public 'orig_type' => string 'page' (length=4)
  public 'disabled_changed' => boolean false

You can use entity_get_property_info() for example

var_dump(entity_get_property_info('node'));

Bundles are a keyed array within the result and they contain a keyed array of the fields and their settings.

Other information about the bundles other than field properties, such as menu callback etc, can be obtained using entity_get_info() where the bundles as keyed array within the result contains other non-field info.


Views to use relative paths for image fields How can we tell views to use relative paths for dispalying images using image fields. I have created a views slideshow which is displaying images using absolute url which is causing the images to reload on each page load.

facing the same issue in other type of views displays like grid and unformated etc...

Add your image to the view (mine is called Image2)

Create a theme file for your image field, see screenshot. (mine is called views-view-field--relative-url-example--page--field-image2.tpl.php and it's bolded). Pick the last one for the most granular themeing possible.

 (full size here)

After you have added the theme file to your theme templates (/sites/all/themes/THEME/templates or similar), hit the "Rescan template files" button. Your field template should be bolded now.

Add the following code to your theme file, I removed the comments but you can leave them in if you like:

<?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

    $url  = file_create_url($row->field_field_image2[0]["raw"]["uri"]);
    $url  = parse_url($url);
    $path = $url['path'];

    print $path;
?>

I only printed the path to demonstrate it works so you will need to add the image tag, etc.

Here is my output:

You may need to clear the cache and be sure to save your view after you update the theme file.