texts: drupal 7 'views'. Use the context filter to path 'directory /% /%'

texts:
Site Drupal 7 Commerce.

path pattern catalog category - 'category / [term: name] / [term: tid]'
To display the product catalog categories set view 'catalog_view' with parameters:

Page settings: path: 'category /% /%', where the first argument - raw name term, the second argument - id term.
The Contextual filters are two filters:

1) Global: Null

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

I need to first parameter of the Drupal path ignored, and the second was used for the filter. But it is impossible.

When outputting through a "Preview with contextual filters:" everything is OK, displays all products in the category (for example, 'category / Tables / 109').

But when you enter the same path in the address bar - miracles. Shows the correct goods category (products with tag id = 109)
but is used template 'page - taxonomy - term.tpl.php'.

If an error in the name of the category (for example, 'category / Tab - les / 109') displayed products with tag id = 109 and used our view 'catalog_view'.

Question two:

1) How do I get on the category / Tables / 109 displayed view 'catalog_view' (ignore the path catalog and filter the first argument to the second argument).

2) How Drupal can trace routing? For example, I set the path 'category / Tables / 109'
and I would like to see how the first through Drupal alias returns the path taxonomy / term / 109
like looking for a match this way what the views. As it is all a matter amenable to debug?


texts: Why Drupal changes the module (system table) bootstrap value after i set it with an SQL query?

texts:
I need to run some hooks very early in the boostrap like enhanced_page_cache does.

I copied the same hook_update to set my module as available in Drupal bootstrap
and alter its weight.

/**
 * Ensure the weight of the module is pretty high.
 */
 function MYMODULE_update_7000() {
   // Make sure this module is available on bootstrap.
   db_update('system')
    ->fields(array('bootstrap' => 1, 'weight' => 98))
    ->condition('type', 'module')
    ->condition('name', 'MYMODULE')
    ->execute();
  }

After the update the values are there, but if the caches are cleared, the module's bootstrap value on system table reverts back to 0.

Why is this happening?

How does the Enhanced_page_cache module does it and keeps the value intact?

Do i forget something?

Thanks


texts:
Suppose in a School's website, I have some departments. They want their class lectures, class routines, course curriculum to be uploaded under their departments. Typically we did some very simple things - all the departments are now simple hierarchical pages. How to go with it.

We thought to go with a new content type, where the taxonomy will be the department name, where under the department names will be the type of document (whether class routine, or class lecture etc.) and under that taxonomy if we write a content, then we can go through the taxonomies to the content. In a scene they will be:

Home
  - Departments
     - Zoology
       - Class Lecture
         - Content
       - Class Routine
         - Content
       - Class Curriculum
         - Content
     - Biology
       - Class Lecture
         - Content
       - Class Routine
         - Content
       - Class Curriculum
         - Content

BUT NOT the file directly. We need to attach file under taxonomy, not the content. So there is a problem.

How can we proceed to such extent?


texts: Get UC product attributes using Views Global PHP

texts:
I tried using below code in Views > Global PHP field.

<?php

$request = db_query("SELECT data FROM {uc_order_products } WHERE order_id= $row->order_id")->fetchField();
$att =  $request;

$data = unserialize($att);

if (is_array($data['attributes'])) {
  foreach ($data['attributes'] as $attribute => $option) {
    echo $attribute . ':   ' . implode(', ', (array)$option) . '<br>';
  }
}

?>

Adding above code I get the below error :

  SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

Also how do I print each attribute in a different field?


texts: How to create a node from a Webform using rules?

texts:
I want to create a node based on a webform data using the Rules module. This is because of a complication surrounding relationships within the associated CRM system.

I am already at the point where I have the webform created and have got to the following (and working) point within Rules:

{ "rules_member_news_import_" : {
"LABEL" : "Member News (cloned)",
"PLUGIN" : "reaction rule",
"OWNER" : "rules",
"REQUIRES" : [ "webform_rules", "rules" ],
"ON" : { "webform_rules_submit" : [] },
"IF" : [
  { "webform_has_id" : {
      "form_id" : [ "form_id" ],
      "selected_webform" : { "value" : { "webform-client-form-730" : "webform-client-form-730" } }
    }
  }
],
"DO" : [
  { "entity_create" : {
      "USING" : {
        "type" : "node",
        "param_type" : "newsfrommembers",
        "param_title" : "[data:title_member_news-value-raw]",
        "param_author" : [ "user" ]
      },
      "PROVIDE" : { "entity_created" : { "entity_created" : "Created entity" } }
    }
  }
]

What I need to do is use the rest of the fields in the webform to transpose the information across, for example the body text and an image.

What I am trying to learn is how to also incorporate the body and other information. I used the export to add what I thought would work, for example:

"param_body" : "[data:body]"

within the entity_create action, however when I imported the edited text it simply disappeared, so I am assuming that I have to add a separate action to add entity variables.

I went back to using the menus and I again could not get it to work. I must be doing something basic wrong.


texts: How to add multi nodes on a single page without using an iFrame?

texts:
I came up with the Multi Node Add module to add multiple nodes to single page. But the nodes are shown on iframe.

Is there another way with which we can add multiple node on single page without iframe?


texts: How to set different logout times for roles?

texts:
I would like to define/set a log out time for different roles for my Drupal site.

Say for example if I set log out time for X role for 30 Minutes. The users under that role would be logged out in 30 Minutes from the time they logged in and also I would like to show notification to users for their remaining time for timeout.

How can I achieve that in Drupal?


texts:
Is there a way to limit the number of imagefield fields present in a node?
I am using iTweak Upload, which allows to upload an unlimited number of images, but I need something that can limit the number of uploads.

I want to make a gallery per node with the uploaded files; what module do you recommend?


texts: Feed aggregator does not update RSS feeds when cron job is run (Drupal 7)

texts:
I have several feeds setup in the Feed Aggregator ( admin/config/services/aggregator ) in Drupal 7.

I know that my cron job is running regularly - by checking admin/reports/dblog

But the when I look at the feeds list, the "LAST UPDATE" for each of them shows dates from over a week ago. If I do the update manually, i.e. click update items then the feed is refreshed and new items are available.

But why is the cron job not triggering the updates?

If you can't provide a reason then what approaches to debugging can I use to find and solve the root cause?

I have searched this site already and not found an existing question about this problem. I did find RSS feed not updating using feeds module but that question is about the Feeds module - which I don't use.


texts: How do I add body class on specific content_type who have specific field?

texts:
I need to add class in body when content type article and have image on it.
How do I achieve this?

I checked in theme_preprocess_html only found content_type as string. Don't know how to check image on it.


texts: Public and temporary files error in my "Status Report"

texts:
I just upgraded to 7.25 from 7.19, and now in my Status Report I have a red X on my "Public Files" and "Temporary Files".

  See http://drupal.org/SA-CORE-2013-003 for information about the
  recommended .htaccess file which should be added to the
  sites/default/files directory to help protect against arbitrary code
  execution.

I go to the address above, but I don't have any user friendly explanation of what to do to fix this. Thanks in advance.

Update: (1/8/14)

The answer below fixes the Public files problem 100%.

It does not fix the Temp files. To fix temp files, I go to admin/config/media/file-system and change the path from /tmp to ../tmp

I will update this if this is fixed in a newer version of drupal, or if there is another fix available. I'm not sure if the ../tmp is the correct solution, but it works.


texts:
I have a view set up to display all my taxonomy nodes for "Classified Categories" Vocabulary, in the view I have set up the path to be /Dogs however when it lists the terms they are all linked to /Dogs/(term) and this will then display nothing, but if I change the path from /Dogs/ to /Classified-Categories/(term) it will show.

I've had a look at setting up patterns for my URLs but seem to have no joy. Further on this the terms with spaces are linked with %20 in and will not show even in the changed format; only when I replace the %20 with - will they show.

I'm pretty stuck on getting this to work especially being a Drupal newbie.

This is a screenshot from my current configuration of my view.

Both "Link this field to its taxonomy term page" and "Convert spaces in term names to hyphens" are ticked.**


texts: For CCK fields you can set the display to be hidden for teaser display and shown when in full node display. How can I do the same for a node's body field as it's not listed on the display settings page?


texts: Render entity reference field with link in node template

texts:
I have a content type with an entity reference field to select a user.
Now I would like to render this field in the node template so that the field links to the user profile.
I set the format of the field to "Label" in Manage Display and clicked on the gear so the label is linked to the reference entity.

But because I am printing the field programmatically it doesn't seem to work.

Here's what I do in my node template:

$field_user = field_get_items('field_collection_item', $item, 'field_user');
$field_user_output = field_view_value('field_collection_item', $item, 'field_user', $field_user[0]);
print render($field_user_output);

Does anyone know how to do this?


texts: Form api: Combine two text fields into a div?

texts:
Using the form api is it possible to combine two text fields onto the same row?

E.g. form

<?php
function foo_form($form, $form_state) {
  $form = array();

  $form['range'] = array(
    '#type' => 'fieldset',
 );

  $form['range']['min'] = array(
     '#type' => 'textfield',
     '#title' => 'Address'
  ),
  $form['range']['address2'] = array(
     '#type' => 'textfield',
     '#title' => 'Address'
  )
  // ...
  return $form;
}

Desired output

Range

  <input name="min" /> to <input name="max" />


texts: How to get the file destination from a content type's field_image to upload programatically

texts:
I have a cron job that goes and grabs content from another resource and uploads it into my drupal site, and this includes a link an image that I retrieve and upload into my S3 file system.

My site's file system is set to Amazon S3
For my S3 Configurations, I have access_key and secret_key set in the settings.php file as well as the following settings:

$settings['s3fs.use_s3_for_public'] = TRUE;
$settings['s3fs.use_s3_for_private'] = TRUE;
$settings['php_storage']['twig']['directory'] = 'sites/default/files/php/twig';

My Content Type's field_image settings are to use s3 storage under the folder public/course_images
I've validated the s3 configurations and refreshed the metadata cache successfully

Right now, if I upload an image through the admin interface, it uploads as expected and works perfectly fine. However, in my cron job I keep getting the error The specified file 'temporary://fileBXiPLP' could not be copied because the destination directory 'public://course_images' is not properly configured.
In my cron job, here is how I attempt to upload the file:
$image_url_arr = explode("/", $image_url);
$image_name = end($image_url_arr);
$img = file_get_contents($image_url);
$file = file_save_data($img, "public://course_images/$image_name", FileSystemInterface::EXISTS_REPLACE);

I've tried to replace public://course_images with public://public/course_images and s3://public/course_images and I received the exact same error...
What's even stranger is that my staging instance that has the exact same configurations and the same s3 bucket permissions works perfectly fine (specifically with the s3://public/course_images option).
Considering it uploads fine via the admin UI, how can I get the correct path to be able to upload to S3 programatically?


texts: How to render HTML page with attachments only from the render array?

texts:
I would like to render a full html page(with html and body tags) with content provided by a render array.

What do I need to do in order to NOT render attachments(CSS, JS, drupalSettings) from active theme or modules but solely from attachments defined in the provided render array?

So far this is quite close but I still see attachments from base theme:

\Drupal::service('bare_html_page_renderer')
      ->renderBarePage(
        $my_render_array,
        'Page label',
        'page',
        []
      );

Using my own, empty, theme hasn't helped.

Ok, I had to duplicate what bare_html_page_renderer did since it attached "default" libraries form the system module. So now with my own theme all looks good but the structure is not right. Seems like the placeholders are not working properly.

My html.html.twig source code looks like:

<!DOCTYPE html>

  <title>{{ head_title|safe_join(' | ') }}</title>
  <css-placeholder token="{{ placeholder_token }}">
  <js-placeholder token="{{ placeholder_token }}">

{{ page }}
<js-bottom-placeholder token="{{ placeholder_token }}">

but the rendered HTML will looks like:

<title>Page title</title>
<link rel="stylesheet" href="..." media="all">

the rendered content


texts:
I'm trying to alter an entity form handler. The method EntityType::setHandlerClass() allows for the 'form' handler to be set, but this value is an array, and I only want to override a single item of the array.

The entity handlers definition:

handlers = {
    "storage" = "Drupal\user\UserStorage",
    "storage_schema" = "Drupal\user\UserStorageSchema",
    "access" = "Drupal\user\UserAccessControlHandler",
    "list_builder" = "Drupal\user\UserListBuilder",
    "views_data" = "Drupal\user\UserViewsData",
    "route_provider" = {
      "html" = "Drupal\user\Entity\UserRouteProvider",
    },
    "form" = {
      "default" = "Drupal\user\ProfileForm",
      "cancel" = "Drupal\user\Form\UserCancelForm",
      "register" = "Drupal\user\RegisterForm"
    },
    "translation" = "Drupal\user\ProfileTranslationHandler"
  }

I'm trying to figure out how to override the form.register handler, but as the first argument to setEntityHandler() is a string, I cannot figure out how to set a nested value.


texts: Go to specific page in view using node id

texts:
I have a view composed of single nodes with a pager. Is there any way to link to a specific page in this view using the node id? I can see that the pager uses a page variable in the url, but that carries no information about the node. I can go to a specific node in the view using contextual filters, but if I don't want to filter the results, I just want to jump to a page in the pager by using the node id. Filtering makes the pager disappear (of course).

Is there a way to pass in a node id to the view, use that information to set the pager to that node, and not lose the pager?


texts:
I changed the:

configuration: Site Name --> 'my site name'

But it shows in title bar like this:

  Welcome to 'my site name'

So, how can I remove the "Welcome to" in the title bar, so that the result would be just:

'my site name'

When I inspected the html I found like this:

Welcome to my stie name | my site name

But I wanted to be :

my site name

And I'm using zen base theme and zenophile sub-theme.


texts: Date format on user profile form shown incorrectly - how to change

texts:
I added a date to the user profile form under admin/config/people/accounts/fields. The field is of type 'date', the widget of type 'select list' and I only collect year, month and day.

Without altering anything the date entry widget is shown on the form in the order year-month-day.

Since the order in the Netherlands should be day-month-year, I set out to change the date format by:

Adding a new custom format d/m/Y under admin/config/regional/date-time/formats
Create a new date type called 'test' and referencing the custom format from the previous step under admin/config/regional/date-time
Changed the date display format to the 'test' type, under admin/config/people/accounts/display - press update and save the settings

In the date preview of admin/config/people/accounts/display, the date is shown as DD-MM-YYYY which is the format I want.

Now, going to the user profile page under user//edit, the date order shown as month-day-year.

I have tested this on a clean installation of Drupal 7.33 and the only module added is the date module 7.x-2.8.

How can I change the display order for this specific field?

Kind regards,
Eric van der Staaij


texts:
In my GoDaddy control panel I have scheduled it to run this script every day:
/web/cgi-bin/php5 "$HOME/html/my_site/cron.php

However I cant figure out how I create tasks that will be run when cron.php is run. I have gone through all the documentation and can't find this anywhere (The D6 video tutorial link seems to be down).

For example how would a go about deleting the contents of a temporary folder?. Do I just add some PHP using the unlink command to the cron.php (in which case drupal is not really involved) or is there some setting page that I havent discovered that allows you to create tasks?


texts: How to load a node based on current language?

texts:
I have 2 content bundles for node entity:

Custom Layout Pages (custom_layout)
Recipes (recipe)

Then I created two content using those content types, Potato (recipe) and Homepage (custom_layout).

I have 2 languages for both content, en and fr. I'm trying to load the potato recipe node inside of the homepage content.

So inside the preprocess hook, I have this code

...
if(isset($vars['node']) && $vars['node']->type === 'custom_layout'){
    $recipe_id = 10;
    $vars['recipe_side'] = render(node_view(node_load($recipe_id)));
}
...

Then I echo the $recipe_side in the custom_layout template file.

When I load the fr version of the page, I expected the recipe to be loaded in fr as well, but it always displays the en version.

I'm guessing it's because the en recipe node id is 10, and it doesn't load the translated node.

If that's the case, how can I make it work so that the loaded node follows the current language?


texts: How to get 'add more items' / multiple fields working when creating a custom content type's create/edit input form using templates and theming (D7)?

texts:
For single instances of each field, I've successfully followed arajashe's excellent answer for controlling what input fields get displayed in the content type's create/edit form here:
https://drupal.stackexchange.com/a/68975/1082 - an answer to question: How do you theme a content type's create/edit form in Drupal 7?

But what about fields where you can add more, where you specify in the settings that more than 1 of a field can be added, or even unlimited.

In this case, the above answer does not work. When I click the 'add more items' button for such fields, in my custom form, the new field does not display. Given that I have already displayed the first instance of the field, I would expect the markup output to include a place holder for contain the new input field that would be inserted as a result of clicking the button.

I've started to debug the code involved - 2 screenshots

The first is in field.form.inc and shows the ajax call back code - the code that is called when the add more items button is pressed. This does the job of inserting the markup for the new instance of the field input. For some reason (which is why I'm asking this question), the markup for the second field is not being inserted alongside the first field by this function, when I use a custom template.

The second screenshot shows 2 fields of the same type and the markup that generates them. This is when no custom template is being used - i.e. the default, out-of-the-box input form for add content type that comes with Drupal.


texts: How to edit and theme Comments & Comments form?

texts:
I am building a drupal site using drupal 7 and the adaptivetheme.

I created some a content type called recipes. Than I created a content pane in views to present recipes in panels. I add the comments and comments form to the same panel.

Now I want to present beneath any recipe a comment form and all other comments.
My problem is that I  don't know how to edit the presentation of the comment form. When I checked the comment fields on my content type, I saw only the field "comment_body".

How can I edit the fields and the way they will show on Comments & Comments form?

Below is a screenshot.
I want to remove the field "your name", and change the button "save" to "post comment". How can I do that?

Thanks!


texts:
How can I override the default display of a taxonomy term with a view ?

eg : the path of a taxonomy term taxonomy/artist/artist_name take me to the default display of a taxonomy term and I want to display a specified view to the same path.

in resume override the path.

thanks !


texts: Cann't delete the CSV file after imported by Feeds module

texts: We uninstalled the "Feeds" and "Job Scheduler" modules, after a successful imported csv data by Feeds. However, the csv file is still maintained in "media" list. When we try to delete that file, it say "The file xxx.csv is in use and cannot be deleted". Is there a way to delete that, or do we have to delete from FTP?


texts: How to disable browser autocomplete for the login form

texts:
I would like to remove auto fill user name and password while login or forgot password.

I have tried this but its not working:

if ($form_id == 'user-login-form') {
  $form['name']['#attributes']['autocomplete'] = 'off';
}

What am I doing wrong?


texts: In a template, is it possible to get the content of a block by the block ID?

texts:
I am working with some view templates in Drupal 8, and I have the block ID of another view block I want to pull into the template. Is it possible to use the block ID to get the content of a block in a template?

If this is not possible in Twig, how could I achieve this otherwise?


texts: Adding dividers between list items in the menu.html.twig template

texts:
How do I add dividers between each
 in the menu.html.twig template. Obviously with the code below, the divider also gets added after the last item, which isn't the desired result.

{% import _self as menus %}

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

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}

    {% for item in items %}
      {%
        set classes = [
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}

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

    {% endfor %}

  {% endif %}
{% endmacro %}


texts: Entity reference to user doesn't work without 'administer users' permission

texts:
EDIT: I have most probably found out the reason thy it works (or doesn't work actually) this way. The problem is that I don't have legitimate access to the user node that is being edited. I only 'hacked' the menu system so it let me through but don't really have the real access. Unfortunately I have no idea how to resolve this problem...

I have reworked the system that handles permission to user edit pages so that it allowed editing certain users even without the 'administer users' permission.

The system itself works well, the only problems are entity reference fields on the user. To be more specific, there are two entity reference fields attached to user bundle -> one that references another user 'supervisor' and another that references certain content type.

The problem with these two fields is that the autocomplete feature (I use autocomplete widgets) in the widgets not only doesn't work but even throws a 'access denied' error (in AJAX response).

It works well when current user has the 'administer users' permission but I can't give every user this permission.

BTW: To make it perfectly clear, not even the field that references a normal content type (node) works so the problem can't be in access to user entities as the answer below suggests.

I have tried to look into the entity reference code but have not found anything that would explain this strange behaviour (there's literally zero calling of user_access that might lead to this kind of behaviour).


texts:
I'm trying to pass multiple parameters from one Forena report to another one.
Currently my link looks like this:

reports/aen_multi?startdate={eventdate}&enddate={eventdate}

but this does not work ("Invalid or malformed report document").

For links with only one parameter this works:

reports/aen_multi?startdate={eventdate}

What is the correct way of linking to a report with several parameters?


texts:
I have created a D8 custom field that extends FieldBaseItem. It is already in use storing data.

How do I get the schema updated in the database, for an existing field?

What I've done:

I have added a new column by adding to propertyDefinitions and schema() accordingly.

Here's an example schema. Let's say I just added the admin column.

  /**
   * {@inheritdoc}
   */
  public static function schema(FieldStorageDefinitionInterface $field_definition) {
    $schema = [
      'columns' => [
        'state' => [
          'type' => 'varchar',
          'length' => 2
        ],
        'admin' => [
          'type' => 'int',
          'size' => 'tiny'
        ],
        ...

I've found posts on how to do this in hook_update_N in D7, but it's unclear how to do this in D8.


texts: How to block users to accessing Drupal website if javascript is not enabled?

texts:
I checked many pages in Drupal Answers, which didn't have the answer of the following question:

Consider a case that I need javascript to be enabled for visual effects in drupal design.

How can I stop my website and show a message , if javascript is not enabled in user's browser?

Stop means to block the access of user to the website and showing a message like:

Please enable JS in your browser!

(I use Drupal 7.x)


texts: How can I make a link from content profile node to it's user account page?

texts:
I'm trying to find out how to make a direct link from content profile node view/edit page to it's account page.

As an admin role when I check somebody's profile node I sometimes also  need to check his/her account. So it would be much easier if I can make a direct link.

I need this link to be visible only to Admin role. Is there any way to make it?


texts:
I have a content type with a date field, which I convert to a specific date format in a preprocess function:

$variables['date'] =
\Drupal::service('date.formatter')->format($variables['node']->field_datum->date->getTimestamp(), 'long_date_without_time');

But as Germany is one hour ahead, a date like 2015-03-31 23:01:08 UTC converts to 1. April 2015. How can I convert this to our local time?

EDIT: I already set the correct timezone in the UI. And I just saw that the wrong dates are only shown when I set my system time between 11pm and 1 am...


texts: Should a hook_form_alter be firing both on render and when an additional submit handler is fired?

texts:
I am trying to add an additional submit handler to the user login form, to simply redirect users to the page they were on before landing on the login page (/user/login).

I have the following code attempting to store the current path/destination in the $form_state storage which is working as I expected when the original form_alter is run on render as it alters the redirect property of form_state to the previous page.

However, when the form is submitted, the form_alter is fired again, but this time the form_state storage is empty, thus the current_path/destination is now set to /user/login which is not where the user should be redirected to.

Here is the code I have at the moment, any help would be appreciated as to why the form_alter is run again on form submit:

function MODULE_form_user_login_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $form['#submit'][] = '_module_custom_user_login_form_submit';
  if (is_null($form_state->get('redirect_dest'))) {
    $destination = $_SERVER['HTTP_REFERER'];
    $form_state->set('redirect_dest', $destination);
  }
}

function _module_custom_user_login_form_submit($form, FormStateInterface &$form_state) {
  $destination = $form_state->get('redirect_dest');
  $form_state->setRedirect($destination);
}


texts: how to make radio buttons be one under the other on drupal contact form

texts:
by default the radio buttons on my drupal contact form come out next to each other and the title is very far from the actual button.

with CSS alone it doesnt work.  I seem to need to be able to edit the html which I cant do since its a drupal form. https://stackoverflow.com/questions/26432418/how-to-line-up-radio-buttons-and-text/26432623#26432623

Thanks


texts: What's the correct way to include JavaScript dependencies into modules?

texts: With Composer we can require PHP dependencies for our modules. What's the right way to include third party dependencies such as a jQuery plugin into a module?


texts: What's the difference between 'attachment before' and 'block' in views?

texts:
Recently I followed a tutorial in views which listed taxonomy and gave me a short list above the view with hyperlinked first characters of taxonomy name. In this case, I created a "block".

In investigating the default Glossary view, I see the same hyperlinked first characters of title created by using "Attachment before".

Are there advantages of using one method over the other?


texts:
Recently I've been receiving many spammers creating an account on my website, which is quite basic and for which I don't need users create an account.
What would the likely URL that spam bots are finding be?
Is there a way to turn off account?


texts: Rename/hide "Save" and "Save as draft" buttons for non-admin roles

texts:
I have four content types on my site that registered users can create, but they are set to be approved by admins before publishing. Since the site also sends out notifications to subscribers when a new node is created, the following problem occurred - the regular users could save new nodes which are not published until approval, but the notifications go out immediately after they save it anyway.

The registered users creating new nodes must not have the ability to create i.e. save the node and that's why we added the "Save as draft" option (via Save Draft module). What I need is to only show the "Save as draft" button, possibly under another label and completely hide the "Save" button. Understandingly, I would need to do this only if the user is not an admin or an editor, otherwise I might create a big confusion on the site.

This is the rule which sends notifications to users who subscribed for notifications:

{ "rules_new_content_notifications" : {
    "LABEL" : "New content notifications",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--slucaj_plan" : { "bundle" : "slucaj_plan" },
      "node_insert--inicijativa" : { "bundle" : "inicijativa" },
      "node_insert--izgradnja" : { "bundle" : "izgradnja" },
      "node_insert--projekat" : { "bundle" : "projekat" } },
    "DO" : [
      { "mail_to_users_of_role" : {
          "roles" : { "value" : { "8" : "8" } },
          "subject" : "New content created",
          "message" : "..."
        }
      }
    ]
  }
}

The content approval module only sets the node to "unpublished" after a non-admin saves it and the way the administrators approve it later is to edit it and set as "published".


texts: Ajax redirected page won't save input fields cache

texts:
I have an ajax submit input field which on success redirects the page.
For this redirection I use ctools_ajax_command_redirect() which works great.

My only concern is that the fields will not save the entered values in the browser cache.
I.e. email inputs usually have a list of previously entered emails when using the down key on the field.
As non ajax submitted fields do keep this info I wonder how can I tweek my ajax calls to force the cache.

This is my form:

$form['email'] = array(
    '#type' => 'emailfield',
    '#title' => t('Email'),
    '#element_validate' => NULL,
    '#id' => 'edit-email',
);
$form['continue'] = array(
    '#type' => 'submit',
    '#value' => t('Continue'),
    '#ajax' => array(
        'callback' => 'my_form_callback',
        'event' => 'click',
    ),
    '#id' => 'edit-continue',
);

This is my ajax redirection function:

function my_form_callback($form, $form_state) {
  if ($success) {
    ctools_include('ajax');
    ctools_add_js('ajax-responder');
    $commands[] = ctools_ajax_command_redirect($url, 0, $options);
    print ajax_render($commands);
    exit;
  }
}

Any hint on how I could make the field save the cache values?

Thanks a lot


texts: How can I alter the node title in every display?

texts:
I have a content type "Campus", I would like to concat to the title "Campus name campus". So, there is a hook or something to alter the node getTitle() method in every display?

I've tested:

preprocess_node
preprocess_page
views_pre_build
views_pre_render
entity_view_alter
preprocess_field__title
preprocess_page_title

preprocess_field example code:

function usc_theme_preprocess_field(&$variables) {
  if (!empty($variables['element'])) {
    $field = $variables['element'];
    if ($field['#bundle'] === 'campus' && $field['#field_name'] === 'title') {
      /** @var \Drupal\node\Entity\Node $entity */
      $field[0]['#context']['value'] = 'popopo';
      /** @var \Drupal\Core\Field\FieldItemList $list */
      $list = $field['#items'];
      $val  = $list->getValue()[0]['value'];

      $field['#items']      = $list->setValue('testttttt');
      $variables['element'] = $field;

      $entity                          = $variables['element']['#object'];
      $entity->title                   = 'aaa';
      $variables['element']['#object'] = $entity;
    }
  }
}

Thanks all for help.


texts: Exported feature with roles not imported when loading module

texts:
TLDR; I'd like to export the permissions I've added to the authenticated role, and have them appear on a different server when installing the custom module. However, when I install the module on a fresh server, the permissions for the authenticated user remain as default, but I can see in admin/config/development/features that there are pending changes, and once I import them the settings are correctly applied. Why aren't they applied on loading the module?
Steps to reproduce
First I log into a blank dev site, navigate to admin/people/permissions and add the Article: Create new content permission for the authenticated user (which I know is create article content from looking at the page source in my browser).
I now navigate to admin/config/development/features/edit and select Roles->Authenticate user (authenticated), pick a module name, enable Mark all config as required and click Download Archive.
The result is a module that contains 3 files:
my_module.features.yml
required: true

my_module.info.yml
name: 'my module'
type: module
core: 8.x
dependencies:
  - user

Since I'm using 9.0.7 I changed this to;
name: 'my module'
type: module
core_version_requirement: '^8 || ^9'
dependencies:
  - user

config/install/user.role.authenticated.yml
langcode: en
status: true
dependencies: {  }
id: authenticated
label: 'Authenticated user'
weight: 1
is_admin: false

For some reason Features didn't pick up my permission changes, so I changed this manually to;
langcode: en
status: true
dependencies: {  }
id: authenticated
label: 'Authenticated user'
weight: 1
is_admin: false
permissions:
  - 'create article content'

Now I tried to install the module by copying it to /modules/custom/my_module and running drush en my_module on a completely clean site. However, when I navigate to admin/people/permissions I see this:

When I go to admin/config/development/features/diff/my_module I can see that my features were correctly interpreted, just not applied:

If I now select Import Changes the permissions apply correctly. But why aren't they already applied, when the my_module module is clearly enabled?
I tried playing around with the weight value in user.role.authenticated.yml to no avail (I changed it to 9999 and -9999 but it didn't seem to have any impact).
The fact that I had to modify my user.role.authenticated.yml indicates that something has perhaps gone wrong at the export step, but I don't know enough about the features module to know if these events are related.


texts: How can I bundle installation profile with translation (*.po)

texts:
I have tried a few different approaches to load a translation file (.po) from an installation profile.

The build is pretty close to being typical: a make file downloads core, custom profile  and application theme/modules. Then  drush --site-install --profile cutstom_profile build all of this

All is fine until I try adding locale in profile. Then everything breaks and depending on what I tried, different issues pop up that make it a show-stopper.

I tried having locale and l10n_update as dependencies and having a custom task set the language, but that triggers a database error when drush --site-install runs the second time with  saying it is trying to insert a duplicate.
I tried passing --locale=fr to site-install but that sets default french as default language / locale and is not what is wanted in this case. English is primary language.

Is there any way to install a language from a profile passed drush site-install?

For those needing a fast and dirty way to deal with importing translation files on installation without messing in a profile, simply install these locale oriented drush commands and automate the process with drush.


texts: Include Lead Forensics code in all pages

texts:
I'm trying to include the tracking code Lead Forensics gave me. The code is:

I've tried creating a block with only this in the body, but it doesn't render in the page (when I check the generated code with 'view source code' on the browser, it isn't there). I don't know if it's the correct way to do it. Any idea? Thanks!


texts: Create drupal node programatically and set custom select list field

texts:
I have a Drupal 7 node with custom fields. I have no problem setting values to the single text fields but I'm not sure how to set my select list field to one of the allowed keys of the field.

This is the code I've tried to assign the select list to the 'pending' key.

$node->field_referee_status['und'][0]['tid'] = 'pending';

Node creation code:

// CREATE NODE
$node = new stdClass;
$node->type = 'referee';
$node->title = 'Referee report for xx';
$node->uid = $user->uid;
$node->status = FALSE;
$node->field_referee_status['und'][0]['tid'] = 'pending';
$node->field_referee_id['und'][0]['value'] = 'test';
$node->field_testff['und'][0]['value'] = "testworked";
node_object_prepare($node);
node_save($node);

Question: Does anyone know the correct way to assign the key value to a custom select list field when creating Drupal nodes programmatically?


texts: Search API - Search widget with Facet OR Exposed filters clean url

texts:
I'm trying to create "Search API widget" using two exposed filters "search: Full text" + "taxonomy term: City"

The good example of what I want to achieve would be visible here:

http://olx.in/

Whenever you type in the city + full text search it generates the url such as:

http://olx.in/city-name/q-something/

However if I use exposed filters it doesnt seem to work in that way it creates links like this:

http://localhost/search?search_api_views_fulltext={something}&field_city={taxonomy-term-id}

When after I do the search I use facet filter with pretty paths it gives a bit better result:

 http://localhost/search/field_city/{name_of_region}/field_city/{name_of_region}/field_city/{name_of_sub_region}/field_city/{name_of_region}/field_city/{name_of_sub_region}/field_city/{name_of_city}search_api_views_fulltext=&field_city=1031

But I want the end result pretty much to look like this:

http://localhost/{name-of-city}/search-something

And after searching I want it to activate proper facets for the "field_city" so if after searching someone would want to add facet it would not create a {field_city}/{field_city}

And in order to do that, I was considering instead of using a "exposed taxonomy term filter" to use facet block for "Field_city" but no luck so far.

** Update 01.10.2015 **

I was doing research and I think that the "cities" and "categories" on OLX or any other decent portal are not actually facets or exposed filters, but they are Taxonomy pages with inherited search query.

So if someone types in "Exposed full text search api" a "Yorkshire terrier"
He is redirected to: http://localhost/search?search_api_views_fulltext={Yorkshire terrier}
And on left sidebar he have "Taxonomy menu block" with vocabularies of "small ads categories" with terms such as "animals"
He clicks on "animals" term and the search value follows him.
http://localhost/small-ads-categories/animals/search?search_api_views_fulltext={Yorkshire terrier}
Of course the taxonomy is a search api view
However I also would want to extend this by adding a second parameter which is "city" <- not sure how to do that

Another feature that I'm trying to figure out how to create a "select box" for a city that is not a exposed filter but a link parameter.

For example: if someone wants to search for: Yorkshire Terrier + he selects locations from select box to be: London

Normally it is done by creating exposed taxonomy filter - however it generates ugly url, the thing that I'm considering is using the value that is selected to redirect user to the proper search results page. so if he selects Yorkshire Terrier in london he is redirected to:

http://localhost/london/search?search_api_views_fulltext={Yorkshire terrier}

Where london is also a taxonomy search api url.

** update: few hours later **

After further thinking and trying to solve this issue, using taxonomy terms view block seems like a good idea, but it displays ALL possible terms not only the terms that are related to current search query and that I'm not sure how could I limit ?


texts: D7 - Syntax of js custom file added directly to theme

texts:
Alright, so I've read the documentation of JS framework in Drupal and there is a simple example how the syntax of JS file should look:

Drupal.behaviors.myModuleBehavior = {
  attach: function (context, settings) {
    $('input.myCustomBehavior', context).once('myCustomBehavior', function () {

    });
  }
};

I can't figure out what should I put instead of "myModuleBehavior" when js file is added directly to theme, not by custom module. Any help?


texts: Webform submission token for multivalue download field

texts:
I'm trying to setup a webform that sends links which can be accessed to download a file.
It's working with the first file already, but I can't figure out how to create the token for the other files referenced in a multivalue field:
What's working (for one file):
Here is your requested download: <a href="[webform_submission:node:field_gated_download:entity:field_media_file:entity:url]" target="blank">[webform_submission:node:field_gated_download:entity] </a>
I have tried:
[webform_submission:node:field_gated_download:entity:field_media_file:entity:url:0]
[webform_submission:node:field_gated_download:entity:field_media_file:entity:url:und:0]
[webform_submission:node:field_gated_download:0:entity:field_media_file:entity:url]
[webform_submission:node:field_gated_download:und:0:entity:field_media_file:entity:url]

in almost every combination. It's not working.
Can someone lead me in the right direction?


texts: Migration after server crash: maintenance mode and/or cache problem

texts:
I had a crash of my previous server and I tried to rise my website from the dead. I had backups of all the files & of the database (PostgreSQL). I was not the one who set up the website and my knowledge of Drupal is pretty low.
From what I understood/gathered, it is a 7.54 version and it runs with multisite.

What I did so far:

Import my database backup in PostgreSQL (in the dumbest way possible: recreate the right database & user, import everything back in place);
Upload all the files to my new server (running Debian Jessie);
Give access to the sites/ directories to www-data user;
Clear the sites/mysite/css/ and sites/mysite/js/ directories;
Disable CSS & JS aggregation (using drush).

I did the latest because the style of the website was broken; that was enough to revive it.

I still have on major issue: when I log in, I get the maintenance message. I therefore tried to disable maintenance_mode with drush; it didn't work.

I saw it could be related to cache issues; I therefore tried to clear the cache (once again with drush with drush cc all). It put the whole site in maintenance, and not only when I'm logged in.

I am not sure where the problem comes from. Any hint or suggestion would be greatly appreciated!


texts:
I want to add an action that shows a view whenever the user earns User Points. I checked it and there's no rules for Views so I'm wondering how could I do it.

I'm using Drupal 7.


texts: How do I make the select options have a textfield beside them instead of a box?

texts:
I created a webform that uses dynamic select options generated from a specific content type, which represent objects. I would like to have a text field beside each one to in which the user can input the desired quantity of the object.

I have tried looking this up on Google but to no avail. How should I go about doing this? Is there a module or a specific way by which I can implement this?

Thanks for reading this.


texts:
I need to associate sub, which is received as part of $userinfo in openid_connect_save_userinfo, but I don't see it as part of the claim options.  I also don't see that it's stored elsewhere.

I am using the openid_connect project.

I'm wondering if I'm missing something in configuration and maybe I need to do something custom.


texts:
I need to create a view which provide a list of past years, where I could define the past time duration, like display the past 10 years.

Which kind of field do I use?


texts:
I tried to create a node through external application using web services. This having only two fields node title and cck field image. i will grateful if anyone share the JSON format to post the images. I tried using format that mentioned below link but its failed means image not uploaded.

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

Any one guide me do this.

Thanks..


texts: How to get the path to theme in Views for linking an Image

texts:
When creating a view, I rewrote the output in "Rewrite Results". There I have an HTML with a link to an icon in the theme folder.

[field_output]

[field_text_output]

As you can see that I am hard-coding the path to my icons. This works if this View Page is accessed from home page. But when this View page is accessed from some 2nd or 3rd level page, the icons are not shown.

Is there any way I can get a relative path to my theme within Views?

Thanks.


texts: How to structure a "many-to-many" relationship between nodes

texts:
I would like to have 2 node types, Sellers and Products. Each seller can have many products, and each product can have many sellers. Also, the relationship between Sellers and Products would need to contain a price.

What would be the best way to create that relationship, making it easy to list all the Products a seller sells on their page (with prices), as well as listing all of the Sellers selling a product on their page (with prices)?


texts: What is reliable way to get the node id from the path alias in Drupal 8?


texts:
I am getting the following error when invoking "commerce_cart_order_product_line_item_delete()" in a custom module I'm writing.

  Fatal error: Call to undefined function commerce_entity_reference_delete() in
  /Users/[username]/Documents/Sites/[site_name]/profiles/commerce_kickstart/modules/contrib/commerce/modules/cart/commerce_cart.module
  on line 1268

The commerce_entity_reference_delete() function that Drupal claims it can't find resides in:

  /[site]/profiles/commerce_kickstart/modules/contrib/commerce/commerce.module

Which, if I understand correctly is THE main commerce module that makes the whole shopping cart functionality work. So, my commerce module is enabled (because my shopping cart is working, and which is confirmed also on the Modules page), so why isn't commerce.module serving up the function above for me?

Aren't I allowed to call commerce_cart_order_product_line_item_delete() from a custom module?


texts: Multilingual article should display 404 when a translation is not available

texts:
I setup Drupal 8 with 2 languages English & Arabic.
Now when an article (English for eg.) does not have a translation (in Arabic) and the user switches the language from the menu. The page loads in Arabic and the article loads in English.
I need to return a 404 or something different.

Any advise would be helpful.


texts: How to resize an image programmatically when creating node?

texts:
I have created a content type with an image field. I have to add the content type programmatically.  From my form submit function I can get the fid like:

$product_image = $form_state['values']['announced_product_image'];

I'm wondering how I can programmatically resize an image when creating a node.

I have tried:

$test = file_load($product_image);
$img = image_load($test->uri);
image_resize($img, 200, 200);

But the image is not saving as 200x200.


texts: How does Drupal verify sessions from the cookie value?

texts:
Sorry, I know it's weird, but I'm trying to integrate another php application with Drupal.  I want to know if the user is currently logged in to the Drupal site, even though the request is going elsewhere.  I'm getting the cookie out of a Guzzle request object.  As far as the application is concerned (because of Nginx proxying), the origin is the same, and the cookie is getting passed successfully.

Here's what I'm getting out of the Guzzle request object:

array(1) {
  ["SSESSdbf18a05343cfb88719ee68ff6159a52"]=>
  string(43) "5eW8YPdDPjojAjuokObuD5R2L7cyOfffmBuVAdHzWwU"
}

The above value is also what the browser reports.

But, in my sessions table in the DB, there is no session that resembles this, either in the sid or the session column.

How does Drupal check the DB for a valid session cookie, and where should I be looking in core to copy this?


texts: Change workbench_moderation_state from select to radio

texts:
I have workbench installed, and want to change the moderation status dropdown in the add node form to a radio.
But I don't get it. I have a custom module with a hook_form_alter hook which prints the $form array via

  dsm($form)

This does NOT print any workbench_moderation_state variable.
If I print it via print_r($form), I get a

 [...]
 [workbench_moderation_state_new] => Array (
   [#title] => Moderation status
   [#type] => select
   [#options] => Array (
     [needs_review] => Current: Needs Review
     [draft] => Draft
     [published] => Published
   )
   [#default_value] => needs_review
   [#description] => Moderationsstatus für diesen Inhalt setzen.
   [#access] => 1
 )

So it has to be there.

Why is the workbench_moderation_state_new Array not displayed in krumo via  dsm(), but printed via print_r()
(more important) Why the f**k does a simple

  $form['workbench_moderation_state_new']['#type'] = 'radio';

  not change the select into a radio, but introduce a new empty radio button in the form? I tried to follow the Drupal form API.

Argh. As almost always, I found the answer myself 5 minutes after posting here. Cost me 3 hours of searching and try-and-error before. workbench_moderation_state_new is a sub-array of options.

So a $form['options']['workbench_moderation_state_new']['#type'] = 'radios'; does the trick. Mind 'radios' instead of 'radio' as well. For anyone interested.
Problem solved.


texts: Taxonomy Term View not showing image field

texts:
Drupal 7, Views 3

I have created a Taxonomy Term View for a particular vocabulary. If I set the Format Show option to "Fields", and add the Taxonomy name and image fields, then for some reason only the name shows. If I change it to "Rendered entity" then everything works fine. Another weirdness: this is only for some vocabularies - for some other vocabularies, the fields option works just fine (it shows the image). Any thoughts on why this might be? Any ideas how to debug this? Thanks guys.


texts:
In my website project, users can import youtube video via youtube url into their profile.

But I've no idea which module can do this.

Thanks for your help !


texts: Customize CKeditor/IMCE file upload function

texts:
D6 with CKeditor Module, CKeditor 3.6.4, and IMCE

This setup is working fine, but I dont want to use the 'Browse Server' Dialog. The ideal solution is to use the 'Insert File' Button (found on the Browse Server Dialog) instead.

So that the user is on a ckeditor form, clicks the image button, and on that dialog there is a button to upload a file instead of the 'Browse Server' button..everything else is the same. I'm looking on doing something similar on the link button.


texts: Module/code to automatically generate an id number for title of page

texts:
I want to automatically generate a project id. (To go where the title would go on a drupal webpage)

I am guessing this might be possible with php? But i don't know whether it is possible to do it for a title because I have only managed to acheive php in the code.

I want the title to identify a project and each project to have sub cases (also with unique identifiers).

I don't want the number to be randomly generated but rather it have some attributes that can be used to determine characteristics about the project.

Ideally, I want t end up with an id which is something like this eg

 Ldn101201

where
ldn is the city 10 is the start month 12 is the start year and 01 is the project number.

Ldn will be inserted because the user opening the project is based in london
1012 will be inserted because this was the date when the project was made
and the last number will be the generated number tagged on.

I really would be happy if I can at least get an ascending ids for when projects are created but if anyone has ideas about the more complicated part that would be great help also.

Hope that makes sense.


texts: After installing Drush on Mac it only downloads drupal 6x

texts:
I am having issues installing Drush on Mac OSX 10.9.5. I have tried a variety of methods. The most successful have been;

Using homebrew

Drush 7 using composer

Each method had produced a version of Drush, however each appears old and drush dl drupal downloads the 6.x version, as does drush dl drupal 7.x.

Can you please suggest:

1) How to ensure old versions of drush are removed to ensure that a new installation goes smoothly.

2) The recommended method for installing the latest stable Drush version on Mac OSX 10.9.5

I had tried to delete the old drush version manually by removing folders. Now the composer installation method seems to fail as I get:

Pauls-iMac:~ Trotter$ composer global require drush/drush:dev-master
Changed current directory to /Users/Trotter/.composer
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
  - Installing drush/drush (dev-master 78b1538)
    Cloning 78b15385ba97890dc3431790494f26d6be99ede9
    Failed to download drush/drush from source: The process "git clone --no-checkout 'git://github.com/drush-ops/drush.git' '/Users/Trotter/.composer/vendor/drush/drush' && cd '/Users/Trotter/.composer/vendor/drush/drush' && git remote add composer 'git://github.com/drush-ops/drush.git' && git fetch composer" exceeded the timeout of 300 seconds.
    Now trying to download from dist
  - Installing drush/drush (dev-master 78b1538)
    Loading from cache

    Skipped installation of bin drush for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.php for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.bat for package drush/drush: name conflicts with an existing file
    Skipped installation of bin drush.complete.sh for package drush/drush: name conflicts with an existing file

I can see that I don't have drush installed as what drush gives No such file or directory and drush info gives -bash: drush: command not found


texts:
I have a content type that has a field collection item, which is to be shown as select list. I am using hook_form_alter to do that. I also want a filter such that it picks node id from URL and sets values against that node to my select list. Here is my code:

 $url_arg=arg();
 $node_id=$url_arg[1];
 $node=node_load($node_id);
 $info = field_info_field('field_testing_code');
 $values = &$info['settings']['allowed_values'];
 $values= array();

I reinitialized the array to remove any existing values. Here is how I assigned values:

$i=0;
while($node->field_consignment_text_field[und][$i][value]){
  $values[$node->field_consignment_text_field[und][$i][value]] = $node->field_consignment_text_field[und][$i][value];
  $i++;
}
field_update_field($info);

Suppose I have 2 nodes A and B opened in two different tabs. A have field collection item values "11" and "22" while B has "33" and "44". On reloading both tabs it sets "11" & "22" or "33" & "44" to both tabs. On reloading one tab at a time, it gets correct value.

I think this is due to simultaneous calls to form_alter. How can I handle that? Is there any way to wait a process unless the other complete its execution?

Or any other solution?


texts:
I'm trying to create a json from Views, using Views Datasource.

The problem is that if I create a display "page", using Json as style, if I try to go to www.mysite.com/path/to/page the system doesn't return me the Json (as I see in the preview of the view) but an entire classic drupal page with the output of the json in the content region (so I've menus, regions, etc).

Is there a way to obtain the output as a simple json?


texts: How do I suppress a warning or error message for site users?

texts:
file_unmanaged_copy() drupal_set_message() on certain conditions. Even with visible errors messages disabled, anonymous users see this. Indeed, the comment in the code even has a TODO to change it to an exception.

Obviously I don't wish to hack core. Is there a clean way to suppress this for anonymous and non-administrator users?

Notably, the message is in a t() function, so I could use the String overrides module, but this would affect all users (including site administrator), so it's a bit problematic.


texts:
I'm trying to set up drush + phpunit, following these two guides:

the official Drush/tests/README.md
Getting Started Testing Drush Commands which is the most recent guide I could find

Here's what I have so far:

macOS Sierra 10.12.2
PHPUnit 5.7.5 at /users/wim.mostrey/.composer/vendor/bin/phpunit
Drush 8.1.9 at /users/wim.mostrey/.composer/vendor/bin/drush
Drush tests at /users/wim.mostrey/.composer/vendor/drush/drush/tests
a simple test migrateManifestTest at /users/wim.mostrey/.composer/vendor/drush/drush/tests/migrateManifestTest.php

I try to run the test using the following command:

UNISH_NO_TIMEOUTS=1 UNISH_DRUPAL_MAJOR_VERSION=8 ./unish.sh --filter=migrateManifestTest

However I get the following error:

PHP Fatal error:  Class 'Unish\UnitUnishTestCase' not found in /Users/wim.mostrey/.composer/vendor/drush/drush/tests/bootstrap.inc on line 51

I tried searching online for this error but got no results at all. I tried running both unish.sh and phpunit from different locations and using different configuration options, to no avail.

Any help would be highly appreciated.


texts: In a message about a new comment, how to tell if the comment needs approval or not?

texts:
I am currently using Triggers + Actions to send the node author an email when a new comment is added.

Some of the commentators on my site do not require approval (registered users and repeat commentators).

I would like to indicate in the mail whether the comment requires approval - or send a different message all together in this case. I didn't find any way to configure this.

Answers to a related question suggested the Rules module, but I didn't find a way to make a condition based on whether the comment needs approval.

Edit: I think that the relevant conditions is about comment:status. This field doesn't appear as a data selector in Rules, for some reason.


texts: How to display DB data from Custom module using custom HTML markup?

texts:
I am putting a custom module together. It will take data submitted from a form from site users and store it in the DB. Admins will then be able to review the data and make changes to it. It is easy enough to display the DB data with something like:

return theme('item_list', array('header' => $header,'items' => $rows));

But I need to customize it to have custom HTML markup. Any thoughts, answers or direction?


texts: How to create one node tpl files for multiple content types?

texts:
In my site I have 10-15 content types that have the exact same node template layout. Like node--productone.tpl.php, node--producttwo.tpl.php etc...

How can i create one node tpl files for that similar type of content types?


texts: Create hook menu with custom module (child/%)

texts:
In my custom module I want to create menu with the name "child/%" is it possible. When I create menu "child/test", whenever I load the page http://localhost/project/child/test it gives error page could not found. so if I run http://localhost/project/%E2%80%8Bchild/test like this it is working.
Its confusing, Kindly clarrify.

Thanks,
John.


texts: How to set root of programmatically rendered menu

texts:
I'm currently attempting to create a plugin where the user can choose what level of a menu to render regardless of what page they're on. I'm generating the form where the user can select the menu level here

public function blockForm($form, FormStateInterface $form_state) {
    $menu_name = 'main';

    $menu_tree = \Drupal::service('toolbar.menu_tree');

    $parameters = new \Drupal\Core\Menu\MenuTreeParameters();
    $tree       = $menu_tree->load($menu_name, $parameters);

    $manipulators = array(
        array('callable' => 'menu.default_tree_manipulators:checkAccess'),
        array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
        array('callable' => 'toolbar_menu_navigation_links'),
    );

    $tree = $menu_tree->transform($tree, $manipulators);
    $list = ['none' => $this->t('None')];
    foreach ($tree as $item) {
        $list += [$item->link->getPluginId()=> $item->link->getTitle()];
        if ($item->hasChildren) {
            foreach ($item->subtree as $subitem) {
                foreach ($subitem->subtree as $subitem_child) {
                    $list += [$subitem->link->getPluginId() => '-'.$subitem->link->getTitle()];
                    foreach ($subitem->subtree as $sub_subitem) {
                        $list += [$sub_subitem->link->getPluginId()=> '--'.$sub_subitem->link->getTitle()];
                    }
                }
            }
        }
    }

    $form        = [
        'menu'            => [
            '#type'          => 'select',
            '#title'         => $this->t('Top level of menu'),
            '#default_value' => $this->configuration['menu'],
            '#options'       => [
                $list,
            ],
        ],
    ];

    return $form;
}

This works, and the user can select the level of the menu they want, but I'm not sure what to use in order to render the menu at that level. I did see that I could get a plugin

    $menu_name  = 'main';
    $menu       = $this->configuration['menu'];
    $menu_tree  = \Drupal::service('toolbar.menu_tree');

    $parameters = new \Drupal\Core\Menu\MenuTreeParameters();
    $tree = $menu_tree->load($menu_name, $parameters);

    $manipulators = array(
        array('callable' => 'menu.default_tree_manipulators:checkAccess'),
        array('callable' => 'menu.default_tree_manipulators:generateIndexAndSort'),
        array('callable' => 'toolbar_menu_navigation_links'),
    );

    $tree = $menu_tree->transform($tree, $manipulators);
    foreach ($tree as $item) {
        var_dump($item->hasChildren);
        if ($item->hasChildren) {
            var_dump($item->link->getTitle().' - '.$item->link->getPluginId());
            foreach ($item->subtree as $subitem) {
                var_dump($subitem->link->getTitle().' - '.$subitem->link->getPluginId());
                foreach ($subitem->subtree as $subitem_child) {
                    var_dump($subitem_child->link->getTitle().' - '.$subitem_child->link->getPluginId());
                    var_dump($subitem_child->link->getTitle().' - '.$subitem_child->link);
                }
            }
        }
    }

I have the pluginID of the selected in the form, but I'm not sure how to make any use of that. I tried using
        $parameters->setRoot('818bf040-f12a-4915-835f-b9339eb7c828');

Where 818bf040-f12a-4915-835f-b9339eb7c828 in this case was the pluginid of the selected menu item, but that caused the menu to not return anything.

Is there a way to render a menu and set the root to a specified location inside that menu programmatically?


texts: Can drush accept piped commands for aliases?

texts:
Can drush take piping commands for a multisite command using an alias?

I'm trying to setup a simple refresh function from my prod to dev/staging. Any pointers or tips would be welcome. just started learning this stuff.

drush $prodalias sql-dump --gzip >/tmp/$site.sql.gz

gunzip /tmp/$site.sql.gz | drush $devalias sqlc


texts: Fatal error: Unsupported operand types in form.inc

texts:
I'm getting the following error message:

  Fatal error: Unsupported operand types in /var/www/public_html/domain.com/includes/form.inc on line 1079

It seems to be because the following code for an admin menu.

function MY_MODULE_admin_menu() {
  $menu_items = db_query("SELECT * FROM my_module")->fetchAll();
  $header = array('Template ID', 'Name', 'Type', 'Template');
  $rows = array();
  if (!empty($menu_items)) {
    foreach ($menu_items as $menu_item) {
      $rows[] = array($menu_item->tid, $menu_item->name, $menu_item->type, $menu_item->template);
    }
  }
  return theme_table(array(
    "header" => $header,
    "rows" => $rows,
    "attributes" => array(),
    "sticky" => true,
    "caption" => "",
    "colgroups" => array(),
    "empty" => t("Table has no rows"),
      )
  );
}

What's causing this? As far as I can tell, this is how it is supposed to look for Drupal 7.


texts: How to update disabled modules using Drush?

texts:
Is there a way to update disabled modules with Drush?

Currently, when I try to update a disabled module with Drush, I get this message:

  Project has no enabled extensions and can't be updated

Enabling the module is not an option as this is a live site, actually many sites. They all run off of the same Drupal code base. Some modules are used by some sites but not others (possibly not on the main site).

If Drush can't handle this, what's an easy alternative for updating modules?


texts:
I'm not necessarily looking for a module for this, but I'm curious where to start to get the following functionality:

Each content entity has an unlimited amount of image fields. So if I had 5 images I want to be able to "scroll" through them on the frontpage. The scrolling functionality is that when you hover over the image, it shows different images. The frontpage is generated by a view

I'm basically making a TV show site with screenshots and I want the user to be able to preview some screenshots on the frontpage by simply hovering over the episode image.


texts: How to set DataDefinition::create('integer') to allow bigint numbers

texts:
I'm trying to create a FieldType in Drupal 8 which needs to be stored as bigint.
I set the field in the schema:

public static function schema(FieldStorageDefinitionInterface $field_definition) {
return array(
  'columns' => array(
    'value' => array(
      'type' => 'int',
      'size' => 'big',
      'not null' => FALSE,
      'unsigned' => TRUE,
    ),
  ),
);

}

I then added the propertyDefinitions:

public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
$properties['value'] = DataDefinition::create('integer')
  ->setLabel(t('Field value'));

return $properties;

}

When trying to add an integer of more than 9 digits I get following validation error:

  This value should be of the correct primitive type.

How can I get this correct?

Thanks!


texts: How to concatenate fields in Views with different separators (Settings)?

texts:
I have 4 fields : lastname, firstname, middlename, suffix

I selected TABLE Format. In the Settings tab, I put all fields together in the first column so I can have them together in one row, but I want the display to be:

Jones, John David Jr

instead I can get

Jones John David Jr

or

Jones, John, David, Jr

In other words, the separator is applied between every field, and I want it applied only after the first.

I tried the UNFORMATTED LIST but that didn't provide me with any way to concatenate.


texts: On content edit, how can I check/select a bool field based on which tab is active?

texts:
I have a content type with a paragraph that has two fields, each field inside its own tab controlled by the form display like so:

Here is what the set of tabbed fields looks like when editing a piece of content of the content type:

The paragraph also has a bool field called field_active_callout_tab with two values: 'Single' and 'Multi', same as the tabs.

If the 'Single' tab is clicked, I want the bool to be checked. If the 'Multi' tab is selected, I want the bool to be unchecked.

I tried to use the Conditional Fields module, but it will not allow control by tab label. How can I establish this dependency between the tab and the bool?


texts: How can I create a menu item corresponding to a link to another (external) site?

texts:
In my menu I can create an internal link corresponding to a path like → '/path/to/node'.

But when trying to create a link to an external website (like → http://www.external.com), the link actually becomes → https://www.mywebsite.com/http://www.external.com

So basically, external links are not recognized as external. But instead they get added to the base URL.

How can I make this to work?


texts: How to programmatically set a node field as empty?

texts:
I have some nodes of a content type with following fields:

title
body
image

I want to programmatically (!important) set the body field as empty (to make it like it was never set with any value).

This is what I have done:

$this_node = node_load($nid);
$this_node->body = array(); //to set it as an empty field
node_save($this_node);

After executing this, the node is not saved. Instead, in db_log following error is loged:

PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '104418'
for key 'PRIMARY': INSERT INTO {node} (nid, vid, type, language, title, uid, status, created,
changed, comment, promote, sticky, tnid, translate, uuid) VALUES
(*******placeholders & their values*******) in drupal_write_record()
(line 7170 of /var/www/rotary.local/docroot/includes/common.inc).

Is there someting I am missing? How I can set the body field as empty?

NOTE:

I don't want to use field_attach_update for caching purposes.


texts: Language switcher using get language variable instead of prefix in Drupal 8

texts:
In Drupal 8 setting  url with path prefix for language detection, works fine. But when I include the language switcher block included with Drupal, the links instead of using the language prefix, show links using the variable language in the url.

How can I make the language switcher make use of the language prefix instead?


texts: how to replace title field with some other field in entity reference field list?

texts:
I created a content type 'country' with three fields title,description,code and i referred this content type 'country' in content type 'city' using entity reference module. In the creation page of the content type 'city' it displays a dropdown with the list of 'country's  title. every thing working fine.

but i want concatenated value of title and code in the drop down list is it possible ?


texts: How to add to 'Secondary Local Tasks' on Order page

texts:
Can someone tell me how I can add another item on the Orders page to the existing 'Secondary Local Tasks' which is currently two buttons :- 'Apply Pricing Rules' and 'Simulate Checkout Completion'.

I am overriding page--admin--commerce--orders.tpl.php and would like to add a button to the $secondary_local_tasks variable but can't find where it's set. It's not a menu and isn't in template.php. Any ideas?


texts:
I got my database crashed and fixed it, but some tables missed some of its data. one of these tables are the table that contains the preset values for imagecache (imagecache v 1.6.2.1, Drupal 6.19).

mysql> select * from imagecache_preset;

+----------+-----------------------------------------+
| presetid | presetname                              |
+----------+-----------------------------------------+
|        1 | article_headline_main                   |
|        2 | article_headline_thumb                  |
|        3 | article_headline_node                   |
|        4 | article_behind_the_news_old             |
|        5 | article_main_news_old                   |

By editing any of the above presets, i found that it is UNSET and I have to respecify action, height and width.
I have a dump of my database, but I need to know the table that contains the preset values so I can get them back from the backup. Which database table is it?


texts: what is the strongarm variable addititonal_settings_active_tab_*

texts:
I am using the Features and Strongarm module to move my work between sites. I am using them as a way of version controlling changes made in the database (as Configuration Management module has many issues.)

I am trying to understand what the following settings are, which module (or core) creates them, and should they be passed from site to site:

 additional_settings__active_tab_chapter
 additional_settings__active_tab_committee
 additional_settings__active_tab_document
 additional_settings__active_tab_event
 additional_settings__active_tab_jcr_article
 additional_settings__active_tab_jcr_issue
 additional_settings__active_tab_news
 additional_settings__active_tab_page
 additional_settings__active_tab_success_stories

The last piece of these settings ie: 'chapter' are the names of the content types on the site. Should I be passing these variables?


texts:
Trying to manipulate a form that can be a select / radios or text field based on the user configuration...

If the user wants to use radios for the form... then my module will render the  using standard drupal render system.

However when I use theme('radios',$variables['element']) it doesn't work at all... the output is:

However if I use: drupal_render_children($variables) it works perfectly...

Any clues on why theme('radios') behave differently as the rest of the form API items?

This is the code I'm using:

  $form['radio_test'] = array(
    '#type' => 'radios',
    '#title' => 'test',
    '#options' => array( 'a', 'b', 'c' ),
  );

  dpm(theme('radios',$form['radio_test']));

And this is the output


texts: How to add JavaScript to a specific View if I don't know the node?

texts:
I've seen the answer here using the NID but I don't know this, I only have the URL. Is there is another way to do this please?
function MY_THEME_preprocess_node(&$vars) {
    if($vars['nid'] == 'XX'){
      drupal_add_js('path/to/js/file.js');
    }
}


texts: "An illegal choice has been detected" error on user creation

texts:
When creating a new user, I got this error:

  An illegal choice has been detected. Please contact the site administrator.

I'm sure I entered all the required information. This is when I am logged-in as administrator.
I'm using drupal 7.10.

[Edit]
I have a few lines of code in my hook_form_alter() which alters the user registration form :

if($form_id == 'user_register_form'){
    $form['profile_main']['#weight'] = 10;
    # Password and Confirm password
    $form['account']['pass']['#weight'] = -9; # move above E-mail address
    # User role
    $form['autoassignrole_user']['#weight'] = 2;
    $form['autoassignrole_user']['user_roles']['#attributes'] = array('onclick' => "Drupal.mymodule.toggleProfile(this)");
    if(in_array('administrator', $user->roles)){ # if master administrator, hide it
        $form['autoassignrole_user']['#required'] = FALSE;
        $form['autoassignrole_user']['#type'] = 'hidden';
    }
}
elseif($form_id == 'user_profile_form'){
    if(!in_array('administrator', $user->roles)){ # if not administrator
        $elems[] = 'timezone';
        $form['timezone']['#required'] = FALSE;
        $form['timezone']['#type'] = 'hidden';
    }
}


texts: Taxonomy autocomplete - show results of words starting with letters written

texts:
I am having hard time to explain this but this is the case:

I have taxonomy with 80000 terms (country/city).

When i type for example "N" or "NE" or "NEW" i get results with terms that contain all type.
So for "NEW" in autocomplete i get:
Abercarn-Newbridge
Ballycanew
Binhai New Area
Bowmanville-Newcastle
Carnew etc...

What i would like is to get:
New York
or
New Zeland
or any other city/country that starts with letters which i input.

I installed and tried http://drupal.org/project/taxonomy_autocomplete_settings which works but only for views exposed filter which is great.

Problem is that for node/add node/edit it doesnt work. (as explained here http://drupal.org/node/1527756 .Autocomplete circle just keeps spinning not showing any results.)

I have to use autocomplete for add/edit becouse Hierarchical select module is taking around 20-30 to load for parent and that much for child term too while autocomplete reacts in miliseconds.


texts: How do I save a managed_file to a user profile in a hook_submit

texts:
I'm trying to save a file that the user has uploaded using my form.

My form:

$form['fifth']['field_cv'] = array(
        '#title' => t('CV'),
        '#type' => 'managed_file',
        '#size' => 19,
        '#upload_location' => 'public://',
    );

My validator using hook_validate:

$file = file_load($form_state['values']['fifth']['field_cv']);
// Change status to permanent.
if($file) {
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);
    file_usage_add($file, 'popover', 'document', $file->fid);
}
else {
    form_set_error('CV', t('Er is geen cv geüpload'));
}

So now in hook_submit how do I add this to the user? Do I need to create an extra database field for this? And should I save only the $fid ( file id ) in this field?

OR

Is there a better way so drupal takes care of this and also revisions of this field are saved?

building this in D7


texts:
I try to print field value in a node--template.html.twig without whitespace.
This field is a select in admin page.

Location|Location
Achat|Achat

This is how my value is print :

  {{ content.field_type }}

  field.html.twig :

{% for item in items %}
{{- item.content -}}
{%  endfor %}

I try some twig argument like

  {{content.field_type|trim}}

But when i print like this, it's empty.

So where are this whitespace ? same if i try to test the value in if else condition :

This doesn't work because of whitespace :

  {% if  content.field_type == "Achat" %}

This work :

  {% if  content.field_type|render|trim == "Achat" %}

So for test a value it's ok, but for print the value if i use

  {{content.field_type|render|trim}}

i got same result with whitespace.

So if someone can tell me where is add this whitespace and how remove this in twig.
I use the boostrap theme, but i don't see anything who add whitespace.


texts: classified ads: paid option with rules and commerce

texts:
I am trying to create a classifieds site like the site "leboncoin.fr".

I block me at establishing a system of paying options for the advertiser:

Paying options:

promote your ad for one week (€ 30); for a month (80 €)
add 7 photos and more
add a logo

You will find an attached image of the example of boncoin

I know that the modules Trade and Rules must be used, but I can not get it to work.


texts: Alternative #markup in a block's build function

texts:
Version: Drupal 8.7.x

I am adding some canvas element to my page, and it gets ignored by Drupal. I can't even see it in the source page of browser.

If I have something like this in my code:

public function build(){
   $content = "Something<canvas id='12' width='100' height='100'>
               </canvas>"
   return ['#markup'=>$content];
}

View page source will only shows

 Something

I was thinking that this might be an issue with the #markup. I was wondering if there are any alternative way to work with canvas.


texts: How do I set the total submissions limit when I create a node?

texts:
I'm using "Webform Node" module to create event registrations.

Now I can set the total submissions limit of event in Structure> Webforms> my webform type

and when I create a webform node, there is no setting option:

Because every event has different submissions limit, I want to set the limit when I create the webform node, instead of in the webform type, how can I do it? thank you so much!


texts:
I created a custom field. The hook_field_widget_form has an submit element with an ajax callback:

  //Add more
  $element['add_zone'] = array(
    '#type' => 'submit',
    '#name' => $field_name . '-add_more-' .'name',
    '#value' => t('+'),
    '#limit_validation_errors' => array(),
    '#submit' => array('dms_polygone_add_more_add_one'),
    '#ajax' => array(
      'callback' => 'dms_polygone_add_more_callback',
      'wrapper' => 'zones-fieldset-wrapper-'. $field_name,
    ),
  );

I add 2 fields of my custom field type to a node. Ex: field_polygone (field type: polygone) and field_polygone_2 (field type: polygone).
When i press the 'add_more' button of my first field_polygone, my callback function 'dms_polygone_add_more_add_one' thinks the trigger element is field_polygone_2.

Callback function:

function dms_polygone_add_more_callback($form, $form_state) {
  //@todo: $i gebruiken voor veld als er meerdere waardes zijn toegestaan.
  $parents = $form_state['triggering_element']['#parents'];
  return $form[$parents[0]][$parents[1]][$parents[2]]['zones'];
}

$parents[0] is the field_name => When i press 'add_more' , the $parents[0] variable in the callback function should be 'field_polygone', but its field 'field_polygone_2'.

How can is solve this problem? Why does the callback function think the trigger element is field_polygone_2 instead of field_polygone.


texts:
I need to fill Billing Info form with data that the user has filled in another page of my commerce site.

I've made a hook_form_alter with the following weird code (with the help of kint):

function HOOK_form_alter(&$form, $form_state, $form_id) {
   switch ($form_id) {
    case 'commerce_checkout_flow_multistep_default':
      $form["payment_information"]["add_payment_method"]["billing_information"]["address"]["widget"][0]["address"]["#default_value"]["given_name"]="NAME";
      $form["payment_information"]["add_payment_method"]["billing_information"]["address"]["widget"][0]["address"]["#default_value"]["country_code"]="IT";

It works with name but it does not select the country code; i would also like to hide some fields (like address2) ... is there a way to unset() or hide() a field? If i try to hide($form[....]) it does not hide it because it only contains the item value. I have not found a way, indeed, to modify/insert fields for this form.

I know i can do it via CSS, but i would prefer to do it in form_alter.


texts:
After I installed and enabled the webform module, my admin toolbar got messed up.

Whenever I click on 'Content -> Add Content' I immediately get redirected to #overlay=node/add/webform. I can still go to the separate content types by altering the link (eg. '#overlay=node/add/news').

I have tried disabling the module and uninstalling / reinstalling, but to no avail.

Is there a way to restore the functionality?

EDIT: Apparently my content types have disappeared...


texts: How to execute system cron manually via drush or drupal UI?


texts: How do I programmatically create an entity reference in hook_entity_info()?

texts:
Is there a way to create an entity reference in hook_entity_info? I was hoping for something like the following.

'entity keys' => array(
  'id' => 'id',
  'store_ref_id' => 'store_ref_id',
),

I have a content type store with its ID, and a new entity_type product. I would like to have a field in the new entity referenced to content type.

How can I do this?

Would it be better to re-use the already created field, which is used as reference between content types?


texts: Unable to retrieve node object in a block without access permission to said node

texts:
I'm trying to do a little statistics on nodes and display it on a block. I utilized menu_get_object('node', 1, $path) to get the node object of those nodes with the properties that I want.

So my problem is, in admin accounts, this works fine and well. however, in a normal user account, menu_get_object('node', 1, $path) returns null for any node that the normal user has no access to. is there any way to circumvent this?

So far I've tried using node_load(), and I also tried putting all the data analysis code inside a hook_cron(). Neither worked.

Using db_query() is not an easy task either, as I'm trying to obtain the node's parent node,and that parent's node parent node. That data is serialized. If it matters, I'm using Open Atrium, and I'm trying to obtain the topmost Space for a particular node.


texts: why does drupal_get_path() not work in my code?

texts:
somehow drupal_get_path is not working I'm my module in my function vacancies_manage_test_pager()

drupal_get_path() returns notting ( empty string or NULL or something ) when I DSM(drupal_get_path('module','vacancies_manage')); I get an empty message

module code:

/**
 * Implements hook_permission
 */
function vacancies_manage_permission() {
    return array(
        'manage own vacancies' => array(
            'titel' => t('Manage own vacancies'),
            'description' => t('Allows users use the own vacancies page'),
        ),
    );
}

/**
 * Implements hook_menu
 */
function vacancies_manage_menu(){
  $items = array();

    // Test items
    $items['vacancies_manage'] = array(
      'title' => 'Vacatures beheren',
      'description' => 'Eigen vacatures beheren.',
      'type' => MENU_NORMAL_ITEM,
      'page callback' => 'vacancies_manage_test_pager',
      'access arguments' => array('manage own vacancies'),
    );

    // needed for jQuery / ajax callback
    $items['vacancies_manage/callback'] = array(
      'title' => 'vacatures beheer Callback',
      'type' => MENU_CALLBACK,
      'page callback' => '_vacancies_manage_test_pager_callback',
      'access arguments' => array('manage own vacancies'),
    );

    return $items;
}

function vacancies_manage_test_pager() {
    drupal_add_js(drupal_get_path('module', 'vacanies_manage') . '/jquery.url.js' );
    drupal_add_js(drupal_get_path('module', 'vacanies_manage') . '/vacanies_manage.js' );
    drupal_add_js('initializeTable();', 'inline');

    return ('

');
}

function _vacancies_manage_test_pager_callback() {

    global $user;

    header("Content-type: text/html");
    header("Expires: Wed, 29 Jan 1975 04:15:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-cache, must-revalidate");
    header("Pragma: no-cache");

    // build header for HTML table

    $header = array (
        array('data' => t('Titel')),
        array('data' => t('Aangemaakt op')),
        array('data' => t('Gepubliceerd')),
        //array('data' => t('Dupliceer')),
    );

    // query db for user nodes
    $query = db_select('node','n');
    $query->fields('n', array('nid','title','created','status'));

    if($user->uid !== "1" ) {
        $query->condition('n.uid', $user->uid);
    }

    $results = $query->execute();
    dsm($results);

    // display nodes
    $rows = array();

    foreach($results as $vacancy) {
        $rows[] = array(
            'data' => array(
                $vacancy->title,
                $vacancy->created,
                ($vacancy->status == 1?t('Ja'):t('Nee')),
                //dupliceer
            ),
        );
    }

    //Theme the html table
    $html = theme('table',
        array(
            'header' => $header,
            'rows' => $rows,
            'sticky' => TRUE, // Optional to indicate whether the table headers should be sticky
            'empty' => 'U heeft geen vacatures.', // Optional when no results
        )
    );

    $html .= theme('pager',
        array(
            'tags' => array(),
        )
    );

    die($html);
}


texts:
I'm creating a mobile app in Ionic (which uses Angular). I've set up a D8.3-dev BE which will hold the users and their data.

I've figured out how to register as an anonymous user (this is why I'm using D8.3-dev because this functionality is introduced here) and wrote a blog post about it (https://fonsvandamme.be/en/blog/how-create-user-rest-drupal-8).

Logging in also works after I registered a user.

This is how I login:

  /*
   * Login User with username and password.
   */
  login: function (email, password) {

    var defer = $q.defer();

    $http({
      method: 'POST',
      url: config.endpoint + '/user/login?_format=json',
      data: {
        name: email,
        pass: password
      },
    })
      .success(function (data, status, headers, config) {

        // Store the CSRF token.
        localStorage.set('csrf_token', data.csrf_token);

        // Store the Logout token
        localStorage.set('logout_token', data.logout_token);

        // Set the user object.
        localStorage.setObject('user', data.current_user);

        defer.resolve(data);
      })
      .error(function (data, status, headers, config) {
        defer.reject(data);
      });

    return defer.promise;
  },

When logging in I receive the following:

current user object, a csrf_token and a logout_token.

When I use these tokens to logout (I tried a lot of different ways already:

  /*
   * Logout User.
   */
  logout: function () {

    var defer = $q.defer();

    $http({
      method: 'POST',
      url: config.endpoint + '/user/logout?_format=json&token=' + localStorage.get('csrf_token'),
      dataType: 'json',
    })
      .success(function (data, status, headers, config) {
        defer.resolve(data);

        // Go to the login page.
        $state.go("login");
      })
      .error(function (data, status, headers, config) {
        defer.reject(data);
      });

    return defer.promise;
  },

I keep getting the following error:

{"message":"\u0027csrf_token\u0027 URL query argument is invalid."}

So it seems the crsf_token I use from logging in isn't correct.

What am I doing wrong or overseeing here?

EDIT: after testing a lot and trying it seems like I need to use get. I use this code now for logout but I still get a 403:

  /*
   * Logout User.
   */
  logout: function () {

    var defer = $q.defer();

    $http({
      method: 'GET',
      url: config.endpoint + '/user/logout?_format=json',
      headers: {
        'X-CSRF-Token': localStorage.get('csrf_token'),
        'Authorization': 'Basic xxxxxxxxx',
      },
    })
      .success(function (data, status, headers, config) {
        defer.resolve(data);
      })
      .error(function (data, status, headers, config) {
        defer.reject(data);
      });

    return defer.promise;
  },

Here is what the Drupal 8.3-dev BE returns, it seems like it recognizes the user I want to log out but it's still throwing the 403.


texts:
on my website, i have articles. All of them have custom field named event date. I want to select 50 nodes of type article with event date value "2016-07-29 16:25:00". How to do this?

I tried following code, but it looks like query cannot find any custom field column.

$nids = db_select('node', 'n')
->fields('n', array('nid'))
->fields('n', array('type'))
->fields('n', array('field_event_date'))
->condition('n.type', 'article')
->condition('n.field_event_date', "2016-07-29 16:25:00")
->range(0, 50)
->execute()
->fetchCol();


texts: Strict warning: Only variables should be passed by reference in Open Restaurant

texts:
I installed Open Restaurant based on Drupal 7.x.

As soon as I insert any menu item into create categories, I get this warning:

  Strict warning: Only variables should be passed by reference in sizzle_preprocess_views_view__content__menus__all_menus() (line 69 of /web/htdocs/xxxxxxxxxxx/home/profiles/restaurant/themes/sizzle/includes/menu.inc).

I checked the line and I got this code:

// Render the category and add it to template.
$variables['term'] = drupal_render(taxonomy_term_view($term, $view_mode));

I don't know how to improve this, in order to solve the issue.
Writing to the group that made Open Restaurant I didn't got any answer. Hence my post here.


texts: views contextual filter based on NID that is selected from a list

texts:
I have a slideshow in front page build by with Views and placed by Panels.

Currently i'm using contextual filter based on Nid and end user should enter Nids in Panels pane setting like "6,14,54,98" but it's not user friendly.

I need a list of nodes that end user can select nodes and the list automatically returns Nids.


texts: How to check in a rules condition if an image field has value?

texts:
Is there any way to check if a field has no value (image field) after saving the content in Rules? I tried Data Value is Empty, but it doesn't work!

Output of the rules:

{ "rules_autos_featured_listing_without_image" : {
    "LABEL" : "Autos: featured listing without image",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "TAGS" : [ "autos" ],
    "REQUIRES" : [ "rules" ],
    "ON" : { "node_insert--listing" : { "bundle" : "listing" } },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_listing_grouping" } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_feature" } },
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_images" } },
      { "data_is" : {
          "data" : [ "node:field-feature" ],
          "value" : { "value" : { "feature" : "feature" } }
        }
      },
      { "data_is_empty" : { "data" : [ "node:field-images" ] } }
    ],
    "DO" : [
      { "data_set" : { "data" : [ "node:field-listing-grouping" ], "value" : "1302" } }
    ]
  }
}


texts: Create a view which shows related staff members based on taxonomy

texts:
I wish to show relevant staff members when users a viewing a particular page. For example when certain pages about membership are being viewed i wish to show the staff members designated as a 'Member Relations Officer'. I have a taxonomy called 'selected job roles', in which 'Member Relations Officer' is a taxonomy term. At the moment I have set up the staff members as users on the site, therefore they are not a distinct content type. I have added a 'selected job roles' term reference to the user fields within Account Settings.

I also added the 'selected job roles' term reference to the basic page content type. I have created a view block called 'selected job roles' in which I am trying (and failing) to set up a contextual filter correctly to show the staff members. I have a basic page with 'selected job roles' set as 'Member Relations Officer' and also a user with 'selected job roles' set as 'Member Relations Officer'. I have been trying to get it to work by doing things like setting up the contextual filter get the 'taxonomy term from url' when the 'Filter Value is not available'. However none of the contextual filter settings i have tried work.

Could somebody please advise me what settings i should using in the contextual filter? Was setting up the staff as users a mistake that is stopping this from working properly? Thank you in advance.