How to add user info along with address info in a single form using 2 content types? I have a content type 'Person', one field of which has a entity reference to a content type 'Address'.

I would like an anonymous user to add their information along with their address in a single form using these two content types. What should I use to do that?  Do I have to code it or does a module or a combination of modules help me?

Also similarly, for a logged-in user, I would like them to be able to edit their information which was previously saved. How do I do that?

Notes:

I would like the anonymous users to register and also provide a few more pieces of profile information. Of course, I do limit what else they can do till they get approved by the administrator.
I could capture the address information in the same content type but the reason I am thinking of separate content type is because two people can have the same address and I don't want to have redundant information. It would also provide me a way to figure out people who live in the same household. Also, I don't want to lose the address if someone moves and decides to update their address. It looks like I can add/edit two different nodes in the same page. If not reference, how? Do I have to code for it or there are modules that can do it?
My choice of 'address' as an example was a bad one. My broader question is: Given two tables with one of the fields as a foreign key into the other, in Drupal, how can I create, update, delete corresponding rows in the two tables at the same time. The interface being user friendly UI for end user. Does I have to do this in code, or is there a single module or a set of modules that can be used to accomplish this? I am not looking for a full solution as much as pointers in the right direction.

You probably should have a look to Profile2 module. If you really want to use content types, you should have a look to Inline Entity Form and then configure permissions to be sure users can only edit their own content.

Hope that helps ;-)


Is there a way to restrict some pages like node/add, /user/login and more? Can we restrict some page like

node/add
/user
/user/register - as I dont have login/registration page at all
/user/login
node/200 or node/500 - so that may be of any content type

and it should be unlimited. I need to show Access denied page when somebody accessed those pages.

Though I can use programmatically drupal_access_denied() function, do we have any other option on this.

You can use the Rules module to restrict access to those selected pages. Here is a rule (in Rules export format) which should be pretty close to implement such access restrictions as you're asking for:

{ "rules_limit_access_to_some_urls_" : {
    "LABEL" : "Limit access to some URLs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "init" : [] },
    "IF" : [
      { "user_has_role" : {
          "account" : [ "site:current-user" ],
          "roles" : { "value" : { "1" : "1" } }
        }
      },
      { "OR" : [
          { "data_is" : {
              "data" : [ "site:current-page:path" ],
              "op" : "IN",
              "value" : { "value" : [
                  "node\/add",
                  "user",
                  "user\/register",
                  "user\/login",
                  "node\/200",
                  "node\/500"
                ]
              }
            }
          },
          { "text_matches" : {
              "text" : [ "site:current-page:url" ],
              "match" : "node\/\\d+\/something",
              "operation" : "regex"
            }
          }
        ]
      }
    ],
    "DO" : [
      { "redirect" : { "url" : "no_access" } },
      { "drupal_message" : {
          "message" : "Access to the content located at the path you tried to use is not allowed.\r\n\u003Cbr \/\u003E\r\nIf you think this is an error, please contact us.",
          "type" : "warning"
        }
      }
    ]
  }
}

Check the paths in the above rule to ensure it fits your own needs. Also note that I include an extra path that corresponds to "node/*/something" (in case you'd also want to limit access to any such URL. Replace the something in it to fit your needs. Or if you don't have such URLs then just remove that entire Rules Conditions (with the regex in it).

And indicate the correct path of the redirect to be perform (= change the "no_access" make it fit your "no access" page). Possibly you may also want to adapt the roles for which these validations should be applied.

For more details/background about using such rule, refer to my answer to the question "How to make the permissions of a module more granular?".


How to translate dates? I have a calendar view in my Drupal 7 website, that looks like this:

And I also have a date field in a Webform:

All of these appear in english, of course. But, I want to translate all dates to portuguese.

How can I do that easily?

Thanks a lot.

Most of Drupal contributed modules have their translation under Drupal Translations

If you visit the site and search for Date, you will notice list of countries and languages.

I notice Portuguese translations for Date module.

Portuguese, Brazil
Portuguese, International
Portuguese, Portugal

Download the correct language translation file by selecting the version of Date module your using.

Go to http://[your_site]/admin/config/regional/translate/import . To import the downloaded file.

For more information about Translation and how to build multi language site please refer to my answer in https://drupal.stackexchange.com/a/184623/24038


I don't see Views Theme Suggestions For some reason I don't see the views theme suggestions in my twig debug information? What do I miss?

In my development.services.yml in set debug to true.
I do see debug information and theme suggestions from other page items.
I do see views debug info but not the theme suggestions. See image below:

On other website I see suggestions like this:

This is a bug in Drupal 8 core, currently being worked on in several different core issues, many of which have working patches.
If you need the functionality now, you have two options:

Try the patches from comment #22 (or more recent) on Issue #2923634 and the patches on Issue #2752443.  Read the comment thread on #2923634 to get a full understanding of what's going on here.

Or use the well-vetted patch from comment #139 on Issue #2118743 which has been postponed in favor of option 1 above.

I'm using the patch from option 2 (#2118743) successfully. Please note that this does go against the standard core contributor recommendations. But the reason is because #2118743 has a single, well-vetted and working patch for something that is only enabled / used during development, and instead of needing to test out various combinations of two separate patches that are still under development. Once the better solution (#2923634 and #2752443) get fixed in core, #2118743 should be obviated and no longer required.


Changing URL alias of webform breaks template I created a webform with a URL alias of contact-us. The edit URL is http://local.mysite.com/node/1/webform. I have two custom templates, page--node--1.tpl.php and webform-form.tpl.php. Everything works correctly.

Now I've been asked to change the URL alias of the page to feedback. As soon as I do this, the form stops displaying. I've error-logged things out, and when the alias is changed, it's not getting to the webform-form.tpl.php.

I'm confused - I understood that webform-form.tpl.php (without a specific form name) would be applied to any and all webforms. Is this incorrect? Or is there something else I'm missing that would cause a URL change to break this way?

Edited to add that there are no changes to template.php.

Check which template name Drupal suggests after you changed URL alias.

Enable debug option so you could see template name suggestions (they shown in the html source as commented out strings).

You should see something like this:

In your case the new suggestion could be:
webform-form--feedback.tpl.php or page--feedback.tpl.php


menu icon image is not coming I am using drupal7 with menu icon module. I added a image on Home menu. but this is not showing.
Here is my link

I am unable to rectify the problem.

Your CSS in style.css line 432 is overwriting the CSS that the module is trying to use. You should probably comment that CSS out or edit/remove it's background property.


Rules replacement pattern missing I have a content type including these two fields

and now I want to use those fields in a "Rules" action, but they are not present in the replacement patterns to choose, and they're not present in the Data Selection  mode either.

What have I missed? Would appreciate if someone could point me in the right direction.

My rule export code

{ "rules_fiberbest_llningsemail" : {
"LABEL" : "Fiberbest\u00e4llningsemail",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "rules" ],
"ON" : { "node_insert--fiberbestallning" : { "bundle" : "fiberbestallning" } },
"IF" : [
  { "node_is_of_type" : {
      "node" : [ "node" ],
      "type" : { "value" : { "fiberbestallning" : "fiberbestallning" } }
    }
  }
],
"DO" : [
  { "mail" : {
      "to" : "me@example.com",
      "subject" : "Fiberbest\u00e4llning",
      "message" : "Ny fiberbest\u00e4llning fr\u00e5n hemsidan skapad [node:created]\r\n\r\n[node:url]\r\n[node:field-f-rnamn]\r\n[node:field-efternamn]\r\n[node:field-adresss]\r\n[node:field-postnummer]\r\n[node:field-postadress]\r\n[node:field-fibertyp]",
      "language" : [ "" ]
    }
  }
]

You need to:

Add Condition >> Content is of Type >> [your content type]

OR

Add Condition >> Entity Has Field >> node:field-telefon

Add Condition >> Entity Has Field >> node:field-signatur

OR

Add Action >> Fetch Entity by Property >> Node >> telefon >> node:field-telefon

Add Action >> Fetch Entity by Property >> Node >> signatur >> node:field-signatur


How do I create extra permissions for an eck created entity? I have created an entity using Entity Construction Kit (ECK) and wish to add extra permissions for that entity such as view own, edit own and delete own. I see there has been some movement in this thread Better Permissions and a few others to create better permissions in general for entities but I want to know how can I do it in my own custom module.

I do not want every person on the site to be able to view,edit,delete so I have disabled those perms for my created entity.

I'm stuck and cannot find any good documentation on it.

You need to alter the entity info using:

hook_entity_info_alter

and add the access callback

e.g:

function EXAMPLE_entity_info_alter(&$entity_info) {
  $entity_info['my_entity']['access callback'] = 'my_entity_access';
}

and then in my_entity_access

function my_entity_access($op, $entity = NULL, $account = NULL) {
  switch($op){
    case 'view':
    // view check
    // e.g return user_access('view my_entity', $account);
    break;
    case 'create':
    // create check
    break;
    case 'update':
    // update check
    break;
    case 'delete':
    // delete check
    break;
  }
  return FALSE;
}

See node_access for more info

You may want to use hook_permission to define your own permissions also.


Rewrite output of view summary I'm trying to display a quick summary of the number of different types of products on our site.

The summary contextual filter does this... but it adds hyperlinks to the items and I can't turn that off, and I can't customise the HTML tags or rewrite the output. Is there any
to do that?

Thanks

You can override the default views templates for summaries in your own theme. There are two of them, which are located at:

sites/all/modules/views/theme/views-view-summary.tpl.php
sites/all/modules/views/theme/views-view-summary-unformatted.tpl.php

Which one you have to override depends on the type of summary.


phone field with constraint and format Is there a way to make a phone field that would only accept numbers (no spaces) and will format them as the user types?

Note: I read somewhere that text fields can be configured that way but I could not find how. I also tried integer field but this feels wrong

Try the Masked-Input module. It does exactly what you are looking for.


Drupal 7: how to build a form system I want to build something like:
We have 2 type of users: staff and student.
Student logins into a drupal site, then a collection of forms presented to the student
Form type 1: Student selects a form then fill in all fields. After hitting the submit button, data will be saved as a node.
Form type 2: Similar as form type 1, except the same student visits the same form, s/he will see the previous data s/he entered.
Very similar situation for staff.
I wonder what are the basic steps I need to take.

I can't give the complete solution, Yet I will try to relate things what you have asked to things what we have in Drupal,

Form type 1 =>  Any Node type (say Article)
Form type 2 =>  Any Node type (say blog)
Student => Drupal User (has a profile of student, use profiles2 module )
Teacher => Drupal User (has a profile of Teacher, use profiles2 module )

User Permissions for Node creation, Node edit by its own author. Views to display the forms and user redirection module to get something you want.


Ajax callback on Views exposed form filter I'm trying to add an #ajax callback method to my views exposed form filter select box.
But it seems the form have some issues with the callback.
My code is pretty simple
/**
 * Implements hook_form_FORM_ID_alter() for views_exposed_form.
 */
function mymodule_form_views_exposed_form_alter(&$form, FormStateInterface $form_state) {
  if ($form['#id'] == 'views-exposed-form-viewid') {
    $op = ['hi' => 'hi', 'all' => 'all'];
    $form['test'] = [
      '#type' => 'select',
      '#name' => 'test',
      '#empty_option' => 'none',
      '#options' => $op,
      '#ajax' => [
        'callback' => '_my_call',
        'event' => 'change',
        'wrapper' => 'edit-output-test',
        'progress' => [
          'type' => 'throbber',
        ],
      ],
    ];

    $form['callfield'] = [
      '#type' => 'select',
      '#options' => [],
      '#prefix' => '
',
      '#suffix' => '
',
    ];
  }
}

function _my_call(array &$form, FormStateInterface $form_state) {
  $response = new AjaxResponse();
  $message = 'test';
  $response->addCommand(new HtmlCommand('#edit-output-test', $message));
  return $response;

}

When I try to change the 'test' select box from view edit screen I get the below error
"Symfony\Component\HttpKernel\Exception\HttpException: The specified #ajax callback is empty or not callable. in Drupal\Core\Form\FormAjaxResponseBuilder->buildResponse() (line 67 of /var/www/mypoc/docroot/core/lib/Drupal/Core/Form/FormAjaxResponseBuilder.php)."
When I change the filter from the front end I get the following error
"An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (32 MB) that this server supports."
And I see a lot of similar issues -
Ajax callback is not working on views exposed filters
Ajax submission leads to => An unrecoverable error occurred. The uploaded file likely exceeded the maximum file size (2 MB) that this server supports
Any working example would be great!
Thanks.

Sounds like there is an ongoing core issue queue -
https://www.drupal.org/project/drupal/issues/2842525
After applying the patch -
https://www.drupal.org/files/issues/2020-03-27/2842525-83.patch this seems to work.


Where is the documentation for core associative arrays? I have been using Drupal for a few months now at work. I love the developer documentation, but I have to say, I feel like its incomplete -- either that, or I just don't know where to find the other half.

I see documentation for functions and hooks everywhere, but I don't see any documentation for the format of core data structures.

Example one: this page from the official docs has extensive explanation on hook_wysiwyg_editor_settings_alter, but it gives no complete disclosure what the $settings parameter can contain.

Example two: this page from the official docs has great explanation of the concept of "Render Arrays" and the functionality thereof, but has no description of the format of the associative array passed to the render() function, causing me to var_dump($user_page) for hours and come up with monstrosities like: <?php echo $user_page["system_main"]["nodes"][$first_key]["field_objective"]["#object"]->field_targets["und"][0]["safe_value"]; ?> on my custom .tpl.php files.

Is this information in the code itself, or somewhere else?

Render arrays are defined (in Drupal 7) with the hook_element_info hook.

To see what attributes a render element can accept you can check the MODULE_element_info function that defined it.

For example looking at system_element_info we can see that the page render element accepts a #show_messages attribute and that it contains a boolean value.

For more information you can also look for the template_preprocess_ELEMENT function for the element.

template_preprocess_page in our example.


How to rename a view returned by REST API Very new to Drupal (running 8.5.6) and inherited some code I need to tweak. We invoke the API request like so (which may wrap the Drupal API..I am not sure)
https://api.mysite.org/backend/api/constants/en?_format=json
I get a fairly large JSON object returned.  There is a view I created called myview that is returned in the json with the name of view_35. I have two other test instances where I created the same view by name referencing the same fields.  But in one instance the name is returned in the JSON as view_38 and in the other view its view_31.  I noticed that I could alias the fields.  Is there a feature like that for views?  In other words, I want to name the view so it can be consistently referenced in the code that consumes the JSON.  The client side of the app that invokes the api is Angular, if that makes any difference.

The answer was already in the question.  Turns out the option to add aliases is exactly the same for other fields...it's just a little counter intuitive. Go to Administration-->Structures-->Views--> Constants view --> Edit --> then select "Constants" from the "Displays" Then select "Settings" next to Show... All the aliases can be entered there.  Then save the changes.  Now you can reference the view by alias rather than the view_[ID] reference.


How to redirect user to previous page after form submit? I can redirect user after adding a node to any another page but would like to redirect them to previous page they were linked from. Now I use the following code:

function user_add_node_form_foto_node_form_alter(&$form, &$form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'user_add_node_foto_node_form_submit';
}

function user_add_node_foto_node_form_submit($form, &$form_state) {
  $form_state['redirect'] = 'node/add/foto';
}

How can I change a code to redirect users to previous page after submitting the form?

EDIT: Every foto node type has a node reference field "field_relate_to_gallery". By using this I created a gallery in Views and added a link "Add foto in gallery" on gallery page linking to add node form. I would like returning users back to gallery after adding a node "foto". That means that a have a lot of galleries with different ID and a cannot redirect the this form only to one particular gallery.

My Solution If someone is interested in. I did it by using node reference from url module. Now my user can add an image from gallery page (there is a link to add node form) and after submitting it he returnes to the gallery page.

You want drupal_get_destination(). This function creates a 'destination' query parameter suitable for use in l() that will redirect the user back to the page they came from after submitting the form. So, when you create your link to add a new node, use the l() function along with drupal_get_destination(). For example...

l('Add new foto', 'path/to/add/a/foto', array('query' => drupal_get_destination()))

That should do it.


Couldn't avoid duplicates and merge rows on my views I have a view of list of contents referenced in many others content types in my site.
Lets talk about just 2 content types :
A content type called container is referenced in a content type position, so we say that the container has many positions.
Container position is a select list field in Position, for every item in this select list, there are some fields to fill.for example if I select 'on board' I have to fill the field 'date of loading', If I select 'in the shipper' I have to fill the field 'name of shipper'.
So in my view I want to display  the list of containers with informations from the positions where they were: container;date of loading;port of loading; shipper.
When I created the view I get duplicated results for every container. I tried aggregation and distinct option, It not works, or it removes duplicates without merging the rows if use them both.

Update:
My question is similar to this Views - adding relationship adds duplicate row for each relation

Consider using the Views Distinct module. From its project page:

  Relationships or other joins in Views often create "duplicate" results. For example, a node with a field that has multiple values may show up in the View once per value in the multi-value field. It's frustrating, and the "DISTINCT" SQL query option in the Views UI does not actually solve the problem because the result row is technically distinct. This module aims to give a simple GUI method to remove or aggregate these "duplicate" rows.


Can I add a menu link with a parameter? I would like to add a menu link using the "Link"-Field with Autocomplete, but I would like to add a parameter afterwards.

Pretty much like this:

...which is not working.

Is that possible? Thanks!

I didn't find a direct answer, but I used the module "Menu Link Attributes" to add a class and used JS to add the parameter:

$('#menu ul li a.parameter').each(function() {
    $(this).attr("href", $(this).attr("href") + "?p=parameter");
});

Maybe that's helpful.


How to call a javascript function? I have included in my theme a new javascript library(Easy-Responsive-Tabs-to-Accordion) which converts horizontal tabs to accordion.
So I have included in my .info theme
scripts[] = js/Easy-Responsive-Tabs-to-Accordion/js/easyResponsiveTabs.js

Then,according to the instructions,I have to call the javascript function $('#demoTab').easyResponsiveTabs();

My question is:Where to add this javascript function?
thanks

You can continue easyResponsiveTabs.js as normal JS and add your function call. Also you can call this function almost anywhere (like tpl.php file), even in the block/node (where you are using this script for conversion) wrapped in the <script> tag like:

<script>
$('#demoTab').easyResponsiveTabs();
</script>

I would go with drupal_add_js in template.php file of your theme.

Update

Using drupal_add_js you can do it like this:

drupal_add_js('jQuery("#demoTab").easyResponsiveTabs();', 'inline');


What are recommended filters for using Pagespeed along with Drupal 7 (and Advagg enabled)? We are planning to integrate Google Pagespeed module in our Drupal 7 site which is already using Advanced for CSS/JS Aggregation (Advagg).

Based on the inputs at https://www.drupal.org/node/2182289#comment-8421621 , it seems that Pagespeed CSS/JS filters are not needed since the same job is done by Advagg. Pagespeed has other useful filters for image optimization and inlining critical css.

My question: If someone is using Pagespeed along with Drupal and Advagg, can you share the Pagespeed filters that you are currently using or would recommend? If you are using Pagespeed with Drupal but without Advagg, please share your filter recommendations.

I have been searching extensively on this topic but couldn't find much practical information on using Pagespeed along with Drupal.

Every site is different. I recommend extensive testing. http://www.webpagetest.org/ is one of the better sites for testing the frontend and seeing what options are best for you're site. Be sure to test more than just the frontpage & look at the connection view; using the bundler you can adjust this a little bit, try a bundle of 1 or even 10. Point is you'll need to experiment to get the best results. The modifier has lots of things you can do to tweak things; deferring the js is one of the better options in my opinion.

I've heard that google pagespeed has a +-20% difference; it works better or worse depending on various factors. Give it a try and be sure to test!

Work on inline css is being done btw: https://www.drupal.org/project/css_delivery


Path (URL) to call custom module function I am developing a custom module and I need an URL that would trigger an action when called.

The purpose is for an external server to call this address passing some variables through $_REQUEST['message'], and then return a STRING with the success/error string. So the URL in question is only supposed to be called by a machine.

I now have a PHP file in the root that does the job, but I'd like to integrate it to the Drupal way through this custom module.... Is there a way to do this?

Thank you

The best way to do this is to build a custom module and implement the hook hook_menu().

You'll need to implement:

a .info file with metadata about your
module
a .module file containing
hook_menu() and your callback

foo.module should look like this:

function foo_menu() {
  $items = array();
  $items['foo/myurl'] = array( // change 'foo/myurl' to the url you want
    'title' => 'Callback',
    'type' => MENU_CALLBACK,
    'page callback' => 'custom_callback',
    'access arguments' => array('access content'),
  );
  return $items;
}

function custom_callback () {
  // Parse $_REQUEST parameters
  return 'success';
}


None of the forms are submitting I have a strange problem - on my local installation none of the forms are getting submitted.

I can access forms and when I click submit, page just reloads and nothing happens. That applies for all configuration forms, as well as node save/edit forms. Strangely, I can log in.

I don't really know where to look. Any suggestions?

This can happen when there are problems with your local .htaccess file -- it might be that Apache locally is not set up to read .htaccess files, or there may be an error in the file, or it may be missing altogether.

If the issue is specifically with the login form, you might be having issues with HTTP/HTTPS switching if your site is configured to attempt to negotiate the scheme, but your local server is not configured to serve HTTPS.


Add different paragraphs block on translated nodes Is it possible to add additional paragraph blocks on an translated node?

If yes; How? I've tried messing around with configuration; but cannot get it to work as expected.

If not; How do we go around this behaviour?

That is an open issue. At the moment you can only translate the fields inside of paragraphs, not the outside structure of the paragraphs.

See this issue:

[META] Support translatable paragraph entity reference revision field


How do I prevent a module from being loaded? I am developing a custom module, from this module im trying to disable other modules (for certain reasons).

Let's say I want to disable the search module, how would I do this?

See module_disable and the comments therein for how to place it within a profile.install or module.install file.


Multiple field value amount based on role I am looking to add a single image field to a content type, and allow a different amount of images based on a users role.

Business Free User can upload 1 image (as profile pic)
Business Silver User can upload 3 images
Business Gold Users can upload 9 images

I've been searching high and low for a module to swoop in and save the day, but im not having much luck. Has anyone found something that can do this for me?

I'm using the field permissions modules to hide fields based on role. The fall back here would be to have 3 images fields, one for logo, one for 2 more images (to make 3) and one for 6 more images (to make 9) but I'm building a pretty big site here and would like to reduce the amount of fields where I can.

I would take a look at this question: Specific number of values in field setting per role. The hook_form_alter method is the way I would approach it.


Remove email validation from Feed Import I'm trying to import about 15000 users from a CSV file. Most of the users have valid email addresses, but some (+/- 5000) don't, they're also not blank fields.

Is there a way that I can bypass the email validation? Or a module that can easily help with this?

I've tried re-importing the CSV file with "Do not replace existing users" and removing the email field from the mapping, and I still cannot import them and am getting the "User name missing or email not valid."

I have Optional Mail installed, and have tried importing after disabling the email field for registrations and edit pages and still get the same error.

Any ideas?

The validation logic for the email is embedded within the user feeds module in FeedsUserProcessor.inc which means the best way to go about this is to create you own, almost identical, feeds processor in your own custom module. Read up on how to create a custom processor.

After reading that documentation you'll need a processor class and you can use FeedsUserProcessor.inc within the feeds module as a starting point. Copy that file into your own module where necessary, rename it and also rename the class name defined within the file. In this file you should see this implementation of the entityValidate function:

/**
 * Validates a user account.
 */
protected function entityValidate($account) {
  if (empty($account->name) || empty($account->mail) || !valid_email_address($account->mail)) {
  throw new FeedsValidationException(t('User name missing or email not valid.'));
  }
}

Remove the !valid_email_address($account->mail) bit in that if statement and configure your feeds importer to use the custom processor you just created.

FYI, I would not recommend importing users with invalid email addresses as this will cause major problems with your users trying to use your site properly.


Anyway to disable minification (make line breaks) in the source view of CKEditor WYSIWYG My question is different from one I've seen answered quite a bit here and elsewhere. My line breaks are showing up in WYSIWYG and the rendered content just fine. However, I was wondering if there is a way to make CKEditor/WYSIWYG preserve line breaks when I view the code as well. I sometimes need to edit code in the HTML, and it's a mild inconvenience to have to sift through minified code to find stuff.

Any help is appreciated. Thanks.

Edit WYSIWYG profile that uses CKEditor and in "Cleanup and output" settings check "Apply simple source formatting". (screenshots below for visuals)


Listing variable values using drush I would like to list the values of certain variables using Drush in order to make sure they are in fact the variables that I intend to add to my feature. It seems that some variables are parents which contain multiple children. I use a drush/features/git workflow with a purchased but customized theme and following is my example for clarity.

In my feature myfeature_theme_helper there are two variables that I exported to it: theme__settings and theme_settings. I want to be able to view what values each are storing so I can determine if they should be removed from my helper. One of them contains an active tab, for example, which is not a setting that I want to commit to code.

Thank you!

If you do

drush vget theme_THEMENAME_settings

it will give you all nested variables but nested variables  don't work

drush vget theme_THEMENAME_settings.toggle_name
drush vget theme_THEMENAME_settings:toggle_name

so the only way I found to get nested variables is with the use of grep

so for my theme I would do something like this

drush vget theme_THEMENAME_settings | grep toggle_name:

or do further processing using cut to get just the value of this variable

drush vget theme_THEMENAME_settings | grep toggle_name: | cut -f2- -d:

where theme_THEMENAME_settings is my variable and toggle_name is the nested variable name


How to add alt tag to image from views I have created views with image gallery. Now I want to add alt tag to image how can I do it. I have not enabled alt field in content type configuration.

I want add alt tag to already existing images. Kindly provide the solution to achieve this.

There is no way to add unique alt text using views, unless... you use:
Editable Fields

This module allows CCK fields to be edited on a node's display (e.g.
at node/123), not just on the node edit pages (e.g. node/123/edit). It
also works within views etc. Anywhere a 'formatter' can be selected,
you can select editable (or click to edit).

Video tutorial/demo
You would have to enable the alt in your content type, then you should be able to edit it in your view.

I have more than 150 content. So i am asking for alternative

I take it you're looking for an easy & quick way so you don't have to edit 150 nodes one by one.
Another method
would be to find the alt field in your database and export the table as .csv file.
Then edit it using excel, and add your alt text here, save.
Import back in and clear the Drupal cache.


How to link Images of one node to other node? I've created a content type of image.

I am using a view to display the images on the homepage. I would like each of the three images to link to existing pages/nodes (not the nodes of images themselves).

I want to link images of node a to node b is that possible ?

How would I go about doing this?

Whichever way you look at it I would say that these images should be a field on the entity that they are linking to ( you are going to have a validation nightmare having a multiple image field and an entity reference field that can't be forced to have x number of values easily ). The easiest way to then render these would be to use the views module, create a block displaying fields and selecting he image field and clicking the box to link the image to the original piece of content. You can also have a filter to select only entities where this field is filled.

In reality though a better approach would be to create a menu ( this is what you are doing after all ) and put in the images using css.
example:

#block-system-main-menu li a {
  display:block;
  width:100px;
  height:100px;
  background-repeat:no-repeat;
}
#block-system-main-menu li:nth-child(1) a {
  background-image:url('../images/icon_1.png');
}
#block-system-main-menu li:nth-child(2) a {
  background-image:url('../images/icon_2.png');
}


Drupal .dev database problem Drupal website unexpectingly takes all data from .dev db, thow settings point the main db.

Is there any way to fix that?

Your settings are messed up somehow. I'd suggest looking into the multi-site capability to keep things straight.

You would create directories for live and test under /sites. Assuming example.com and test.example.com are your site:

/sites
    /example.com
        settings.php    # connection details for your live database

    /test.example.com
        settings.php    # connection details for your test database

    /example.local
        settings.php    # (optional) details for local development environment

Under this scheme, when you browse http://example.com, Drupal will look for the database settings in /sites/example.com/settings.php. When you browse http://test.example.com, Drupal will look in /sites/test.example.com/settings.php and so on.

An alternative would be to use environment variables set in you Apache or Nginx configuration. You would then use the PHP getenv() function to access the values. This approach would be a little bit harder to set up and troubleshoot.


How do I programmatically set cache age? Drupal 8:

I have the code for a block successfully doing its work and returning it. The block is called "RacerProfile" and it dumps all its content into variable "$pageContent". At the very end it returns the #markup. Ok. Now how do I tell this to invalidate every six hours?

/**
 * Provides a 'Racer Profile' Block
 *
 * @Block(
 *   id = "racer_profile",
 *   admin_label = @Translation("Slider v1 block")
 * )
 */
class RacerProfile extends BlockBase {
  /**
   * {@inheritdoc}
   */
  public function build()
    {
    // does all the work to make $pageContent via non-drupal database queries
    return array('#markup' => $this->t($pageContent),  );
    }
 }

In other Drupal answers, I've seen "D8 has cache tags and contexts that will automatically invalidate the block if something changes." Ok, my code is checking a second database. There's no way for Drupal to know what's changing over there. (Without checking, obviously.) So how do I add cache tags with specified timeouts? I can't find examples.

Notes:

-Obviously, this is not related to the Maximum Cache age within the admin area of Configuration > Performance > Caching > Page cache maximum age. I don't want this to apply to the entire site, just this block.

-Obviously, this is not related to settings.php in any way either, since again I don't want to have this apply to the entire site, and the various modules will have different timeout requirements.

-The traffic for the site is relatively low volume, so if rendering a thing four times a day even it only needs to be done once a day isn't a problem. Every six hours means that it's changed before people wake up across four time zones. Mostly. ;)

-(edit addition) The block needs to have its cache controlled for anonymous users.

This is all done from the render array itself.  The nitty gritty details are documented in Cacheability of render arrays.

In your case, you need to do something like

return [
  '#markup' => $this->t($pageContent),
  '#cache' => [
    'max-age' => 86400, // one day in seconds
  ],
];

This uses the #cache entry for the render array, and sets the max-age to be one day.  This is where you would also add in your cache contexts.

As a side note, try to avoid using '#markup'.  Use themeable elements, either though code or Twig.


Openlayers Views map with auto render? I have an openlayers map view that is populated with user IP address.
I need the map to update automatically (without refreshing) when a new users visits the site.

Much like the behavior of the map on http://drupal.org/ i.e markers would appear but stay on map.

If anyone can point me into the right direction it would be much appreciated.

Thanks in advance!

For reference, here is a description on how the map on the D.O homepage was built. https://association.drupal.org/node/784

To achieve what you want, you could use the Views Auto-refresh submodule of the Views Hacks module to auto refresh the openlayers map view in short intervals.


Will managed files be deleted if no corresponding entry exists in file_usage? I am using the services module to implement a REST API.  One resource allows POSTs with uploaded files.  During a services pre-process function I save the file to the temp directory.  During a services post-process function, I move the file to a private directory, call file_usage_add, and save the host entity.  When a validation error occurs between saving the temp file and moving the temp file to a permanent location, I am not explicitly deleting the temp file.  I thought drupal cron would take care of this for me, since no entry for this file exists in file_usage.  However, it doesn't appear that cron is taking care of this for me.  Any thoughts as to why this is?

When reviewing file_managed, I see the temporary file that I'd like deleted.  When reviewing file_usage, I don't see any corresponding record.

Update -- One additional piece of info: in most cases, the file is actually missing.  I believe this is due to OS reboot clearing out the /tmp directory.  Regardless, would system_cron still remove the file_managed entry for a file if the actual file were no longer found?

This problem arose since I started uploading files from a native mobile app. The filename is the same every upload.  There are some cases where the temp filename doesn't exist in the /tmp directory, but a record in file_managed still exists with a URI of that filename.  So I'm getting an integrity error when the file_managed table is being saved.  I plan on updating the app to create a random filename.  In the meantime, I'd like to clean up the database and surrounding "glue" logic that manages these files.  If system_cron will do it all for me then great.  But from what I can tell, system_cron is not removing old, completely unused (and unreferenced) records in file_managed.

Drupal automatically deletes temporary files in system_cron().

Permament files which have no file_usage are not deleted, however.


Can't see error messages when creating Drupal form in a separate file Suppose, I want to use Drupal libraries inside a separate php file to generate a form. I created 3 functions:

function add_form
function add_form_validate
function add_form_submit

And then used drupal_get_form / render to get the HTML code. But when I insert invalid data, I don't see the error message - just the red border of the text input. Here is the minimal example to reproduce the error (file is called test.php and is located inside Drupal directory):

<?php
//including Drupal libraries
define('DRUPAL_ROOT', $_SERVER['DOCUMENT_ROOT']);
require_once(DRUPAL_ROOT . DIRECTORY_SEPARATOR . 'includes'.  DIRECTORY_SEPARATOR . 'bootstrap.inc');
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

//form with 1 text field and submit button
function add_form($form, &$form_state)
{
    $form['text'] = array(
        '#type' => 'textfield',
        '#title' => 'Insert text',
        '#required' => true,
        '#attributes' => array('autofocus' => 'autofocus'),
        );

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

    return $form;
}

//text must be 'aaa'
function add_form_validate($form, &$form_state)
{
    if ($form_state['input']['text'] != 'aaa')
    {
        form_set_error('text', t('Text is not aaa!'));
    }
}

function add_form_submit($form, &$form_state)
{
    print "I am inside add_form_submit<br>";
    var_dump($form_state['input']);
    exit;
}
?>
<!DOCTYPE html>
<html>
  <head>
    <title>element</title>
    <link type="text/css" rel="stylesheet" media="all" href="/modules/system/system.base.css">
    <link type="text/css" rel="stylesheet" media="all" href="/modules/system/system.theme.css">
    <link type="text/css" rel="stylesheet" media="all" href="/modules/system/system.messages.css">
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
  </head>
  <body>
<?php
//here is the problem: I don't know, how to output the error message
print theme('status_messages');

$content = drupal_get_form('add_form');
$content = render($content);
print $content;
?>
  </body>
</html>

It is working fine for me, only thing is that I get the error message only when submitting for the second time, that is because you are printing the status message before the drupal_get_form(). So if I print the message after drupal_get_form() then it is working as expected.


How to Use Contextual Filters I have a view where I'm showing all postings by post author. Right now, I show (and filter) the posts by author name using contextual filters.

I want to change it so that I still use the username in the contextual filter, but when I override the the title, I want to show the human readable name.

So, for example,

www.example.com/postings/kyle.keiper

Currently shows

Postings by kyle.keiper

in the title.

How can I change the view so that the URL stays the same, but it shows "Postings by Kyle Keiper"?

You need to rewrite the output of the field and use PHP for the text string manipulations.

Two modules can help you do that. Note that you'll likely choose one of these two modules. they aren't dependent on each other. They can both help you get what you want in different ways.

Views PHP
Computed Field

You might need to turn the title off and create it instead in the View header using "Global: text" and turning tokens on their. The token for username (which is "[name]" will use the value from the written output you've used when defining the field.


Search API Views - Show search string in text I created a view to display my indexed data, anything works just fine. What I now want to achieve is, that only the part of the bodytext is displayed, that contains the search string. The default drupal search engine can do this, but I have no idea how to achieve this using views.

Someone got an idea how to do that?

Greetings

SG


how to make images clickable in a listing (numerous thumbnails) in our event_parent http://imgur.com/a/ezlMM content view we have a listing (field_listing) field that contains numerous thumbnails and they need to redirect to their specified event page. we are on drupal 7

Click on the field for the image and you should see "link image to" and you can select "content". Set the filter criteria so that the system knows what content to link to. Also, the image should be coming from the content, such as as a thumbnail.


Off-site payment method from the terminal Just wondering if it is possible to setup an off-site payment from the terminal. I've already created a custom module for a custom offsite payment method for standard user checkout process. I also need to add this option to the terminal so it can be used by Admins when creating an order in the backend

Is that doable?

Just to note, I'm a Drupal beginner so I may have missed something obvious.

This isn't doable, unfortunately, because it would require a redirection process that is currently only supported by the checkout form. If it's a requirement for a site, I'd pursue a way for administrators to use the checkout form like a normal customer and submit payment being redirected from there instead.


Passing field value to #autocomplete_route_name in custom form I am creating a custom form where I have 2 fields.

Taxonomy : select field having list of vocabularies.
Terms : Autocomplete field having terms list.

When I start typing in terms field, the value of the term field is passed to the routing function. However I also need the value of the taxonomy field in routing function so that I can restrict the terms list.

Is there anyway that I can get the other field values in the routing function?

Here is my buildform function :

public function buildForm(array $form, FormStateInterface $form_state) {
  $form['taxonomy'] = [
    '#type' => 'select',
    '#title' => $this->t('Select Taxonomy'),
    '#options' => $taxonomies,
  ];

  $form['taxonomy_terms'] = [
    '#type' => 'textfield',
    '#autocomplete_route_name' => 'unido_drupal_admin.get_taxonomies'
  ];

  return $form;
}

Here is my routing function :

public function get_taxonomies(Request $request) {
  // Here I need to get taxonomy field value to restrict the result.
  $params = $request->query->all();
  $result = \Drupal\taxonomy\Entity\Vocabulary::loadMultiple();
}

Thanks.

You need to define #autocomplete_route_parameters. I'm not sure if the form gets rebuilt during autocomplete queries (most likely not!) so you might need to define a #ajax on the vocabulary selector in order to rebuild the form and return the taxonomy_terms field with correct parameters set. This way you're defining a clear dependency, that field 2's available values depend on field 1's value. Below code is untested, but hopefully pushed you in the right direction:

public function buildForm(array $form, FormStateInterface $form_state) {
  $form['taxonomy'] = [
    '#type' => 'select',
    '#title' => $this->t('Select Taxonomy'),
    '#options' => $taxonomies,
    '#ajax' => [
      'callback' => 'Namespace\To\Your\Entity::vocabulary_callback',
      'event' => 'change',
      'wrapper' => 'term-wrapper'
    ],
  ];

  // Initially return a disabled field.
  $form['taxonomy_terms'] = [
    '#type' => 'textfield',
    '#disabled' => TRUE,
    '#prefix' => '
',
    '#suffix' => '
',
  ];

  // If someone's chosen a vocabulary, rewrite the field.
  if ($vid = $form_state->getValue('taxonomy', false)) {
    $form['taxonomy_terms'] = [
      '#type' => 'textfield',
      '#prefix' => '
',
      '#suffix' => '
',
      '#autocomplete_route_name' => 'unido_drupal_admin.get_taxonomies',
      '#autocomplete_route_parameters' => ['vid' => $vid],
    ];
  }

  return $form;
}

public function vocabulary_callback(array &$form, FormStateInterface $form_state) {
  return $form['taxonomy_terms'];
}

You also need to define this as a route parameter in your route's path element:

unido_drupal_admin.get_taxonomies:
  path: '/path/to/your/autocomplete/{vid}'

And also accept the parameter in your autocomplete function:

public function get_taxonomies(Request $request, $vid) {

There might be better ways to do this though, but with my limited D8 knowledge, this is how I'd approach it.


Global math expression in a views I added a global math expression field to a views(table display) i just want to sub two fields values,but the the result it's not exact what i want.
Example for that(9000 - 5000 = 4).
How can i change the format or something like that to convert the result to 4000?
Thanks.

Your problem is the number format of your fields.  Turn off the comma that delineates thousands.


How can I transfer node and comment records from Drupal 6 to Drupal 7? Is it possible to export particular nodes and comments in Drupal 6 and import them in Drupal 7? I do not want to copy the whole database and then upgrade it, but be able to move particular records.

You could look into using the Migrate module. Although I haven't used it myself, I know that many have been using it to move content from a Drupal 6 website into a Drupal 7 website. Be aware that it is an advanced module that has no UI (that I'm aware of). It integrates with Drush and allows you to create migration scripts and run them from the command line.


How to put a token in field Simplenews -> Subscribtion block -> block message I want to add a token in a field which is used when the simplenews module is installed and configured. There is then a block available for each newsletter.
In this block the user can fill in his email and push the subsribe button.

I want to display a token in this field:

Block > Simplenews subscribption block > block message.

(the block title is supporting tokens, but the block message not)

How to do this?

It's likely there's no off-the-shelf solution here. The block message field is a variable in the Simplenews module. It's not possible to make variables dynamic; there's no hook to override variable values.

In order to make something like this happen, you'd have to use a combination hook_form_alter() to change the block setting form & hook_block_view_alter() to alter the output of the Simplenews block.


Administrator verification for user role type Is it possible to add admin verification for specific user roles.  For instance, my site has three user roles, one of which would should get verified before gaining access to the content.  I realise there is an option " Visitors, but administrator approval is required" in the
people > administration tab, but this would be for all users.

I'm managing roles directly through Drupal 7 and not using any modules such as profile2.

Thank in advance,

Cheers,

For the record, the option you refer to ("Visitors, but administrator approval is required") is not for all users.  It only applies to the Anonymous user role, and means that the Anonymous user is allowed to register at the site (gaining the Authenticated user role), but only after the administrator has approved the registration.

The "standard" way of doing this in Drupal is to set up the site so that the "Anonymous" user role does not get access to the content you want to reserve for verified users.

Then, to gain access the anonymous user must 1) register; and 2) the administrator must approve the registration (using the option you refer to).

How would this model work for your site?


How to use non-english language in code I'm italian and I've to develop a multilingual drupal site but english translations of strings (that should be added in code or templates) will be done in the future.

Is there a way to use in code a non-english language and use t() and other functions to translate them in english?

AFAIK core's does not support (and could take a while to do so) keyed based translation (like Symfony or other do). Theres an idea queued but seems to fall on deaf ears.


Hide one form element until another is selected Is there any way to disable the field 'model_article_nr' until 'model' is selected

this is what i have and as it is now i can select 'model_article_nr' before i have choosen a model which leads to wrong article nummer if i change model afterwords, because when no model is selected the first model is standard in my '$article_list[$curent_model]' and beeing displayed as options in 'model_article_number'

$model_list = array();
$article_list = get_model_article_list();

foreach($article_list as $key => $value) {
        if ( empty($curent_model) ) $curent_model = $key;
        $model_list[$key] = $key;
    }

$form['model'] = array(
        '#type' => 'select',
        '#title' => t('Model'),
        '#title_display' => 'invisible',
        '#empty_option' => t('Select Model'),
        '#options' => $model_list,
        '#ajax' => array(
            'callback' => 'form_model_callback',
            'wrapper' => 'article-number-ajax-wrapper',
        ),
        '#prefix' => '

',
        '#suffix' => '<button type="button" class="btn tooltip-btn" data-toggle="modal" data-target="#model-help"></button>
',
    );

    $form['model_article_nr'] = array(
        '#type' => 'select',
        '#title' => t('Article Number'),
        '#title_display' => 'invisible',
        '#attributes' => array('placeholder' => t('Article Number'), 'class' => array('space-bottom')),
        '#empty_option' => t('Select Article Number'),
        '#validated' => TRUE,
        '#options' => $article_list[$curent_model],
        '#prefix' => "
",
        '#suffix' => "
",
    );

And my callback

function form_model_callback($form, &$form_state) {
    return $form['model_article_nr'];
}

As @leymannx stated you can achieve this using #states. Here is a simple example:

 $form['show_textbox'] = array(
  '#type' => 'checkbox',
  '#title' => t('Show text Box 1'),
        '#attributes' => [
        'id' => 'show_textbox',
        'name' => 'field_show_textbox',
      ],
);

    $form['text_box1'] = [
      '#type' => 'textfield',
      '#size' => '60',
      '#placeholder' => 'Enter Name',
      '#attributes' => [
        'id' => 'text_box1',
        'autocorrect' => 'none',
        'class' => 'text_box1',
        'autocapitalize' => 'none',
        'spellcheck' => 'false',
      ],
      '#states' => [
        //show this textfield only if the radio button 'show_textbox1' is selected
        'visible' => [
                ':input[name="field_show_textbox"]' => array('checked' => TRUE),
        ],
      ],
    ];

You can always change the condition.


Google analytics module vs direct code insertion in tpl file Shall I install google analytics module or just put GA code in page.tpl file as there are too many modules and I dont want to add one more module. what do you suggest?

It is fine if you want to put the snippet in the page.tpl.php file. You will basically benefit Google Analytics module's conditional-snippet features.

If you put the snippet in page.tpl.php file,

Admin theme will not be tracked (which is usually Seven, which is in core - don't hack core!)
Users cannot opt-put for tracking (See your drupal.org account edit page for an example). this is independent from browser's Do Not Track (DNT) header.
You will find it difficult to track custom variables.
You will find it difficult to track events (downloads, etc). But you can put a modified static snippet and it should work as if it was from Google Analytics module. You can also track messages ($messages) using GA module.
You will need to edit all your page.tpl.php variants to add the code.
Other modules will not be able to control your snippet. Not compatible with js_alters.
You will find it difficult to track internal search.
All users, including admin roles, which is usually not necessary to track.
Cache the code locally.

In my opinion (and some little home-done tests), caching the code locally is not a good idea. GA service is so popular so the chance of having a locally cached version of ga.js is very good. If you cache it, browser will have to download the same code from your server (But you can track users those who have blocked ga.js using AdBlock plugins).

For sites that I maintain in long run, I'm fine to use the snippet directly (in page.tpl.php or html.tpl.php). Many sites don't require A/B testing, goal tracking, custom variables and other bells and whistles. If you explicitly call node_load() , user_load(), user_access(), or other functions, that's a signal that you might want to use GA module instead of the in-house coding.


ckEditor Uploading Issue I installed ckeditor and all went well but now the issue is it can not allow me to upload an Image : when I drag and drop an image it shows a blank line . and if I click on the image icon, it opens but when i try uploading and image it takes me to the page where I was. and nothing happens.do I need any other module to help it upload ? . please I am asking for any help

We use a module called IMCE (https://drupal.org/project/imce) to upload images/files via ckeditor. Works really well and has a nice interface.


Ajax form an multi-select I have a form which provides select2 when the select1 is changed. However I would like select2 to be a multi-select. I can't seem to get this to work. It populates a single select input just fine, but not the multi-select. Any tips would be appreciated.

public function buildForm(array $form, FormStateInterface $form_state, $options = NULL) {
  $form['expeditions'] = [
    '#type' => 'select',
    '#title' => $this->t('Choose Project'),
    '#empty_option' => $this->t('Select a project'),
    '#default_value' => '',
    '#options' => $options,
    '#ajax' => [
      'callback' => '::getDeployments',
      'wrapper' => 'deployment-wrapper',
    ],
  ];

  // Disable caching on this form.
  $form_state->setCached(FALSE);

  $form['deployment_wrapper'] = [
    '#type' => 'container',
    '#attributes' => ['id' => 'deployment-wrapper'],
  ];

  return parent::buildForm($form, $form_state);
}

public function getDeployments(array &$form, FormStateInterface $form_state) {
  $expedition_id = $form_state->getValue('expeditions');
  if ($expedition_id != "") {
    $arms_config = \Drupal::config('arms.settings');
    $rest_root = $arms_config->get("arms_rest_uri");

    $client = \Drupal::service('http_client');
    try {
      $result = $client->get(
        $rest_root . 'arms/projects/' . $expedition_id,
        ['Accept' => 'application/json']
      );
      $expedition = json_decode($result->getBody());
    }
    catch (RequestException $e) {
      watchdog_exception('arms', $e);
      drupal_set_message('Error fetching project.', 'error');
    }
  }

  $options = [];

  foreach ($expedition->{'deployments'} as $deployment_id) {
    array_push($options, $deployment_id);
  }

  $form['deployment_wrapper']['deployments'] = [
    '#type' => 'select',
    '#title' => $this->t('Choose Deployment(s)'),
    '#options' => $options,
    '#multiple' => TRUE,
  ];

  return $form['deployment_wrapper'];
}

It is not possible to create a select element in an ajax callback, because the form builder needs to know about it.

Move all code from ajax callback to buildFrom(). Make this code conditional on form_state.

Your callback contains only:

return $form['deployment_wrapper'];


How can i fix broken link of an image being viewed in Drupalgap after being uploaded with Drupalgap also By using Drupalgap i create an article and attach/upload an image to that article. Image of name: myimage.jpg has the actual absolute path in website: http://www.example.com/sites/default/files/myimage.jpg. In View(and also in Edit) menu tab inside Drupalgap the image seems to be broken. By debugging i get that in the View it tries to show an image with absolute path of http://www.example.com/sites/default/files/styles/medium/public/myimage.jpg which doesn't exist. What exists in that specific folder is a renamed clone of my image with absolute path http://www.example.com/sites/default/files/styles/medium/public/1495486688801.jpg .
To make things weirder, yesterday's articles created with the same method, which appeared also to be broken yesterday, today are shown just fine. Just fine means that the link of the image being shown points to the correct cloned image: http://www.example.com/sites/default/files/styles/medium/public/1495486688801.jpg .
?q=drupalgap/node/55.json is today's article json  with broken links
?q=drupalgap/node/53.json is yesterdays's article json which shows image as expected.
Both get 200 OK response.
In the 2nd json references the image (...)"filename":"1495486688801.jpg","uri":"public://1495486688801.jpg"(...)
 and the 1st as

(...)""filename":"IMG-8a92960d1864691a4e03c9cfe9ee8516-V.jpg","uri":"public://IMG-8a92960d1864691a4e03c9cfe9ee8516-V.jpg"(...).

Default Display in site uses Large image style and Drupalgap display uses Medium image style for the article node.
I have to mention that the same warning as the issue 776 appears to my log file.
 WARNING: drupalgap_remove_page_from_dom() - not removing the current page (node_add_article) from the DOM!
Maybe medium style is not created as per need of my mobile's request.

UPDATE

I installed the imageinfo_cache module and now (confirmed after 3 newly created articles nodes with images) images are not broken in the View menu tab in Drupalgap. But in the Edit menu tab is still broken.

It sounds like you need to add this to your settings.php file:

$conf['image_allow_insecure_derivatives'] = TRUE;


New subscriber notification How can I get an email notification when there is a new subscriber? I can't find this setting on the Simplenews module, but I do find "Send e-mail" in "Configuration > Actions".

Does Simplenews has this feature? Can Send e-mail actions make this work? if so, how?

Enable the Simplenews Rules module within the Simplenews project. It will add 2 events A user has been subscribed & A user has been unsubscribed.

Use the subscribe event combined with your Send mail action to send a message on user subscription.


Contextual links for a custom module I want to add in a contextual link to a block.

The block shows up in different pages, not just a specific page.

Here is my current setup

$block['content'] =array(
    '#markup' => _get_markup(),
    '#attached' => array(
        'css' => array(
            drupal_get_path('module', 'module_name') . '/css/main.css',
        ),
        'js' => array(
            drupal_get_path('module', 'module_name') . '/js/main.js'
        ),
    ),
    '#contextual_links' => array(
        'add content' => array('add/content/', array('content')),
    ),
);

Based on the documentation, this should work for drupal 7 but it does not for me.

To be able to add your custom contextual link, you first need to check the Contextual links module is enabled. Even though you define everything correctly, it would not show, if it is disabled. Also, you need to set context to MENU_CONTEXT_INLINE in your menu items.

/**
 * Implements hook_block_view().
 */
function example_block_view($delta = '') {
  $block = array();
  switch($delta) {
    case 'my_custom_block':
      $block['subject'] = t('Example Block');
      $block['content'] = array(
      '#markup' => _get_markup(),
      '#contextual_links' => array(
          'add content' => array('add', array('node')),
      ));
      break;
    default:
      break;
  }

  return $block;
}

/**
 * Implements hook_menu().
 */
function example_menu() {
    $items['add/%/content'] = array(
        'title' => 'Add Content',
        'type' => MENU_LOCAL_ACTION,
        'context' => MENU_CONTEXT_INLINE,
        'page callback' => 'contextual_node_page',
        'page arguments' => array(1),
        'access callback' => TRUE,
    );

    // To use local task menu items, there must be a parent page.
    $items['add'] = array(
        'title' => 'Contextual Link Page',
        'page callback' => 'contextual_node_page',
        'page arguments' => array(1),
        'access callback' => TRUE,
    );
    return $items;
}

Additional resources

https://www.drupal.org/docs/7/administering-drupal-7-site/working-with-contextual-links
http://dominiquedecooman.com/blog/drupal-7-tip-add-contextual-links-anything


How can I ensure that availability calendar only show one month at a time? I'm displaying a calendar on a basic page and I have specified that I want the monthly views to show only 1 at a time.  1 per col / 1 per row.

For some reason 3 are displayed.

my calendar can be seen at seosolutions.london

How can I only display 1 month at a time? can I hard code this anywhere?

I found a css fix for this:

availability_calendar.base.css

adding

.cal-viewport { width: 220px !important; }


Setting default content permissions? I've got a Drupal site with a large amount of CCK fields already populated. I'd like to allow non registered users to be able to submit a particular content type, but I don't want all the fields to be available to them.

I can, obviously, use Content Permissions to do this, but I have 100+ fields that I would need to set individual permissions for, and would also need to set permissions every time I added a new field.

Is there a way I can set default permissions for all fields? So, for example, all fields are editable by admin and viewable by all.

I think, the module Field Permissions can solve all of your problems.


Patching docroot htaccess: file not found I tried to create my first patch file in order to reverse the overwriting of the scaffold file .htaccess after executing composer install. I get the following errors:
can't find file to patch at input line 5
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git a/web/.htaccess b/web/.htaccess
|index 6f9123d..4ae5471 100644
|--- a/web/.htaccess
|+++ b/web/.htaccess
--------------------------

Script cd web && patch -p1 < ../patches/htaccess.patch handling the post-drupal-scaffold-cmd event returned with error code 1

This is how the patch file looks like:
diff --git a/web/.htaccess b/web/.htaccess
index 6f9123d..4ae5471 100644
--- a/web/.htaccess
+++ b/web/.htaccess
@@ -113,7 +113,7 @@ AddEncoding gzip svgz
   #
   # If your site is running in a VirtualDocumentRoot at http://example.com/,
   # uncomment the following line:
-  # RewriteBase /
+  RewriteBase /

   # Redirect common PHP files to their new locations.
   RewriteCond %{REQUEST_URI} ^(.*)?/(install.php) [OR]

And this is how it is loaded in composer.json:
"post-drupal-scaffold-cmd": [
     "cd web && patch -p1 < ../patches/htaccess.patch"
]

Look your patch already has the path to web/ in it:
--- a/web/.htaccess
+++ b/web/.htaccess

Just remove the cd web &&  and adjust the path to the patch accordingly.
"post-drupal-scaffold-cmd": [
     "patch -p1 < patches/htaccess.patch"
]


How to expose grouping in Views? I have a view, where I use grouping to display publications by year.
Format: HTML List -> Settings -> Grouping field Nr.1: Year

This is what I get:

Is there a possibility, to expose this grouping to the website user? So that the user can group for example by publications type or author? So the same functionality like exposing filters?

kiamlaluno gave the perfect hint. Without actually using any additional modules, you can just use tabbing for multiple views, each with different grouping.
Thats how you do it:

Create a new view as a page
Page settings -> Menu -> Path -> e.g. /publications
No Menu link

Add a new page to the view with the same credentials like the one above (in my case grouping by field_year) - IMPORTANT
Page settings -> Menu -> Path -> e.g. /publications/by-year (keep the root path)
Page settings -> Menu -> Default menu tab
Parent menu item -> Default menu item

Add a new page to the view with different credentials (in my case grouping by field_type)
Page settings -> Menu -> Path -> e.g. /publications/by-type (keep the root path)
Page settings -> Menu -> Menu tab

Finally there are three pages:

In the frontend it will look like this:

I hope this steps help you a bit. In this way, you can create as many views as you like.

Thanks to the community again.


Where do I translate a string? Where is the page in the administrative section where I can put the translations in Drupal 8?

If you mean the "Interface Translation", it should be available under this URL => http://foo.bar/admin/config/regional/translate

If you clear the cache after activating the Interface Translation module, you could also see this option under "Configuration" >> "Regional and language" >> "User interface translation" menu


Use content field as data attribute in Views html I have a piece of content with an 'Asset Type' field value of Vidyard.  I am using the Views module to render this content on another page.  I have added those fields to the View, but is it possible to add them as a data-attribute to the HTML.  For example, the Views module outputs:

    etc.

How can I add my "Asset Type" field as a data-attribute to the list item.  Making my output:

Is there a way to do this without altering the template?

There are some limitations if you can't change the output templates for the view (and I'd assume if that's the case a views pre render is also out of scope). If you can accept them within the <li> (instead of on the <li>) you can rewrite the field to use a token. Make sure the field that is just data is listed before the field it will be attached to, enabled rewriting on the field, and use the field tokens to attach the value as an attribute. You'll most likely want to suppress the field from output and do some data cleaning to make sure invalid characters don't end up in the token (like ").

You can attach classes based on the row value to the li by using the same token you would use on the rewrite. Drupal will ensure it's safe for output, but then your data is a class and not the attribute you are seeking.

You'll have more control over the output, and you'll be able to build more elegant solutions if you use hook_views_pre_render() to modify the output more directly.


Storing data as entity or node? I am working on a module where I need to save thousands or I guess millions of data (product'data from various e-commerce sites). So I am not sure of saving that data in a custom table by using custom entity or should I save that data in nodes?

As for searching, a user can use elastic or search_api_solr and use views for displaying the data, so is it better to use custom row or nodes to save that much of data?

I actually disagree with the comment from @Kevin, using or not using nodes can make a huge performance difference, for multiple reasons.

Yes, node is a pretty standard content entity, but..

It is revisionable
It is translatable
It has a bunch of standard base fields like promote, sticky that are likely not relevant for your use case
Any data that actually is relevant needs to be stored in configurable fields, which results in additional tables.

So if you need 20 additional fields to store stuff, you end up with 4 base tables and 40 additional tables, so 44 tables in total.

If you don't need revisions and translations and assuming you only have single-value fields, you can do that with a single table instead with a custom entity type and base fields. If you need revisions then it's 2. And each multi-value field does require 2 additional tables but usually there are not that many of those.

With millions of records, it's definitely worth thinking about if creating a custom entity type is worth it and sounds like for that case, the answer is probably yes.

It's worth pointing out that there's still a decent amount of modules (even in core), that currently only work with nodes, e.g. book or diff. So make sure that you don't need any of that or be prepared to re-implement that functionality.


Why aren't the options in my dynamically inserted webform showing up? I've created a webform with one question that includes a list of checkboxes.

I made the webform available as a block, and am rendering the block in my template using:

<?php
$block = module_invoke('webform', 'block_view', 'client-block-#####');
print render($block['content']);
?>

However, when the form renders, I see the title of the question and the submit button, but the options are not visible. How can I debug why the checkbox options aren't showing up?

I checked admin/reports/dblog and it turns out the select_or_other plugin wasn't properly installed, stopping the options from showing up at all.


Why do I get pathauto errors when using node_save? When I'm programatically creating nodes using the code found here I keep getting the following errors:

  Warning: Illegal offset type in isset or empty in
  pathauto_cleanstring() (line 180 of
  .../sites/all/modules/pathauto/pathauto.inc).

  Warning: Illegal offset type in pathauto_cleanstring() (line 223 of
  .../sites/all/modules/pathauto/pathauto.inc).

I have tried providing a default $node->path value, not including a value, setting the value myself using pathauto_cleanstring(), but nothing seems to work. I find it odd that I'm getting the error twice too :s

The solution to this question didn't help either unfortunately :(

Any help on this would be greatly appreciated!

UPDATE:

So, the problem had to do with the data that I was using to create the path. I'm loading an XML file using simplexml_load_file. The value I was using for the node title was a SimpleXMLElement

SimpleXMLElement Object
(
    [0] => Node Title
)

Which needed to be cast as a string before saving it as the nodes title. Thank you all for your help!

Try this:

      $path = 'your value for the path';
  $node->path = array('alias' => $path);


how we can upload file on media browser type field programmatically how we can upload file on media browser type field programmatically.

  Below are my code:

$temp_attachpath = MYFILEPATH;
        $attachpath = drupal_realpath($temp_attachpath);
        if(file_exists($attachpath)){

            $file = (object) array(
                'uid' => 1,
                'uri' => $attachpath,
                'filemime' => file_get_mimetype($attachpath),
                'status' => 1,
            );
            // We save the file to the root of the files directory.
            $file = file_copy($file, 'public://');
            $new_node->field_upload_file[$new_node->language][0] = (array)$file;
        }else{
            $new_node->field_upload_file[$new_node->language][0] = '';
        }
        node_submit($new_node);
        node_save($new_node);

i change my code and its working for me now.

$temp_attachpath = MYFILEPATH;
$attachpath = drupal_realpath($temp_attachpath);
if(file_exists($attachpath)){

    $file = (object) array(
        'uid' => 1,
        'uri' => $attachpath,
        'filemime' => file_get_mimetype($attachpath),
        'status' => 1,
    );

    $file = file_save_data(file_get_contents($attachpath), 'public://'.basename($attachpath));
    $file->filename  = basename($attachpath);
    $file->display = 1;
    $file->description = "";
    $new_node->field_upload_file[$new_node->language][0] = (array)$file;
}else{
    $new_node->field_upload_file[$new_node->language][0] = '';
}
node_submit($new_node);
node_save($new_node);


How to allow a particular user to take quiz very next day in drupal I have gone through so many question asked here but not find exact answer. The main problem I have faced is to create a quiz using 7.x-4.0-rc2, I made some user who can take quiz. One user can take quiz only once, but I need that particular user can take quiz again very next day (After 12AM).

I would suggest to make use of rules:

Create user role (by hand) which always access to quiz let say QUIZER
On Event "I want to enter Quiz"
Look up Time Last entered date from current olr
Check if allowed to go on
Add role quizer to current user
On event "I'm stopping the Quiz"
Remove role quizer from current user
Save Time last entered Quiz in user profile


content type showing as link but not in "node_type" table In the development of a Drupal7 site, I have used various methods of creating profiles for customers of the site. One of the methods involved using a rule to create content for user who creates an account.

Unfortunately, this method did not work out, so the plan changed. At this point, the content type that was created by the rule cannot be removed and is showing up in the list of options for creating content, but is not in the node_type table in the MySQL database. I cannot seem to be able to remove this content type from showing up on such list.

The content type is not showing up under the content types administration interface, but it is showing under the add content list given to users who want to add content.

What methods can i take to manually remove a content type from the list of options given to a user in creating content?

Found the resolution on drupal.org

One comment explains how to "reset" the content type from the navigation menu.

  This fixed the problem! What I did:

Go to the navigation page, admin/structure/menu/manage/navigation
find the link to the content type that is no longer there. It should be in the list under "add content".
To the right there's buttons to edit and reset the link. You want to reset. This forces Drupal to reevaluate the link.
It refreshes and poof! Gone from navigation, from add content page as well.


How do I add a Product to the Cart programmatically in Ubercart? I'm creating a section of my site where users must purchase individual nodes of a certain content type. In an effort to enhance usability, I allow the user to create the node without paying, but then save it as "Unpublished" so it's not yet visible on the site. Then, once the user pays, we'll publish their node. So whenever a user creates a node of a particular type, it should add a Product (which represents the right to post that particular node) to the user's Cart.

I know I can implement hook_nodeapi() to hook into the node creation event, but how do I add the product to their cart?

Is the node that users create is a valid product type node? In any case you can try this - http://api.lullabot.com/uc_cart_add_item

uc_cart_add_item($nid, $qty = 1, $data = NULL, $cid = NULL, $msg = TRUE, $check_redirect = TRUE, $rebuild = TRUE)

Here $nid = nid of the product, $cid = cart id (also user id) - look at http://api.lullabot.com/uc_cart_get_id

Hope this helps.


Splitting 'unlimited' body fields I have set the 'Body field settings' > 'Number of values' to 'Unlimited'; so the user can add as many 'body' fields as they like.

I have then added the following piece of code to my themes 'node.tpl.php' file:

<?php $i=0;
while ($i<=10) : ?>
<section class="box page-box">
<?php print render($content['body'][$i]);
$i++; ?>
</section>
<?php endwhile; ?>

This code outputs each of the 'body' fields in a section/div and then adds a number of blank sections/divs until it hits 10!

How would I find out the total number of 'body' fields so that it only outputs the available number and not all 10? I was trying to use 'foreach' but couldn't seem to get it working.

This issue was solved using a function in my template.php file to get the field data out of entities, which I found here.

/**
 * Returns field values as actual entities where possible,
 * also allows selection of individual items to be returned
 */
function field_fetch_field_values($entity_type, $entity, $field_name, $get_delta = NULL, $get_key = NULL) {
  $values = array();
  if (isset($entity->$field_name) && !empty($entity->$field_name)) {
    foreach (field_get_items($entity_type, $entity, $field_name) as $delta => $item) {
      $value = $item;
      $keys = array_keys($item);
      if (count($keys)==1) {
        $key = $keys[0];
        switch ($key) {
          case 'nid':
            $value = array_shift(entity_load('node', array($item[$key])));
            break;
          case 'uid':
            $value = array_shift(entity_load('user', array($item[$key])));
            break;
          case 'tid':
            $value = array_shift(entity_load('taxonomy_term', array($item[$key])));
            break;
          case 'vid':
            $value = array_shift(entity_load('taxonomy_vocabulary', array($item[$key])));
            break;
          case 'value':
            $value = $item['value'];
            break;
        }
      }
      else {
        if ($get_key && isset($item[$get_key])) {
          $value = $item[$get_key];
        }
        elseif (array_key_exists('value', $item)) {
          $value = isset($item['safe_value']) ? $item['safe_value'] : $item['value'];
        }
      }
      $values[$delta] = $value;
    }
  }
  if (is_numeric($get_delta)) {
    return isset($values[$get_delta]) ? $values[$get_delta] : NULL;
  }
  return $values;
}

I then created the code below in my node.tpl page to check how many 'body' fields were in the array.

<?php if (render($content)) :
$contArray = array();
$summary = field_fetch_field_values('node', $node, 'body');
$contArray = $summary;
foreach ($contArray as $value) : ?>

<?php print $value; ?>

<?php endforeach; else : ?>

There is currently no content for this page.

<?php endif; ?>


Defaut image value not showing up In my article content type, I've added a header image (field_header_image) field which I placed a default image into it so that all articles would have a default image used if one wasn't needed. However, when creating an article and leaving that field as the default value, it doesn't actually use that default value. The page is created as if that value is empty.

Is there any way to make sure that this default value is used?

Is there a way to do this through the .theme file? Is this the best way to do it?

If the default image was set correctly then the newly saved article nodes should pick it up. Check if the website's log show any related error messages.

If you want to go with another method then just:

Copy node.tpl.php in your website's themes folder to node--article.tpl.php;
Open node--article.tpl.php in editor and place the following code just before print render($content);:

<img src="/path-to/image/image_file_name.ext">

Save.
Clear your website's cache and revisit any article node.


D7: How do export content types, module settings, taxonomy terms, webforms and other nodes? It seems D7 lacks an important feature for migrating data content types, module settings, taxonomy terms, webforms and other nodes.

I tried with Features modules but it seems it creates modules out of features and this is bad.

Where is Drupal CCK Content Copy Module  for Drupal 7?

It is not bad.  It is preferable to store as much configuration as possible in code, so that it can be version-controlled and deployed easily elsewhere with Git etc..  Features makes this possible somewhat, but it is not yet feature-complete.  Some work that is still on-going:

Taxonomy terms: This will be implemented with a combination of Features and Deploy, but it is not quite ready.  See http://drupal.org/node/1245582#comment-5146834 for details.
Content type settings: A fair amount of this is now working, but Strongarm needs to be set up first for these to be exported with Features.  See Features does not capture important settings while exporting a content type for details.

As there is no more CCK in Drupal 7, that content-copy feature is no longer available.  We've moved onto Fields.  If you want a quick way to get bundles exported without getting into Features, check out the Bundle copy module.


How can I display the results of webform submission in a block and place it on front page? So I'm using the Webform module to collect data, and I want to display the results in a Drupal block and place it in an appropriate theme region in my site.

Like for example the following: I want to display the analysis with the charts  of my result (created with the Charts module) in the front page of my site.

Is that doable?

There are 2 possible approaches to consider, as further explained below ...
Approach 1: using the Charts modules
This is like rolling your own cookies. You create your chart (as you already seem to have done in the image above), using either the "Charts API" (= write some PHP code to populate the charts Array, whereas you put that PHP code in the content of your block) or using the "Views integration of the Charts module" (where you format the Views result as a block).
Disclosure: I'm a (co-)maintainer of the Charts module,
I hope this does not violate the site's policy on self-promotion.
Approach 2: using the typical Webform related charting modules
If you want to create charts from the survey results of the Webform module, there are 2 typical/popular alternatives to pick from:

Webform Charts (used in about 350 sites), to display Webform results in a graphical manner using a charting library.
Webform Chart (used in about 575 sites), which integrates with the "Analysis" tab of a Webform (created with the Webform module) to provide charts for each individual component's analytical data.

The Drupal 7 version of both modules, requires the Charts module (dependency).
Note:
In both approaches you need to decide about which "Charting Library" (= engine) you want to use, either Google charts (easiest setup) or Highcharts (which might require a license also). At any time it should be pretty easy to swap between either library also (that is a key feature of the Charts module also ...).


How to cache POST requests with Boost Boost reacts and caches only GET requests. Does anybody know how to force it to cache POST requests too e.g. using specific key param in URL?

Or at least how to call Boost method that caches request and method that check whether this page exists in cache?

Update :

Answer below is good and marked it as an answer but i decided that i am not so familiar with Boost and Drupal to go so deep so now i am using Boost for cashing GET requests and my own module to cache POSTs. Boost works faster because it uses redirects within HTACCESS but it requires additional setup. Even though method below is a little slower it allowed me to change execution of my AJAX from 5 seconds to 900 ms in average.

My module :

It maybe absolutely wrong so do not think that this is a recommendation, just keep in mind that this is easy enough even without Boost.

// I am caching AJAX POST requests and thus separate these actions by URL params

function customactions_init() {

    $template = null;
    $cache = isset($_REQUEST['cache']);

    if ($cache) {

        switch (true) {
            case isset($_REQUEST['views']) : $template = json_encode((array) $_REQUEST['views']); break;
            case isset($_REQUEST['nodes']) : $template = json_encode((array) $_REQUEST['nodes']); break;
            case isset($_REQUEST['loaders']) : $template = json_encode((array) $_REQUEST['loaders']); break;
        }

        $cache = DRUPAL_ROOT . '/sites/cache/' . md5($template);

        // if file cache was found - use it and stop everything else

        if (is_file($cache)) {
            die(file_get_contents($cache));
        }
    }
}

// Define some static path - can be moved somewhere to config

function customactions_get_directory() {
    return DRUPAL_ROOT . '/sites/cache/';
}

// Returns path to cached content that was built based on URL params

function customactions_get_key($params) {
    return customactions_get_directory() . md5(json_encode((array) $params));
}

// Clear cache when some node changes

function customactions_node_presave($node) {
    @array_map('unlink', glob(customactions_get_directory() . '*'));
}

Any template file, e.g. page.tpl.php :

<?php

    $nodes = array();
    $ids = array_unique((array) $_REQUEST['nodes']); // Get node IDs from AJAX

    foreach ($ids as $k => $v) {
        $nodes[$v] = drupal_render(node_view(node_load($v))); // Create nodes
    }

    ob_start(); // Start buffering output
?>

    <?php print sonifi_render(sonifi_device() . '/header.php') ?>

        <?php print implode('', $nodes) ?>

    <?php print views_embed_view('footer', 'default'); ?>

<?php

    $output = ob_get_clean(); // Closing buffer

    // If module and its function are enabled then create cache file

    if (function_exists('customactions_get_key')) {
        file_put_contents(customactions_get_key($_REQUEST['nodes']), $output);
    }

    print $output; // otherwise show content as usual
?>

You would need to do 2 things. Create your own hook_init that runs after boost_init to modify the global $_boost['cache_this'] value & use hook_boost_cookie_handler_callback_alter to write your own boost_cookie_handler function that works with POST.

To check if the page exists in the cache the boost_block_view_status() function has the parts needed but it has not been abstracted out so you would need to create your own function to do this.

That will cache POSTs.

If you want to serve from the cache on a POST (ignore the post) in your htaccess file remove RewriteCond %{REQUEST_METHOD} !^(GET|HEAD)$ [OR].

A lot of things can go wrong if doing this. It's a bad idea 99% of the time.


Locking access to /user redirect if logged out We have a Drupal 7 site that uses a bespoke login module for ordinary users. Certain (administrative) user rôles, however, must use the core login form at /user to log in, as they have escalated privileges. Regular users get a login form at / (redirected from any URL when not logged in) and cannot log in at /user; administrative users cannot log in at /, but must use the form at /user — these two forms ask different login questions.

We would like to be able to restrict the /user login form to a whitelist of IP addresses, so that only users coming from known IPs can use this form to log in. This would seem simple, at a first glance, as we could use Apache to reject requests for ^/user$ coming from non-whitelisted IPs, except that Drupal also uses /user as a redirect to the currently-logged-in users's profile page and this link appears in a handful of locations in our site.

Now I don't want to go hacking through Core, but I can't see how I can enforce the whitelist for anonymous users, whilst allowing any authenticated user to access their own profile page on the URL /user.

Should I go through everywhere that we link to /user (including the menu block) to substitute in the user's profile ID, or is there some more-elegant solution that I'm just not seeing?

All suggestions gratefully received  :o)

I'm not sure this is necessarily the 'best' way to handle this but you could override the access callback for the user and user/login paths in a custom module and do your whitelist check in there:

function MYMODULE_menu_alter(&$items) {
  $items['user']['access callback'] = 'MYMODULE_access_callback';
  $items['user/login']['access callback'] = 'MYMODULE_access_callback';
}

function MYMODULE_access_callback() {
  global $user;

  if ($user->uid) {
    // If a logged in user is trying to access the login page, deny access
    if (arg(0) == 'user' && arg(1) == 'login') {
      return FALSE;
    }

    // Otherwise let the user see their page
    return TRUE;
  }

  // If we've got this far the user is not logged in and the access
  // is based on the whitelist
  $whitelist = get_whitelist_array();
  if (in_array(ip_address(), $whitelist)) {
    return TRUE;
  }

  return FALSE;
}


profile2 image field not show images I tested my profile2 image field at upload moment and the file upload successfully and unexpectedly after save changes the image fid appears like 0 but the image don't show.

What I do?

Thanks!

Finally I found that I have an module conflict, if you decide to use DDF (Dynamic Dependent Fields) you must think before make tests with profile2 fields.


error when trying to clear the cache in drupal I was going to use mailchimp module to create my newsletter but an error revealed saying that i should  install the version 2.0 of librairies, so i delete both modules, started again,that worked just fine .
When i went to  settings of mailchimp, this error revealed:

  1)Fatal error: Call to undefined function
  mailchimp_signup_entity_access() in
  C:\Users\user\Sites\devdesktop\drupal-7.37\sites\all\modules\entity\entity.module
  on line 657

So , i tried to clear caches ,another error revealed:

  2)
   i-Warning: Invalid argument supplied for foreach() in
  drupal_schema_field_types() (line 7159 of
  C:\Users\user\Sites\devdesktop\drupal-7.37\includes\common.inc).
  ii-Notice: Undefined variable: field_types in
  drupal_schema_field_types() (line 7162 of
  C:\Users\user\Sites\devdesktop\drupal-7.37\includes\common.inc).
  iii-Warning: array_keys() expects parameter 1 to be array, null given
  in drupal_schema_fields_sql() (line 7179 of
  C:\Users\user\Sites\devdesktop\drupal-7.37\includes\common.inc).
  and Recoverable fatal error: Argument 2 passed to
  SelectQuery::fields() must be of the type array, null given, called in
  C:\Users\user\Sites\devdesktop\drupal-7.37\includes\entity.inc on line
  317 and defined in SelectQuery->fields() (line 1301 of
  C:\Users\user\Sites\devdesktop\drupal-7.37\includes\database\select.inc).

 any help please!

If the on option is grey, it means the module is required by another one. Deleting it will cause other modules to break. The correct thing to do would be to disable the depending modules, then disable the main modules and then go to the 'uninstall' tab and uninstall the module.

But for now try running update.php (drush updb) first and see if it helps. If not. Uninstall the modules properly, install the previous versions, disable and uninstall the previous versions and then install new versions again.

This works in most cases.


"New" Marker for Comments does not vanish The "New" marker above comments does not vanish in my theme. It is basically vanilla Bartik with some tweaks.
The marker is hidden by default and inserted via JS according to this comment in comment.html.twig:

  Hide the "new" indicator by default, let a piece of JavaScript ask the
  server which comments are new for the user. Rendering the final "new"
  indicator here would break the render cache.

This seems to be working as the marker is displayed after loading. The problem is that it is always displayed even on repeated views of the article. I have investigated it for some time now. It appears that the AJAX call to /history/NID/read always returns the current timestamp, not the timestamp of the previous view. Returning the timestamp of the current request does not make a lot of sense to me.

Is my analysis correct so far? Should /history/NID/read return the last instead of the current? If that is true, what could be going wrong here?

Thanks in advance,
Eric

Trying this out in vanilla Bartik doesnt have issues.
I couldn't say for sure without looking at your "modifications". But on digging a little deeper I assume it's one of the following

The reason for your issue is most likely your modifications to node.html.twig(or node--article.html.twig)

You would have rendered 'comments' outside of

<article{{ attributes}}>
</article>

in your template.
You would have removed a required attribute "data-history-node-id"
from

<article>
</article>

tags in your template

Details:

/history/NID/read always returns the current timestamp

The module in question here is the new core 'history' module.
The path "/history/NID/read", if you check history.routing.yml, resolves to readNode() in HistoryController
In there you can find a call to
history_write($node->id());
first and then followed by a call to
history_read($node->id())
which would return the current timestamp (because it has just updated it in the previous history_write line)

According to the function description

  "Marks a node as read by the current user right now."

so it is used to mark a node as read by the user and not to get a node's last read timestamp.

The new marker logic is at core 'comments' module
comments/js/comment-new-indicator.js
processCommentNewIndicators() function.

The following line will not return a value

    var $node = $placeholder.closest('[data-history-node-id]');

if the $placeholder(marker) was not inside  tag with attribute "data-history-node-id"
if the article didn't have the attribute "data-history-node-id". Make sure you don't remove it from your node.html.twig (or equivalent)