texts: How to associate programatically the translation of new term to the original existing term?

texts:
I've terms which share the same id in stored in field and I'd like to associate translation between them, so they're grouped on the same page at /taxonomy/term/%/translate

So I've existing original English term, then I'm creating manually term with different language, so I'm expecting this term to associate with the original one.

Not sure which hook would be the best, or it doesn't matter:

hook_taxonomy_term_presave
hook_taxonomy_term_insert

So in example I've:

/**
 * Implements hook_taxonomy_term_presave().
 */
function foo_taxonomy_term_presave($term) {
  $bundle = 'countries'; // Example bundle name
  $vid = ($voc = taxonomy_vocabulary_machine_name_load($bundle)) ? $voc->vid : NULL;
  if ($term->vid == $vid && module_exists('i18n_string') && $term->language <> 'en') {

    if ($shared_id = $term->field_shared_id[key($term->field_shared_id)][0]['value']) {

      // Find term which points to the same country, but in English
      $query = new EntityFieldQuery();
      $org_term_res = $query
        ->entityCondition('entity_type', 'taxonomy_term')
        ->entityCondition('bundle', $bundle)
        ->propertyCondition('vid', $vid)
        ->fieldCondition('field_shared_id', 'value', $shared_id, '=')
        ->propertyCondition('language', 'en')
        ->execute();

      // Load term in the main language
      if ($org_term = taxonomy_term_load(reset(reset($org_term_res))->tid)) {
        // If original term is loaded, continue translation
        $langcode = $term->language;
        $key = i18n_object_info('taxonomy_term', 'key');

        $result_translation = i18n_string_translation_update(
          array('taxonomy', 'term', $term->{$key}, 'name'), // Array or string concatenated with ':' that contains textgroup and string context where to store source and translation.
          $term->name,      // Translation string for this language code.
          $langcode,        // The language code to translate to a language other than what is used to display the page.
          $org_term->name   // Optional source string, just in case it needs to be created.
        );
        watchdog('foo', "Added !source translation: !translated in !lang (key: !key)", array('!source' => $org_term->name, '!translated' => $term->name, '!lang' => $term->language, '!key' => $term->{$key}), WATCHDOG_NOTICE);

      } // end: if

      i18n_string_object_update('taxonomy_term', $term); // not sure if it's needed for something

    } // end: if
  } // end: if

}

So the main translate part is in i18n_string_translation_update().
But it simply doesn't work as expected. The $result_translation returns the right data, but the association is not visible in UI at taxonomy/term/%/translate

There is no much documentation about it apart of Using the i18n API from other modules

So I'm using the right function in the right way?

Related:

how to get the translated taxonomy term programmatically?


texts: Theming blocks individually, by region, or by module

texts:
I want to create a bock template for a certain region & a certain module. Drupal 8 does not offer these hook suggestions. In Drupal 7 it was easy to do.

I want to create block--[region]--[module].html.twig. How can I add this theme suggestion?


texts: Which type of page to use for a customized front page in Drupal 7?

texts:
I am watching the following tutorial on panels. The author is creating a content type for 'Home page', and later, a node view variant of node templates. He mentions that he is not 100% about this way of proceeding, but he is used to it.

The more I learn about this subject and the more I try to replicate this approach, the less I am convinced by it. Creating a content type for a home page seems like an heresy.

The panels dashboard offers to create panel pages, but also landing pages. It seems to me like a landing page would be enough (after setting it as the default front page), but would a panel page offer more benefit in this case?


texts:
First of all this question is exact copy of this one (I'm sorry for that). But I don't get one thing.

My content-specific theme function works fine!
I have a theme, called "nbttheme" and content type with machine name "nbt_text"

and declaration of

function nbttheme_node__nbt_text(&$variables) {
    return "hello";
}

does the work, I have only "hello" in node output. So the theme function EXISTS, contrary to what mr. Clive had said. Am I wrong?

And, if the theme function works then there must be a preprocess for it, called nbttheme_preprocess_node__nbt_text() but this doesn't work

So where am I wrong? It seems inportant for me and I want to understand Drupal's theming flow entirely.

P.S. This way has worked for with views, there is a template for row output in my project: views-view-fields--latest-additions.tpl.php, hence I would have had a nbt_views_view_fields__latest_additions() function for theming.


texts: Drupal 7 sessions wiped after changing settings.php

texts:
Yesterday afternoon I had an administrator uncomment and modify the $base_url variable in our production environment. Any changes made in the repository fires off a redeployment which has never been an issue. Upon the server coming back up, we started receiving complaints that user's who were now logged out.

Does changing settings.php do something behind the scenes that I'm unaware about (session.cookie_lifetime or session.gc_max_life).

I do not have access to the database nor can I retrieve it from our prod environment.

Any help is appreciated so that we don't run into this issue again!


texts: Adding child elements to checkbox/radio form elements

texts:
How can I add child elements to a checkbox/radio element? I have the following code.

$form['search_product'] = array(
    '#type' => 'radio',
    '#title' => t('Product'),
);

$form['search_product']['search_attributes'] = array(
    '#type' => 'checkboxes',
    '#options' => array(
        'name' => t('by Name'),
        'model' => t('by Model'),
        'catalog_no' => t('by Catalogue No.'),
        'manufacturer' => t('by Manufacturer'),
        'description' => t('by Description'),
    ),
);

"search_attributes" checkboxes don't show up on the form, and I have only one radio.


texts: Facebook share is not working (Drupal 6)

texts:
facebook share is not working on my Drupal website which is in Drupal 6 and using php 5.3. Attached is the snapshot of the share button. While sharing the content it is navigating to site search link (I can't attach snapshot of the problem as i am a new user of this website)

Please suggest how to over come from this problem....


texts: Redirect to main view URL when no contextual filters are set

texts:
I have a view in drupal 7 with no contextual filters at all set.

Let's say it is a simple list of nodes of the type "item" and that the url is http://example.com/listofitems

I also have pathauto patterns set for the individual nodes. So if an item titled "my item" is created the url would be http://example.com/listofitems/my-item
This is important to know because I don't want to set another view for the path listofitems/%.

Given that no view or URL alias exists for listofitems/foo I expected that this URL would give a 404 error: http://example.com/listofitems/foo

Instead it shows the full view with no errors.  This is confusing and bad for SEO.  If a bot hits http://example.com/listofitems/foo/bar/foo/bar/foo/bar/blahblahblahblah they should get a 404 message.  Or better yet, they could get a 301 redirect to the main view url.  In any case, they should not be allowed to stay on the non-existant URL and see the view with no errors.

How can I accomplish this?  Is there a trick I'm missing or a reason that this is the default behavior?


texts: Should we use Drupal Commerce for a real estate site?

texts:
we are about to build a real estate website for a property agency. The site allows visitors to look for apartment for rent/sale.

Property search is actually the first main functionality. Users can search real estate with its attributes such as: price, land area, building area, number of room, facilities, etc. Second main functionality is they can also filter the property list (search result), sort or paginate it.

The visitors can make a contact too, just a simple form with anonymous user information and an ID of real_estate content type maybe. Users don't have to login to contact.

The following features is not needed: User authentication, Checkout Progress, Payment, Cart, Order, Comment, Discount, Shipping, Taxing.

We wonder if we can use Drupal Commerce to get quickly some out-of-the-box features (advanced search, filterable/sortable list) or it's better to build things from scratch.

PS: We've found "A Real Estate Website Using Drupal" but we still wonder if the Drupal RETS Real Estate Framework (dRealty) module can fulfill our requirements and if the first answer is still consistent as it has 6 years old.


texts: Transfering a drupal site from localhost to online and viceversa

texts:
I am about to finish my first Drupal site and I wish to upload it on the server. However, I am going to add content when the site is online but every time I make a change online I would like to add that change to the site on localhost (changes in content, new module additions, etc.). What is the least time consuming way to achieve this?
With .html sites it is very easy because you only need to have the .html file saved offline and online and that it is. What things do I need to consider with a Drupal site? I would like to always have the exact same files, modules, content, configuration on the online version and the offline version of my site.

Thanks in advance.


texts: Extricate commerceguys/profile getType() on null

texts:
Customer bought a D8 theme with Drupal Commerce installed with it. Every time I start out to build a custom module, at some point the site goes down with what I suspect is due to a misconfiguration involving the profile module which is a dependency of the Commerce Suite according to composer.lock.
The latest is a simple custom form and when I hit submit I get a stacktrace. The general form is the same for every page where it seems to be attempting to build a SQL query involving the profiles table. This is the top of the stack trace for this Drupal home page.

Error: Call to a member function getType() on null in
Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::propertyDefinitions() (line 73 of
 core/lib/Drupal/Core/Field/Plugin/Field/FieldType/EntityReferenceItem.php).
Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::propertyDefinitions(Object) (Line: 118)
Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem::schema(Object) (Line: 713)
Drupal\Core\Field\BaseFieldDefinition->getSchema() (Line: 736)
Drupal\Core\Field\BaseFieldDefinition->getColumns() (Line: 388)
Drupal\Core\Entity\Sql\DefaultTableMapping->getColumnNames('uid') (Line: 310)
Drupal\Core\Entity\Sql\DefaultTableMapping->getAllColumns('profile') (Line: 428)
Drupal\Core\Entity\Query\Sql\Tables->getTableMapping('profile', 'profile') (Line: 207)
Drupal\Core\Entity\Query\Sql\Tables->addField('status', 'INNER', NULL) (Line: 52)
Drupal\Core\Entity\Query\Sql\Condition->compile(Object) (Line: 162)

My efforts to uninstall the Commerce Suite crash the site attempting to uninstall one of its dependencies, like Price or Product. Of course, I attempt to click the link to remove all data from that dependency, usually returning a 500 error.

I'm sure I'm not understanding how Entity can be modified and how to fix this, but when this happens the site is hosed and no UI can be used since emptying the cache.* tables and drush pm:uninstall mycustommodule have been run. The only way I've been able to get out of this crashed state was to import an old database.

Looking at the stacktrace, is it the profile module that's causing the crash here?


texts: Unable to export and import custom block type fields

texts:
I have created a new custom block type and added some fields to it.
I am able to export and import the custom block type in another Drupal instance via configuration management, but there are no fields.

How do I import the fields too?


texts: What hook can access every field label at once and change the label of one?

texts:
I am trying to change the display label of one field on a node (not the form), depending on the value set in another field in Drupal 7. I don't want to change the label in the database, just on the final node page when you view it, if another field is set to a certain value.

I tried a few different hooks with no luck. Some can access every field, but only the value and not the label. Some can access the label on a per field basis which I can get half working (Set a flag in another function if the field is set correctly) but that only worked if the fields are checked in the right order.

So which painfully obvious hook will allow me to check a field setting and then edit the display of a label on another only on the node page? My perusing of the hook documentation and Google have not helped.

Thanks!


texts: Reserve stock on order complete not working

texts: I am working on Commerce 2.x and I am trying to reduce the stock value when someone adds an item in the cart. When I check the stock config there is an option to check the Reserve the stock on order complete Will that option do the same functionality. If yes, I am unable to see the reduced stock value when any item in the cart.


texts: Error messages do not appear on pane, instead appears on top of the overall form

texts:
I just added a new checkout pane to checkout form. I am trying to swap its orginal pane validate callback with my custom validate callback as I want my error messages to appear on top of the pane, which is also the existng way of drupal commerce.

As per the commerce API, the only current way of doing this would be to hack the pane's 'checkout_form_validate' callback in hook_commerce_checkout_pane_info_alter() and then replace the original pane validate callback with my custom validate callback.

I am successful in replacing the original callback, however my error messages still appears on top of the checkout form, instead of appearing on top of the pane, although the error class is rightfully assigned and highlights the error fields as required.

Any code example will be highly appreciated.

/**
 * Implements hook_commerce_checkout_pane_info_alter
 */
function checkout_forms_commerce_checkout_pane_info_alter(&$checkout_panes) {
    if(isset($checkout_panes['customer_profile_appointment_d'])){
        $checkout_panes['customer_profile_appointment_d']['callbacks']['checkout_form_validate'] = 'checkout_forms_commerce_checkout_form_validate';
    }
}

/**
 * Checkout pane validation override to validate customer profile and appointment
 */
function checkout_forms_commerce_checkout_form_validate($form, &$form_state, $checkout_pane, $order) {

    $first_name = $form_state['values']['customer_profile_appointment_d']['field_first_name_']['und'][0]['value'];
    $last_name = $form_state['values']['customer_profile_appointment_d']['field_last_name']['und'][0]['value'];

    //Some validation tests ... kept it simple for brevity.
    if (is_numeric($first_name)) {
        form_set_error(customer_profile_appointment_d . '][field_first_name_', t('Numeric characters are not allowed.'));
    }

    //Some validation tests ... kept it simple for brevity.
    if (is_numeric($last_name)) {
        form_set_error('customer_profile_appointment_d][field_last_name', t('Numeric characters are not allowed.'));
    }
    return TRUE;
}


texts: What's the best way to delete all content without a content type?

texts:
Due to an error during migration, some of the content has been left hanging without a content type and did not port over correctly.

What is the best way to delete these around 1000 records? Unfortunately they do not share any particular characteristics to be able to search them from the frontend easily.


texts: Exporting the entire website, except users and content?

texts:
As the title says. I need to export a whole project I've been working on to a production website in a different location. I need to export the modules, views, blocks, everything BUT the content and the users. I don't want the content as I made dummy content, and the user is a dummy user as well.

I was thinking on making a distro, but then I'd be missing on the structure. I would export the structure, but I need the modules as well. What's the solution for this sort of issues? My other solution is to build everything on production again, which is going to be draining.

I would also use a Dev -> Stage -> Prod workflow, but this will be a one time thing.


texts: Programmatically node update while saving node

texts:
How can I update the value of the field in the nodes while save/update the node?
When you save/update the node value from the field was taken and save in the same field in the other nodes.
I tried to do it hook_ENTITY_TYPE_presave()

$nodes = Node::loadMultiple($nids);
foreach ($nodes as $node) {
  $node->set('name_field', $value);
  $node->save();
}

But this causes infinite recursion


texts:
I have modified user-picture.tpl.php the follow way:

$employeeid = token_replace('[current-user:field_employeeid]');
?>
<?php if ($user_picture): ?>

    <?php print $user_picture; ?>

<?php elseif ($employeeid): ?>

    <img src="../../sites/default/files/pictures/<?=$employeeid?>.jpg"/>

<?php endif; ?>

by adding a token_replace to manage the current-user avatar for a company directory. I have left the original options in place because there is the possibility for non employees to be logged in.

THE PROBLEM:

The above code works, provided you are the current user, I need the employee avatar to show for everyone. I have tried replacing

curent-user:

for

user:

with no success. The whole reason for this is so that the employee avatar is automatically pulled from an IMCE managed folder and NOT left up to the employee to "get creative".

Any constructive thoughts or suggestions would be appreciated. Thanks!

SOLUTION:

if (isset($account->field_employeeid['und'][0]['safe_value'])) :
    $employeeid = $account->field_employeeid['und'][0]['safe_value']; ?>

        <img src="<?=base_path()?>sites/default/files/pictures/<?=$employeeid?>.jpg"/>

<?  else: ?>

        <?php print $user_picture; ?>

<?  endif; ?>


texts: Automatically add meta tags on node creation

texts:
I'm currently maintaining a lot of different sites containing the same information pages (example: profile pages with the same content but on different sites/base URL) and I'd like to consolidate this into a single URL housing all the profile pages. However, the first phase of this task was to develop a way to automate a rel=canonical metadata tag on creation of a node.

What would be the best way to meet this requirement? Is there a hook I can use?


texts: How to show the user badges in my tpl.php file?

texts:
This maybe a dumb question but what am I doing wrong?

From here: https://www.drupal.org/node/942014

It says I have to insert:

if (module_exists('user_badges')) {
    print user_badges_for_uid($uid);
  }

When I insert that on the last line of my  node.tpl.php it just shows as Text (like the whole code shows on the website). What am I doing wrong??

Can someone please help me?


texts:
PDOException: SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dropjob.semaphore' doesn't exist: SELECT expire, value FROM {semaphore} WHERE name = :name; Array ( [:name] => variable_init ) in lock_may_be_available() (line 167 of D:\drop_job\includes\lock.inc).

Can anybody help me to solve it
I will be greatful


texts: Will assigning a name string to user #0 do any harm?

texts:
By default, the {users}.name set for the Anonymous "user" (i.e. uid=0) is "" (empty) in Drupal 7.

This design choice is inconvenient for me in a module I'm maintaining (see issue #2099123 for background).

For instance, I need "Anonymous" to be available when there is an autocomplete form field that accepts a user name. Also, when I print out lists of users stored as serialized data in blobs, I want "Anonymous" to appear if there is a uid=0 somewhere in the list.

I've tried to use hook_username_alter(), but it has no impact on autocomplete widgets or serialized data.

I've looked for an API function to change the {users}.name field, and not found it.  I know there is a Drupal rule of thumb that say that updating another module's tables directly (i.e. without going through that module's API) is bad.

However, the solution I currently favour is to add a form to the admin interface that when clicked, does the following if the name field for uid=0 is "". (It does nothing if this field is not empty.)

$query = db_update('users')
  ->fields(array(
    'name' => 'Anonymous',
  ))
  ->condition('uid', 0)
  ->execute();

I've tested this solution, and it solves the problem.

I've verified that leaving the author field empty to assign node ownership to user #0 (as suggested by the the hint "Leave blank for Anonymous.") still works after this database update.

I understand that the value of {variable}.anonymous may not be "Anonymous", but believe I can live with that.

Question 1: Will assigning a string value to this particular field if it is empty have potential to break something on a site that installs my module?

Question 2: Is there a more Drupalishly right way to do this? (I.e. a way where I do not have to interfere with a piece of data that rightfully belongs to the user module.)


texts: How to handle with broken module installation

texts: I prepared a module that has some issues. I tried to install it, but while installing it crashed. I'd like to make some tiny changes and reinstall it, but the module is set as installed. When I go to uninstall this page is no longer available, because while module was installing it provided some changes, so uninstall page crashes. I know how to uninstall a broken module, but this procedure is pure evil and it takes a wile. Is there, so the changes are rolled back if the module has some issues?


texts: "Show as expanded" selected but children menu items not displaying

texts:
I am using a Bartik theme in drupal 7, and am trying to display a Page created using views under one of the Menu items. I've selected the "Show as expanded" for the parent item, however the child item is not appearing when I hover over the parent. Why would this be the case? How do I fix this?

I've displayed the same Menu in the sidebar, and there, it is displaying the child menu item. Also, I've tried disabling the css, and the drop down menu item is still not appearing...


texts: Can you create a new block region using just a module?

texts:
I am writing a module that will, using javascript, create a slide down container at the top of the page. (modelled on the login here http://xenforo.com/community/).

Rather than hardcode the content in this slide-down region, I'd rather just create a new block region, and let the user put whatever blocks into it he/she sees fit.

The thing is, this sort of thing would normally be done with the theme, not with a module. Is it possible to define a new block region using a module, and if so, how?


texts: 'Views Field' issue in NO RESULTS BEHAVIOR - Hide if empty not working

texts:
'Hide if empty' configuration of views is not working properly as a result all the empty fields are showing.

Is there any work around to force fully hide empty fields in the views result (Page/block) neither using the configuration under 'No Results behaviour nor using views-php/block-php?


texts:
I cannot edit my navigation menu.  I think this comes from upgrading from Drupal 6 to 7.

I get this error message:

  URL:
  http://www.energyjustice.net/admin/structure/menu/manage/navigation

  Referrer: http://www.energyjustice.net/admin/structure/menu

  Message:

  Recoverable fatal error: Argument 3 passed to l() must be an array,
  boolean given, called in
  /home/energy/public_html/modules/menu/menu.admin.inc on line 102 and
  defined in l() (line 2340 of
  /home/energy/public_html/includes/common.inc).

I've googled this problem and it happens a lot - I just haven't found a solution that I can use.  What can I do?

It might have something to do with the internationalization/translation and that I had an & symbol in the menu name.  I've since changed the name, but the problem remains.

Rebuilding the menu doesn't help.

Drupal 7.14.


texts: How do I display the file size of attachments on a node templates?

texts:
Is there any way to display the file size of attachments on a node through the node template programmatically?

I read How do I display the attachment's file size of a node? but it seems that the answer for that questions is only valid for Drupal 7, and those approaches aren't valid for Drupal 8 node templates.


texts: How to show all nodes and comments by a user in a single view?

texts:
I am using Drupal 8 in combination with the Forum module, and I'd like to show all comments and nodes by a user on his profile page, in a single view.

I can't find a way to get this to work, because they are different entity types.

I've tried using two relationships, but that only gives me rows with each comment linked to each node.

Is this at all possible?

EDIT: This is an example of the result that I'm trying to achieve:

Comment 5
Comment 4
Node 2
Comment 3
Node 1
Comment 2
Comment 1


texts: Views(Cache enable, pagination enable) page is showing page 1 data after page 1

texts:
I am using some caching modules like views_content_cache, cache_actions, entity cache for caching.
I have created a page using views(cache enable) with pagination. The problem is
when i go after page 1, it shows page 1 data and if i refresh the page its showing correct data. But if i disable the views cache its working perfect.

Can anyone suggest any solution?

Thanks in advance.


texts: How do I display a message to users, with the selections they has made from the contextual filter?

texts:
I have a view with more than one contextual filters.
For example, filter on Age, and Gender. if the filter is on Age, and/or gender
I would like to display a message to the user regarding the selections he/she has made. i.e, Message to user: "you are filtering on age"...
How can i achieve this? I thought about writing my own module to do it, but i figured there might be an exiting module, or solution that does this already.

Thank!!


texts:
I have created a view to show users their uploaded content. It works well enough. Now if the user has not created any content then the view should output 0 or some custom message.

In earlier versions, there used to be a Empty Text field under Basic settings. I am using Drupal 7 with the latest Views.

So after some searc, I found it should occur under "No Results Behavior" in "Advanced Settings" but I do not seem to find an empty text there. I found "Global text" so there I write my message, but it does not display anything if the view is empty.

Do you have any suggestions?


texts: How we can get the value entered in search API autocomplete field in jQuery?

texts:
I got a requirement to send the search text to GTM for tracking purpose. I have a field which is from search api autocomplete module. I am not getting the value in jQuery on click of submit button. I tried like below but no success:

var search_key = $('.path-frontpage .ui-autocomplete-input').attr('value');

Can anybody implemented such thing. Please help

DOM:

<input placeholder="Search MyP&amp;O" data-drupal-selector="edit-keywords" data-search-api-autocomplete-search="search" class="form-autocomplete form-text form-control ui-autocomplete-input" data-autocomplete-path="/search_api_autocomplete/search?display=page&amp;&amp;filter=keywords" type="text" id="edit-keywords" name="keywords" value="" size="30" maxlength="128" autocomplete="off">


texts: Programmatically assign a node to an organic group

texts:
How can I programmatically assign a node to an organic group?

I have tried the followings and non of them worked (assuming $target_group is the group ID that I want the $node to be assigned to):

$node->og_groups = array($target_group => $target_group);
node_save($node);

,

$group = node_load($target_group);
$node->og_groups[0] = $target_group;
$node->og_groups_names[0] = $group->title;

What is the proper way to do this?


texts: How can I get all those entity types which generates with new module installation

texts:
I am in need of showing all those entity types which gets generated by installing contributed modules and are not in Drupal by default.

For Ex:

I have installed "Profile2" module then for this I have two entity types:

Profile
Profile type

Then I have installed "Field collection" module and for this I have one entity type:

Field collection item

I want to get all the three above entity types only.

I have tried using function "entity_get_info(NULL)" but it is giving me all the entity types in Drupal 7.


texts:
How can I implement hook_views_query_alter() in Drupal 8?

In Drupal 7, I could use the following code.

$args = arg;
$node = menu_get_object();

if ($args[0] === 'my_view') {
  $query->orderBy('node_field_data_created','ASC');
  if (!empty($node) && $node->type == 'category') {
        $filters = $query->getFilters();
        $first_filter = $filters[0];
        if ($first_filter['#value'] == "(category) AND node_field_data.status:(1)") {
            $query->condition('field_category', $node->nid, '=');
        }

In Drupal 8, this code doesn't work.

Can anyone help me out?


texts: Modify custom search box added in page.tpl.php

texts:
My Drupal theme (Nexus) doesn't have a search bar in the header.
So added a custom header in page.tpl.php using the following code.

 <?php if ($search_box):?>
<?php print $search_box ; ?>
<?php endif; ?>

I wish to modify the search-box a bit, so I added the following lines
to nexus_form_alter function in template.php.

if ($form_id == 'search_block_form') {
    print $form_id;
    //$form['search_block_form']['#title'] = t('Search'); // Change the text on the label element
    $form['search_block_form']['#title_display'] = 'invisible'; // Toggle label visibility
    $form['search_block_form']['#size'] = 20;  // define size of the textfield
    $form['search_block_form']['#default_value'] = t('Search Site'); // Set a default value for the textfield
    $form['actions']['submit']['#value'] = t('GO!'); // Change the text on the submit button
    $form['actions']['submit']['#attributes']['alt'] = "Search Button"; //add alt tag
    unset($form['actions']['submit']['#value']); // Remove the value attribute from the input tag, since it is not valid when input type = image

    //$form['actions']['submit'] = array('#type' => 'image_button', '#src' => base_path() . path_to_theme() . '/images/icon-search.png');

// Add extra attributes to the text box
    $form['search_block_form']['#attributes']['onblur'] = "if (this.value == '') {this.value = 'Search Site';}";
    $form['search_block_form']['#attributes']['onfocus'] = "if (this.value == 'Search Site') {this.value = '';}";
  }

But the above piece of code doesn't have any effect on the search box that appeared on the top. I suppose that since I have manually printed the search
box at the header, hook_form_alter may not be of any use to me.

Can anybody suggest how to change my search-box characteristics.


texts:
I have a profile page with many paragraph sections. I am trying to open the input form for every paragraph separately into a modal form. I don't want to  manually build a form for each paragraph. The paragraphs on the profile page should open into a modal form after I click a Edit link under that paragraphs section. Therefore, Drupal should use its own entity form.

How can I say to Drupal that it should open a paragraph into an entity form?


texts: I am looking to have a subfooter that I can toggle with all types of rich content based on the page that visitors are on.  I would like to be able to say the homepage has this block, the blog section has this block, and so on.  I have quite a few uncategorized pages that I would like to be caught in a 'default' block of some form.  The issue is, if I have a default, it will show two if a condition is met with another context.  I would prefer to avoid the use of php snippits in blocks if possible.


texts: Restrict access to text formats for certain role

texts:
For every user with role company manager i have made tab My company(in user profile) where user can see node_edit of their company(node). And i need to set default format to plain-text and hide text-format drop down list only for this role. Ofc. i can do this for every user, i can change settings in my content type field settings, but this way the other users will not see it too.

Any suggestions? how can i achieve this?


texts: how to change taxonomy term fields before being created first time

texts:
I'm trying to copy parent's image field to a "goint to be created" taxonomy term using this code but it isn't working:

function my_module_taxonomy_term_insert($term) {
    if ($term->vid == 29) {

        //if any of parents have logo then copy it
            foreach ($term->parent as $p) {

            if (isset($p->field_image[LANGUAGE_NONE][0]['fid'])) {
                //copy the image
                $filepath = drupal_realpath($p->field_image[LANGUAGE_NONE][0]['uri']);

                // Create managed File object and associate with Image field.
                $file = (object) array(
                            'uid' => 1,
                            'uri' => $filepath,
                            'filemime' => file_get_mimetype($filepath),
                            'status' => 1,
                );

                $term->field_image[LANGUAGE_NONE][0] = (array) $file;
            }
        }
    }
}

How to do this?


texts: In which file should I write db_add_field function

texts: I am writing a module for which I have to add a field to my database. So I need to use  db_add_filed function, So in which file I should use this function? I mean should it be in .module file or .inc file?


texts: Array of items as contextual filter in Views

texts:
I need to create a View which displays content of users that their username should be passed as contextual filter. The number of parameters (usernames) are not specified but the View must include every username that is passed via url, as an example

example.com/some-path/user1
example.com/some-path/user1/user2
example.com/some-path/user3/user2/user12

the view must include all of pathes like the above ones and filter the contents but I really have no idea how to implement this using Views UI. I can do this programmatically by looping through each component of the url but I don't want to use such methods.


texts: Can I control the weight of a library loaded through a theme preprocess function?

texts:
I have a base theme that loads several libraries, some through the libraries.yml file and some loaded conditionally in a preprocess function. I also have a base theme with its own library loaded through libraries.yml.

This is the order they are loading in:

Libraries loaded in base theme's libraries.yml
Libraries loaded in sub theme's libraries.yml
Libraries loaded in base theme's preprocess function

This is a problem because I need to override some CSS from the libraries loaded in the base theme's preprocess function in my subtheme. I want it to load like this:

Libraries loaded in base theme's libraries.yml
Libraries loaded in base theme's preprocess function
Libraries loaded in sub theme's libraries.yml

They are loading in that order regardless of the CSS weights defined in the libraries file (base, theme etc.).

Is there anything I can do about this? This is the relevant code from the base theme, used in hook_preprocess_html().

  if (\Drupal::moduleHandler()->moduleExists('module')) {
    $variables['#attached']['library'][] = 'basetheme/library';
  }

Will libraries loaded through a preprocess function always load later than the libraries loaded through libraries.yml? Are there any resources that explain this? And as an aside, where would libraries loaded through twig go?


texts: How do I modify menu links depending on context?

texts:
I'm trying to create a menu for a department & group-based company such as:

Presentation (/<department>/<group>/presentation)
Projects (/<department>/<group>/projects)
Personnel (/<department>/<group>/personnel)

Instead of having one static menu per <department>/<group>, what should be a proper approach to create just one dynamic menu which automagically updates its links to <department>/<group>?


texts: In Drupal Fullcalendar, how do I add an additional field to the calendar view?

texts: I need to add one more field to the Fullcalender views. Anyone know what code I need to edit to take care of this?


texts:
I am attempting to create a simple user dashboard that will let a user do things throughout the site like edit menus and content.

I would like to have a dropdown that lists all the custom menus on the site and after they select one it would take them to the edit page.

How would I go about doing this within my module?


texts: Can I by pass the one time login page that forces a use to click "log in"?

texts:
I'd like to send a user to a specific page on their one time login.  I'd also like to not force them through presentation of the page that says :

This is a one-time login for USER and will expire on DATE.
Click on this button to log in to the site and change your password.
This login can only be used once.
Log In

I understand  the redirection I want to do can be done on a form submission override on the Login button form. link

I'd like to achieve the redirection AND by pass the one time login page.

My intial though is that the onetime login page is essencial to the one time login process. Is that true?

Thanks in advance.


texts: Programatically render a block in a twig template

texts:
I need to render a views block in my page.html.twig template. In D7 I would do this:

<?php
  $block = module_invoke('module_name', 'block_view', 'block_delta');
  print render($block['content']);
?>

In Drupal 8 module_invoke is deprecated and recommended to use this: (I've added the block's name as the second parameter)

Drupal::moduleHandler()->invoke($block, 'views_block__blog_block_1', $args = array());

I tried a few things. First tried to do it in a twig template but I don't know how to call php functions in a twig template, so that didn't turn out too well.

Then I called the function in the preprocess_page() function in the .theme file but before I could get it to work I tried something simpler just to try make a variable work inside the twig template which didn't work either, for example:

In the template_preprocess_page(&$vars) function in the .theme file:

$test = 'Hello World';
$vars['$my_var'] = $test;

I tried to call my_var inside the twig template but it didn't work and I got an error message saying "The site has an error, please contact the administrator"

So, to summarize, here are my questions:

How do I make variables available inside twig templates?
How do I call functions inside twig templates?
Do I render blocks inside the .theme file or twig template?


texts: how to bring Core forum discussion with comment on front page

texts: I am using core forum in drupal 7. my requirement is how to bring forum discussion question with comment on front page.


texts:
I need to check whether a hook is implemented in a module, so I chose module_hook function. In the documentation it states that the Return Value will be:

  TRUE if the module is both installed and enabled, and the hook is
  implemented in that module.

Now, I named a callback function (not a hook) in my module as "my_module_abc()"

Note: my_module is the name of my module.

  If I test this function in module_hook like below:

module_hook('my_module', 'abc');

  It returns TRUE.

I thought It would return TRUE only for registered hooks and not for any function callbacks. Does module_hook know the difference between a function and a hook?
Is there any function like hook_information($hook) which returns information about a hook?

Is this right? Am I missing something?


texts:
I'm trying to use Panels to arrange content on my site. I've made some strides in creating a panel that displays a view of images based on different criteria.

I added a page (panel) which allows me to tap into Drupal's menu system and make a tab called Photos. Now I want to add a number of variants to this panel, and I want links to those variants to show up in the sub-tab (MENU_DEFAULT_LOCAL_TASK). Since there does not seem to be any way to add a menu item for each variant, I'm wondering what is the best way to do this.

I see two possibilities, both of which don't seem ideal:

I could write a module, that adds the  default local tasks to the menu item.
I could add a separate panel page for each variant, and use the menus there.

It seems like there should be an easy solution to this. Can anyone help me?


texts: How do I count the number of Facebook likes in articles?

texts:
I am working on a Drupal 8 site. I added fblikebutton to my articles to enable users to like content.

Is it possible to get the number of likes for each article as field? I am using the Views module to show the latest 3 articles, as in the following screenshot.


texts:
I'm looking for a module that will let me limit users to certain domain names when they edit a Link field.

For example, only let users enter a URL if the domain name is facebook.com, twitter.com or plus.google.com.

This list must be easily editable by admins.

Does such a module exist?

(Also: See my other question, if there is some a module that can do both it'll be great)


texts: Unpublished content type using rules module based on user role

texts:
I have a website were there are two type of users, Administrator and Clients.

I would like to add a rule that should apply if the user is Clients.

The rule should unpublished the new content and send an email to administrator.

I have manage to create the rule which is working fine but the condition is not working.

currently the rule is applying to all the user types.

I am confuse what to use as a data selector to apply the rule only to Clients users.

Thanks,


texts: Modifying an Existing Entity Column in hook_update_N

texts:
This is a tricky problem but here is the jist of it. I have an entity that has a property called revision_id. Through hook_update_N I want to do 2 things.

Change the db column name to node_id
Convert the data in this db column from VIDs to NIDs

The code that takes care of this is...

function research_annotator_update_7100(&$sandbox) {

  // Change the db column.
  db_change_field(
    'research_annotator_annotation',
    'revision_id',
    'node_id',
    array(
      'description' => 'The node the annotation belongs to.',
      'type' => 'int',
      'unsigned' => TRUE,
      'not null' => TRUE,
      'default' => 0,
    )
  );

  cache_clear_all();

  // Change revision ids into node ids.
  $arr_annotations = entity_load('research_annotation');

  foreach ($arr_annotations as $o_annotation) {
    $o_annotatedNode = node_load(NULL, $o_annotation->node_id);
    $o_annotation->node_id = $o_annotatedNode->nid;
    entity_save('research_annotation', $o_annotation);
  }
}

I also updated the entity property definition to represent the new node_id column...

research_annotator_entity_property_info() {

  $arr_propertyInfo = array();

  $arr_propertyInfo['research_annotation'] = array(
  'properties' => array(
    'node_id' => array(
      'label' => t('Revision'),
      'type' => 'integer',
      'description' => t('The revision id this annotation belongs to.'),
      'setter callback' => 'entity_property_verbatim_set',
      'required' => TRUE,
      'schema field' => 'node_id',
    ),
    ...snip

The problem is, when I run the update the first time, it gives me the following error...

Failed: PDOException: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'base.revision_id' in 'field list' ...

In the database, the changes have been made to the column but the data has not been converted. If I clear all caches and run the update again then everything works as planned. I suspect that because the entity cache is not cleared after the db column change, the error appears.

If this is the case, how can I ensure the entity cache is cleared immediately after db_change_field is called in the update hook?


texts:
I'm using TinyMCE and I'm using the Full HTML format which shouldn't strip any tags. I copy another web page with an html5 audio tag in it and paste it into the editor. I can see the html5 audio player there, but when I save, it is stripped out.

I tried again and this time brought up the raw html editor and directly put the audio tag into the html. When I click Update, the audio tag is stripped out.

Here is my Full HTML text format config:


texts:
So... I created a few groups and a new content-type. The problem is that I don't know how to display content linked to a certain group using a path like: "/[-content-type]/[group-name] (using views, of course). As far as I know it has something to do with contextual filters, but that's where my knowledge ends.

Thanks for any help.


texts: Drush Remote Alias Fails with No Drupal Site Found

texts:
This is incredibly frustrating. Here's the deal. I have a drush alias defined for a server I'm working with. No matter what command it is, if it needs to bootstrap Drupal it fails with no drupal site found or some variant. Running drush with --debug gives me less than useful information although if you'd like to see it I'm happy to provide it.

I can run drush @alias sqlc and get the mysql command line on the remote server. I just cannot run things like drush @alias st or drush @alias cc all for example.

If I SSH to the server, change into the directory (i.e. /sites/default) and run the same commands they work fine. So this is only when going over a remote alias.

Here's the alias definition:

$aliases['alias'] = array(
     'uri' => 'site.com',
     'root' => '/usr/share/nginx/html/drupal/docroot',
     'remote-host' => 'us-west-2.compute.amazonaws.com',
     'remote-user' => 'ubuntu',
     'ssh-options' => '-i /Users/name/.ssh/id_rsa -q',
     'db-url' => 'mysql://dbuser:dbpassword@localhost/www',
     'path-aliases' => array(
       '%files' => 'sites/default/files',
       '%dump-dir' => '/tmp'
      ),
      'command-specific' => array (
        'sql-sync' => array (
          'no-cache' => TRUE,
        ),
     ),
);

Am I missing something here? I've done this a thousand times and for whatever reason this time it refuses to work.

Note: I have downgraded to Drush 6.x just in case it was a 7.x problem. Same result.


texts: Views relationship based on user viewing node

texts:
So this is what im looking to do:

I have added a field to my users where they can enter their age in a numerical value.

I also have a referenced product which can only show on its referencing node.

I would like the view to only display the referenced product on its referencing node if the users age is greater than 18.

I have setup the content view and can get the referenced product to display on its referencing node however when I add the age field as a filter it can only reference the relationship I set as content:author as this was the closest I could find. What I want is something like user session etc so it references the current logged in user.

Any ideas would be great.

Thanks all


texts: Should store input format in the database?

texts: When using the WYSIWYG editor, should I store not only the text but also the format ("Full HTML"/"Filtered HTML"/...) in the DB?


texts:
I have multiple vocabularies:

Year Model
Origin
Make
Model
Variants

Year Model:

2016
2015
...
2002
2001

Origin:

American
Asian
European
Japanese

Make:

Audi
BMW
Chrysler
Dodge
Ford
Ferrari
...
Hyundai
Mitsubishi
Subaru
Toyota
Volvo

Model:

R8
Fortuner
Montero Sports
XC90
Forester
116i

Variants:

FSI Quattro 4.2L Gas 6Spd MT AWD
G 2.5L Diesel MT 4x2
GLX 2.5L Diesel MT 4x2 (Non-VGT)
X 2.0L Gas AT AWD

What I wanted is for example I am going to select American as origin then I wanted the Make vocabulary to only display the make/brand under American. I tried several contrib modules like Term Relations, Taxonomy Set Lineage, Combined Termref but I cannot achieved what I want (maybe I overlooked the contrib modules I tried). Is there a way that I can specify the relationship between terms of different vocabulary.

Here is my thought:

Vocal Origin   - American
               - European
               - Asian
               - Japanese

Vocab Make     - Ford (Parent Term: American)
               - Toyota (Parent Term: Japanese)
               - Audi (Parent Term: European)

Vocab Model    - Fortuner (Parent Term: Toyota)
               - Mustang (Parent Term: Ford)
               - A1 (Parent Term Term: Audi)

Vocab Variants - Turbo FSI 1.4L Gas S-Tronic (Parent Term: A1)
               - G 2.5L Diesel MT 4x2 (Parent Term: Fortuner)
               - EcoBoost Premium 2.3L Gas AT (Parent Term: Mustang)

I know that I this is pretty simple using parent-child terms in a single vocabulary but the issue with this solution is the editors will not be able to easily add new items as that could be confusing to them. Doing in a separate vocabulary will allow them to easily manage the terms.


texts: Custom php in rules how to check users' geolocation lat lon field and return only users in certain area

texts: I have some custom php, sending privatemsgs to users who have some term_reference field terms that match node term_reference field terms. I need to add into this so that it only contacts users who are within a certain range of area based on their lat lon that they entered on sign up. I am sure this is a very common thing to do e.g. showing users nearby etc. If you can point me in the right direction, would be great.


texts:
I am using Drupal 7.

I want to make different looking pages, but I can't do this because it is always using the main theme block regions, and I can't change my specific page elements. For example, I want to make a page that has a cartoon images and another page that has a movie images on the background, and the block regions can be reordered.
I tried Pages in Structure menu, but I don't understand it. I created one page, and assigned it a URL, but I can't access the page with my URL, as it says "page not found."


texts:
I create orders programmatically, and I have a tax problem: the order, after changing the line item price, always has the tax cost with the old product price.
How can I refresh the adjustment tax after changing the line-item price?

foreach ($entity_ids as $entity_id) {
    $abo = Node::load($entity_id);

    //utilisateur
    $user = $abo->get('field_utilisateur')->getValue()[0]['target_id'];
    $utilisateur = \Drupal\user\Entity\User::load($user);

    //profile
    $entity_manager = \Drupal::entityTypeManager();
    $profile = $entity_manager->getStorage('profile')->load($user);

    //abonnement
    $nid= $abo->id();

    //livraison
    $date_livraison = new DateTime();
    $date_livraison->modify('next friday');

    //ligne de commande
    $line_items = array();
    $abo_array= $abo->get('field_abo_produits')->getValue();

    foreach ($abo_array as $abo_item) {
        $ligne = $abo_item['target_id'];
        //load produit abonnement
        $item = \Drupal\commerce_order\Entity\OrderItem::load($ligne);
        $quantite = $item->getQuantity();
        $produit = $item->getPurchasedEntity();

        $order_item = \Drupal\commerce_order\Entity\OrderItem::create([
            'type' => 'default',
            'purchased_entity' => $produit,
            'quantity' => $quantite,
            //'unit_price' => $role_price,
        ]);

        $order_item->save();
        array_push($line_items,$order_item);
    }

    //creation de la commande
    $order = \Drupal\commerce_order\Entity\Order::create([
        'type' => 'default',
        'store_id' => 1,
        'checkout_flow' => 'boulangerie',
        'uid' => $user,
        'billing_profile' =>$profile,
        'field_abonnement' => $nid,
        'placed' => time(),
        'field_date_livraison' =>$date_livraison->format('Y-m-d'),
        'order_items' =>$line_items
    ]);

    $order->save();
    $order->set('order_number', $order->id());
    $order->save();
    $order->set('state', 'complete');
    $order->save();

    //prix custo
    foreach ($order->getItems() as $ligne_de_commande) {

        $produit = $ligne_de_commande->getPurchasedEntity();
        //prix
        if ($utilisateur->hasRole('biocoop')) {
            $role_price = $produit->get('field_prix_biocoop');
            $role = 'biocoop';
        }

        if ($utilisateur->hasRole('montagne')) {
            $role_price = $produit->get('field_prix_montagne');
            $role = 'montagne';
        }

        if ($utilisateur->hasRole('vente_directe')) {
            $role_price = $produit->get('field_prix_vd');
            $role = 'vente_directe';
        }

        $unit_price = new  \Drupal\commerce_price\Price($role_price->number, 'EUR');

        $ligne_de_commande->setUnitPrice($unit_price);
        $ligne_de_commande->save();

    }

    $order->save();
}


texts: How to use reorder image in touch devices

texts:
I am using the Core default image system.
Right now i can use mouse to reorder images by drag/moving them up and down

But in touch mode with Smartphone/devices. it doesn't work.

Is there a plug in out there or any script i need to implement to make it work?

Thank you very much in advance.

Cheers
Kim


texts: Do I need to add a template_preprocess to declare I am going to use the content type fields in node--content-type.tpl.php?

texts:
I am trying to use custom templates for the first time, with zen. So I might miss a step.

I have created a node--something.tpl.php for a "something" content type. I have successfully tested it with a few fixed and variable values like $date and $name. But when I try <?php print render($content['field_example']); ?> it outputs nothing, same for <?php print render($content['field_field_example']); ?> and a few other combinations, and clearing caches at every move.
I have the feeling that I miss maybe a preprocess declaration in the template.
The theme version 7.x-5.5.
 The resource documents I am using are:

https://www.drupal.org/node/1728164
https://api.drupal.org/api/drupal/modules!node!node.tpl.php/7

I am a bit lost here.


texts: What are the criteria to decide between modules ThemeKey and Switchtheme?

texts:
There are (at least) 2 modules that allow for switching between themes, i.e.:

ThemeKey.
Switchtheme.

What are the typical criteria, or pros/cons, for a site builder (without any custom coding or custom theming) to decide for either one?

I have the impression that using ThemeKey the administrator (only) determines how the theme is switched, while by using Switchtheme it is rather the user who decides (from a list predefined by the administrator). Am I close?


texts: How to perform a query using a specific field of a node entity reference

texts:
I have a content type that has a node entity reference field. My base query looks like

$event_nids = \Drupal::entityQuery('node')
    ->condition('type', 'my_content_type')
    ->execute();

I'd like though to be able to sort by the title field of the referenced field type. I attempted

$event_nids = \Drupal::entityQuery('node')
    ->condition('type', 'my_content_type')
    ->sort('field_referenced_node.title', ASC)
    ->execute();

But I receive the error

  Drupal\Core\Entity\Query\QueryException: Invalid specifier 'title' in Drupal\Core\Entity\Query\Sql\Tables->addField()

Is it possible to sort a node query by a field inside a referenced node?


texts: Autocomplete field - fill the selected id into another form element (eg. hidden field)

texts:
this was already asked here
Handling id from autocomplete field

but still without answer: I have an autocomplete field which uses geonames query to search cities. After value is selected I want the city name and admin area to fill into the autocomplete field, and to fill geoname_id of selected value into another (hidden) field. I don't want the geoname_id to be visible - it looks kind of ugly...

I've tried to hack the autocomplete.js and added following line

$("#search-geoname-id").val($(this.selected).data('autocompleteValue'));

into Drupal.jsAC.prototype.hidePopup function

then also tried

$("input[id=search-geoname-id]").val($(this.selected).data('autocompleteValue'));

but both without effect :/

Thanks for your help, Tomas


texts: Separating contextual-links CSS, out of the CSS of menus and other associated markup

texts:
The following problem happens when you style menus in Drupal, using CSS. The problem is especially dominant when you edit the <a> tags of a menu, but happens in regards to all of the menu markup.

The following images describe problems for two different menus, in which CSS directives I gave to my #navigation selector and its <a> tags, such as height: 60px, display: inline-block, and color: #fff, are inherited by the contextual links markup and thus destroy its appearance and making it impractical if not nonfunctional.

Thus, the solution I need is to separate the contextual links CSS from the themes', loading it afterwards or hardcoded somehow.

I dedicate this question to experienced themers: How can one load the contextual links with "hardcoded" CSS code, so they won't inherit anything from CSS directives I write in any theme-dependent CSS.

Code information:

Twig data:

{{ menus.menu_links(items, attributes, 0) }}

{% macro menu_links(items, attributes, menu_level) %}
  {% import _self as menus %}
  {% if items %}
    {% if menu_level == 0 %}
      <ul{{ attributes.addClass('menu') }}>
    {% else %}
      <ul class="menu">
    {% endif %}
    {% for item in items %}
      {%
        set classes = [
          'menu-item',
          item.is_expanded ? 'menu-item--expanded',
          item.is_collapsed ? 'menu-item--collapsed',
          item.in_active_trail ? 'menu-item--active-trail',
        ]
      %}
      <li{{ item.attributes.addClass(classes) }}>
        {{ link(item.title, item.url) }}
        {% if item.below %}
          {{ menus.menu_links(item.below, attributes, menu_level + 1) }}
        {% endif %}
      </li>
    {% endfor %}
    </ul>
  {% endif %}
{% endmacro %}

Mobile-first responsive CSS:

#navigation {height: auto; padding: 10px 0 10px 0; background: #0a97b7}
    #navigation ul {display: none} /*For JS conditioning: if none than...*/
    #navigation li {display: block}
        #navigation a {color: #fff}
            #navigation a:hover {text-decoration: none}
    .navtoggle {display: block; padding: 10px 25px 10px 0; font-size: 24px; background: none !important}

Desktop level CSS:

@media screen and (min-width: 1080px) {
    #navigation {height: 60px; padding: 0}
        #navigation ul {display: block}
            #navigation li {display: inline-block}
                #navigation a {height: 60px; line-height: 60px; padding: 0 15px 0 15px; display: inline-block}
                /*<a> must be either block/inline-block to have its height changed.*/
                    #navigation a:hover {background: #55cfd6; text-decoration: none}
    #navigation .menu-item {display: inline-block; float: right}
    #navigation .is-active {background: #55cfd6}
    .navtoggle {display: none !important}
}

Complete reset of the contextual links class as follows, isn't effective (nor it is adequate) and is overridden by more specific codes:

.contextual ul       {background: #fff !important}
.contextual li       {display: block !important}
.contextual a        {color: black !important; height: auto !important; line-height: 1.3em !important; background: #fff !important}
.contextual a:hover  {background: #f4f4f4 !important}

Every in-place menu seems better with this compelete reset, but it still don't cover all menus.


texts: I managed to get fields inline on node display, but cant find a module to help me do it on node input. I am mostly using DS, field collection and field group (field gruop has this option but only for display, not for edit.)


texts: Problem with escaped characters in attributes

texts:
The default theme_image() is implemented as

function theme_image($variables) {
  $attributes = $variables['attributes'];
  $attributes['src'] = file_create_url($variables['path']);

  foreach (array('width', 'height', 'alt', 'title') as $key) {

    if (isset($variables[$key])) {
      $attributes[$key] = $variables[$key];
    }
  }

  return '<img' . drupal_attributes($attributes) . ' />';
}

drupal_attributes() is implemented as

function drupal_attributes(array $attributes = array()) {
  foreach ($attributes as $attribute => &$data) {
    $data = implode(' ', (array) $data);
    $data = $attribute . '="' . check_plain($data) . '"';
  }
  return $attributes ? ' ' . implode(' ', $attributes) : '';
}

and check_plain() as

function check_plain($text) {
  return htmlspecialchars($text, ENT_QUOTES, 'UTF-8');
}

Since htmlspecialchars() is being called with ENT_QUOTES, single quotes in my title and alt text on the image are being escaped as &#039; and double quotes as &#quot;, so hovers look weird.

Is there an acceptable, safe, secure way to handle this situation?


texts:
I am attempting to add a conditional stylesheet to my user registration form which has an alias called "signup"

This is the code I am using, however this does not seem to work.  I have tried loads of other different ways but I cannot seem to find any clear documentation on how to do this.

Any ideas on this?  The simpoer the better, my code seems to be quite complex for something so simple.

Thanks

function mytheme_preprocess_page(&$variables, $hook) {
$matches = "signup";
$path = drupal_get_path_alias($_GET['q']);
$page_match = drupal_match_path($path, $matches);
if ($path != $_GET['q']) {
$page_match = $page_match || drupal_match_path($_GET['q'], $matches);
}
if ($page_match) {
drupal_add_css(drupal_get_path('theme', 'mytheme') . '/style.css');
}

Also tried this to no avail

function mytheme_form_alter(&$form, &$form_state, $form_id) {
global $user, $theme;
switch ($form_id) {
    case 'user/register':
      $form['#attached']['css'] = array(
        drupal_get_path('theme', 'mytheme') . '/css/new.css',
      );
    break;
 }


texts: I can only create 8 child pages in a book not beyond that,It seems like the depth of the child pages is set to 8 but i could not find the location where the depth was set.Please help me


texts: Moving nodes and menus between environments

texts:
I've a large menu of basic pages I'm trying to move from my D7 development environment into production.
So far I've been trying to use the Node Export module to build a feature. That didn't seem to include any of my URL aliases or menus, with pages ending up with menu links generated seemingly at random (I guess to do with the order the nodes were created at import?).
I've tried using the Menu Export/Import module, but that doesn't seem to fix very much. I can't see a way to build it in to the feature, so I'm importing the text file manually, but that still results in a menu that bares little resemblance to the one in the starting environment. It doesn't seem to recognise many of the pages it's trying to link to actually exist.
Am I doing something wrong? Or is there a better solution?


texts: How to get Q & A of a webform submission?

texts:
Main goal is to get user filled in form into a pdf. Got my pdf & sending it with email. But I cant figure out how to get Q & A from a submission. I have sid of submission. I tried

      $storage = \Drupal::entityTypeManager()->getStorage('webform_submission');
  $webform_submission = $storage->loadByProperties([
    'entity_type' => 'webform',
    'entity_id' => 'questionnaire',
  ]);
  $submission_data = array();
  foreach ($webform_submission as $submission) {
    $submission_data[] = $submission->getData();
  }

Webform is not attached to node.

Thanks


texts: Configuration - > Zones admin page missing?

texts:
I've installed Drupal Commerce 2 and as explained here:
https://drupal-commerce.readthedocs.io/en/latest/v2/building-blocks/address/zones.html
there should be a "Zones" admin page at Configuration -> Zones. But I don't have that page and I only have "default" zone?!?
Only relevant module I found is:
https://www.drupal.org/project/address_zone
but it exists only for Drupal 7?!
What I'm trying actually is to configure Commerce Product Tax, which exists only for D8 and at screenshot from module page:
https://www.drupal.org/project/commerce_product_tax
... they do have zones "France" and "France (Corsica)", so this should be possible somehow I guess.
How to administrate those zones and why I don't have that page under "Configuration" in my back-end?


texts: Need help getting custom form to theme based on selected criteria

texts:
I have a form I want to theme one of two different ways depending on what the user selected.

Say it's a form to show a report about Cats they can choose a summary or a detail report type.

If they choose detail they should get a table that lists cat name, age, color, breed, location.

If they choose summary they get a table that has each breed listed once with the count of cats at that location

Currently to theme my results I am doing the following:

if(isset($form_state['storage']['results'])) {

    $form['results'] = array(
      '#type' => 'markup',
      '#markup' => theme('cat_detail_results', array('items' => $form_state['storage']['results'])),
    );

}

return $form;

}

I thought I would be able to enter an if statement here and achieve what I wanted but it doesn't work.

if(isset($form_state['storage']['results'])) {

    if ($form_state['values']['reporttype']=='detail')
     {
    $form['results'] = array(
      '#type' => 'markup',
      '#markup' => theme('cat_detail_results', array('items' => $form_state['storage']['results'])),
    );
   }
   else {
      $form['results'] = array(
      '#type' => 'markup',
      '#markup' => theme('cat_summary_results', array('items' => $form_state['storage']['results'])),
   }

  }
}

return $form;

}

Does any one have any suggestions for what I want to do or do I just need to create a separate form for these two report types?

Thanks for any help!!


texts: Drupal 7 how to programmatically display resent comment from all article with author image and comment content?

texts: I'm just use built in function comment_get_recent($number); but its only fetch resent comment's subject and author name, is any built in function available which display resent comment with author image comment subject and comment content?


texts: Link one title to a different page other than its content of a view page

texts:
I have a Drupal 8's views page in which Title and body of a specific content type is listed. I have enabled the title to link its content (node).

Supose if I have a list of 10 titles with its body listed, is there any way to override the link of one or two titles in order to redirect to a different page rather than its content/node.


texts: form_alter and #element_validate inside .module file

texts:
Inside my .module file, I have created a hook for alter register_form and add a password field with a custom field-validation:

function xenforo_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
  $form['password'] = array(
    '#type' => 'password_confirm',
    '#size' => 25,
    '#required' => true,
    '#element_validate' => array('check_password'),
    );
}
function check_password($element, &$form_state) {
  if ($element['#value'] != 'test') {
    form_error($element, t('Error: TEST'));
  }
}

I use #element_validate, and when I submit my form with a bad value $element['#value'] != 'test', I don't have an error and the registration is completed, why #element_validate don't work here please ?

Thanks.

EDIT:

I have find a solution:

  function xenforo_form_user_register_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
    $form['password'] = array(
      '#type' => 'password_confirm',
      '#size' => 25,
      '#required' => true,
      '#attributes' => array('autocomplete' => 'off'),
      //'#element_validate' => array('check_password'),
      '#process' => array('processPasswordConfirm'),
    );
  }

  function processPasswordConfirm(&$element, \Drupal\Core\Form\FormStateInterface $form_state, &$complete_form) {
    $element['pass1'] =  array(
      '#type' => 'password',
      '#title' => t('Password'),
      '#value' => empty($element['#value']) ? NULL : $element['#value']['pass1'],
      '#required' => $element['#required'],
      '#attributes' => array('class' => array('password-field')),
    );
    $element['pass2'] =  array(
      '#type' => 'password',
      '#title' => t('Confirm password'),
      '#value' => empty($element['#value']) ? NULL : $element['#value']['pass2'],
      '#required' => $element['#required'],
      '#attributes' => array('class' => array('password-confirm')),
    );
    $element['#element_validate'] = array('check_password');
    $element['#tree'] = TRUE;

    return $element;
  }

  function check_password($element, &$form_state) {
    if ($element['#value'] != 'test') {
      //form_error($element, t('Error: TEST'));
    }
  }

But I have again the error with form_error() and password as displayed as two field without


texts: How to show a block on pages with a path like '/member/*' but not 'member/*/likes'?

texts:
I want to show a block on a member's profile page (member/*) but not on member/*/likes.

It doesn't seem I can do this without PHP in the block settings, does it?


texts: How to make a view that only shows content a user has not voted on

texts:
I'm working on a project that asks a group of users with a specific role to vote on content produced by users with a different role.

The group who votes is supposed to try and vote on each item, so I'm trying to make a view that will give them pages of the content.

I would like the view to only show the content that they have not yet voted on, so when they have voted on all items, nothing is displayed in the view.


texts: How can I use jquery to trigger a click on page load?

texts:
I'm using Drupal 8. I have a vertical tabs menu on a content edit form. When the page loads, I want to trigger a click on one of the vertical tabs based on the value of a checkbox, which was determined by the tab that was open the last time the page was saved. (Similarly, when a vertical tab is clicked, this also changes the value of the checkbox; this code works as expected).

My code was working last week, but now I can't figure out what's wrong.

(function($, Drupal) {

Drupal.behaviors.calloutControl = {
        attach: function (context, settings) {
                // check if active callout tab is checked or not; trigger a click on the tab that corresponds to the value
                if ($(context).find('input[name*="[field_active_callout_tab]"]').prop('checked', false) == true){
                        $(context).find('.vertical-tabs .vertical-tabs__menu .vertical-tabs__menu-item.last a').trigger('click');
                        console.log("I'm MULTI");
                }
                else{
                        $(context).find('.vertical-tabs .vertical-tabs__menu .vertical-tabs__menu-item.first a').trigger('click');
                        console.log("I'm SINGLE");
                }

                // check and uncheck field_active_callout_tab based on multi or single link tab selection
                $(context).find('.vertical-tabs .vertical-tabs__menu .vertical-tabs__menu-item.first').click(function () {
                        $(context).find('input[name*="[field_active_callout_tab]"]').prop('checked', true);
                });
                $(context).find('.vertical-tabs .vertical-tabs__menu .vertical-tabs__menu-item.last').click(function () {
                        $(context).find('input[name*="[field_active_callout_tab]"]').prop('checked', false);
                });
        }
};

})(jQuery, Drupal);

Here is what it should look like to the user:

Page loads
Tab is open that was open on last save

For the first portion of the conditional, I have tried altering it slightly to remove the '== true', and then the first part of the code runs, triggers a click on the last tab and logs "I'm MULTI":

if ($(context).find('input[name*="[field_active_callout_tab]"]').prop('checked', false))

with '== true', the code will only run the second portion and log 'I'm SINGLE', triggering a click on the first tab.

In other words, I have correctly identified the tab elements and can interact with them, but they are not responding as expected.

Can someone please check my code to see if I am missing something? How can I use this jquery to trigger a click on page load?


texts:
How can I restore the original position (order and initial regions) of blocks on Drupal 7?

I need to make a button that you can restore the block position on Drupal 7. What function or table can be used?


texts: How do I determine the route of my view?

texts: I made a new view page and I want it to be in the router table so that I can know its route, but it's not there.  How can I determine the route of this view or insert it into the router table?


texts: How to access a selected label instead of value

texts:
I have a select list of states:

AL|Alabama
AK|Alaska
AZ|Arizona
AR|Arkansas

In code to access the selected state value I can run code like this:

...
$entity->get('field_state')->value;
...

I get the values like AL or AK.  How can I get the labels like Alabama or Alaska?


texts: How do I make a custom entity update or create automatically update the solr index?

texts:
I have implemented a custom entity type which is essentially identical to what the Model module does, with a few additional fields.

I have followed the Apachesolr User module to understand how to index my custom entities in the solr index. But when I add, or update and existing, entity the solr index is not automatically picking up the changes.

/**
 * Implements hook_apacheolr_entity_info_alter().
 */
function my_entity_apachesolr_entity_info_alter(&$entity_info) {
  $entity_info['my_entity']['indexable'] = TRUE;
  $entity_info['my_entity']['status callback'][] = 'my_entity_status_callback';
  $entity_info['my_entity']['document callback'][] = 'my_entity_solr_document';
  $entity_info['my_entity']['reindex callback'] = 'my_entity_solr_reindex';
  $entity_info['my_entity']['index_table'] = 'apachesolr_index_entities_my_entity';

  $entity_info['my_entity']['result callback'] = 'my_entity_result';
}

This is the hook I had to implement to index my content, the various callbacks are irrelevant. It is worth noting the index table needs to be implemented in hook_schema() as well. This can be easily seen in Apachesolr User


texts: How do I theme a link with twig for a specific content type?

texts:
I'm trying to create a custom file-link.html.twig for a particular content type. I've looked at https://www.drupal.org/node/2354645 which doesn't link plugin theme twigs like file-link but tried file-link--<CONTENTYPE>.html.twig anyway. It doesn't work.

None of the variables passed include the node or content type. Any ideas on how to proceed?


texts: As you know drupal has a function " node_type_get_types " that we can use to get the type of the node, so is there also a function that we can use to get the nid of the current node that we are viewing?


texts: Real-time workflow scheduled transitions?

texts:
I have a simple workflow and am trying to figure out a way to get workflow scheduler to make node state changes in real time, at their scheduled time.

I set the state change on a node to occur at 09:00 from draft to live.
If cron runs before 09:00, the state does not change until the next time cron runs.
If the next time cron runs is not until 11:00AM, the state change doesn't occur until 11:00.

This is a problem since editors expect their content to go live when they tell it to go live. This does not seem like difficult functionality, but maybe I missing something basic. I understand that I can run cron more frequently, but it seems crazy that my cron schedule has to match the editor's publishing workflow, as in, "you should always have articles go live at 9am because that's when cron runs". What happens when editors want a node to go live outside of the normal cron schedule? It seems I missing a way for Drupal to "wake up" at this time and run cron to make the node live. Does anyone have a way to do this that I am overlooking? I find it hard to believe that news sites running in Drupal like economist.com or examiner.com don't have this type of real-time scheduling functionality. Thanks in advance.


texts:
How can I disable blocks (e.g., the menu block or the search block) from a custom module?

Concretely I have an access to my clients managed by a custom module, and I don't want anything appears on their access page except my company's logo.


texts: Pass title of current node to subsequent node created in modal

texts:
I need to pass the title of the current node to the title field of an add node form that pops up in a modal using. I am using auto node title which allows the use of tokens as replacement patterns but [current-page:title] results in the title 'Create User Photos', the title of the add node form. Can anyone tell me how to pass the title of the review node either through auto node title or by changing the form's title to match the review node?

I am using the form block module to render the add node form as a block then using js to display it as a modal. I am trying to pass the title to make the nodes related if you will.

I am open to other ways to relate the nodes.

A little context: I've got restaurant review nodes with photo galleries. Users can add photos to a reviews gallery via a modal form that creates a new node containing the photos. I would like the title of the new photo node to match the review node's title but I haven't been able to do that.


texts: How should I upgrade a customized theme?

texts:
I have made some custom changes to my theme files template, CSS and tpl files. Is there a best practice method of updating the theme besides going line by line and re-inserting my custom changes after uploading the new theme?
Is there a better way to approach this in the future?


texts: How do I update modules with security release only using composer?

texts:
On a Drupal 8 site, using the drupal-composer/drupal-project template, how would I go about updating only those modules which have a security release?

Our policy is to not update any module in our monthly maintenance routine unless it has a security update.

Ideally I'd like to find a solution which could be automated.


texts: Header region causing the page to be too wide

texts: When viewing my website on Internet Explorer there seems to be a big space on the right where the page has scroll bars to take in the full width. I think its to do with my header image. It seems ok in Firefox and chrome. Can anyone suggest a way to get this working on IE?


texts: Node Migrations with programmatic url aliases

texts:
Can anyone advice me on how to programmatically create multiple url aliases for each row of a migration?

I am using the Migrate module to migrate page content into Drupal from an XML document.

The existing system has multiple url alias data for each page and I need that same information represented in Drupal - which is proving to be challenging.

I tried doing the following in the complete function of my custom migrate class:

function complete($entity, $row) {
    // drush_print_r($entity);
    // Create an object with our redirect parameters
    $redirect = new stdClass();
    $redirect->source = "node/{$entity->nid}";     // From URL
    $redirect->source_options = array();
    $redirect->redirect = 'http://www.google.com';        // To URL
    $redirect->redirect_options = array();
    $redirect->status_code = 0;            // Redirect Status, 0 is default
    // $redirect->type = 'redirect';
    $redirect->language = LANGUAGE_NONE;
    // Create the redirect
    redirect_save($redirect);

 /****************** **I also tried the following** *******************/
    // $entity->path['alias'] = 'test/testing';
}

I then carryout a sample migration but my url redirects are not present in the node edit area.

Can anyone help, please?


texts: Custom label on shipping service in Checkout

texts:
I am grouping multiple products of an order and ask buyer to select a shipping service for each group.(because they get dispatched from different locations and have different delivery options)

This works ok, I can see the summarised shipping services at the checkout review (e.g. a line for each service with a value of service cost times number of groups this has been selected for).

However I cannot manage to label each shipping line item properly so that we would know what shipping was selected for which group/product.
I am using the flat rate module. The label on checkout review pane is still the title of the shipping service as defined in the backend.

After modifying the line_item_label, the line item shipping service display_title or title, I still get the name of the shipping service instead of my custom text.

I am not using Rules because my logic is too complex. dpm-ing the line items shows the altered title.

Any ideas what to do?


texts: Cache images served in http instead of https

texts:
It's more than one year I have changed my website from http to https. There is still pages that are not correctly served by drupal.
On some pages there are still images that are served by http instead of https, example:

  http://domain.com/site/sites/default/files/ctools/style/_temporary/2d16a055ca7679c4c225b905b9c58939/rounded-shadow-background.png

As this page/image is created live and the image belongs to panels module, I have no idea where to search for this problem, drupal? ctools? panels?
I use the last drupal version 7 with panels, ctools and zen theme.

All caches and views were cleared many times.
Any help is welcome, thanks.


texts: How to show images below a select box according to the value?

texts:
Let's say I have a select box with values : 1, 2, 3, 4, 5, 6. Every value has it's own image, which I want to display as a description below the select field. Any Drupal / AJAX way to show this?

By the way this is NOT a custom form. This is a node creation and edit form.


texts: DatabaseScheme Error when trying to install Jabber

texts:
PROBLEM: Got the following error when trying to install Jabber. This seems like a generic error. I have a feeling that the issue is similar to this post. I created a bug report so the maintainer can either help or include what ever fix comes from this.

  DatabaseSchemaObjectExistsException: Table jabber already exists. in DatabaseSchema->createTable() (line 657 of public_html/d7/includes/database/schema.inc).

BACKGROUND: I have an OpenFire server running and was curious as to the integration with Drupal 7 and O.F. This post talks about the very same thing expect.. XMPP Framework Module is for D6. The alternative for D7 is Jabber.

I've tried both the DEV & BETA branches and both throw the same error on install. On uninstall of the module, there is another error but I've removed all entries into the DB for jabber myself.

If I try to goto the admin/settings/jabber page. It doesn't show up. Thus telling me it wasn't installed right.

How can I fix this error so the jabber module will install properly?

EDIT: After installing the DEV version. I just realized the Jabber settings page does show, although the previously mentioned error still pops. There are also additional errors but those are not relevant to this question.


texts: How to stop the script drush if previous command failed?

texts:
Any idea how can I tell the script/drush to stop when the previous command failed?

Ex:

#!/bin/sh
#
echo "Disabling parallel config..."
drush vset parallel_enabled 0

drush vset preprocess_css 0
drush vset preprocess_js 0
drush cc all

# Disable Mobile theme
echo "Disabling Mobile theme..."
drush dis --yes mobiletheme

# Disable Zen theme
echo "Disabling Zen..."
drush dis --yes zen

# Running the site to offline mode
echo "Running site in offline mode..."
drush vset --yes site_offline 1

# Deleting node revisions
echo "Deleting node revisions..."
drush delete-revisions -y

echo "Clearing all the caches..."
drush cc all

# Rename duplicate files
echo "Renaming duplicate files..."
drush rename-duplicate-files

drush pm-uninstall publication_date -y
drush pm-uninstall date -y
drush pm-uninstall custom_pagers -y
drush pm-uninstall custom_breadcrumbs -y

I want something like this:

#!/bin/sh
#
echo "Disabling parallel config..."
drush vset parallel_enabled 0
if [ ! success ]; then
  echo "The command failed to execute."
  exit
fi


texts: Need filter on value of a field in a specific node of different content type in Views

texts:
I have content type pick_topic, containing an entity ref taxonomy field topic. There is one node of this type. It defines the topic of the month. Several views blocks and pages need to only display content nodes with this topic value. Example: taxonomy topics: dogs, cats, rabbits.

The user (site manager) edits this node and selects a topic from dropdown. Say it is dogs. My view of another content type, articles, contains topic field. How can I filter the view based on the pick_topic topic value equal to the article topic field value, in this case dogs?


texts: Why does form ID get displayed to drupal_set_message?

texts:
I'm upgrading from 6 to 7 (thankless task!) and Ive noticed that in the admin section the name of any form that is on the page seems to get output to drupal_set_message (it appears in the green box) I thought this to be unusual but possibly deliberate on the part of the module author. However, in my custom module I have a form and when ever I go to the page the name of the form appears in the green status box.

Can anyone shed any light onto why this may be happening?


texts: How should I implement hook_help()?  Should I output the content of the README.txt file, or inline text?


texts: One time change field + personal comments

texts:
I'm not very familiar with all the modules for Drupal. Therefore, let me try to explain what I'm looking for.

1) The users shall be able to create nodes with some specific fields. Some of those fields shall be writable only one-time.

2) To this node only the author and users allowed by the author shall have access.

3) Additionally the users who have access to nodes of another user shall be able to make comments (including attachments). Something like a discussion forum to each node, but only the author of the node and the creator of the comment shall see their nodes.

Hope it's somehow understandable.

Are there any kind of modules for any of the above requests?


texts: How to reuse existing images in field type "Image"

texts:
I have custom ContentType with one field of type Image.
Currently, when I edit a node I can only upload new images from local to server.
I want to have the option to select images already existing on the server.

I think that the way to go is to use the EntityBrowser and/or FileBrowser modules
but I don't know how to make this work.
I can create the EntityBrowser instance but how do I tell the ContentType field Image to use it?

I'm on Drupal 8.

Your help is appreciated.
--Josef


texts: Delete block settings when removing a block from hook_block_info()

texts:
My module creates blocks. These may come and go and I want to make sure I'm not leaving cruft behind, e.g. settings from the configure block screen for blocks that no longer exist (i.e. are no longer returned by my hook_block_info()).

I've noticed that removing a block and then adding a new one (with the same delta) magically brings up the old config.

What should I do in my module to clean out this config? (or is it somehow done for me in an occasional cron?)


texts:
I am using content type in Facet. The search result will be having an option to choose the content type to filter the result.

I want the search should show the result with particular content-type filtered by default. Is it possible? If so, how to do that?

To be little more clear instead of

https://example.com/searchpage?search_terms=xxxx

I want to search as following by default.

https://example.com/searchpage?search_terms=xxxx&f[0]=content_type:content_page&f[1]=content_type:cotent_page


texts: How to get XML/JSON data for api.drupal.org?

texts:
In my earlier question How to get node IDs from drupal.org?, I can get the XML data of a node by going to https://www.drupal.org/api-d7/node/274365.xml where 274365 is the node id of a particular page. In similar way I can access all the node in drupal.org Website.

Now I want the same kind of XML data for a node pages in https://api.drupal.org.

For example what is the XML data page for https://api.drupal.org/api/drupal/includes!module.inc/group/hooks/7 ?


texts: Send argument to custom field constraint

texts:
I have created custom field type with custom constraint defined and called successfully, the question is how to send the field settings to my constraint in the code block below.

/**
 * Plugin implementation of the 'custom_field_type' field type.
 *
 * @FieldType(
 *   id = "custom_field_type",
 *   label = @Translation("custom field type"),
 *   description = @Translation("custom field type"),
 *   default_widget = "number",
 *   default_formatter = "number_integer"
 * )
 */
class CustomFieldType extends IntegerItem {
  /**
   * {@inheritdoc}
   */
  public static function defaultFieldSettings() {
    return array(
      'type' => array(
        '#type' => 'radios',
        '#title' => t('type Validator'),
        '#default_value' => 'none',
        '#options' => [],
        '#description' => t('types.'),
      ),
        ) + parent::defaultFieldSettings();
  }

  /**
   * {@inheritdoc}
   */
  public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
    $type_options = array(
      'type1' => t('type1'),
      'type2' => t('type2'),
      'none' => t('type1 and type2'),
    );
    return array(
      'type' => array(
        '#type' => 'radios',
        '#title' => t('type Validator'),
        '#default_value' => $this->getSetting('type'),
        '#options' => $type_options,
        '#description' => t('types.'),
      ),
    );
  }

    /**
   * {@inheritdoc}
   */
  public static function propertyDefinitions(FieldStorageDefinitionInterface $field_definition) {
    $properties['value'] = DataDefinition::create('integer')
      ->setLabel(t('type'))
      ->addConstraint('CustomCheck')
      ->setRequired(TRUE);
    return $properties;
  }
}

How to send the field settings as arguments to the constraint as the validation only takes the field value as parameter.

/**
 * Validates the CustomCheckConstraint.
 */
class CustomCheckConstraintValidator extends ConstraintValidator {

  /**
   * Validator 2.5 and upwards compatible execution context.
   *
   * @var \Symfony\Component\Validator\Context\ExecutionContextInterface
   */
  protected $context;
 public function validate($data, Constraint $constraint) {
//do custom check here
}
}


texts: Using Contextual Filters to Filter "Content: Published"

texts: Is there any solution to filter "Content: Published" with Contextual Filters?


texts: Bulk update got slower after conversion of database tables to InnoDB

texts:
After I converted the database tables to InnoDB engine from MyISAM, I noticed some operations became very slow, especially on updating multiple nodes in bulk for administrative work. Front end performance seems to be good.

I have tried configuration settings suggested in these articles without any luck: MySQL > YourSQL, and MySQL Performance Blog.

My test script would load 25 different nodes (node_load()) and save them right away (node_save()) in a loop. This script runs for 2 seconds on the server with MyISAM engine; after DB conversion to InnoDB, it now takes 13 seconds.

It also takes much longer to restore InnoDB database from a SQL dump of 500MB; 20 minutes (InnoDB) vs. 2 minutes (MyISAM).

Is this what I should expect from InnoDB engine?

New to InnoDB engine, I'd like to know what I might still be missing in configuring and optimizing InnoDB.


texts: How to 'inject' the "read more" link into a textfield / paragraph (inline)

texts:
Due to client's demand the situation is that I can't use the default (trimmed) body text as a teaser text in a view listing nodes. Instead I have an extra text field which contains 2-3-4 paragraphs so that the client has 100% control of what the teaser text would look like etc.

I would need to place a "read more" link at the end of that custom teaser text. I tried different methods to place such a link inline with the teaser text – but couldn't find a way to actually have a working setup.

I tried the read more module – which works fine with standard situation, replacing/placing the "read more" link inline – but that won't help me here.
I tried overriding the field in views – but that won't let me place the "read more" inside the last paragraph. Either I keep properly formated paragraphs, or I use "inline" or "inline-block" for the p but then the paragraph-structure collapses.
I also tried the read more control module – but that seems to solve problems that I don't have (hiding "read more" links if there is not 'more' to read)

I suppose this must be possible – and would gladly appreciate any tipps or pointers that would lead me in some direction.. thnx!


texts: Replacing Private message module with nodes

texts:
I was looking for a quick answer to the problem of allowing members to write each other messages. The Private message module looked like the most complete solution.

However, it has some significant downsides.

I can't find an API for it anymore. All the links are dead.
It uses awful HTML output which is not responsive so refer to problem 1.
It's not integrated with views!

So I wonder if a poor man's messaging system that simply uses nodes and views would be a more versatile, future proof and potentially more performant replacement. Is private messages dramatically more performant(such that it's downsides are worth it) than using nodes and views for private conversations, of which there would be potentially many?


texts:
I have a view that should show all the images. However, its only showing the first one. All images are set to publish and the sort criteria is set to ASC.

Any ideas?


texts: How can I allow a user to create a user, but not view all users?

texts:
In Drupal 7, I can set the 'administer users' permission to a certain role. However I do not want this role to be able to view and filter/search all users in my Drupal site. The admin/people/create only, but no admin/people  page should be accessible because they have the capability to filter the administrator role! And able to edit it in turn.

Is there a module that can do this?


texts:
I migrated my web to webhosting. There is a problem when I want to add new content, it's not able to add new content with images or files. Do you know where to look to solve it? Does it relate to access rights to directories where Drupal stores those files or is it something else?

When I want to upload an image, it writes:

Warning: move_uploaded_file() [function.move-uploaded-file]: Unable to access public://image.jpg in file_save_upload() (line 1528 of /web/www/x.y.com/includes/file.inc).
File upload error. Could not move uploaded file.

thank you


texts: What is the best practice to change content links based on a class in drupal? I want to have www.example.org transformed to some text based on foo. Should I use hook_view(), or hook_nodeapi()?


texts: In Commerce 2, is it possible to have the product variation automatically created during product creation?

texts:
We have a Commerce 2 store whose products will always only have one variation.

The current workflow to create a new product and its variation is a bit complicated for the user's who will be entering in the product data.

Out of the box you have to click the 'create variation' button after entering in the variation information. There is then additional option buttons to Edit, Remove, or Duplicate the variation.

We'd like to streamline this process and have the single variation created automatically so all the user needs to do is enter a price during the product creation and not have to click any additional buttons.

I was hoping there was a module available that would facilitate this functionality but I was unable to find one.

If not module exists, what would be the best way to achieve this?

Perhaps a custom 'product' form that then creates the Commerce Product programmatically when the form is submitted? I don't really like this idea because I would also have to consider editing the product as well.

Would some custom code be able to tweak the existing workflow to hide the variation info and create it automatically? Perhaps getting the price from a custom price field added to the product entity?


texts: get rid of dropdown list on views exposed filter

texts:
I created a view with an exposed filter, that I set to autosubmitt. So when I start typing in the filter field, the list of items does get filtered live. So far I'm happy.

What I don't like is the dropdown list that also gets updated while typing. How can I tell this field to stop showing a dropdown list at all?