texts: How can I loop through all different Product Types in Craft Commerce?

texts:
I am trying to have a overview page where I want to loop through all available product categories in separate rows. Somehow I was only able to achieve it when I specify the type of the product. That isn't ideal since I want the customer to be able to add new product types which will be displayed in a new row then.

Something like this :

{% set products = craft.commerce.products.type('all').find() %}

{% for 'type #1' in products %}
    ...
{% endfor  %}

{% for 'type #2' in products %}
    ...
{% endfor  %}

etc..

thanks a lot guys


texts: Render image transforms on the staging server

texts:
Are normal workflow involves developing the site locally but making all the database level changes (fields and data) on the sever.

The trick has always been assets.  We don't bother syncing assets, just the database which works fine except when it comes to newly defined image transforms.  They need to be run on the server first to work properly locally.

We end up using Amazon s3 mostly to get around this exact issue but it would be better if I could somehow set a config setting that would tell all my image transforms to use the staging domain.  Is that possible somehow?


texts: Advanced queries with assets and other custom fields

texts:
To optimize performance, I'm trying to create an advanced entry query that selects only specific variables. I can set up the query to grab the entry title, uri, and a custom variable I created ("email" variable). But I don't know how to also select an asset as well. I basically want to create an advanced query that lets me publish the name, uri, email and asset (image variable called 'headshot').

Here's what I have. Just not sure what I need to also add in mu select to get my image asset.

{% set entries = craft.entries()
    .section('persons')
    .select('elements.id, elements_sites.uri, elements_sites.siteId, entries.sectionId, entries.typeId, content.id, content.title, content.email')
    .with(['headshot']
    .all()
%}


texts:
In Craft docs element queries article, there is section "advanced element queries", with methods like where, groupBy etc.
What are example use cases of these methods in Twig templates or PHP modules?


texts:
Does anyone have an experience in using Craft in conjunction with a front-end JS MVC/MVVM framework such as Backbone, Ember or Angular?

We have a project coming up where there may be a lot of JS state management requirement and AJAX calls required, and would like to access back-end data using JSON. However, there is also a strong need for a robust easy-to-use CMS as there will be a lot of content to administer.

My first port of call for this type of application would be some more general server-side framework such as Laravel, but Craft has sort of spoiled us with the content management side of things.

Is there any way of marrying Craft with this kind of project?


texts: Find specific image from global image set?

texts:
I am using a global set to store image assets used across the site.  I am not sure how to reference a specific image. I know how to get the image if its just one, using :

{{ design.imgs | length ? design.imgs.first().getUrl() : '' }}

What if there are several images and I am looking for a specific one?


texts: How can I make an entries query based on currentUser is author or relatedTo currentUser

texts:
My project requires a notifications area. I want to list all notification entries that were created by currentUser or sent to currentUser.
I can do created by = craft.entries().section('thename').authorId(currentUser.id).all()
I can do sent to = craft.entries().section('thename').relatedTo({ targetElement: currentUser, field: 'thefield' }).all()
But is there a single query that will get both?


texts: How do I create a locale dropdown to switch between languages?

texts:
I’m trying to create a dropdown menu to switch between language’s on my site. I am currently doing this with this snippet found on the google plus community:

{% block locale__switch %}

{# Loop through all of the site locales, except the current one #}
{% set otherLocales = craft.i18n.getSiteLocaleIds()|without(craft.locale) %}
{% for locale in otherLocales %}

    {# Find the current entry in the other locale #}
    {% set localeEntry = craft.entries.id(entry.id).locale(locale).first %}

    {# Make sure that it's actually localized to this locale #}
    {% if localeEntry.locale == locale %}

        {# Output a link to it #}
        {{ locale }}
    {% else %}

        {# Output a link to the hompage #}
        {{ locale }}
    {% endif %}

    {% endfor %}
{% endblock %}

But this simply shows a single link to the opposite locale than the current. Basically I want to have something like this:

EN &#9662;

               English

en &#9662;

               Hungarian

hu &#9662;

This probably seems trivial and simple, but I’m having a tough time figuring out how craft works at this level. Any ideas?


texts: Can I find log activity of who deleted a user and who edited an entry?

texts:
Is there a 'latest greatest' tool that I can add that has ongoing logging of disable/enable and delete/update activity of users or entries, etc..?

Is there a good way to track this information before I add on a logging tool?  In other words, is this information somewhere in the mysql database anyways?

I know the current dashboard shows information related to entry creation, but, we have some new users that we are training and they have made some mistakes and we need to track those mistakes down.

thanks!


texts:
I have a simple plugin that's expected POST data from a form:
<form method="post" action="" accept-charset="UTF-8">
    <input type="hidden" name="action" value="{{ actionUrl('broadbean/jobs/new') }}">

When I submit the form, that fails:

Page Not Found
Unable to resolve the request "http:/craft.dev/index.php/admin/actions/broadbean/jobs/new".

If I cut and paste that URL into a new window, I get the plugin response, so what gives here? The plugin is set up to allow anonymous access (but I'm submitting the form from within an admin view anyway).
EDIT:
According to http://buildwithcraft.com/docs/plugins/controllers#posting-to-controller-actions I should be able to put the action URL in a hidden field, which I've done. If I dispense with that and instead put the actionUrl() directly in the form's action parameter, everything works.
Is this a bug? This is on Craft 2.2.2601.
EDIT:
Controller code:
class Broadbean_JobsController extends BaseController
{
    protected $allowAnonymous = true;

    public function actionNew()
    {
        $this->requirePostRequest();

        $result = craft()->broadbean_jobs->createJob();

        var_dump(array(
            'message' => ($result['success']) ? Craft::t('Job created.') : Craft::t('Unable to create job.'),
            'values' => craft()->request->getPost(),
            'errors' => $result['errors']
        ));

    }
}


texts: Custom element from plugin in structure-like hierarchy

texts:
I'm working on a plugin that would require a custom element to have a hierarchy, as in, possibly have a parent set or not. Much like entries have when used in a structure.

I've got my element set up and all the custom fields and the title get saved just fine, however I've hit a wall trying to get them have a parent.

I've tried setting the parent property to another element and after I hit save, it does not seem to properly register it.

Is there a specific way to go about this? The documentation is rather sparse on implementing a hierarchical custom element.

Any pointers or examples on how to implement this would be greatly appreciated.


texts: Guest Entries - Saving entries as drafts

texts:
We're using Guest Entries for comments. When the user posts an entry it automatically appears as a published entry. I'd like to change this functionality so that the entry will enter as a draft until approved.

I've set the user's permissions to "edit entry" but that doesn't seem to do the trick.

Any help would be appreciated.


texts:
Code:

{% for block in entry.testimonials %}

        {% switch block.type %}

        {% case "testimonials" %}

{{ block.personsName }}

          {{ block.quote }}

          {% for asset in block.image %}

          {% endfor %}

        {% endswitch %}

{% endfor %}

Can anyone point out why the...

loop.index0 is divisible by(2)

I have on the div around the image isn't working. I'm getting the 'last' class on everything. The one on the previous div is working fine.

What am I missing?

EDIT:

I've just realised it's in it's own image loop causing the problem. How can I get around this?


texts: Freeform: How do I detect if a form was submitted?

texts:
I'm need to send a google analytics tracking event when a form is submitted. To do that, I need to know on any page of the site if a user has landed there as a result of a form being submitted.

Given that the client can create their own forms, I can't rely on URL parameters, and it could be any form, so I can't set the form handle manually.

How do I detect if any form was submitted?
Freeform's docs explicitly name a form handle, which isn't a dynamic approach ( https://docs.solspace.com/craft/freeform/v3/template-functions/freeform.submissions.html#usage-in-templates ).


texts: Publishing entry returns Internal Server Error (1030 Got error 139)

texts:
Trying to publish changes in one of 3 locales of an entry gives error:

Internal Server Error
CDbCommand failed to execute the SQL statement: SQLSTATE[HY000]: General error: 1030 Got error 139 from storage engine

It is basically a row size problem.
The entry has many fields and there are 3 locales. It is possible to save a draft of the changes made.
What i tried:
On staging server I have solved the problem with changing the database config

innodb_file_per_table=1
innodb_file_format = Barracuda

and then changing row format of some tables (entries, content and fields) to compressed.
This is not possible on live production server since host does not allow it. And also it probably is not the best solution.
I also tried to change the table engine to MyISAM but this gave error:

SQL Error [1217] [23000]: Cannot delete or update a parent row: a foreign key constraint fails

I hope there is a simple solution to all this.
Thank you for your help, I am a bit green in all this, my background is in design.


texts: getPrev and getNext stop working after 100+ entries

texts:
Prev and Next stop working after 100 entries..  There are no template errors.  I can access the pages for the individual entries - but Next and Previous are blank.

Here is my set up...

{% set criteria = {section: 'posts'} %}
{% set prev = entry.getPrev(criteria) %}
{% set next = entry.getNext(criteria) %}

{% if prev %}
my html ...{{ prev.url }} ...my html
{% endif %}

The same holds true for next.

Once there was a template error referencing a null value on prev.url - and referencing an entry ID that no longer appears to exists.  However, I discovered that I had had prev under if next.  That is the only time I was able to produce a template error.


texts:
I'm learning how to use Craft. I've set it up locally using MAMP (regular) on OS X Yosemite (10.10.5). Everything is working fine until I start getting into Twig templates. When I try viewing files that contain twig code in any browser, the browser shows the twig code as content (for example, I see{% block main %} and {# comments #} within the window). I'm thinking this is a MAMP issue.

However, as I understand it, Craft itself uses Twig. If that's the case, then it wouldn't be a MAMP issue, since then both the Craft admin site and my files wouldn't work. Any hints as to where the problem lies would be greatly appreciated. Thanks!

Update: Trying to access it through MAMP Pro to see if that makes a difference. Now I'm being blocked right after the root. Here's a pic of the error (result with localhost in the URL not the file path):

I don't know anything about Apache -- is it safe to display my entire httpd.conf code online to see if anyone knows it's a setting in that files that's causing the issue? I'm sorry -- this question/thread is all over the place.


texts:
For the past couple of months now, I've noticed on my websites using the SearchPlus plugin that indexes are no longer syncing with Algolia. This also means that creating new search indexes is not possible.

I've been updating indexes manually via the Algolia dashboard, but this means that I can't create new indexes at all.

My best guess is that the plugin is no longer compatible with Algolia's API. Has anyone encountered this, or come up with a fix for this issue?


texts: General speed/performance on large Craft build

texts:
Looking for hints and tips on speeding up and streamlining performance of a Craft site as we prepare for launch.

The database is approaching 100MB and whilst it is a fairly large and complex build (multiple locales with fairly extensive use of Matrix) this seems fairly excesive and page load times can be slow. Have looked at the Patrick Pohler post but any general, system level wins would be great as site is crawling a fair bit.

Am getting some performance increase through use of {% cache %} tags but then hitting DeleteStaleTemplateCaches issue qiute regularly which is stopping tasks running.

Any help appreciated!


texts:
Is it possible to restrict access to a page based on a visitor's country?

For instance, only users in the US can view the FAQ page?

Thanks!


texts: Porting from EE - How to filter by category/segment in one template

texts:
Sorry if there is an answer out there for this, I've read quite a few posts but have got myself confused. I hope you can point me in the right direction.

I have this code in my EE template:

{exp:switchee variable="{segment_2}" parse="inward"}
{case value="''"}
{exp:channel:entries channel="portfolio" dynamic="no" status="open" disable="pagination|member_data" orderby="date" sort="desc"}

    {cf_portfolio_link}
    {cf_portfolio_image}
    {title}

{/exp:channel:entries}
{/case}
{case default="yes"}
{exp:channel:entries channel="portfolio" dynamic="no" category="{segment_2_category_id}" status="open" disable="pagination|member_data" orderby="date" sort="desc"}

    {cf_portfolio_link}
    {cf_portfolio_image}
    {title}

{/exp:channel:entries}
{/case}
{/exp:switchee}

I'd like to do the same in Craft - use one template and filter my entries by segment(2).

At present I have this code in my Craft template (the first case works, the second returns a 404):

{% switch craft.request.getSegment(2) %}
{% case "" %}

{% for item in craft.entries.section('portfolioImages').order('id desc') %}

    {% for image in item.image %}

    {% endfor %}

{{ item.title }}

{% endfor %}

{% default %}

    filtered entries to go here

{% endswitch %}

The URL for my portfolio page is mysite.com/work or mysite.com/work/ecommerce-websites if it has been filtered.

I do have a category group set up in the system called Portfolio with 3 top level categories only:

ecommerce-websites
promotion-websites
product-catalogue-websites

Not sure where to go from here now.

Let me know if you need further information.

Cheers


texts: Updated To Craft 3, How To Delete Craft 2 Plugins

texts:
I moved from Craft 2 to 3 but some of the plugins I used at one-time and are no longer compatible with Craft 3.  Those old plugins are now ghosts.  Meaning they are listed in the database and some have their own tables.

How to best get rid of old Craft 2 plugins?


texts: Test for specific or multiple product variants

texts:
I'm trying to test if a product has multiple variants AND/OR test for specific product variants.

{% if product.variants|length > 1 %}

That does not seem to work, even if it is a non-variant product. I understand that even for products without variants there is a 'default' variant, but shouldn't this return false if its a product type without variants given it should have only 1?


texts: How can I get the locales that are actually enabled for a given entry?

texts: I can use getLocales() off of the entry model to get all locales in the system, and whether they are enabled by default for that entry type, but it doesn't actually return which locales are enabled for that given entry. Am I missing something?


texts: Migrate multiple Craft 2 CMS sites on cPanel

texts:
I am completely new to Craft CMS but need to migrate multiple sites at a current hosting provider away to AWS.

Due to a hard deadline, I have been looking at a lift and shift approach for the time being - using a cPanel AMI in AWS and then moving the sites across.

  Does anyone have any experience of moving sites from cPanel to cPanel particularly Craft?

I’ve tried one site already but get a 500 internal server error when trying to browse the site. I’ve amended the db.php file to connect to the database and that looks ok.

Could anyone give me some pointers on the best way to move the sites and anything I need to look out for along the way?

Any pointers or recommendations would be really helpful.

Thank you.


texts: What SQL query can I run to remove all users assigned to a particular group?

texts:
So I have a user group containing a few thousand users and I want to remove all of those users with a SQL script.

These users don't have access to the control panel and so don't have any Entries authored by them.

At the moment I have this:

DELETE FROM elements WHERE id IN (SELECT userId FROM usergroups_users WHERE `groupId` = 5);

It looks like this removes related entries from the users, usergroups_users and content tables by virtue of the foreign key/cascade constraints.

Is there anything else I need to clean up?


texts: Production siteUrl being used in staging environment

texts:
I'm using the following multi-env config. My dev config works as expected. However, when I visit my staging site, it is setting the siteUrl to the production Url

    <?php

    // Dev URL
    $devUrl_au  = "au-site.dev";
    $devUrl_nz  = "nz-site.dev";
    $devUrl_us  = "us-site.dev";

    // Testing URL
    $testUrl_au = "test.site.com.au";
    $testUrl_nz = "test.site.nz";
    $testUrl_us = "test.site.co";

    // Production URL
    $liveUrl_au  = "site.com.au";
    $liveUrl_nz  = "site.nz";
    $liveUrl_us = "site.co";

    return [
        /***************************
        GLOBAL CONFIGURATION
        ***************************/
        '*' => [
            'environmentVariables' => [
                'assetUrl'  => '/',
            ],
            'doAnalytics' => false,
            'omitScriptNameInUrls' => 'auto',
            'enableCsrfProtection' => true,
        'siteRoutesSource' => 'file',
        ],
        /***************************
        DEVELOPMENT
        ***************************/
        '.dev' => [
            'devMode' => true,
            'enableTemplateCaching' => false,
        ],
        $devUrl_au => [
            'siteUrl' => [ 'en_au'  => 'http://' . $devUrl_au . '/',],
        ],
        $devUrl_nz => [
            'siteUrl' => [ 'en_nz'  => 'http://' . $devUrl_nz . '/', ],
        ],
        $devUrl_us => [
            'siteUrl' => [ 'en_us'  => 'http://' . $devUrl_us . '/', ],
        ],
        /***************************
        STAGING
        ***************************/
        $testUrl_au => [
            'siteUrl' => [ 'en_au'  => 'http://' . $testUrl_au . '/', ],
        ],
        $testUrl_nz => [
            'siteUrl' => [ 'en_nz'  => 'http://' . $testUrl_nz . '/', ],
        ],
        $testUrl_us => [
            'siteUrl' => [ 'en_us'  => 'http://' . $testUrl_us . '/', ],
        ],
        /***************************
        PRODUCTION
        ***************************/
        $liveUrl_au => [
            'doAnalytics' => true,
            'siteUrl' => [ 'en_au'  => 'http://' . $liveUrl_au . '/', ],
        ],
        $liveUrl_nz => [
            'doAnalytics' => true,
            'siteUrl' => [ 'en_nz'  => 'http://' . $liveUrl_nz . '/', ],
        ],
        $liveUrl_us => [
            'doAnalytics' => true,
            'siteUrl' => [ 'en_us'  => 'http://' . $liveUrl_us . '/', ],
        ],
    ];


texts: Filter Entries field by category in the CP?

texts:
Is it possible to filter relations entries field by a category in a control panel entry?

I would like to relate two channels using the entries field but I have 100 source entries so I was hoping to be able to filter the list by category to narrow down what is shown in the target entry. Similar to how EE Playa works which allows me to choose the category in which to pull the related entries from when I initially set up the custom field.

Here's a similar thread:
Filtering/searching for entries by category in the control panel


texts:
Has anyone ever tried using Structures instead of Singles? I'm developing something that's kind of like multiple sites in one, they share the same central design, just with content differences and a few colour changes. I thought if I could use a Structure instead of Singles, I could contain each section to a specific area (making it easy to maintain), and use Entry Types to decide on the content.

The problem is with using a Structure is I keep getting Variable "entry" does not exist. errors. Any suggestions?

If anyone can suggest a fix, or a better way of handling something like this, I'd love to hear it!

Thanks


texts: Check the site for missing file links / warn user before removing used files

texts:
A client removed a lot of files in a moment of clarity, not realizing these were used in pages (thinking since they were used in those pages, they were no longer necessary in the assets system).

Before I completely reset the site to a few weeks ago (that was the time before they realized); is there a way to check the site for missing file links, including those in redactor?

Also is there any strategy for preventing clients from removing used assets? In WP for instance you can see which images are "attached". This is not waterproof, but still.


texts:
I've used expression engine but not Craft. I am looking for a CMS more flexible than WordPress. I need to have admins enter location or addresses of meetings and then allow site users search for locations close to them or close to a specific address. Part of the use case is that meeting locations would be posted if the meeting is open or just a contact if the meeting is closed.

Would Craft be a good CMS for this? What about the geo stuff?


texts: Calling a method from a service in another plugin from an event

texts:
I'm having a problem calling a service method from another plugin when hooking into the beforeSend event in the ContactForm plugin. I have the code below in a super simple plugin called ContactFormExtra to catch if someone wants to also subscribe to our newsletter when they fill in the contact form. I have another subscribe plugin setup with it's service class having the methods to do the subscribing - which also handles a simpler subscribe form without the contact form fields. Any ideas on how this could work - or do I need to put all the subscribe stuff again into the ContactFormExtra plugin?

This follows the example on GitHub for pixelandtonic/ContactForm

When trying to subscribe on the contact form, I get this error:

Craft\ContactFormExtraPlugin and its behaviors do not have a method or closure named "_getSettings".

Looks like it's trying to call the Subscribe plugin's functions from the ContactFormExtra plugin?

If I don't choose to subscribe and submit the form, then the Subscribe plugin service call is skipped, moving on to the calls on the ContactFormExtra plugin's service. Then I get this error:

Property "Craft\WebApp.contactformextra" is not defined.

Simple ContactFormExtra plugin code:
(plugins/contactformextra/ContactFormExtraPlugin.php)

class ContactFormExtraPlugin extends BasePlugin
{
  public function init()
  {
    craft()->on('contactForm.beforeSend', function(ContactFormEvent $event) {
      $message = $event->params['message'];
      $subscribe = craft()->request->getPost('subscribe');
      $attribs = $message->getAttributes();
      if ($subscribe == 1) {
        $result = SubscribeService::subscribe($attribs['fromEmail']);
      }
      // save the record
      $attribs = $message->getAttributes();
      $attribs['subscribe'] = $subscribe;
      $enquiryModel = craft()->contactformextra->newEnquiry($attribs);
      craft()->contactformextra->saveEnquiry($enquiryModel);
    });
  }
  ...
}

ContactFormExtra plugin service code:
(plugins/contactformextra/services/ContactFormExtraService.php)

class ContactFormExtraService extends BaseApplicationComponent
{

    public function newEnquiry($attributes) {
      // do stuff here
    }

    public function saveEnquiry(ContactFormExtra_EnquiryModel &$model) {
      // do stuff here
    }

}

Subscriber plugin:
(plugins/subscribe/services/SubscribeService.php)

class SubscribeService extends BaseApplicationComponent
{
  protected $settings;

  private function _getSettings()
  {
    $plugin_settings = craft()->plugins->getPlugin('subscribe')->getSettings();
    $this->settings = $plugin_settings;
  }

  public function subscribe($email)
  {
    $this->_getSettings();
    // do the subscribing here...
  }

}


texts: Search Results In a Drop List/Popup on Same Page

texts:
Does anyone have an example how I would implement search results that appear in a popup on the same form (without redirecting to a results page). The idea would be that as they start to type in the search bar, after a delay I'd show a popup with a few results.

I'm good on the jS, popup part. The part i don't know about is how i would call craft cms dynamically on the same page to get the results (would i do this with JS or with the form tag, can i make the request with JSON/Ajax?). All the examples show the form directing to a results page.

Anyone have any suggestions


texts: Expected performance benefit of using a non-file CacheMethod (Redis, Memcache)

texts:
I'm wondering what kind of performance increase, and in what situations, I might expect from using Redis or Memcache over the default file-based caching.

I know template caching always comes from the DB, so I'm not sure what else I can expect to be cached from Craft itself, and how that might impact site performance.


texts:
I'm trying to group entries by user on my front-end. I've got so far but I can't seem to get any further to my goal of displaying what type of entries they have posted e.g. lifestyle or tech. to do this I need to get the users entries and query a service dropdown field, if they have lifestyle selected in multiple entries only display 1x tag showing the user has lifestyle posts.

So far I'm just trying to query each user's entries.

{% set listings = craft.entries.section('listings') %}
{% set users = craft.users.group('influencer').all() %}

      {% for user in users %}

          {% if user.getPhoto() %}

          {% else %}

          {% endif %}

{{ user.username }}

            {{ user.location }}

{{ user.richText }}

        {% for user, entries in craft.entries.find() | group('users') %}
          {% for entry in entries %}
            {{ entry.title }}
          {% endfor %}
        {% endfor %}

      {% endfor %}


texts: Order history access item/cart totals in payment currency

texts:
I'm a bit confused at how to show previous orders taken in another currency. For example, if I take a payment in EUR but my default currency is GBP the order price (eg subtotal, tax, total, etc) are stored and later retrieved in GBP. If i want to show the amount taken based on the currency used at payment - ie. EUR - I know I can access paymentcurrency from the cart/order object for that currency.

However, I want to convert these based on the conversion rate that was in the CMS at the point of the transaction (which is liable to change at a later date). Is there a way to access the order and item totals for an order in the currency that the item was paid with using the currency conversion rate from when the order was placed?

Sorry if this is straightforward but finding it hard form the documentation and sample templates to work this out.


texts:
Require a little help with removing the pre-parsed text from Dukt's {{ twitterTweetButton() }}

This does not work....

The docs specify the following Twig functions:

text — Pre-populated text highlighted in the Tweet composer.
url — URL included with the Tweet.
hashtags — A comma-separated list of hashtags to be appended to
default Tweet text.
via — Attribute the source of a Tweet to a Twitter username.
related — A comma-separated list of accounts related to the content
of the shared URI.
size — Set to large to display a larger button.
lang — A supported Twitter language code. Loads text components in
the specified language. Note: does not affect the text of the cited
Tweet.
dnt — When set to true, the Tweet and its embedded page do not
influence Twitter targeting including suggested accounts.


texts: Additional criteria to filter status of field passed into RelatedTo

texts:
I'm trying to save all the images related to an entry in a variable. I need the images that are added through a matrix field in the entry. I'm using the following code, but am then also getting images associated with disabled matrix blocks. I only need images from matrix blocks that are enabled.

FYI - body and builder are matrix fields and asset is the corresponding block handle.

{% set imageAssets = craft.assets().relatedTo([
  'or',
  { sourceElement: entry, field: 'body.asset' },
  { sourceElement: entry, field: 'builder.asset' },
]).all() %}

Is there a way I can add conditions onto the fields that I am passing into the relatedTo parameter?


texts: From AttributeType::Enum in Model to a matching selectField?

texts: So I have a model with an Enum and I want a selectField for that Enum. Is there a DRY way to do that ? And if yes does it work with the translation-filter ?


texts: Craft 3 redirecting me 404 after fill up registration form

texts:
I have created copy whole HTML from here (https://docs.craftcms.com/v3/dev/examples/user-registration-form.html). and trying to register but it's showing me an error or we can say it redirects me to 404 error.

URL: lawbros.uldev.co/users/registration.html


texts:
I'm creating a simple site where the user can buy exactly 1 product for exactly 1 price. My client wants to offer PayPal to the users for paying this product.

Which solution/plugin/whatever do you propose? Commerce seems to be a bit too big for this, I don't have lots of products with specifications, etc. But I didn't find any other plugin that can handle PayPal. Any ideas?


texts: HTML being stripped/replaced by redactor on initialising despite being saved correctly

texts:
When i enter HTML into redactor below it will strip out the first closing div and the second opening div leaving one col-md-6.  It actually saves it as I have below but as soon as redactor is re-initialised it strips out the closing and opening tag in the middle again.  This means no one can ever go in an edit the content as it will be a single column again once saved. Current setup of redactor is below and I have unchecked the clean HTML.

One Col

One Col

Redactor JSON config:

{
        buttons: ['html','formatting','bold','italic','unorderedlist','orderedlist','link','image','video'],
        plugins: ['fullscreen'],
        toolbarFixedBox: true,
        replaceDivs: false
        replaceDivs: false,
        paragraphize: false,
        removeEmpty: ['strong', 'em', 'span', 'p']
    }

Any ideas how I can get it just to accept the HTML we enter without problems?


texts: How would I pass and entry's field value to an include?

texts:
I have this:

{% include "partials/includes/page-header" with { 'title' : '{{ entry.heading }}' } %}

But it seems that nothing I do will actually pass {{ entry.heading }} as 'title' in the include.


texts: I'm creating a structure page for collections. What is the best way to display collections by year? Should I use tags? How can I implement that?


texts:
Folks:
A site I have works great in test and has been pushed live. Orders do not complete on the live site. When the transaction is submitted "Card confirmed" appears (I'm riffing off the included templates) and the page hangs. No transaction goes to Stripe and no confirmation email is fired.
I have added the live keys so that's not the issue. Perhaps webhooks are needed?
Any help would be great.


texts: Building Results From Advanced Search Form

texts:
I'm building an advanced search form and having some difficulty with getting the results. The form inputs include price and year ranges. For example, search for used cars from $10,000 to $20,000.

The search is working, here's my results page code:

{% set manufacturer = craft.request.getParam('manufacturer') %}
{% set model = craft.request.getParam('model') %}
{% set bodyStyle = craft.request.getParam('bodyStyle') %}

{% set minPrice = craft.request.getParam('minPrice') %}
{% set maxPrice = craft.request.getParam('maxPrice') %}

{% set startYear = craft.request.getParam('startYear') %}
{% set endYear = craft.request.getParam('endYear') %}

{% set results = craft.entries.section('usedCars').type('entry').search().manufacturer(manufacturer).model(model).bodyStyle(bodyStyle) %}

This is how i'm showing the price range.

{% if minPrice|length and maxPrice|length %}
{% for entry in results if entry.price <= maxPrice and entry.price >= minPrice %}

{% if minPrice is empty and maxPrice|length %}
{% for entry in results if entry.price <= maxPrice %}

and so on etc...

The trouble with this method is it's all based on a whole stack of "IF" statements and when I start to think about adding the year ranges too, my head starts to hurt. Is there an easier way to achieve the same thing?

I'd appreciate any nod in a general direction, or help simplifying my code down...


texts: getUrl using my original develpment server domain

texts:
I have the following code and after moving site to a live server, the img src is using the old domain, however, the anchor links have correct domain name.  Any idea what the issue is?

                                {% for block in entry.threeHomepageImages.type('images') %}

                                                {% if block.image|length %}

                                                {% endif %}

{{ block.imageTitle }}

                                {% endfor %}


texts:
I've done a few installs of Craft and never had a problem. I'm currently trying to do an install on a new server under a subdmomain and getting the following results…

This results in 404
http://staging.example.com/admin

Using /index.php/admin or /index.php?p=admin results in Internal Server Error 500.


texts: FreeForm fields: Need access to customAttributes

texts:
Pretty much a duplicate of FreeForm: Accessing a fields customAttributes but to answer Solspace's comment "Can you think of a use-case where you would apply attributes to a field but then render those manually?", yes I can.

My current project has Company entries and Equipment entries. Each user belongs to a single Company.

When a user fills out a form with a select field where source=entries and target=Equipment, I don't want the user to see all equipment in the system. Only equipment belonging to user's company.

I thought a clever idea would be to add field class "filterEquipment". When rendering my form

if field.type=select and field class contains "filterEquipment" I want to loop through field options and only display equipment that belongs to user's company
else render select field as normal

I'm open to other suggestions.


texts: How do I keep the 2nd  styled inside a  in my Rich Text (Redactor) editor?

texts:
I think this is some kind of a Redactor bug. This used to work just fine but within the last couple of Craft updates all of my words styled with the  within a paragraph tag ends up unstyled with a "" before the words that were styled with with this tag when saved, when loading a saved Entry Redactor loads it this way. It seems to happen only to the second styled  instances. I've contacted support but they didn't have an answer. I'm quite desperate to fix this as it's messing up our style guide Craft based site.

Here is an example shot.


texts:
I'm having some trouble getting started with Craft.

I'm attempting to upload some image assets for the first time.

I've set up an asset source. I've tried using both a relative and an absolute path to the file. I am certain that the absolute path name is correct  because I simply copied from the pwd command on my server. Also, when I look in the directory, I see the uploaded images.

I've also supplied a url for the source. (I've actually tried a few different ones.)

Every time I've made a change, I've gone into settings and run Update Asset Indexes just to be sure everything was up to date.

However, when I try to view the images, I get a 404. I've tried typing the URL into the address bar, as well as clicking on "View asset" on the assets page.

I did see this similar question, but I'm not running an nginx server. I'm running Apache.

I would love any insight on what I could be doing wrong. If you need any additional information, I'll be more than happy to edit it in.

Edit: For clarity, I'm trying to set up my file directory and my url to have different structures, which I believe is possible. For example, I want my images to be in public_html/media/images, but I want the url for images to be http://mysite.com/images. Doing that seems to be what causes the problem.


texts: Extremely slow performance in Control Panel on a VPS

texts:
I am running a staging environment with Craft on a Dreamhost VPS (1 GB Ram, 30 GB SSD Storage). The backend is running incredibly slow. I noticed in the browser dev tools under network the following:

As you can see, the load time for "entries" is 7.5 seconds and index.php?=-admin… is 6s — these are really long load times.
I did a test on a separate domain, same server and all and I noticed when I first install Craft and once in the control panel, it was slow. After a bit of research, I added the code below to the "general.php" file in the config folder and instantly the issue is resolved for the test domain, but this solution did not work for the staging environment.
'*' => [
    'allowUpdates' => true,
],

It cannot be the VPS specs, it seems to me to be a configuration setting within Craft somewhere. I have other VPS accounts with same specs with live sites and not a problem at all.
Not sure if anyone has had similar experiences with Dreamhost or another hosting company with these issues…


texts:
Hi this is a variation of the question asked here on updating the cart using ajax, instead I'm attempting to use the Fetch API. As a test the form submits properly when submitting in the usual way without using the Fetch request. I've attempted to replicate the synchronous request header that I inspected in the Chrome Network tab but I still get a Bad Request error.

HTML:

<form method="POST" id="addToCartForm">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="commerce/cart/updateCart">
    <input type="hidden" name="redirect" value="/cart">
    <input type="hidden" name="purchasableId" value="{{ product.id }}">
    <input type="number" name="qty">
</form>

JS:

let formElem = document.getElementById('addToCartForm');
let form = new FormData(formElem);
let request = new Request('/', {
  credentials: 'include',
  method: 'post',
  mode: 'same-origin',
  redirect: 'follow',
  headers: new Headers({
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
    'X-Requested-With': 'XMLHttpRequest' // so craft detects ajax
  }),
  body: form
});

fetch(request).then((response) => {
  if(response.ok) {
    return response.text();
  }
  throw new Error('Network response was not ok.');
}).then((response) => {
  console.log('Worked:');
  console.log(response);
}).catch((error) => {
  console.log(error);
});


texts: Dashboard grid layout broken after an auto update gone wrong

texts: An auto update went awry. I lost Internet connection towards the end of the update. Each widget now appears on its own row. Everything else looks ok on the front end as well as the admin. When I check for updates, it says I'm up to date. Does anyone have any suggestions as to which files I should update to fix this issue?


texts: Create a variable from content in a matrix field

texts:
I want to create a variable based on the contents of a matrix block.  This is the code I created:

{% for item in entry.screenshot %} //my matrix field
    {% for asset in item.webpage %} // an asset field in the block
        {% set backgroundUrl = asset.url %} //want to declare a variable using the asset url
   {% endfor %}
{% endfor %}

This throws a "backgroundUrl not defined" error when I try to use the variable.  Obviously my syntax is wrong.  Any advice would be appreciated!


texts: Output a Twig tag within another Twig tag

texts:
I have a Matrix with a block for a contact form. I have a field for the email recipients. But the output doesn't work.

How can I render/output the output a tag within another tag, like this?

<input type="hidden" name="toEmail" value="{{ '{{item.mailto}}'|hash }}">


texts:
I'm looking for a way to have email subscribers database within Craft without using third-party solutions such as MailChimp.

I'm going to let users enter their emails to subscribe to site categories / channels and then send custom notifications with Postmaster plugin. Pre-defined subscriptions lists will not work for me.

I also don't have membership system.

So I wonder if there's any way to have subscribers database within Craft? Some plugin that people could use to submit their email and area of interest to subscribe and also to unsubscribe?


texts: Switching to Craft from ExpressionEngine

texts:
my client is looking to move away from ExpressionEngine. One of the reasons for this is that we are approaching the maximum number of sites we can run from MSM due to the limit on the number of columns we can create in MySQL for the data table.

Questions:

Managing Multiple Sites

Is it possible to run multiple sites using Craft?
Can you provide a login for users that would give them access to just their site?
Can you share content from the a global site across local sites?

Forms

Is there a plugin like Solspace Freeform for creating and managing forms?

Search

How does site searching work. Would there be a way to tie this in to display local sites only?

Appreciate the help.


texts:
I have a matrix that contains a block with a category field. I want to loop over the matrix models, in PHP, to get data. Here's what I have so far:

foreach ($user->networksMatrix as $key => $networkLink)
{
    $netArr[$networkLink->id]["fields"]["networktype"] = $networkLink->networktype;
    $netArr[$networkLink->id]["fields"]["networkUrl"] = $networkLink->networkUrl;
}

networktype is a category field. How do I get the get the ID of the category a user selected?

Thanks!

UPDATE

I discovered that the following works:

foreach ($user->networksMatrix as $key => $networkLink)
{
    $netArr[$networkLink->id]["fields"]["networktype"] = $networkLink->networktype->ids()[0];
    $netArr[$networkLink->id]["fields"]["networkUrl"] = $networkLink->networkUrl;
}

Since networktype is a categories field and that field is limited to 1 category I'll only ever get a single result from the method:

ids();

So... I just do this and I'm good:

$networkLink->networktype->ids()[0];


texts: Can't install plugin - Could not find plugin folder in zip

texts:
I'm trying to install the plugin "Download assets" to Craft and I get an error when trying to install.

Directory was unable to install this plugin :(
No files have been updated and the database has not been touched.

Could not find plugin folder in zip

I do have an external site and a local development site. And this happens on the external site. It does however work correctly on the local site, and it's the exact same installation. What could be the cause for this issue?


texts: Show Entries Based on Category - Localised Site

texts:
I have the following code to display entries based on a single category:

{# Identify the primary category you want #}
{% set cat = craft.categories.title('events').level(1).first() %}

{# Grab an array of entries related to the primary category #}
{% set entries = craft.entries.section('projects').relatedTo(cat).find() %}

{% for entry in entries %}

{{ entry.title }}

{{ entry.subtitle }}

  Learn more

{% endfor %}

This works fine for the home locale (en) but on the others it displays all entries regardless of whether the category has been applied to it or not.


texts: How might big Matrix/Relationship fields affect front-end CP performance?

texts:
I frequently run into front-end performance issues in EE CP pages, where I have a big Matrix field (100+ rows), or a Playa field with a long list of entries (3000+ relatable entries), or worst of all, a combo of the two: The page gets really slow, and sometimes freezes, while JS initializes and renders all of those fields and their content.

I'm curious if the same issues would plague big Matrix/Relationship fields in Craft's CP. If not, what architectural differences make it so?


texts: What are the best practices for the development setup?

texts:
I've started with Craft developing all locally. The struggle for me when working locally was synchronizing the database and the backend assets with coworkers on the same project.

In the last project we tried a different approach, where we have the db, the assets and the CP on a server. So all devs involved in the project had the same backend.

What we still had locally were our templates and frontend stuff. The db.php pointed to the remote db. The basepath pointed to our local root so it would load the local templates.

I'm actually pretty happy with that solution the only problem I haven't figured out yet is using image transforms. Since I'm using locale templates (and a locale craft installation for templating ), the transforms tries to generate the images locally which doesn't seem to work. Maybe my configuration is off since I don't have to much experience with transforms and the configuration with this setup can get a little confusing as well :)

How does your setup look while working in a team?

And any suggestions for the my problem with transform?


texts:
Craft CMS allows you to save entries without any validation if it's not an enabled entry.

Is it possible to disable this? I've had a dig through the core Craft code but can't actually find the conditional that makes this happen. It doesn't seem to be in the Entries service or model or their parents.

Thanks!


texts: Plugin to maintain data integrity between related entries?

texts:
I would like to develop a plugin to help better maintain data integrity between related records. Something like the following:

When deleting an entry, check whether the entry has "reverse related entries" (i.e. other entries that relate to this entry), and if so, interrupt the delete process and show a warning — something like: "This entry is currently being referenced by 'xyz' entry. Are you sure you want to delete this entry?". If the user selects 'cancel', then cancel the delete process. (Perhaps in a future version of craft this should even happen by default if the entries field is 'required' on the reverse related entry.)
Even better, would be an option to cascade delete "reverse-related" entries, with a message that said something like: "Are you sure you want to delete this entry and all related data?", which would then initiate a cascading delete process. Obviously you would want to specify which 'related entries' fields will initiate the cascade — perhaps a checkbox on the 'related entries' field settings that read "when deleting related entries, provide an option to also delete this entry".

From what I understand, as of a recent update, I believe we can now stop processes from within an event method (i.e. onBeforeDeleteEntry). So I can see how one might develop the first option fairly easily.

The second option is a bit more complicated, without also developing a 'custom related entries fieldtype'. Something that I would prefer to not do (to maintain future compatibility). Perhaps a separate panel that has a drop down to select from 'all related entries fields', those that should initiate a cascade, that can be used as a lookup table within the onBeforeDeleteEntry event?

I'm just curious if anyone has attempted anything like this? And/or if anyone can recommend a good approach.


texts:
I'm building an overview page that will show a title, thumbnail, etc of the pages inside the structure. I want the nav children to start at the parent page we're currently on. I can get the correct elements to display - they just don't have any entry data like title.  If there's a better way to approach this let me know.

{% set overview = (entry.level == 1) ? entry : entry.getAncestors().level(1).first() %}

{% nav entry in overview %}

{{ cycle(['
', '', '', ''], loop.index0)|raw }}

            {% for block in entry.contents.type('image').limit(1) %}
            {% if block.image | length %}
            {% for image in block.image.limit(1) %}

            {% endfor %}
            {% else %}

            {% endif %}
          {% endfor %}

{{ entry.title }}

        {% ifchildren %}
                {% children %}
        {% endifchildren %}

  {{ cycle(['', '', '', '
'], loop.index0)|raw }}

 {% endnav %}


texts: How Do You Create A Navigation Of Entry Types?

texts: If I were to have entries of types: Book, Film, Note, Post and Bookmark. How would I automatically create a list of links (or a filter) to each entry type?


texts: Programmatically entering data into a table field for an entry

texts:
I now know that you can enter data into an entry's field by using $event->params['entry']->getContent()->handle

But let's say I have a foreach loop and I want to enter each line into an entry that is a table field. So for example:

foreach ($apigrab['properties'] as $specs) {
    $event->params['entry']->getContent()->specs == ??
}

Obviously each table heading has it's own handle and I don't imagine specs.handle would work in this case, and also how would you prevent it from just overwriting the same line over and over again? Would I have to count how many first and tell it specifically where to go?

Thanks in advance.


texts:
I'm posting a lot of newbie questions today, hope that's ok. It will get better!

I would like to add a channel (list/detail) to a structure page.

Home > Pages > List Page

I'm sure I'm looking at it the wrong way. I'm used to create this list page as a "real" page in a structure in another CMS (TYPO3) and add the "channel" content as a plugin.

Maybe in Craft, you don't do that (create the channels "containing page") at all? But then again, how do you tell the main site navigation it should link to the channel?


texts: Is there a maximum number of fields in a single matrix?

texts:
I have a matrix with around 75 fields in it. They are spread over multiple "Block Types". When I create a new field and save the matrix, the new fields aren't being saved.

Even worse, when I create a new block type with new fields and then drag it up in the order, when I save, Craft is deleting (trimming) the last fields in the matrix - even though they are old (already created) fields.

Does Craft have a limit on the number of fields in a single matrix?

Thanks for your help!


texts: Best method to handle %20 in tag URLs with multiple words

texts:
On my page of all tags, it works great except for tags that have more than one word.
The URL is replacing the spaces with %20 as one would expect.

http://www.colorcomputergames.com/tags/

I tried using:

{{ siteUrl }}tags/{{ tag.title | kebab }}

This works great in changing the %20 to hyphens.
However, if I click on a tag with multiple words I go to page not found. Makes sense as the system doesn't see that tag.

  {% extends "_layout" %}
    {% set title = "Tags" %}
    {% block content %}
    {% for tag in craft.tags.order('title') %}

{{ tag.title }}

    {% endfor %}
    {% endblock %}

So next I tried:

{% extends "_layout" %}
{% set title = "Tags" %}
{% block content %}
{% for tag in craft.tags.order('title') %}

{{ tag.title }}

{% endfor %}
{% endblock %}

But that wasn't ideal either.

What is the best way to deal with this issue?


texts: Is it possible to group my Craft plugins using the PSR-0 Standard?

texts:
I'd like to group my Craft plugins using the PSR-0 Standard, I was hoping I could use the following:

CompanyName_PluginNamePlugin extends BasePlugin

plugins/
    companyname/
       pluginname/
           CompanyName_PluginNamePlugin.php

Is it possible to group plugins in sub folders? Or do I just need to prefix my plugin folder - eg:

plugins/
   companyname_pluginname/
       CompanyName_PluginNamePlugin.php

This gets messy if I want to group any further:

plugins/
    companyname_pluginname
    companyname_subgroup_otherpluginname
    companyname_secondsubgroup_otherpluginname

Thanks,

Phil.


texts: ElementAPI: Error's out if entry doesn't have assets

texts:
These keeps erroring out if any of the entries' do not have any assets in the 'listingPhotos' field. However, IF all entries have at least 1 photo in the 'listingsPhotos' field, it works.

The Error Message: Trying to get property of non-object

namespace Craft;

return [
    'endpoints' => [
        'trucks.json' => [
            'elementType' => 'Entry',
            'criteria' => ['section' => 'trucks'],
            'paginate' => false,
            'transformer' => function(EntryModel $entry) {
                return [
                    'ID' => $entry->id,
                    'Year' => $entry->year,
                    'Manufacturer' => $entry->manufacturer,
                    'Model' => $entry->model,
                    'Category' => (string)$entry->category[0],
                    'Pics' => $entry->listingPhotos[0]->url,
                ];
            },
        ],
    ]
];


texts: Recursive relations – how to build list properly?

texts:
I started building a list of recursive relations:

We're in a project, we want to check interviews related to that project, see which persons participated in those related interviews, and then build an ordered list of all those persons – without duplicates.

My first approach was to combine two loops:

{% set relatedInterviews = craft.entries.section('interviews').relatedTo(entry).all() %}
{% if relatedInterviews %}
{% set interviewedpersons = [] %}
  {% for interview in relatedInterviews %}
    {% set relatedPersons = craft.entries.section('persons').relatedTo(interview).all() %}
    {% for person in relatedPersons %}
      {% set interviewedpersons = interviewedpersons|merge([person]) %}
    {% endfor %}
  {% endfor %}

  {% for interviewedperson in interviewedpersons %}
    {{interviewedperson.firstname}}{{interviewedperson.lastname}}{% if loop.last %}{% else %}, {% endif %}
  {% endfor %}
{% endif %}

In PHP, we would now sort and clear duplicates from interviewedpersons, but I see in twig the array sorting possibilities are a bit reduced, right? Probably because building such a list is already more of a controller than a view / template thing?

So is there a better approach to do this double relation, sorting and avoiding duplicates via Craft's Entrymodel?

What about

{% set relatedPersons = craft.entries.section('persons').relatedTo(craft.entries.section('interviews').relatedTo(entry)).orderBy('lastname asc, firstname asc').all() %}
{% for relatedPerson in relatedPersons %}
   {{relatedPerson.firstname}}{{relatedPerson.lastname}}{% if loop.last %}{% else %}, {% endif %}
{% endfor %}

– much better? I'm pleasantly surprised this works. Do I have to check for empty bits, and will duplicates be removed already?


texts: Can't import a complete url into an url field with feed-me

texts:
Description

I have a JSON feed which contains an external URL like "https://example.com" (entries/external_link/url).
There is no error in feed-me logs when I run it, all the text data and assets are imported without any problems. Except for my URL field. I get "[ ]" instead of "https://example.com".

Any help on this ?

JSON exemple

{
    "entries": [
        {
            "id": "140",
            "type": "regular",
            "title": "Banner import title (fr)",
            "subtitle": "Banner import subtitle (fr)",
            "body": "
Banner import body&nbsp;(fr)
",
            "internal_link": [{
                "type": "node",
                "title": "test",
                "id": "6",
                "cta": "Banner import link text (fr)"
            }],
            "external_link": {
                "cta": "Banner import link text (fr)",
                "url": "https://example.com"
            },
            "images": [{
                "url": "",
                "caption": ""
            }],
            "placements": [],
            "postdate": "2019/12/10",
            "status": "1"
        },
    ],
    "nextPage": "",
    "length": 20,
    "totallength": 23
}

Additional info

Plugin version: 4.1.2
Craft version: 3.3.17


texts:
So I am coming from WordPress and typically I would typically handle a post by either hooking into the wp_post action and access the $_POST request that way. Now I believe Craft is built on Yii which is an MVC framework but I cannot find any documentation showing how to handle post requests?

Any help or can you point me in the right direction?


texts:
After submitting the last Craft Update over the CP i got the following error:

Warning: require(/home/xxx/xxx/xxx/vendor/craftcms/cms/bootstrap/console.php): failed to open stream: No such file or directory in /home/xxx/xxx/xxx/craft on line 21

Warning: require(/home/xxx/xxx/xxx/vendor/craftcms/cms/bootstrap/console.php): failed to open stream: No such file or directory in /home/xxx/xxx/xxx/craft on line 21

Fatal error: require(): Failed opening required '/home/xxx/xxx/xxx/vendor/craftcms/cms/bootstrap/console.php' (include_path='.') in /home/xxx/xxx/xxx/craft on line 21

Strangely i have no /bootstrap directory under the following path xxx/vendor/craftcms/cms/..

I tried to execute composer update over ssh, but i get the same message.
I once installed craft manually on our webserver. I'm not sure if composer is installed?

Thank for helping us.


texts: Custom format for Sprout SEO 3 Element Metadata

texts:
Does Sprout SEO work with Neo fields?

I'm trying to create multiple fallbacks within a custom formatted element metadata field in Sprout, so I could just use one Sprout SEO field with element metadata for multiple significantly different sections.

For instance, something like this:

{% if object.comparisonPageBodyText %}{{ object.comparisonPageBodyText | striptags }}{% else %}{{ object.body | striptags }}{% endif %}

I tried this, and it doesn't appear to work with Neo fields.

Ideally, my ultimate thing would be something like:

If comparisonPageBodyText exists, use the first 160 characters
else use the first 160 characters of the first body matrix block
else use the section default
else use the site default

It would be amazing if we could structure the logic inside the gui instead of writing twig, but ultimately this would be fine if I could get it to work.


texts: Get a specific entry by its index or number?

texts:
I'm working with a carousel that has two rows. Each item in the carousel displays an icon for a "media partner". This works all fine and dandy until there's an odd number of media partners, because then there is an extra unnecessary space in the carousel. I have the issue solved logically, but I can't figure out how to implement it into Craft. I need a way to access a certain entry plainly by its number, i.e. the fifth entry, seventh entry, ninth entry, etc.

There are 11 entries that I am working with, however that number may change in the future. So, first, I grab how many current entries there are in the particular field that I am looking for:

{% set entryNum = craft.entries.section('partners').featuredMediaPartner('1') | length %}

This returns 11.

Next, this number gets divided by two, because I want to display the middle partner in the empty space that the carousel creates if there's an odd number (I already have coded to determine what to do if there's an odd number). So 11/2 = 5. How would I access the fifth entry? Thanks.


texts:
I know if I turn off Purify HTML I might be able to get anchors working in Redactor rich text fields, but I want the ole client to be able to insert anchor links.

Does a plugin for this exist, or is it possible to make an 'insert anchor' button on my own easily?


texts: How can I get an entry based on category and slug (via url segments)?

texts:
I am using (and have used) this S.O post to create a product filter/search using multiple categories. Everything is working perfectly.

I am attempting to use the same type of logic to grab ultimately a single entry.

TL;DR: I am trying to get a single entry via 2 url segments.

I believe I am close, but what I am generating for a query isn't quite spot on as I'm always getting into my "No Products" clause.

www.mysite.com/products/toys/my-awesome-toy

{% set category = craft.request.getSegment(2) %}  {# toys #}
{% set product = craft.request.getSegment(3) %}   {# my-awesome-toy #}

{% set relationParam = ['and'] %}

{% if category|length %}
    {% set cat = craft.categories.group('toys').slug(category).first() %}
    {% set relationParam = relationParam|merge([{ targetElement: cat }]) %}
{% endif %}

cat is outputting Toys and my page renders all entries that belong to the Toys category group. Perfect.

{% if product|length %}
    {% set prod = craft.entries.slug(craft.request.getSegment(3)).first() %}
    {% set relationParam = relationParam|merge([{ targetElement: prod }]) %}
{% endif %}

{% set entry = craft.entries.relatedTo(relationParam).first() %}

{% if entry %}
    {{ entry.title }}

{% else %}

No products found.

{% endif %}

prod is outputting My Awesome Toy and now I am getting my "No products found" message. I think it's because prod is outputting My Awesome Toy vs. my-awesome-toy?

I realize I can get any entry via it's slug alone. I am using a dynamic route to create this page that looks like this:

products/tag/slug

I would like to get the entry strictly based on the url segments that way I can make sure my urls are valid. Meaning, I can only find "My Awesome Toy" from the "toys" category. For example:

www.mysite.com/products/toys/my-awesome-toy   {# valid #}
www.mysite.com/products/food/my-awesome-toy   {# invalid #}


texts: Local vs Amazon S3 asset paths in multi-environment config

texts:
I'm looking to pull assets from a local folder when developing locally, and an S3 folder when on staging/production.

Is this possible? It looks like no, but I'm hoping that's not the definitive answer: Multi-Environment S3 Asset Paths

It appears you can't alter the asset 'type'. However, I've seen configs (specifically, this one: https://designkarma.co.uk/blog/localization-multi-environment-setup-in-craft) that seem to use different urls for local vs s3 assets. That gets rid of the ability to set a cache duration and other s3 specific options, however.

Is the only real way to do this is to set CORS settings on the S3 folder to allow connections from a local development URL, and use that for local/staging, and another bucket/config for production?


texts: If an entry doesn't exist in a locale and returns a 404, how can I check if the entry exists in a different locale?

texts:
I'm trying to create a mechanism for informing users that a particular entry is not available in the selected language, and providing a link to read the article in an alternative language.

Therefore, if one of my secondary locales returns a 404 for a particular URL and goes to a localised 404 error template, is there a way to check in the 404 template if the corresponding URL path matches an entry in my main locale, so I can link to that entry from the 404 page?

I think what I want is a method for searching for an entry using a string containing the complete URL path, but I don't think that’s available, so what would be the best alternative?


texts: Setting absolute path to asset files for Craft 3 multisite

texts: Currently, I have 3 sites set up in Craft 3 beta. I'm trying to get all my sites to share one asset folder by using absolute path. However, I can't seem to set it up. The siteUrl is not parsing as I would expect. I would get "{siteUrl}/assets/people/image.png".


texts:
Is there any way to translate this:

{% set shopify = craft.shopify.getProductById({ id: entry.shopifyProduct, fields: 'variants, id' }) %}

to the Element API?

I've tried this, but obviously it doesn't work:

return [
  'endpoints' => [
  'api.json' => [
  'elementType' => 'Entry',
  'criteria' => [
    'section' => product,
  ],
  'transformer' => function (EntryModel $entry) {
    $shopify = craft()->shopify->getProductById({id:$entry->shopifyProduct});

    return [
      'id' => $entry->id,
      'title' => $entry->title,
      'url' => $entry->url,
      'shopifyId' => $entry->$shopify
    ];
  },
]
 ]
];


texts:
Apologies if I am dense, it won't be the first time.

I have thousands of product images that I will output on more than one page, under varying conditions.  Rather than having to do an entry for each product in these circumstances, can I just:

attach product  description fields to the asset field
upload the assets
use Bob Olde Hampsink's import plug-in to populate all the product info to assets fields
fetch the asset and the associated fields in a template
skip the entry part altogether?

This way I could use the same asset in multiple instances without having to reinvent the wheel.

  A. Is this possible?
  B. Is this wise?
  C. If A and B =='yes' what is the most direct way to go about this?


texts: Is it possible to subscribe a user to Mailchimp during checkout in Craft Commerce?

texts:
Our checkout is only for registered users.

Ideally you'd just provide a checkbox that says: Subscribe to Mailchimp?

Any ideas?


texts:
Craft Solo : 3.1.25
Craft Commerce : Lite (2.1.12.1)

I am trying to integrate it with Commerce Lite for a subscription plan.

I Created 1 product at stripe account.
Added stripe keys to my local store.
Payment is working in test mode. ( so keys are correct)

In settings/subscriptions/plans i created 1 plan but not getting any gateway plans ( i am assuming craft will fetch the product created on stripe so that i can link them with craftstore subscriptions)

All the stripe products are fetched.

After reloading the page gateway changed to Plan name ( website subscription plan)

What i am missing ?

Update: I created a gif on the issue.

https://we.tl/t-zluYdB3dzg


texts:
I want to convert a String into kebab-case.

'Hello there' -> 'hello-there'

I'm working in the Element API, so haven't got the pleasure of using the simple Twig filter. I guess there is a way of doing it in PHP. Any suggestions? Thank you


texts: element-api plugin / get entry total in section in Craft 3

texts:
What is the best way to get only the total entry number from a section with the least overhead, in the element-api.php?

Thanks

Mark


texts: Looking for a simple way to add/update information records with CraftCMS

texts:
I'm looking for a simple way to save form data to a database and be able to access that information. I'm not sure if I should use the custom fields or an entry (or a custom table) and if creating a module is the way to go or another easy way to have my form post submit handled with PHP.

I was hoping for a simple example of a module for Craft but I'm not finding it.

For the sake of an example, I'd like to add and edit books in my library:

Book Type:
BookTitle - 50 characters
BookAuthor - 50 characters
BookSummary - 300 characters
Pages - Integer

Thanks.


texts:
I'm just starting to explore the whole power of Craft and I'm really satisfied with its possibilities so far.

But I can't get one thing done, so here's my question:

Is it possible to use matrix fields in my very own plugins? I already finished a form with several fields just as text inputs and stuff but I really need to extend this thing with a matrix field.

Am I just blind and it's documented anywhere or is it a more complicated task than I can imagine at this point?

Thanks for your help.

Jonas


texts:
I have a page where updating the asset indexes is not working.

If I hit «Update asset indexes» The loading animation shows and never stops the animation.

Installed AsyncQueue = Same effect
Increased memory_limit to 128M
max_execution_time is set to 30
There are no stuck tasks
php 7.0.33
CraftCMS 3.15

It works locally (MAMP Apache) so I guess it must be a server thing?!

There are about 10 pdf & jpg assets so it's not a lot.

What else can I do?


texts: How do you gain PCI compliance without certifying your server for Craft, with or without Commerce?

texts:
This is going to be informational, as we had a good conversation over this area on Craft Slack. And good fun trying to get around the idiotic StackExchange 'subjective' monitor to publish it here -- couldn't imagine what this wanted.

Why would you want to avoid PCI compliance on your own server? Because it's a bank-level task to get and maintain it.

See the conversation linked in the answer below, thank you.


texts: Match Matrix Fields Before Looping Through Results

texts:
I hope someone has an example or something similar they have done in Craft before.  Her is what I have.

Structure:

Section -> Flight Company

Matrix Name -> Plane Details

Matrix Block: Plane Model and Part

Matrix Fields -> Model, Part (field type: Category)

I am needing to perform this match example (preferable in crafts.entries query)before looping through the records.

Example match needed:

Model = Cessna

Part = Propx45

I need to match both those conditions before looping through the results later on in the page.  I need to make sure all the Flight Company's match that criteria before outputing the Title of the Flight Company.

How best to accomplish this?


texts: Control Panel: Order search results from a structure?

texts:
A client of mine asked how he can sort entries tied to a specific category in a structure.
I thought to myself that this is easy, so I went and did a search myself:
category_field_name:category_to_display

I will get the result I desire, but to my astonishment I can't order anything. Structure sorting is grayed out.
I know there was a category sources plugin for craft v2, but I don't think that ordering was available there as well?
Is there a way to order results from a structure search?


texts:
Currently I am sorting a category template with this:

'featured desc, postDate desc'

Works as expected. But I would like to sort it first on the featured field, then on the score. Such as

'featured desc, score'

But this throws an error. Can someone explain why that is and how I might achieve what I'm looking for? The first search is good for bringing featured posts to the top, but if there are none or maybe one, the rest of the results are not all that relevant. Ideas?

Thanks in advance.


texts: Craft Commerce > 2.2: How can you order line items?

texts:
As of Commerce 2.2 line items are ordered by date created.

How can you order line items differently?

{% for item in cart.lineItems.orderBy(’sku desc') %} does not work…


texts: How can I do more complicated queries with an ElementCriteriaModel?

texts:
I need to join my 3rd party table with a standard ElementCriteriaModel (ECM). I'd like to start with an ordinary ECM, so my plugin will be compatible with any element type which may exist, now or in the future.

By default, an ECM generates a query which joins multiple native tables. According to Brad in this answer...

  ... think of ElementCriteriaModel as an abstraction on top of DbCommand that makes it easy to search for Elements.

My plugin does not have either a custom Field Type or custom Element Type (which means I can't use modifyElementsQuery when retrieving the data).

How can I expand my ECM query to take additional SQL commands into account?


texts:
I created a user group that has full permissions for User options in the CP, i.e. all the boxed ticked. However, they are not able to edit a user's email address.

When changing the email field and clicking Save it asks for password as usual, accepts it and closes the user form. However, the email does not change and there is no error message.

If I go in as Admin, it works fine, but not for any User Group, irrespective of the fact that their permissions include changing email addresses.

One possible clue is that these users were migrated from an older site and the email addresses have not yet been confirmed. Any thoughts would be appreciated!


texts: Plugin: How to Validate Array field in editableTableField?

texts:
In my template I defined field as:

{{ forms.editableTableField({
  id: 'songs',
  name: 'songs',
  cols: [
    {
      heading: 'Time',
      type: 'select',
      options: [
        {'label':'00:00','value':'00:00'},
        {'label':'00:30','value':'00:30'},
        {'label':'01:00','value':'01:00'},
        {'label':'01:30','value':'01:30'},
        {'label':'02:00','value':'02:00'},
        {'label':'02:30','value':'02:30'},
        {'label':'03:00','value':'03:00'},
        {'label':'03:30','value':'03:30'},
        {'label':'04:00','value':'04:30'},
        {'label':'05:00','value':'05:30'},
        {'label':'06:00','value':'06:30'},
        {'label':'07:00','value':'07:30'}
      ]
    },
    {
      heading: 'SoundCloud URL',
      type: 'singleline'
    }
  ]
}) }}

How do I add validation rules in model? This does not work:

return array(
    'songs[][]' => array(AttributeType::String, 'label' => 'Sound Cloud Track URL','required'  => true),
    'scheduledTime' => AttributeType::DateTime
);

In controller I am doing:

$songs = new PlugInName_ControllerModel();

if($songs->validate()) {
    echo 'Hurray';
} else {
    echo 'Epic Fail';
}


texts: Restrict a users permission to only edit 'translatable' fields on a specific site?

texts:
We would like to have a 'translators' user group, where the members can edit only the 'translatable' fields, but not the non translatable things (images, categories etc).

May be i missed something, but giving users permission to edit a specific site lets them edit all attributes.

Is there a way (permission/plugin/code snippet/best practice) to achieve that?

Thanks.

Thinking of writing a custom validation comparing old to new, or hiding/disabling fields via specific css.


texts:
I am new to PHP and trying to call reCaptcha API in CraftCMS. I have the following variable:

$captcha = Craft::$app->getRequest()->getParam('g-recaptcha-response');

But I get the following error when I submit a form:

Fatal error: Uncaught Error: Class 'Craft' not found

How can I import the Craft class?


texts: EVENT_BEFORE_SAVE event not getting $entry-id when creating an entry

texts:
I don't know if it was with Craft 3.5, but did something change slightly when using the EVENT_BEFORE_SAVE event?
I have a simple use case where I am encoding the entry ID and updating the slug when the entry is saved.
It does check if a title is empty and if the entry is a draft or revision, if any of those are true, then it does not encode it.
After updating from Craft 3.4.30 to Craft 3.5.5 when saving an entry I have noticed that it throws an error as $entry->id returns null, however on refreshing the page and then resaving it, it passes the entry ID in fine.
A basic example of what I have is:
Event::on(
    Entry::class,
    Entry::EVENT_BEFORE_SAVE,
    function (ModelEvent $event) {

        $entry = $event->sender;

        if (ElementHelper::isDraftOrRevision($entry)) {
            return false;
        }

        // Get entry title
        $title = $entry->title;

       if ($title !== null) {
            // Encode entry ID
            $newSlug = Module::$instance->hashid->encode($entry->id);

            // Update slug to be a hash
            $entry->slug = $newSlug;
        }
    }
);

Before hand this worked fine when creating the entry, but now it is requiring me to have to save the entries twice, any thoughts?


texts: What might cause logins to work locally yet not in deployed environment?

texts:
We're getting a 404 (or a Craft 'page not found' error) with this path on the remote server:

http://foo.example.net/admin/actions/users/login

Same database using remote mySQL. Local logins work fine.

Craft CMS 2.6.2989


texts: DRYer way to set column widths than with if statement?

texts:
Craft n00b here. Really loving it so far, but am wondering if how I'm implementing this is the best option, or if maybe there's a more sophisticated solution.

Inside our content builder switch statement, I'd like to provide my client with the ability to build an image-and-text block wherein they can change the widths of the columns via a dropdown (columnWidth), which will then set the widths of the children. Here's what I have so far, but it seems a little inelegant, especially if I were to do more options or columns. Any pointers or is this the best way to handle this?

{% if content.columnWidth == "1-2" %}
  {% set columnOneWidth = "1-of-3" %}
  {% set columnTwoWidth = "2-of-3" %}
{% elseif content.columnWidth == "1-1" %}
  {% set columnOneWidth = "1-of-2" %}
  {% set columnTwoWidth = "1-of-2" %}
{% elseif content.columnWidth == "2-1" %}
  {% set columnOneWidth = "2-of-3" %}
  {% set columnTwoWidth = "1-of-3" %}
{% endif %}

    [...]

    [...]

Thanks!


texts: omitScriptNameInUrls breaks admin asset loading

texts:
I'm having trouble logging in to the admin panel if I set omitScriptNameInUrls to true in the general config file. The login works well on a subdomain, which is odd. It seems that asset loading is messed up with that setting. Random files seems to be broken with an 500 error.

Tested in incognito mode, no luck.

I've seen other admin login error questions here, but I had no luck with them.


texts: Craft 3 protecting a page with a password?

texts: I have used the Guest Entries to create a plugin where anonymous users can create a entry. I have a password field on each entry. Now I want the guests who have created the entry to be able to login with this password and edit the entry they created. I don't need user validation etc for this, just a single password. Is this possible in Craft 3?


texts: How can I stop a duplicate entry being created & provide feedback?

texts:
I have a booking form on my site, which when submitted creates a new entry which has two fields: an Entries field which links to a single User, and another Entries field which links to a single Event.

The title field of the entry is set automatically to "[date of event] - [username]".

The problem is that some users are booking twice for the same event. We need a way to limit bookings to ONE PER USER. Is there a way to prevent an entry with the same title being created, and rather than just failing to submit the form, give the user an error message saying "you can't book more than one place"?

Form:

<form method="post" action="" accept-charset="UTF-8" class="custom">
    <input type="hidden" name="action" value="entries/saveEntry">
    <input type="hidden" name="redirect" value="events/book/complete/{{eventID}}">
    <input type="hidden" name="sectionId" value="18">
    <input type="hidden" name="enabled" value="1">
    <input type="hidden" name="fields[userBooking][]" value="{{userID}}">
    <input type="hidden" name="fields[eventBooking][]" value="{{eventID}}">
    <input type="submit" value="Confirm Booking" class="button secondary">
</form>

Related question (possibly could be solved with the same answer) - I need to limit the number of bookings an event can take in total. So for example:

Event One: Bookings per user: 1, Total places: 35
Event Two: Bookings per user: 1, Total places: 50

This needs to be done with template code, not a plugin. Any ideas?


texts: Problem with @font-face url 500 server error craft style

texts:
So not sure what the problem is really have tried a few ways but I can't get font-files to work.

I have placed my font files in

 root/craft/templates/assets/fonts/bootstrap

Here is an example of @font-face that I am using...

@font-face {
    font-family: "Glyphicons Halflings";
    src:
    url("{{ siteUrl }}/assets/fonts/bootstrap/glyphicons-halflings-regular.eot?#iefix") format("embedded-opentype"),
    url("{{ siteUrl }}/assets/fonts/bootstrap/glyphicons-halflings-regular.woff2") format("woff2"),
    url("{{ siteUrl }}/assets/fonts/bootstrap/glyphicons-halflings-regular.woff") format("woff"),
    url("{{ siteUrl }}/assets/fonts/bootstrap/glyphicons-halflings-regular.ttf") format("truetype"),
    url("{{ siteUrl }}/assets/fonts/bootstrap/glyphicons-halflings-regular.svg#glyphicons_halflingsregular") format("svg");
}

In firebug I get "NetworkError: 500 Internal Server Error - http://example.com/assets/fonts/bootstrap/glyphicons-halflings-regular.woff"

If I try to access the file directly I get the following message with craft styling etc so this is a craft error not a typical 500 error.

Internal Server Error

Unexpected character ""

Now if I try to access a css file it works fine, but my font files are returning 500 errors.

I have placed my css files in

 root/craft/templates/assets/css


texts:
I'm new to Craft and PHP, so thanks ahead of time!

Is it possible to override a model method with a plugin? For example, I want to add some additional functionality to the getUrl method of the AssetFileModel class. Can this be done in a plugin?

Thanks!


texts:
I have managed to sort most Craft CMS questions out by reading the docs and feedback on StackExchange but am having issues with this one.

I have a page with a list of entries down the right side and the main entry content to the left.

The list is paginated.  When I go to say page 2 of the pagination and click on an entry, the page reloads with the page 1 pagination list.

How can I get the page to remember that the entry belongs to page 2?

{% paginate craft.entries.section('orchard').limit('5').id('not ' ~ entry.id)  as entriesOnPage %}

 {% for entry in entriesOnPage %}
   {% for asset in entry.mediaThumb %}

{{ entry.title }}

   {% endfor %}
 {% endfor %}

      {% if paginate.prevUrl %}

&laquo;

      {% endif %}
      {% for page, url in paginate.getPrevUrls(5) %}

{{ page }}

      {% endfor %}

{{ paginate.currentPage }}

      {% for page, url in paginate.getNextUrls(5) %}

{{ page }}

      {% endfor %}
      {% if paginate.nextUrl %}

&raquo;

      {% endif %}

{% endpaginate %}

Many thanks, Alex


texts: Resaving Entries hitting a mysterious memory limit

texts:
I renamed a channel section and Craft (2.6.3012) is trying to resave all the entries therein (about 500 entries, many with up to 10 localized versions). I'm constantly getting this error (in /craft/storage/runtime/logs/phperrors.log):

[26-Mar-2018 15:53:40 UTC] PHP Fatal error:  Allowed memory size of 268435456 bytes exhausted (tried to allocate 43 bytes) in C:\server\project_x\craft\app\helpers\ModelHelper.php on line 95

Here's the thing... in php.ini, the memory_limit setting is set to 512M. Not the 256M one would expect from the error. In Craft's admin/utils/phpinfo page, it shows that PHP does indeed have a limit of 512Mb, but the process still hits a mysterious memory limit at 256MB.

I'm running locally on XAMPP, PHP 5.6.24 (switching to PHP 7 prevents me from being able to login for some reason), and this is just part of setting up a site, so I don't care about performance or advisable settings with this issue.

What am I missing?


texts:
I would like to turn on a profiler in Craft CMS so I can see what DB queries are being run and how long they take.

Is this possible?


texts: How do I get the column headers of a table in a matrix?

texts:
I'm trying to write a general purpose matrix template and I've come up on a little snag with tables fields. I see no way to get the column header values.

The answer here mentions craft.fields.getFieldById(block.fieldId) but that doesn't appear to exist according to the documentation, nor did it work properly.

The closest I've gotten is this dirty slice job and that only gives me the ids of the columns. So I can do some string manipulation to get them close to the value but they can be completely different as well.

{% set first = block.table | first %}
{% set columns = first | keys | slice((first | length) / 2, first | length) %}

Any ideas would be helpful!

I'm trying to accomplish this:

<table>
  <thead>
    {{ loop through table headers }}
  </thead>
  <tbody>
    {{ loop through table data }}
  </tbody>
</table>


texts: Localized Craft Build with Vanilla Forums?

texts:
Anyone have any luck getting a localized Craft build working with a localized Vanilla Forums install?

I've got MAMP installed, in conjunction with CodeKit. Craft itself is running fine. I installed the Vanilla Forums directory under the Templates directory. Whenever I visit craft.dev/vanilla(MAMP) or macbook.local:5757/vanilla (CodeKit) in my browser, I get a Page Not Found error. If I go straight to the index.php file, it spews out the actual ph


texts: Structure unable to find _entry template

texts:
I have a Structure named "pages" which is set to use the template named "_entry".

When trying to visit one of the pages I’m just getting a blank screen.

The Craft log shows an error in the template loader because it can’t find a template.

  Craft\TemplateLoaderException: Unable to find the template
  "about/index". in
  /path/to/site/craft/app/etc/templating/twigextensions/TemplateLoader.php:123

The structure is set to use the template named _entry which is present and all as it should be.

I have tried renaming the template to no avail.

Other parts of the site are working fine. It only seems to be this Structure that has a problem.

The problem is occurring on an Azure VM running Ubuntu 16.04 LTS with PHP 7.0, running MySQL 5.7 with Strict mode disabled and managed with ServerPilot. I'm pretty sure it's been working OK since I deployed to Azure a couple of days ago but I can't explicitly remember testing these pages since my involvement has largely been on a different part of the site (which is working OK).

This is working fine locally, and has been working fine on a test server set up at Digital Ocean (I've decommissioned that but I'm in the process of setting it up again to test this).

Update: I can confirm the same code works perfectly on the Digital Ocean/ServerPilot combo so it appears to be something Azure or possibly MySQL 5.7 related (the Azure deployment is using MySQL 5.7 with Strict mode disabled)

Update: I'd incorrectly read the error message. The _entry template appears to be found. But this is then trying to load another template (in this case about/index) which is where things fail.
There is no about/index template it should fall through to a generic template.

{% if craft.request.getSegment(2) %}
    {% set internal = craft.request.getSegment(1) ~ '/' ~ craft.request.getSegment(2) %}
    {% set index = craft.request.getSegment(1) ~ '/index' %}
{% else %}
    {% set internal = entry.uri ~ '/index' %}
    {% set index = entry.uri ~ '/index' %}
{% endif %}

{% include [internal, index, '_generic'] ignore missing %}


texts: I need to build a plugin or module that hooks into the Sprout form upload file function so I can add text programmatically to the user uploaded filename.  I've had input before that I should work with the hooks that Sprout provides.  However, I am newish to how Craft 3 functions and I am not familiar with how hooks work.  Can anyone please direct me to any tutorials or education sources that explain how hooks work?  Are they a basic, inherent process of plugin development?  I've only been able to find a tiny bit of documentation on hooks regarding Craft 2.


texts: Duplicate meta descriptions when category has multiple pages

texts:
Does anyone know how to solve the problem of duplicate meta descriptions appearing when a category has multiple pages?

For example:

Category: Telephones
Pages: 5 pages

All 5 pages end up with the same meta description, titles and keywords. Only the content is changeable?


texts: Can only submit my Sprout Form form if I'm logged into my site

texts: I have a basic Contact form built in a site I manage for a client. But for some reason, the form fails to submit if I'm (or the user using the site) isn't logged into the site (CMS). But this site is a basic marketing site, so visitors to the site do not have Craft CMS user accounts. Any idea what could be happening here? The logs don't help.


texts:
If you have a checkbox  field on an entry type, how do you display all the selected values for an entry in a template with twig?

Using this for page permissions via user groups. We have a plugin that adds a new field type "user groups". It lists all groups (which we have many) on the admin page of each entry. We want to check which groups will have access and then limit the page to users in that group only.

edit: not using a standard checkbox field but a new field (via plugin). https://github.com/quebecstudio/usergroupfield


texts:
Is there a way to reset an admin account's password by modifying the MySQL directly?

I've found the craft_users table where the hashed password is stored but I don't know how to hash a string so that it will be read correctly by Craft.


texts: Is it possible to change one segment of the current url and keep the rest of it the same in a cleaner way?

texts:
How would you go about changing one segment of the current url? I have a select in the footer that you can click on a country name and then it redirects you to the homepage of that country version of the website.

<!-- language: lang-twig -->
<form action="" name="dropdown">
    <select name="country-select"  id="country-select" class="form-control" onchange="location = this.value;" autocomplete="off">>
        {% set locales = craft.i18n.getSiteLocaleIds() %}
        {% set locale = craft.locale %}
        {% for loc in locales %}
            {# checking if current loop has active locale #}
            {% set isHome = (loc == locale) %}
            {% if isHome %}

                {% if loc == "en" %}
                    <option value="/{{ loc | replace({'en': 'eu'}) }}" selected>Europe</option>

                    {% set myJs %}

                        var currentCountryLocale = "Europe";
                        var currentCountryLocale = "{{ loc | replace({'en': 'eu'}) | trim('_') }}";

                    {% endset %}

                    {% includeJs myJs %}

                {% else %}
                    {% set subTags = locale|split('_') %}
                    {% set territory = subTags|length > 1 ? craft.i18n.getLocaleData(craft.locale).getTerritory(subTags|last) : '' %}
                        <option value="/{{ loc | replace({'en': ''}) | trim('_') }}" selected>{% if territory %}{{ territory }}{% endif %}</option>

                    {% set myJs %}

                        var currentCountryName = "{{ territory }}";
                        var currentCountryLocale = "{{ loc | replace({'en': ''}) | trim('_') }}";

                    {% endset %}

                    {% includeJs myJs %}

                {% endif %}

            {% else %}

                {% if loc == "en" %}
                    <option value="/{{ loc | replace({'en': 'eu'}) }}">EU</option>
                {% else %}
                    <option value="/{{ loc | replace({'en': ''}) | trim('_') }}">{{ loc | replace({'en': ''}) | trim('_') | upper }} </option>
                {% endif %}

            {% endif %}

        {% endfor %}
    </select>
</form>

I have been trying to figure out how to switch only the country/region part of the url, which is segment(2), but all of my experiments so far have been extremely complicated and confusing and I haven't found a good solution yet. Am I missing something? There must be a more efficient way to accomplish this, as it's probably not a good idea to wrap conditionals inside of conditionals inside of more conditionals.

I also have the added complexity of needing to include a continent (Europe) as one of the versions of the website, for which I'm using the "en" locale, as you can see in the bit of code above.


texts: Is there a way to prevent Craft from backing up the database before updating?

texts:
When Craft tries to apply an update, it tries to back up the database. Although that's great in general, backing up a large database using PHP requires a lot of memory and resources that might not be available in the hosting environment or the client does not have enough access to make any related adjustments.

Is there a setting of some kind that would prevent Craft CMS from backing up the database when updating? I already use a command line script to backup the database before applying an update.


texts: I'm trying to import data with the import plugin into entries with a SEOmatic field. How is structured this field and how can I insert the data?


texts: Best Practice on how to build a Pricing Page on CraftCMS

texts:
CraftCMS gives us so many ways/options on how to build pages that I'd love to see what people are doing with their pricing pages!
I'm planning on building something similar to Amilia.com or Slack.com.
My thoughts:

Create 1 single page for the pricing page.
Create 3 entries in a structure for the 3 plans? (Or I don't need this?)
Create a features structure for all features?
For each feature entry put a field for each pricing plan?
Or do I just make it using a matrix field with a super table field?

I'd love to hear the best practices and what would be the best way to build a pricing page and all of its content. Thanks!


texts:
I am deploying a Craft site, I have it installed and everything is working fine, but whenever I try to access the admin panel I get a generic 404. I have tried every solution offered in similar questions, none of them work.
Here's my .htaccess file:

<IfModule mod_rewrite.c>
    RewriteEngine On

    # Send would-be 404 requests to Craft
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !^/(favicon\.ico|apple-touch-icon.*\.png)$ [NC]
    RewriteRule (.+) index.php?p=$1 [QSA,L]
</IfModule>

And my Apache Virtual Host file:

<VirtualHost *:80>
        ServerAdmin info@servername.com
    ServerName servername.com
    ServerAlias www.servername.com
        DocumentRoot /var/www/servername.com/public_html/web/

        <Directory /var/www/servername.com/>
            Options Indexes FollowSymLinks
            AllowOverride All
            Require all granted
        </Directory>

        ErrorLog ${APACHE_LOG_DIR}/error.log
        CustomLog ${APACHE_LOG_DIR}/access.log combined

        <IfModule mod_dir.c>
            DirectoryIndex index.php index.pl index.cgi index.html index.xhtml index.htm
        </IfModule>

</VirtualHost>

Making the url hostname/index.php/admin does work, however.
Any suggestions would be much appreciated, or if more information is required please let me know.


texts:
Doing some testing, and stumbled across the "CraftSessionId" cookie...

What's the difference between CraftSessionId and a normal PHP session? Is there any difference at all? What's the best way to refer to the current session?


texts: How can I prevent my client from auto-updating Craft in production? I don't want them to run Craft updates on the production site, but the "updates" badge seems irresistible to them. I would prefer to run Craft updates in my dev environment, version control with Git, test, and then deploy at my leisure.


texts: How do I fix PHP Notice - Undefined index: releaseDate?

texts:
I'm getting this error:

Undefined index: releaseDate in craft/app/etc/behaviors/AppBehavior.php(500)

Line 500: $row['releaseDate'] = DateTime::createFromString($row['releaseDate'], null, false);

Is there anything I can do to fix this?


texts: Sorting by date field across sections not working

texts:
I've seen a number of answers prescribing how to sort across different sections...but I'm not seeing it work. Here's what I've tried:

{% set profileIds = craft.entries.section('profiles').order('profileBorn asc').ids() %}
{% set eventIds = craft.entries.section('events').order('eventDate asc').ids() %}
{% set timelineIds = profileIds|merge(eventIds) %}
{% set timeline = craft.entries.id(timelineIds) %}

Or:

{% set timeline = craft.entries.section(['profiles','events']).order('GREATEST(eventDate, profileBorn) desc') %}

Then for either, I'm doing:

{% for entry in timeline %}

In both cases, I get entries in the following order, with their {{ entry.profileBorn }} or {{ entry.eventDate }} shown here:

1832-02-01 / events entry
1830-01-01 / profiles entry
1840-01-01 / profiles entry

Any thoughts? Thanks!

UPDATE:

This looks like the SQL being generated by the first answer's suggestion, which is still outputting the event entry first.

SELECT `elements`.`id`, `elements`.`type`, `elements`.`enabled`, `elements`.`archived`, `elements`.`dateCreated`, `elements`.`dateUpdated`, `elements_i18n`.`slug`, `elements_i18n`.`uri`, `elements_i18n`.`enabled` AS `localeEnabled`, `content`.`id` AS `contentId`, `content`.`title`, `content`.`field_profileBio`, `content`.`field_body`, `content`.`field_profileBorn`, `content`.`field_copyright`, `content`.`field_datePrecision`, `content`.`field_datePrecisionBorn`, `content`.`field_datePrecisionDied`, `content`.`field_profileDied`, `content`.`field_eventDate`, `content`.`field_mediaCaption`, `content`.`field_mediaPublicationDate`, `content`.`field_mediaSource`, `content`.`field_mediaTitle`, `content`.`field_siteTitle`, `entries`.`sectionId`, `entries`.`typeId`, `entries`.`authorId`, `entries`.`postDate`, `entries`.`expiryDate`, `structureelements`.`root`, `structureelements`.`lft`, `structureelements`.`rgt`, `structureelements`.`level`
FROM `craft_elements` `elements`
JOIN `craft_elements_i18n` `elements_i18n` ON elements_i18n.elementId = elements.id
JOIN `craft_content` `content` ON content.elementId = elements.id
JOIN `craft_entries` `entries` ON entries.id = elements.id
JOIN `craft_sections` `sections` ON sections.id = entries.sectionId
LEFT JOIN `craft_structures` `structures` ON structures.id = sections.structureId
LEFT JOIN `craft_structureelements` `structureelements` ON (structureelements.structureId = structures.id) AND (structureelements.elementId = entries.id)
WHERE (((((elements_i18n.locale = :locale) AND (content.locale = :locale)) AND ((elements.id=:elementsid1) OR (elements.id=:elementsid2) OR (elements.id=:elementsid3))) AND (elements.archived = 0)) AND ((elements.enabled = 1) AND (elements_i18n.enabled = 1) AND (entries.postDate <= '2017-07-12 12:47:25') AND ((entries.expiryDate is null) OR (entries.expiryDate > '2017-07-12 12:47:25')))) AND (elements_i18n.enabled = 1)
GROUP BY `elements`.`id`
ORDER BY GREATEST(field_eventDate, field_profileBorn) asc LIMIT 100