texts:
How can I cache an entry, lets say a product card but exclude an dynamic part? Like amount of favorites / Or link to add or remove to favorite.

{% set item = craft.shortlist.item(entry.id) %}

{% cache globally using key "product-card-" ~ entry.id until entry.dateUpdated %}

   ...

   {{ entry.title }}

   ...

   // EXCLUDE THIS PART FROM CACHE
   {% if item.inList %}

    {% else %}

    {% endif %}

{% endcache %}

In EE CE Cache there you had {exp:ce_cache:escape}. How can I do this in Craft?

Made a feature request for escaping parts of cache for dynamic data.

http://feedback.buildwithcraft.com/forums/285221-feature-requests/suggestions/7412950-exclude-cache-for-dynamic-data

PLEASE VOTE :-)


texts: Is a backup needed before updating? Will installing new updates have any affect on the pages already saved or the existing structure?


texts: Commerce 'Edit Order' page taking 10 seconds or more to render

texts:
The individual order view in the CP is taking 10 seconds or more to be displayed, how can we avoid/debug this?

PS. Can ignore the errors in the log (I think) as  they are just mmikkel\cpclearcache\{closure}    Error registering AssetBundle - Unable to find the template “_components/utilities/ClearCaches”.


texts: UsersController's actionUploadUserPhoto and actionCropUserPhoto with Element API

texts: Can you use the Element API plugin to utilize UsersController's actionUploadUserPhoto and actionCropUserPhoto methods?


texts:
I have followed the instructions for removing index.php and it works on all pages with the exception of pages with channels. So I would see http://www.example.com/index.php?p=news/2016/news-title.

I also added the 'omitScriptNameInUrls' => true, in the general.php file.

Here is what I have in 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>

<IfModule mod_deflate.c>
    AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript image/svg+xml
</IfModule>

<IfModule mod_headers.c>
    <FilesMatch "\.(eot|otf|tt[cf]|woff2?)$">
        Header set Access-Control-Allow-Origin "*"
    </FilesMatch>
</IfModule>

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]


texts: The client has unfortunately deleted some orders from the Craft Commerce plugin. Does anyone know if it's possible to recreate deleted orders?


texts: New entries not appearing on template page

texts:
My client has been adding some new entries in a channel called Products. These are using different templates that are selected when creating the entry.

The entries on a few different template types are no longer appearing in the last few days. I have checked that the templates have all the correct field handles and there doesn't seem to be anything missing. I have also tried clearing the cache.

Does anyone have any idea why new entries may not be appearing?


texts: How to subscribe to an entry and get notified by email in case of new comments?

texts:
I am thinking about a possibility to let members subscribe to a blog entry, and then get notified in case of new comments related to the respective entry. The comments are stored as entries in a Craft CMS channel.

My idea is to use the Like for Craft CMS plugin for the subscription to a blog entry. In a second step I would try to use the Postmaster for Craft CMS plugin to notify the subscribers by email. I hope that this will be possible using the Postmaster Developer API, but I am not sure.

What is your opinion regarding my idea? Do you know perhaps an easier approach.

I very much appreciate your help, thanks!


texts: I've managed to create a simple plugin for craft and get it into my project. It shows up just fine but I can't make any edits. I've tried editing the original plugin files and updating via composer and that doesn't work, and I've tried to edit the plugin files directly in my craft project and that doesn't seem to work as well. I'm sure there is a simple answer but I'm pretty lost.


texts: Draft from front-end form with limited field set

texts:
I have a front-end form which sends a limited selection of the fields to the action entryRevisions/saveDraft (actually a custom plugin action, but in the it end up there). I expected it to take the already published entry's data and creates a new draft based on the data of the published one overriden with the posted data. But it seems this is not the case. Now I have drafts with only the few fields from the front-end form.

Of course I can get the entry data of the published entry before saving the draft and overwrite it with the post data, but maybe you guys know a simpler/better solution?


texts:
I have two forms on my site, one that you can use to sign up as a registered user that allows you to view content through out the site and participate in steps (tests) etc.

The second form is a form that allows you to just download CERTAIN content on the site rather than view the whole site's content.

I need to figure out how to separate users when signing up, the forms are pretty identical other than 2 options. However if the user wants to come back and register for the site after downloading the content, i need to figure out a way where they can use the same email they used in the past.

I have 2 forms one for registered users and one for kit users
registered users form gets FULL access to the site and kit users get access to one page with some downloads.
if user signs up for kit i need to separate the kit users from registered users.
if the user comes back, need to figure out how to let them use the same email they originally used.


texts:
I'm trying to clear templates cache. The Craft CMS 3 documentation says:
 You can also manually clear all of your template caches from the Settings page, using the “Clear Caches” tool.

When I go into Settings, I don't see any options to clear the cache there, nor is it within any of the other options there (General, Sites, Routes, etc). Do I have to enable the utility somehow?  Thanks in advance for your help.


texts:
With Craft Commerce, users have the ability to save, edit and delete addresses.

At present, if a user wants to add or edit an address, they are taken to a separate page. I want to know how I can embed a new address form (or indeed one with an existing address) into a modal on the same page.

This is the default code that displays the list of saved addresses and an 'Edit' link:

{% if craft.commerce.customer.addresses %}
  {% for address in craft.commerce.customer.addresses %}

      Edit
      <form style="position:absolute;" method="POST">
        {{ getCsrfInput() }}
        <input type="hidden" name="action" value="commerce/customerAddresses/delete">
        <input type="hidden" name="id" value="{{ address.id }}"/>
        <input type="submit" class="button button-outline" value="x"/>
      </form>
      {% include 'commerce/_includes/address' with {'address': address} %}

  {% endfor %}
{% else %}

You currently have no addresses saved. Go ahead and add one.

{% endif %}

This is the code for the modal dialog:

  <button data-remodal-action="close" class="remodal-close"></button>
  [CODE HERE]

....which is triggered by:

Call the modal with data-remodal-id="modal"

How do I go about embedding the address form into a modal? So that when a user clicks 'edit' or 'Add' a modal dialog appears with the relevant content?

Help would be much appreciated as this is a little beyond me.


texts: Internal Server Error for admin login and dashboard

texts:
I deployed a Craft 3 site and the site is fine, however when I try and go to /admin to login I get a Craft "Internal Server Error - Server Error" message and can't access the dashboard.
Any ideas where to look?

Thank you!


texts: How can I get the index of an occurrence in a repeating event on the calendar month view?

texts:
I'm using the calendar demo templates that came with Solspace Calendar (documentation here). I've got a couple repeating events and I want to output the occurrence index (Day 1, Day 2, Day 3, etc.).

Here's the code for the specific day:

{% for entry in day.events %}
  {{ entry.title }}
{% endfor %}

From the docs, I'd think occurrenceCount to work, but it returns 0 for each event vs the index of the occurrence.


texts: Look up a specific Variant, using the variant's ID?

texts:
When looking up a specific product by ID, you'd do something like this:

{% set product = craft.commerce.products.id(productId).first() %}

If you instead have a variant ID and want to find a specific variant, what is the Variant equivalent of that code?


texts: ContactForm Plugin - Where does the email source come from?

texts:
Trying to find out where the source email comes from with the ContactForm Plugin. The plugin is perfect and saved me a lot of time, so thank you guys!

Alas, my client is getting emails from the site in my name, yet I can't see where this is being sourced form - except possibly my profile page.

Is there a place I can configure the email for the ContactForm plugin other than changing the email address for the admin account?

Many thanks,

Stephen


texts: Can Craft's Rich Text fields be configured to use Redactor's autosave?

texts: The question really says it all. Here's the autosave docs page: http://imperavi.com/redactor/docs/settings/autosave/


texts:
Currently I have infinite scroll setup as below, but when changing the ordering of the entries, then loading more through the infinite scroll it's not loading in the order of the entries.

Set Sort Options

    {% set sortOptions = [
        {
            label: 'Name Z - A',
            value: 'title desc'
        },
        {
            label: 'Name A - Z',
            value: 'title asc'
        },
    ] %}

{% set selectedSortOption = craft.request.getParam('order', 'title asc') %}

Pagination Loop

{% paginate craft.categories.group('university').order(selectedSortOption).limit(1) as pageEntries %}

    {% for category in pageEntries %}

          {% for asset in category.universityLogo %}

          {% endfor %}

{{ category.description }}

    {% endfor %}

      {% if paginate.prevUrl %}
          Previous
      {% endif %}
      {% if paginate.nextUrl %}
          Next
      {% endif %}

    {% endpaginate %}

Javascript Adding Query

{% set orderJs %}
  $(function(){

    $('#sortQuery').on("change", function(e){

     // Get the value from the select
     var filter = $(this).val();
     document.location.href = '{{ craft.request.getUrl() }}?order=' + filter;

   });

  });
{% endset %}
{% includeJs orderJs %}

Endless Scroll jQuery


texts: Entry saving in task fails due to required assets/matrix fields being read as blank, even through they are not

texts:
I have a task that is used to collate relationship data for a specific entry and save it as JSON to a text field in that entry. Everything is working fine, except for the saving of the entry which fails because the required Matrix / Assets fields in the entry are being read as blank. I've checked to make sure that the entries have all required fields completed, but the errors still persist.

The entry saving code in the task:

$entry->getContent()->setAttribute('latLngs', json_encode($latLngs));

craft()->entries->saveEntry($entry);

The errors being returned:

[_errors:CModel:private] => Array
(
    [gallery] => Array
    (
        [0] => Gallery cannot be blank.
    )
    [standardContent] => Array
    (
        [0] => Standard Content cannot be blank.
    )
)

Where gallery is an Assets field, and standardContent is a Matrix field. All other required fields seem to be working fine with no errors.

Is this to do with the way I'm saving the entries, or something else?

Thanks!


texts: Pasting tables from Microsoft Word into Rich Text fields

texts: How do you paste a table created in Microsoft Word into a Rich Text field in Craft?


texts: there is tool forms(/craft/app/templates/_includes/). But I cannot find usage manual, ex. options for forms.select etc. Where is it, guys? Thank you


texts: How do you clear the templatecachequeries table?

texts:
I just noticed that on a site we launched a month ago, the templatecachequeries table is now 500mb. I'm only using the {% cache %} tag in one place on the site, around the main content matrix field. There are about 52000 rows in the templatecachequeries table now.

I've cleared the caches from Utilities, and I've re-saved all the sections but the rows are all still there. Are these meant to get deleted at some point? Is it safe to delete the rows?


texts: Categories or Structures: Most efficient way to organize FAQ sections

texts:
Working on a plan for a site that has multiple audiences, with a FAQ section for each audience.

FAQ entries are organized by Topic (Finance, Advertising, Publicity)

each FAQ entry can be associated with multiple topics

FAQS and Topics are also organized by audience: (trainee, associate, lead)

a given FAQ entry or an entire Topic full of entries can be associated with multiple Audiences

It would be nice to be able to order the entries in each topic, but not a must have.

The three separate FAQ pages would have content that maps out like this, as an example:

Trainee Audience page

Advertising
     Ad Entry 1
     Ad Entry 2
Finance
     Fin Entry 1
Publicity
     Pub Entry 1

Associate Audience page

Advertising
     Ad Entry 2
     Ad Entry 3
Publicity
     Pub Entry 2

Lead Audience page

Advertising
     Ad Entry 1
     Ad Entry 2
     Ad Entry 3
Finance
     Fin Entry 1
     Fin Entry 2
     Fin Entry 3

I know that this can be accomplished in various ways using categories, structures, and related entries, but I'm aiming for efficiency, then ease of editing for the users.

I've tentatively landed on this:
One main Structure, with Topic and FAQ entry types. Both entry types have a Category field to select audience

but not sure if I'm missing a better option for performance/ease of use.  Any advice is appreciated!


texts:
I have Neo fields in my entries which I want to be populated by a JSON feed pulled in through Feed Me, im using elementApi top create the JSON feed.

The Feed Me setup runs fine and there are no errors. My issue is that I'm un-able to map the Neo Fields when it comes to the configuration screen (where you select the Feed Element from your fields to map with the JSON fields), because I am only seeing the top-level of the Neo fields.

Any help would be greatly appreciated


texts: Saving a variant with new stock from plugin

texts:
Has anyone had any luck trying to save a variant via a plugin?

I'm trying to integrate with a 3rd party inventory system and want to grab the current stock information and update my variants. Currently I have

$criteria = craft()->elements->getCriteria('Commerce_Variant');
$criteria->sku = $sku;
$variant = $criteria->first();

Which works just fine to grab the variant i need, but...

$variant->stock = 99;
craft()->commerce_variants->saveVariant($variant);

This gives me no error, but does not update the variant in the database. What is the method I should be using to achieve this?


texts: ImageOptimze - Will removing image Variant Ratio delete image files?

texts:
We want to remove an image ratio from out variant options. Will the files with that image size automatically be removed when we do so? If not how do we ensure they are?

We are looking to remove them to increase the storage amount on our s3 instance.


texts: Is it Possible to Connect a Custom Stylesheet to Redactor via the Config?

texts:
I am running into an issue with Redactor in Craft and I am wondering if anyone can help me sort it out. I am trying to set up multiple rich text fields with different stylesheets connected to each. I've tried out the redactor styles plugin and while it does connect the custom stylesheet to the field, it only allows me to specify one stylesheet site-wide.I took a look at the redactor docs, and it looks like there is an option in the settings for specifying a custom stylesheet, but I can't find an example of how to implement it, and I've tried adding a line to my config but it doesn't work. Here's an example of what I tried in the config:

{
buttons: ['html','formatting','bold','italic','link'],
plugins: ['styles'],
toolbarFixed: true,
stylesheet: "http://mysitedomain.com/assets/css/redactorStylesHeader.css"
}

The stylesheet item I saw in the docs is here: https://www.modmore.com/extras/redactor/documentation/configuration/#stylesheet

Am I not understanding the docs correctly? I was thinking that you could specify a stylesheet option with a url to the stylesheet you want to use and it would use it as a custom stylesheet in addition to what is loaded into redactor.

Can anyone help clarify this for me?

Thanks,

Brian


texts:
I'm just wondering when it comes to Element API is there a way of returning a type of Category.

I'm returning all the other information fine.

'fees.json' => [
    'elementType' => 'Entry',
        'criteria' => [
            'title' => craft()->request->getQuery('title'),
            'section' => 'fees',
        ],
        'transformer' => function(EntryModel $entry) {
            foreach ($entry->fee as $block) {
                $matrixSections[] = [
                    'first' => $block->firstInstallment,
                    'second' => $block->secondInstallment,
                    'full' => $block->full,
                    'grant' => $block->feeCategory
                ];
            }
        return [
            'title' => $entry->title,
            'menu' => [
                'sections' => $matrixSections
            ]
        ];
    }
]


texts:
I have a channel which is basically a list of articles. Each article is associated with one or more companies. When I click on companies I want to show all  the articles related to the company. I got that working, but now I want to show all the articles which have download types inside of them. So I had created a Matrix field type. I want to search for articles which will return all the articles which have those and then exclude them from other list which won't have any download association.

Is this doable?


texts: Grouping entries by a custom date conditional

texts:
I'm looking to group entries based on a condition between two custom date fields and the current date. I'm not even sure this is possible, but this is how it would appear visually:

Happening Now

Entry 1

Entry 2

Happening in the future

Entry 3

Entry 4

Happened in the past

Entry 5

Entry 6

These entries all have two custom date fields, biddingStartDate and biddingEndDate. If the current date is between biddingStartDate and biddingEndDate, it should go under "Happening Now"; if the current date is before biddingStartDate, it should go under "Happening in the future"; and if the current date is after biddingEndDate, it should go under "Happened in the past".

The other large question here would be: how would the headings even be created since they're dynamic and not stored in the database?


texts: Rich text editor Redactor adding additional paragraph p tags

texts:
The rich text editor redactor is adding in additional p tags to rich text content. Is there a way to modify this so it accepts the unmodified HTML but still has the advantage of WYSIWYG editing?

Perhaps it is fixed in version 10.0.1 as I see Craft uses v9.2.6 of this editor. Will it be upgraded perhaps to test?

Update: This seems to be part of the config: http://imperavi.com/redactor/docs/settings/clean/#setting-replaceDivs

I believe we should be able to turn on/off some things. e.g. http://imperavi.com/redactor/docs/settings/clean/#setting-removeEmpty http://imperavi.com/redactor/docs/settings/clean/#setting-paragraphize


texts:
When creating, editing or deleting anything in CP the notification with "An unknown error occurred" is appended at the top.

I check the console and I get a 500 on these:

/index.php/admin/actions/tasks/runPendingTasks
/index.php/admin/actions/tasks/getRunningTaskInfo

Nothing is in the logs that I can see.


texts: striptags but leave link test in between

texts:
I have a rich text (redactor field) that I'm using striptags on to remove the html markup from the front end. However I noticed for links it whips out the link and the text in between. Is this something I can fix with a regular expression? Can you even do that with a twig filter? If so does anyone have an example?

Here is my code:

{% set articleText = myFirstMatrixBlockWithType.blogArticleText %}
{% if articleText | length > 200 %}
    {% set articleTextTrim = articleText | slice(0, 200) ~ '...' %}
    {{ articleTextTrim | striptags }}
{% else %}
    {{ articleText | striptags }}
{% endif %}


texts:
I set up a new shop and the base currency is US dollars. However I want to change this to Euro's. How can I do this?

In Commerce --> Settings --> Payment Currencies I can add new currencies but I can't set it as the new default.

Am I looking in the wrong spot?


texts: Why am I getting ?p=oldpage in a 301 redirect?

texts:
Not sure whether this is directly related to Craft but I’ve been using this method for years and it has always worked with other sites.

I’m replacing an old site and some pages have moved. I want to redirect any old pages to the new url since there are already indexed.

I’m using a simple redirect 301
Redirect 301 /work/project-name http://www.mysite.com/case-studies

I’m getting http://www.mysite.com/case-studies/project-name?p=work/project-name and of course a page not found since this is not where I intended the page to go.


texts: Restricting relationship field by author

texts:
First site using Craft and impressed thus far.

I'm going to be allowing CP access for all users, and these users will have access to multiple channels. I want them to be able to relate their entries from different channels to each other, but only be able to select from their own entries within the relationship field.

I can't seem to find anywhere that allows this. I did a test with 2 separate users, and when I went to relate, I could see the other user's entries available for relationship in the entries relationship field. This won't be acceptable as each user should be in their own silo and only have the ability to relate their own entries.

Is there any way I can accomplish this that I'm missing? (edit: without custom field type)


texts: How can I enter data in a matrix field with a front-end form?

texts:
I want to use a front-end form for certain users to post entries. However, the entry layout contains a Matrix field. How can make a field where people can enter content in a matrix row? Suppose I have a matrix field called bodyNews containing a text field called text. I thought I could do this:

<textarea id="body" name="fields[bodyNews][text]"></textarea>

But that doesn't seem to work. Any ideas?


texts: List entries from different locales using localeEnabled

texts:
I have two locales (de, en) and a set of entries. Some have only the german locale enabled, some only the english one. Some have both enabled. Those entries have a status of "live".

What I want to achieve: When I’m on the english locale for example, all entries should be listed. If an entry is not available in the english locale, show the german one instead (or the disabled english one, if that would be possible).

I thought this would work:

{% set entries = craft.entries({
    section: 'mySection',
    localeEnabled: false
}) %}

{% for entry in entries %}
    {{ entry.title }}<br>
{% endfor %}

But this list only shows the entries for the current locale, but not for other locales. I can’t set status: null like mentioned in this thread, because I only want entries to show up that are set to "live".

Any hints? Or is it just not possible without setting status: null? I’m on Craft 2.6.2985.

Alternatively I could query for one locale first, then for the other one and merge the results. But that seems not very desirable for this rather simple need.


texts:
Whats the recommended way to have javascript based filtering and sort table views in a plugin tab?

Is is possible to use garnish to do that or should we be looking at external libraries like:

http://www.datatables.net/


texts: Verify if unrelated items are in the cart

texts:
Folks:

In this scenario, a main product has multiple accessories (which are, of course, related to the main product through relationships). Only certain accessories are related to the main product. The user can place main products and unrelated accessories into the cart. I'd like to display a warning that they are ordering incompatible items.

I understand that you can use empty or relatedTo to find out if a relationship exists between entries but in this case, I need to know if accessories unrelated to the main product are in the cart.

Is this possible?


texts:
The craft docs on eager loading show you how to eager load image transforms in twig.

{% set entries = craft.entries({
    with: [
        ['coolImage', { withTransforms: ['transform'] }]
    ]
}) %}

However it doesn't show you how to actually USE them once they're eager loaded. Accessing the eager loaded element itself is easy:

{% set teaserImage = entry.coolImage[0] ?? null %}

But I'm not sure how to access the transform from there. Using getUrl('transform') appears to still result in an extra query per element loaded (compared with .url() and no transform).

{{ teaserImage.getUrl("transform") }} {# Boo - extra queries #}

What am I missing?

Thanks :)


texts: Template Errors with Include on Single Entry

texts:
Now I've run into a really odd issue. I've got a hero include that is working elsewhere on the site, but on this one single it's not working at all. On a working "Single" the code is this

{% extends "_layout" %}

{% block content %}

{% include '_includes/hero'
  with {
    imageName : 'page-hero-about',
    className : 'about',
    imageAlt  : 'Photo of store front',
    findStore : false,
    leadCols  : 'col-md-6',
    leadClass : 'lead'
  }
%}

And on the other non-working single the code is this:

{% extends "_layout" %}

{% block content %}

    {#{% set entry = craft.entries.id(72) %} #}

    {% include '_includes/hero'
      with {
          imageName : 'page-hero-mission',
          className : 'mission',
          imageAlt  : 'Teaching people to read',
          findStore : false,
          leadCols  : 'col-md-9',
          leadClass : ''
     }
%}

On the non working page if I don't set the entry id I get a variable "entry" does not exist (though this is not needed on the working single). However once I do set that I get this error Object of class Craft\ElementCriteriaModel could not be converted to string Have googled but can't seem to find anything.  Also the code is pretty much identical so am at a loss


texts: Archiving by month and year - timezone could not be found error

texts:
Following the answer in this thread -Linking and showing archive by month  by P&T has worked fine for previous sites but now I'm getting the following error. I've checked I have a Time zone selected in System settings.

DateTime::modify(): Failed to parse time string (first day of archive
2018 00:00:00) at position 13 (a): The timezone could not be found in
the database

Template:

{% set month = craft.request.segment(3) %}
{% set year = craft.request.segment(4) %}

{% set firstDay = now | date_modify('first day of ' ~ month ~ ' ' ~ year ~ ' 00:00:00') %}
{% set lastDay = now | date_modify('last day of ' ~ month ~ ' ' ~ year ~ ' 23:59:59') %}

{% set archive  = craft.entries.section('bulletinOnline').postDate('and', '>= ' ~ firstDay, '<= ' ~ lastDay) %}

{% for entry in archive %}

  ...

{% endfor %}


texts: I created a Vue component. And in this component, I use axios to send post request when it's mounted, CSRF token also included, but still got 400 status. Anyone know why?


texts:
I am trying to use the Placid plugin to retrieve track-names from an external service, and having problems. I have the following code:

{% for song in craft.entries.section('music') %}
  {% set params = { 'id' : song.itunesId } %}
  {% set lookup = craft.placid.get('itunesMusic', { params : params } ) %}

  {% for track in lookup.results %}
    {{ track.trackName }}
  {% endfor %}
{% endfor %}

The values of song.itunesId and params seem to be set correctly, however lookup.results is returning the same track.trackName on each iteration of the loop.


texts:
I'm trying to set up Craft and on deployment to a staging server am getting the following error message:

  An exception has been thrown during the rendering of a template
  ("Craft can't connect to the database with the credentials in
  craft/config/db.php.") in "_layout" at line 39.

The config file in question is posted up at https://gist.github.com/cole007/f32c7ba984a3d35b1d24

Any thoughts?

Cheers in advance,

Cole


texts:
A bit of an extension of my previous query at Auto-login on account activation

I want to a user to:

automatically login on account activation, and
be redirected to a predetermined page on account activation.

Thanks to @steverowling managed to do the former using his autologin plugin(1). However struggling with the latter. I can't see how to specify the redirect location and on activation/login the user is always redirected to the site homepage.

Any thoughts on how to specify a redirect destination in conjunction with the above functionality?

Cole


texts: Rich Text field is stripping anchor while showing the content

texts: I am facing a strange issue. All the anchors are getting stripped while publishing the content of Rich Text field. Could anyone please help me.


texts:
Short story: I need your help sending value from dropdown selection as data to controller so my div updates with the filtered entries based on the selection.

Long story and code: I have a listing of entries in my template as follows:

{% for entry in craft.entries.section('live').find() %}

{{ entry.title }}

{% endfor %}

I know I can filter those results with a field handle by updating the first line above with:

{% for entry in craft.entries.section('live').hostSite('weDo').find() %}

However I'd like to filter that listing of entries with a dropdown list that contains the available field handles, ie 'weDo, 'theyDo':

<select class="filter">
    <option value="all">all sites</option>
    <option value="weDo">sites we host</option>
    <option value="theyDo">sites they host</option>
</select>

I'd like to do this with Ajax and a controller I set up:

**Javascript**
// Add an event listener for filter clicks
$(function () {
    $('body').on('change', 'select.filter', onFilterClick);
});

// Event handler for the filter click
function onFilterClick (e)
{
    e.preventDefault();
    var data = this.value;

    $.ajax({
        method: 'get',
        url: 'actions/websiteListing/checkStatus',
        data: data,
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
    })
    .success(function(data) {
        $('.livelisting').html(data);
    })
    .error(function(data) {
        console.log('error', data);
    });
}
**Controller**
<?php
namespace Craft;

class WebsiteListingController extends BaseController
{
    protected $allowAnonymous = true;

    public function actionCheckStatus()
    {
        $criteria = craft()->elements->getCriteria(ElementType::Entry);
        $criteria->section('live');
        $criteria->hostSite = 'weDo';
        $criteria->limit = null;

        $entries = $criteria->find();

        foreach ($criteria as $entry) {
            echo $entry->title . '
';
        }
    }
}

I know the ajax is pretty trashy, but the url to the controller file is working correctly because when I make a selection from the dropdown menu, my div.livelisting is replaced by the single entry available with the field handle of 'weDo'.

Here's where your help is needed! The 'weDo' value in my controller needs the data sent from Ajax. Thanks for your expertise.


texts:
I am trying to integrate PayPal Pro into Craft Commerce, I have my API details added to the payment gateway and I have disabled test mode. I know these keys work as they have been used before.

On checkout, when I have PayPal Pro selected as a payment method, I receive an error "Invalid payment or order. Please review." when I press checkout.

I have two questions;

Could anyone give me an idea as to why this payment gateway isn't
working but the other payment gateways are working fine? Maybe I'm making a common mistake somewhere.
Are there any ways of dumping out errors, the flash errors don't seem to provide any detail which is making debugging this issue difficult.

Thanks.


texts:
I'm new to Craft and exploring whether it's worth my team moving our existing, deeply-structured content site onto Craft CMS.

We have a heavily nested sitemap at the moment with 6 top-level categories and up to 5 nested levels of subcategory, eg:

- Cat 1
    - Sub Cat 1A
    - Sub Cat 1B
        - Sub Sub Cat 1Ba
        - Sub Sub Cat 1Bb
    - Sub Cat 1C
- Cat 2
    - Sub Cat 2A
    - Sub Cat 2B
- Cat 3
    - Sub Cat 3A
        - Sub Sub Cat 3Aa
    - Sub Cat 3B

I'd like these categories reflected in URL slugs for entries, eg. /cat-1/sub-cat-1-a/ and /cat-3/sub-cat-3-a/sub-sub-cat-3-a-a etc.

I made a Category Group called "Navigation" then made a bunch of categories and nested sub-categories. I added a section and made sure it had a Category field in its Entry Types.

What I can't do, though, is get those URLs to work. I've tried following the instructions from Brandon Kelly here but I only ever get URLs generated with the top-level category slug (eg. /cat-3/{entry.slug}.

Oddly, when I select a category for an entry, no matter how many levels deep I select from, the category shown when I edit the post is always the top-level one, not the one I actually selected. Could this have something to do with it? I've ticked the "Categories in this group have their own URLs" option when editing my navigation Category Group.


texts: How do I pull out a total of 4 rows from all my matrix blocks?

texts:
I have an entry that has a matrix field, which has a table in it; I am trying to pull out 4 rows from the latest block, but if there aren't 4 rows then I would like it to pull out the remainder from the older blocks (So I always have 4 items displayed, even if the latest matrix block only has 1 table row in it).

This is what I have so far, but this is pulling out the latest 4 rows from EACH matrix block, so if I have 2 blocks it displays 8 items.

Does anyone know if what I'm trying to do is possible?

{% for entry in craft.entries.section('sectionName').find() %}
    {% for block in entry.matrixField %}

    {% if block.type == "blockType" %}

        {% for row in block.tableField | slice(0, 4) %} <!-- I tried .limit(4) here too -->
            {{ row.title }}
        {% endfor %}

    {% endif %}

    {% endfor %}
{% endfor %}

Any help is appreciated!


texts:
starting point

I have the following offer with quantity discounts for a series of my products:

Buy 1 item and get $5 off per item
Buy 2 items and get $10 off per item
Buy 3 items and get $15 off per item

I set these discount rules in my control panel under "commerce" > "promotions".

product template

Now in my product template, I would like to be able to output (for each quantity level):

the normal (non-discounted) price
the discounted price
savings in terms of $
savings in terms of %

example

For example it would then say on the product page (output):

  "If you buy 2 items, you only pay $[discount price for 2 items]
  instead of $[normal price] per item. So your total today is only
  $[2 x discount price for 2 items] insted of $[2 x normal price].
  You therefore save $[(2 x normal price)-(2 x discount price for 2
  items)]. That's a discount of […]%."

The same goes for the discount offer of ordering 1 item or 3 items.

How can I accomplish this with all the discounts and math operations involved?


texts: How to get specific single with status live

texts: How can I get a specific single (careers) with status live in twig?


texts: Missing Matrix content after upgrading from Craft2 to Craft3

texts:
I’m upgrading my Craft2 blog to Craft3 at https://brill.blog.
I’ve got a loop to display text, images, and block quotes from a Matrix field, that follows this pattern:

{% for block in entry.matrixContent %}

    {% if block.type == "imageBlock" %}
        <img src="{{ image.getUrl(transform) }}" alt="{{ image.title }}" />

    {% elseif block.type == "textBlock" %}
        {{ block.text | smartypants | replace({'&nbsp;' : ' '}) | raw }}

    {% endif %}

{% endfor %}

The actual code has lots more 'elseif's for image rows, block quotes etc. This all works fine in Craft2.

For Craft3, I’ve added .all() to the first line. But the result is that the only image blocks get rendered correctly, and everything else is missing.

Is there anything obvious I should be looking for?

I’d be happy to post much more code, if anyone here is willing to look through it.

Thanks in anticipation.


texts: Filter Entries within a page dynamically based on category

texts:
I'm creating a portfolio page, and I have a summary list of project entries displayed. At the top of the page, I've got a dropdown displaying a Category field. e.g. craft.categories.group('industry')

My question: Is it possible to display/filter entries of a particular category dynamically/immediately when a dropdown entry is selected (using only Twig)? Or do I have to use Javascript?

Sorry for this basic question.


texts: Is it possible to limit users to adding/editing entries in specific categories?

texts:
I'm building a site that regroups several properties, and I'd like each manager to edit content in his property only. All properties use the same templates and share content between each other.

I first tried to create a new section for each property, but it occurs to me that it would be much simpler to have a "room" and "facilities" section (and templates), and then divide everything using categories.

However at the moment user permissions only allow a user to add any category to their entries, which could lead to mistakes if users are not careful.

Would it be possible to limit users to a single category, so that user1 can only edit entries in category1 and user2 in category2? Any tips on how to approach this?

Thanks in advance


texts: Is it possible to run Craft CMS with putenv() function disabled?

texts:
I’m using shared hosting which supports several CMS like Wordpress, Jumla, etc. In phpinfo there is putenv in disable_functions. Craft CMS needs this function to load variables from .env file. I can acces all varibales at least from $_ENV[].

Is there a way how I can install and use Craft CMS in this environment or is putenv(), getenv() must have?

Thanks a lot for help


texts: How to use Position Select in Matrix blocks?

texts: How does one use position selects to float an element in Craft CMS template? Say I want to allow an author to center or float a quote block to the right or left using a position select. How would I do this in the template?


texts:
With regards to logging in your own plugin, is there a point which could be considered "You are logging too much" For example. In a service I currently have something like this:

public function getSomeRecordsByParentId($id)
{
  FooPlugin::log(Craft::t("Getting all records for parent id {$id}"), LogLevel::Info);

  // .. do service logic here

  FooPlugin::log(Craft::t("Found {$recordCount} records for parent with id {$id}"), LogLevel::Info);
}

And then again

public function getRecordById($id)
{
    FooPlugin::log(Craft::log("Trying to find record with an id of {$id}"), LogLevel::Info);

    $record = FooRecord::model()->findByPk($id);

    if(!$record)
    {
        FooPlugin::log(Craft::log("Unable to find record with id {$id}"), LogLevel::Error);
        throw new HttpException(404);
    }

    return FooModel::populateModel($record);
}

I know I'm only doing two per function at the moment but when they are all called it can really start to stack up.

I guess what i'm asking is are there any real performance hits that are going to be noticeable or has anyone noticed anything from logging a lot of things?


texts: Craft Installation - Getting a Forbidden Error

texts:
A forbidden error appears and can't get it to disappear. I've gone through the installation process several times and everything else works.

When I load the URL "test.craft.dev", I get back "Forbidden: You don't have permission to access / on this server."

Things I've tried:

1) db.php

$craftPath = '../craft';

2) folder structure

/craft/..
/public/index.php

Any help would be greatly appreciated.


texts: How do I programmatically set a Users company field?

texts:
I'm currently able to add a user with the following code (from the Docs):

$user = new UserModel();
$user->username  = 'tommy';
$user->firstName = 'Tom';
$user->lastName  = 'Foolery';
$user->email     = 'tom@thefoolery.com';

$success = craft()->users->saveUser($user);

if (!$success)
{
    Craft::log('Couldn’t save the user "'.$user->username.'"', LogLevel::Error);
}

How can I also set the Profile Company name??

I've tried the following with no luck:

$user->company = 'ACME';

$user->setContent([ 'fields' => ['company' => 'ACME'] ]);


texts:
I'm using Rias500/craft-contact-form-extensions plugin for creating custom email confirmation templates, and it works great but when I try to override the template (because I need confirmation emails per form) in my form with (which is the example in the documentation):

<input type="hidden" name="message[template]" value="{{ 'contact'|hash }}">

It will still send the email in the template I set in my CP. Am I doing something wrong?

If anyone knows another good solution for this then I like to hear it.


texts:
In my product catalog, some product images need to have the css attribute object-fit: cover while some need the object-fit: contain:

I'd like to detect the white background, possibly on upload (to ease processing when live). I am currently using Imager for transforms, and I would guess that plugin could have some detection feature, but I can't seem to find it.
Reading around a little suggests reading all four corners of the image and determine white bg if all four pixels are white -- but how can I do this? (and how can I do it on file upload?)
Comments for provided solution
Craft CMS has a powerful event system that lets you attach to events and then perform further actions on the entities involved.
I created a site module based on nystudio107's template, and inserted the provided code.
Then I created the field hasWhiteBackground as a lightswitch field, and ran a console command ./craft assets/resave as documented in the Craft CMS 3 docs, to update the lightswitch for existing assets.
I am using imager to transform the images and to create srcset. I use the hasWhiteBackground to do either a fit or crop mode to the resize operation:
{% set image = p.productImage.one()|default(null) %}
{% set transformedImages = craft.imager.transformImage(image, [
    { width: 269 },
    { width: 246 },
    { width: 209 }
    ], {
        ratio: 1/1,
        position: image.getFocalPoint()|default("50% 50%"),
        mode: image.hasWhiteBackground|default(false) ? 'fit' : 'crop'
    })
%}

I then added the class contain to each image outputted:
 class="{{ image.hasWhiteBackground ? 'contain'}}">

The class simply adds the following css to the image:
.contain {
    object-fit:contain;
}

Here is what the result looks like:


texts: How can I mitigate caching performance issues with Craft?

texts:
I ran into problems with the performance of one of our Craft sites. This showed up as:

MySQL running out of memory and crashing, because Apache was using up all the memory in backgrounds tasks,
Sometimes getting blank, white pages back from the cache instead of real results, and
background tasks hanging and failing to clear out stale cached pages.

The website we've built uses caching on nearly every page.


texts: Can fields be reused with a different name per section?

texts:
I've got a redactor field used on several sections, and category groups. Is there a way to change the displayed name per section in the edit form?

On a category group the field is, 'Category Description', and on products, 'Product Description', but under the hood they're both 'richText'.


texts: Rounding down issue with commerceCurrency filter

texts:
We have a site-wide sale on with 10% off products. On the category/detail page the commerceCurrency filter appears to round down, but when a customer adds an item to the basket, it's shown correctly as the rounded up price. Just had a complaint that it was 1p more than advertised (can you believe!).

Weirdly it rounds up correctly on my dev machine, which is running Ubuntu Desktop. Both running 18.04 LTS and PHP 7.3 with the same packages installed.

I have dug around the commerce/yii codebase and it's ultimately using the vendor/yiisoft/yii2/i18n/Formatter.php asCurrency() method.

I can write my own macro/filter to correct this, but seems like a bug to me.

e.g. Price £16.95, on Sale, £15.255.

{{ product.defaultVariant.salePrice|commerceCurrency(cart.currency) }}

Results in £15.25, but the value 15.26 is saved to commerce_lineitems and added to the cart.


texts:
$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'stories';
$criteria->search = $this->query;
$criteria->order = $this->orderSql();
$criteria->limit = 1000;
$criteria->visibility = $this->checkVisibility();
$criteria->thisIsAGuide = ':empty:';

I need help adding a relatedTo criteria to help pull related entries.

The current search scope is searching on entries ("Story").
The entry("Story") contains an entry ("channel").
That channel has a category("brandCategories")

I need to return stories that contain entries that have a matching brandCategory.
That brandCategory is getting pulled from a GET var of "&brands%5B%5D={{categoryId}}


texts: Getting started with CraftCMS 3.1's project config files and I can't find any documentation about whether storage/config-deltas/delta.yaml should be committed to git


texts:
We would like to show a page which lists all Authors, and their respective entries, eg.

Dan Griffey

Entry 1
Entry 2

Joe Blogs

Entry 1
Entry 2

Have tried a few options but alas none working, so would appreciate any help / examples.


texts: Latency issues on local development server

texts: I do craft development on a local setup (using a virtual .dev host). The one very annoying issue I experienced is a large latency (~10s) I get while using the backend – f.e. saving an fresh entry or creating a new field. The latency vanishes as soon as I disconnect from the internet. Is there any "call home" function build into craft that causes the delay?


texts:
I'm trying to integrate the ElementAPI plugin into my site. Essentially, I need to output all of the assets within the website into a JSON file that I can link to in the load manifest of PreloadJS. If you read the docs here, you'll see that the images can be loaded from an external JSON file.

Here's what I've been working with so far:

<?php
namespace Craft;

return [
    'endpoints' => [
        'assets.json' => [
            'elementType' => 'Entry',
            'criteria' => ['section' => 'news'],
            'transformer' => function (EntryModel $entry) {
$images = [];
        foreach ($entry->featuredImage as $image) {
        $images[] = $image->url;
        }
                return [
                    'image' => $entry->image
                    'jsonUrl' => UrlHelper::getUrl("assets/data.json")
                ];
            },
        ]
    ]
];

So, to sum up, what I'm needing to do is build an API that will get a list of all the assets used in my site and output them into a JSON file that I can link to in a JS file as part of the PreloarJs plugin. This would make my preloader dynamic and allow me to keep my javascript external, rather than getting the assets inline, which I have been doing.

Thanks!


texts: Can you hook into a Redactor field before render?

texts:
I am wanting to hook into all my redactor fields content before rendering and update any inline links to include a title="" attribute. Is it possible to hook into the field before it is rendered? With PHP or in settings (https://imperavi.com/redactor/docs/settings/)?

Thanks


texts:
This seems like an odd question, but I've looked through the documentation, Slack, and the StackExchange and it's weird that I'm not seeing anything... so I feel like I'm overcomplicating it.

How do you set a Single (or anything for that matter) to be the homepage of a Craft 3 site? In Craft 2 there was the "This is for the homepage" option, but I don't see that in Craft 3. Is that because it hasn't been implemented yet or is there a new best practice for doing this? Is this going to be something added into Setting > Sites section?


texts:
I need to take a file, and email it to a large group of people. Naturally, I'll be using a custom plugin Controller to trigger the email blast.

I'm already aware of this similar thread, but I don't believe it will solve my problem. If I remember correctly, Craft's native email model isn't capable of sending to more than one person at a time. More importantly, I don't want our server to be labeled as a spammer!

Would it make sense to run this process through a Task? Each individual email could be sent out as a separate step in the task.

What is the best way to bulk email an attachment?


texts:
I have created a Global with the handle 'footer', which contains a Matrix field 'links' and I'm trying to get this into a template, but I can't seem to get this to work.

The 'links' Matrix contains a Block Type 'navigation' with a Plain Text field 'navigationHeadline' and a Table field 'navigationLinks'. The table field contains 'linkLabel' and 'linkUrl' columns (see attached image).

I'm ultimately creating my navigation in a Global with a Headline and some Links and the Headline should only appear if each block has some links;

{% for block in entry.links %}
    {% if entry.navigationLinks | length %}

{{ block.navigationHeadline }}

        {# Show the navigationHeadline if it has links #}

            {% for row in entry.navigationLinks %}

{{ row.linkLabel }} - {{ row.linkUrl }}

            {% endfor %}

    {% endif %}
{% endfor %}

I wondered if anyone can help me resolve my obvious errors. Thanks.


texts:
'criteria' => [
    'section' => 'news',
    'date' => craft()->request->getPost('date')
],

How to make that worked like this:

'criteria' => [
    'section' => 'news',
    'date->format("Y-m-d")' => craft()->request->getPost('date')
],


texts: Using FeedMe 2.x with a custom authentication mechanism

texts:
I have a Craft 2 project which is using an older version of the FeedMe plugin 1.x. In order to use a specific XML feed this site uses, a custom XML feed service was implemented with a custom feed type available to select from the feed type option in Craft FeedMe back-end, but this involved directly editing the FeedMe plugin files.

The reason for this is because a specific authentication mechanism is required before being able to interact with the feed in the form of a unique token passed by the Authorization HTTP header obtained from a separate auth endpoint first. This is then added to the feed request via curl, so its authenticated and returns data.

The current implementation added an additional service within feedme/services/ which extends FeedMe_FeedXMLService to handle the token authorisation part and added an additional enum type, record type, model type. In theory could a separate plugin be created that provides the service without having to modify the core plugin? Or could the approach be different given the changes with the 2.x version of the plugin?

It looks v2.x has changed quite a bit looking at the core plugin files with potentially more options for customisation, but I'm not sure if the implementation we have is possible to move to 2.x easily.


texts: We're having trouble with images being transformed with glitches in them. What would you advise to debug behavior like this?


texts: Can I apply adjustments (discounts) through a controller?

texts:
I have a controller which when called (actions/some-module/discount-link/apply?code=abc) associates abc with an entry and based on some stuff in that entry populates the cart with some specific products. This works well.
What I want to do next is apply a discount to each line item that the cart is populated with. Setting up an adjuster as per the docs was no problem, but when I'm trying to add adjustments to the cart from within my controller I can't figure it out.
The last part of of my controller:
foreach ($cart->getLineItems() as $item) {
    $adjustment = new OrderAdjustment;
    $adjustment->type = 'discount';
    $adjustment->name = '$2 off';
    $adjustment->description = '$2 off everything in the store';
    $adjustment->sourceSnapshot = ['data' => 'value'];
    $adjustment->amount = -2;
    $adjustment->setOrder(Order::findOne($cart));
    $adjustment->setLineItem($item);

    plugin::getInstance()->getOrderAdjustments()->saveOrderAdjustment($adjustment, true);
}

Craft::$app->elements->saveElement($cart);

Is the entire thing wrong? Or am I not saving the adjustments to the cart correctly?


texts: "Error on creating empty cart" Craft Commerce (Market Commerce)

texts: When adding products to cart, was not getting same error in past but don't recalling changing anything. Using mostly default templates.


texts: In an Asset field, how to use a dynamic subfolder field value that is dependent on the element type?

texts:
I have a field named image that is assigned to an entry as well as a category.

When a user edits an entry, I would like the subfolder to be named after the section.handle property.

When a user edits a category, I would like the subfolder to be named after the group.handle property.

Is there a way to achieve this? I've tried something like this:

{{ section.handle ?? group.handle }}

...but unfortunately it does not seem to work.


texts:
After setting up a template file article.html in craft/templates folder, and creating the section article with the uri article and setting the entry template as article in the admin, on trying to see the Live Preview of the page when I go to it in the entries list I get a Craft page with the error:

  Page not found

I thought it might have something with cache maybe, so I cleared that, but I still got the same error. Why I am getting this error, and how can I fix that?


texts: How can I use 'where' in an advanced search query?

texts:
I came across this handy tip for search queries on Twitter:
https://twitter.com/nystudio107/status/1354815792638955524/photo/2
{% set entry = craft.entries({
section: 'blog',
where: ['like', 'title', 'rob']
}).one() %}

This finds you 'Robert' in the title.
However, my setup is more complex and I am struggling with how to integrate the 'sounds like' or 'like' option. Extract:
{% set search = [] %}
{% set search = search | merge([query.q]) %}
{% set searchParameters = search | join(' ') %}
{% set queryParameters = queryParameters | merge({'search':searchParameters}) %}
{% set entryQuery = craft.entries(queryParameters).limit(null) %}

How can I translate the above to that kind of code?
Thank you!


texts:
I have created a shipping method in the CP but when I output cart.availableShippingMethods a null value is returned. I've checked my database and the shipping method is there.

Is there something I'm missing?


texts: Craft.createElementSelectorModal in a tooltip is causing field to disappear

texts:
Problem:

In a plugin for a custom field I want to have an Element Selection Modal so I'm calling: Craft.createElementSelectorModal()

On an Element Detail page this is no problem. But, in a tooltip (say from the element Index for example) calling the same code causes the Field to be completely removed from the DOM.

I've even tried this with no settings:

Craft.createElementSelectorModal('Entry', {})

And it's still the same thing, the entire field gets removed from the DOM just on initialization.

Questions:

Is Craft.createElementSelectorModal still the right thing to use to trigger an Element Selection modal?

If not, is there something else I should use?

Image Progression:

Edit:
For what it's worth I also tried BaseElementSelectInput and had the exact same results.


texts: Commerce - add new tab to order page in control panel

texts:
I'm am creating module that provides integration with shipping service for Craft commerce.
UX wise, it would be best if I could put module functionality in separate tab on order page. Mind you, I know that we can add new tabs using order fields functionality. But i wonder if it is possible to "hardcode" new tab using some php code. Some events maybe?


texts: Using cURL or file_get_contents is empty when calling a Craft page

texts:
I'm trying to load a page from a Craft based website using file_get_contents or cURL. Using get_file_contents I get an empty result, using cURL I can see that the request is getting redirected to the login page.

If I switch to a different domain that is also running Craft the file_get_contents and cURL both work fine.

Any idea what could possibly be causing the redirect to be happening?


texts:
In Freeform Pro's spam blocked keyword settings I have the following list:
website's design
website marketing
visa credit card
Do you accept

Emails are going to spam with the note:
Field "message" contains a blocked keyword "you" in the string...
The keyword in the above message is "you" which is part of "Do you accept". I was expecting the "separate multiples on new line" in the instructions would catch "Do you accept" but not "you". I tried putting them in quotation marks but emails with just "you" are still get tagged as spam. This seems to be a bug.


texts: Show only children relative to current page

texts:
I have this structure section:

1.0 Nav point level 1
  1.1 Nav point level 2
  1.2 Nav point level 2
  1.3 Nav point level 2
2.0 Nav Point level 1
3.0 Nav Point level 1

I want to show only top level points as long as there is no children ont the current page.

Example:

When im on page 1.0 Nav point level 1 the navi shoud look like above (Because the current page has descendants).

But when im on 2.0 Nav Point level 1 the navi should look like this:
(Everything below level 1 not visible because the current page has no children.)

1.0 Nav point level 1
2.0 Nav Point level 1
3.0 Nav Point level 1

I tried to wrap the children tag into a conditional. But that's not allowed:

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

{% if topLevel.hasDescendants %}

      {% set subnav =  topLevel.getDescendants()  %}

      {% nav page in subnav  %}

            {{ page.title }}
            {% if entry.hasDescendantes %} // this does not work at all.
              {% ifchildren %}

{% children %}

              {% endifchildren %}
            {% endif %}

      {% endnav %}

{% endif %}

I can't wrap my head around it.


texts: Adding file uploads to commerce product line items?

texts: Does anyone have any experience with adding file uploads to the add to cart forms on product pages within commerce? I've seen some examples of users attaching them to orders (didn't work for me), but I'm looking to give customers the ability to attach per each line item.


texts: Linking to Sections: do it or do something different?

texts:
I'm pretty new to Craft, so I'd like to know if there's a best practice when linking to a section, assuming the section has an index.html template for its "homepage."

I'm currently using the following to loop through all Sections and then give me their URL, but in sort of a hacky way. This is one of a couple ways I've found to do this, but my Homepage singlepage entry outputs as http://example.com/__home__ which is super weird.

{% set sections = craft.sections.getAllSections() %}

{% for section in sections %}

        {{ section }}

{% endfor %}

```

If the best practice is to do something completely different, then feel free to set me straight! Thanks!


texts: Unable to set cart currency in index.php

texts:
Craft: 2.6.2976
Commerce: 1.2.1341

I want to force currency depending on language (en_us and no). The user should not be allowed to choose.

I've added two currencies 1) EUR - base, 2) NOK.

Putting define('COMMERCE_PAYMENT_CURRENCY', 'EUR'); in the index.php for the english site, and define('COMMERCE_PAYMENT_CURRENCY', 'NOK');in the index.php file for the norwegian site does not work.

The currency is always EUR.

To be clear: Using {{constant('COMMERCE_PAYMENT_CURRENCY')}} does output the correct currency as set in index.php, however the cart is what always remains in EUR (base).

Is this a bug in Commerce?


texts: Craft CMS 3 error in Windows installation process

texts:
I was tried to run Craft 3 on a Windows machine, it has shown the multiple errors.

An Error occurred while handling another error:
yii\base\InvalidConfigException: craft\web\Request::cookieValidationKey must be configured with a secret key. in D:\xampp\htdocs\craft\vendor\yiisoft\yii2\web\Request.php:1554
Stack trace:
#0 D:\xampp\htdocs\craft\vendor\yiisoft\yii2\web\Request.php(1536): yii\web\Request->loadCookies()


texts: How do you debug problems with a migration?

texts:
I've created a simple migration to create a table for my plugin, but when I update the plugin via the CP, I get the following message:

  Craft was unable to install this update :(

  The site has been restored
  to the state it was in before the attempted update.

  There was a problem updating your database.

As it's the only change to the plugin I think it's safe to say my migration isn't up to task.

How do I know exactly what's wrong with my migration though? There don't appear to be any logs generated to show the actual error being caused. I'm running in devMode, and I can't see anything in the browser console and there don't appear to be any errors in the standard logs.

For reference, here is the migration I'm trying to run, which was created manually rather than using yiic:

<?php
namespace Craft;

/**
 * The class name is the UTC timestamp in the format of mYYMMDD_HHMMSS_migrationName
 */
class m171129_103222_myplugin_createLogTable extends BaseMigration
{
    /**
     * Any migration code in here is wrapped inside of a transaction.
     *
     * @return bool
     */
    public function safeUp()
    {
        craft()->db->createCommand()->createTable('myplugin_log',
            array(
                'eventId' => array(AttributeType::Number, 'required' => true),
                'level' => array('column' => ColumnType::Varchar, 'maxLength' => 5, 'required' => true),
                'message' => array(AttributeType::String, 'required' => true),
                'date' => array(AttributeType::DateTime, 'required' => true),
            ));

        return true;
    }
}


texts: Check the field type of all the attributes of an entry

texts:
Here's the whole picture:

I'm trying to make an API endpoint which should output everything from an entry:

First I did this:

    public function transform(Entry $entry)
    {

        return $entry->getAttributes();
    }

That outputs every field on the entry. But, in the fields containing related items like categories or header_images, In the response I got,looks like the query without being executed:

{
    ...
    "from": null,
    "groupBy": null,
    "join": [
        [
            "INNER JOIN",
            "{{%relations}} relations", [
                "and",
                "[[relations.targetId]] = [[elements.id]]",
                {
                    "relations.sourceId": "35",
                    "relations.fieldId": "15"
                },
                [
                    "or",
                    {
                        "relations.sourceSiteId": null
                    },
                    {
                        "relations.sourceSiteId": "4"
                    }
                ]
            ]
        ]
    ]
    ...
}

I found out that doing ->all(), I get the correct response.

    public function transform(Entry $entry)
    {
        $attributes = $entry->getAttributes();

        $attributes['categories'] = $entry->categories->all();

        $attributes['header_image'] = $entry->header_image->all();

        foreach ($attributes['header_image'] as $key => $image) {
            $attributes['header_image'][$key] = $image->toArray();
            $attributes['header_image'][$key]['folder'] = $image->getVolume();
        }

        return $attributes;
    }

But of course that limits me cause I have to know the field handle (header_image).

First: is there a smart/better way to get the related?

The idea I got to solve this is: Loop through all the fields, and if the type is Asset or Category, do the ->all(). But I cannot get the type of the field. I'm trying stuff like:

        $fields = $entry->getFieldLayout()->getFields();

        foreach ($fields as $field) {
            $field->getContentColumnType(); //Or something
        }

But well, doesn't really work.


texts:
I've got a parent template which contains the following code:

{% include '_layout' with {'countryCode': 'au'} %}

I have a global set with the handle au_Variables, and within that a field with the handle vimeoVideoId_au

The problem I'm having is with trying to render the following global: {{ au_Variables.vimeoVideoId_au }} dynamically, using the countryCode.

I've tried

{% set videoId = countryCode~'_Variables.vimeoVideoId_'~countryCode %}

And then outputting {{ videoId }} but all I get is the string au_Variables.vimeoVideoId_au, not the rendered global.

Any ideas how to do this in Twig?


texts:
I'm working on Craft plugin which should find entries with special tags.
In my action I have a string:

$entries = Entry::find()->section('Projects')->type(['Projects']);

and it returns all entries that I should get. But I also need related to this entries tags.

Something like this:

foreach ($entries as $entry) {
    $tags[] = $entry->getRelatedTags();
}

But this doesn't work :)

Could anybody help get related to entry tags for entry?


texts: Add custom column to the orders list page

texts:
Does anybody know if it is possible to add a column to the orders list page?

I can choose the 'Foo' label, but when the page want to show the orders list I get the following error:

"{"error":"An exception has been thrown during the rendering of a template (\"Getting unknown property: craft\commerce\elements\Order::foo\")."}"

I use this code:

Event::on(
    Element::class,
    Element::EVENT_REGISTER_TABLE_ATTRIBUTES,
    function(RegisterElementTableAttributesEvent $e) {
        $e->tableAttributes['foo'] = [
            'label' => "Foo"
        ];
});

Event::on(
    Order::class,
    Element::EVENT_SET_TABLE_ATTRIBUTE_HTML,
    function(SetElementTableAttributeHtmlEvent $e) {
        if($e->attribute === 'foo'){
            $e->html = 'BAR';
        }
    }
);


texts:
We've just had a security review of a client's site and one main issue raised is that a brute force attack would reveal the password if the username was guessable (ie "admin").

Could a limit on the number of login attempts be a possible feature in the future? Failing that does are there any suggestions for how we could best protect against this sort of intrusion with the current version of Craft?

Thanks!


texts: htaccess non-www rewrite showing index.php in URL

texts:
I am using htaccess to rewrite any www url to a non-www version

RewriteCond %{HTTPS} !=on
RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^(.*)$ http://%1/$1 [R=301,L]

When I type domain.com/about it works fine, however when I type www.domain.com/about it changes the URL to domain.com/index.php?p=about

I have 'omitScriptNameInUrls' => true, enabled.
I also have this in my .htaccess file

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]

What am I doing wrong here?

Edit:
Here is the the vhost file.

<VirtualHost *:80>
    ServerName domain.com
    ServerAdmin webmaster@domain.com
    DocumentRoot /var/www/

    <Directory /var/www/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        allow from all
    </Directory>

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


texts:
Is it possible to protect a page with a single password? Instead of using crafts user features, can I allow an admin to set a specific password from the edit page? When a user visits that page, they have to type in that password to view its content.

We aren't protecting anything that requires a high level of security. But we would like to prohibit access from any old visitor.

One possibility I'm considering is to have a password text field associated with that entry. Then when the user submit the login form, we can do a simple logic check to see if the password is valid. If so, we can set a “logged-in” status to either a PHP session or a cookie.

https://github.com/lewisjenkins/craft-lj-cookies

https://github.com/stuartalexwhitehead/remember

I wonder if anyone else in the Craft community has tried to implement something like this.


texts: How to use url segments like with Freebie in EE

texts:
I'm trying to make the jump from EE to Craft but struggling in this area (and thinking I may be approaching this all wrong).

In EE, I often use url segments (in combination with Freebie to ignore them) for certain logic in templates (ie. adding a last segment of 'thanks' to show a thank you message).

I cannot figure out how to do this well in Craft - or even if it is the right approach.

I have a channel entry with a slug of 'contact' and want to add 'thanks' to the url to conditionally display a thank you message on that page. I know I could add a route so that 'contact/thanks' will still load the correct template for that channel but I then run into the issue of that URL not matching the entry slug and no entry data is available for {{entry.whateverFields}}.

So then I did this to try to get around the issue by putting all my entry data in a for loop:

{% for entry in craft.entries.section('standard').slug(craft.request.firstSegment) %}
    {{entry.title}}
    ...other template code in here
    {% if craft.request.lastSegment == 'thanks' %}
        ...thank you message
    {% endif %}
{% endfor %}

This lets me now get the correct entry data loaded for this entry (or others in this section) and my thank you message still appears however it just feels like an awkward way to do it and I suspect in other scenarios it could become really messy.

Is there a better way to approach this in Craft?

Or can you actually have Craft ignore certain url segments?


texts: Is it possible to set any attributes (such as a class) of the `a` tag when using `getLink()`?

texts:
This code:

{{ foo.getLink() }}

Outputs this:

NAME_OF_PAGE

What I really want is something like:

NAME_OF_PAGE

Is it possible to set "class" and/or other html attributes when using Craft CMS Entry Property getLink()?


texts: Issues with returnJson not returning html?

texts:
Im running in to issues with returnJson not returning html or just returning and empty object:

$userHtml = craft()->logic->renderSiteMacro('_macros/elements', 'listing', $args);

$this->returnJson(array(
     'success' => true,
     'existing' => $userHtml
));

The return JSON is always:

{"success":true,"existing":{}}

I have double checked the html output exists and the issue persists:

Whether returning a simple string or large chunk of html
And with and without single quotes
When renderSiteMacro functions runs the code through the raw filter and not


texts: How to use Twig to pull drop down menu items for a front end form

texts:
I have this code that will pull the values of a checkbox or radio from the fields in Craft CMS, do be used and selected by a user on a front end form.

    {% for checkboxOption in currentUser.fieldHandle.options %}
        {% set checked = false %}

        {% if checkboxOption.selected %}
            {% set checked = true %}
        {% endif %}

            <input type="radio" value="{{ checkboxOption.value }}" name="fields[fieldHandle]" {% if checked %} checked="checked" {% endif %}>{{ checkboxOption.label }}

    {% endfor %}

How do I do the same for a dropdown list?


texts: How do image focal points work in Craft 3? I see the dot in the CP, but I'm unable to set the focus.


texts: How to update front end Craft new row - stuck on JavaScript

texts:
I'm building out a front end entry form with a Natrix and everything is coming along fine. However when users create a new row each new row needs to be unique in order to be saved. This is where I'm stuck.

Simplified HTML:

    block id: new_0

    <input type="text" name="fields[staffProfiles][new_0][fields][employeeName]" value="" placeholder="Full Name">

    <input type="text" name="fields[staffProfiles][new_0][fields][jobTitle]" value=""  placeholder="Job Title">

JS:

var blocknum = 0;

// add a new person
$('#addPerson').click(function(e){
    e.preventDefault();
    console.log('clicked addPerson');

    //iterate blocknumber
    blocknum = blocknum+= 1;
    console.log('blocknum is ' + blocknum);

    var newPerson = "

";
    $('.newBlock').append(newPerson);
    $('.newBlock .newperson:last-child').load('/store/newperson');

    // replace all instances of new_0 with new1, new2 etc.. as rows added
    // this line doesn't do anything, why?
    $('.newBlock .newperson:last-child').replace('new_0','new' + blocknum);

})

console.log('blocknum is ' + blocknum); is showing that the blocknum is increasing with each row. the Replace in the last line of javascript is just not doing anything.

The new person row gets added via ajax correctly but each time it's added [new_0] needs to be unique, but nothing I'm trying is working.


texts: Craft Commerce Digital Products delete multiples

texts:
Craft Commerce Digital Products:

Why aren't there checkboxes next to the product names so I can delete multiple items at once?

It exists in regular Craft Commerce Products.


texts:
I'm trying to validate my form before the charge.js is triggered.

I've decided to drop submit button in favour of a standard button and then use valid() method to process submit, so this is what I have now:

<form id="charge-form">
<!-- some fields here !-->
<input id="submit" type="button" value="Subscribe">
</form>

<script>
  $("#charge-form").validate();
  $("#charge-form").charge();
  $("#submit").click(function() {
    if ($("#charge-form").valid()) {
        $("#charge-form").submit();
    }
  })
</script>

Validation works, and when testing the conditional statement with console.log it also works properly, but when actually used it gives $form.get(...).submit is not a function in the console in charge.js

Did anyone make jQuery Validate work with Charge?


texts: PHP error when rendering a template from __toString()

texts:
I have a model with the following functions:

public function render()
{
    $render = craft()->templates->render('myplugin/templates/mymodeltemplate');
    return $render;
}

public function __toString()
{
    return $this->render();
}

Calling __toString() gives me the following error:

Fatal error: Method Craft\MyModel::__toString() must not throw an exception in /projectpath/craft/app/vendor/twig/twig/lib/Twig/Extension/Core.php on line 0

I've found this explanation:

http://php.net/manual/en/migration52.incompatible.php

But I'm not sure how to work around it and accomplish what I'm trying to do...


texts:
I have searched the forum and cannot find the answer to my question.
I know how to populate a dropdown with the categories that are already in the system, but what happens if the category that needs to be assigned to the entry doesn't exist in the list of categories.

So, my question is this. Is there a way to display the dropdown of categories, as well as having the ability to add more categories via a form on the front-end?

Thanks


texts: Is it possible to create a Custom Widget that behaves like the 'Deprecation Errors' warning on the Dashboard? When active, the widget would appear on all users', or particular user groups, dashboards at the top and display new information, warnings and anything else that may be of use.


texts: HTML Email Template setting not working for reset password email

texts:
I'm on the latest release of craft 3.x. I have the HTML Email Template setting set to a twig file in my templates folder. When sending a test email the template is used to send the test email, however when I call Craft::$app->users->sendPasswordResetEmail($user); from my plugin code, the template file is not used and the default system email template is used.

Is there something I'm missing here?


texts: Title Format - Object Label instead of Value

texts:
I am trying to get the label from an object instead of its value to use as the automatic title for my entries.
For example: I have an entry that contains a dropdown with the handle exampleOne with values Item One, Item Two, etc. In the title format field I enter {{object.exampleOne}} and it outputs itemOne. It appears craft is outputting the "value" of that dropdown but I instead want it to output the "Label". Is this possible? I looked through the docs and did some googling but to no avail. I also tried {{ object.exampleOne|label }} but it failed to rename the entries.
Thanks in advance for any assistance!


texts:
I want to write an entire loop into a field like this:

Obviously this is not working. What would be the correct syntax when twig is written inside a field?

Also is there a name for the twig tags inside a field? I have a hard time searching the interwebz for this.


texts: Importing Commerce Variants from google sheet

texts:
How I should set up google sheet data to import Commerce Variants from it?
It is necessary that the Variants are imported in the same way as this example.

Thanks.


texts: How do you auto zoom/center Smart Map with multiple markers?

texts:
How can I auto center and zoom my Smart Map with multiple markers?
Something like this:
var bounds = new smartMap.map.LatLngBounds();
smartMap.map.fitBounds(bounds);


texts: Iterate through Super Table field in plugin

texts:
I have a Super Table field with two columns, one is a category field, the other an assets field (limit 1 on both). How can I iterate through it to get the category and asset selected for each row in the table?

$superTable = $entry->colors;
foreach ($superTable as $row) {
    // Category field handle is `color`
    // Asset field handle is `image`

    // I've tried various things here, but I don't understand how to get the fields
    // I'm looking for the category ID and asset ID in every row of the table
}


texts:
I am trying to create an endpoint that outputs the latest updated entry in each section (Themes, Videos and Screensavers) like this:

url/updated.json

{
 themes: '2016-08-22',
 videos: '2016-08-18',
 screensavers: '2016-07-20'
}

I can't think of how to do this but here is my code so far, no dice so far tho:

'updates.json' => [
        'elementType' => 'Entry',
        'paginate' => false,
        'criteria' => ['section' => '', 'limit' => null,],
        'transformer' => function(EntryModel $entry) {
            $screensaversLastUpdated = $entry->dateUpdated;
            $videosLastUpdated = $entry->dateUpdated;
            $themesLastUpdated = $entry->dateUpdated;
            return [
                'themes' => $screensaversLastUpdated ,
                'screensavers' => $screensaversLastUpdated ,
                'videos' => $videosLastUpdated
            ];
        }
    ]

Any help would be much appreciated!

Thanks!


texts: Migrating Craft site to another server --- throws 404 for all pages but homepage

texts: I've been asked to migrate a Craft site from one server to another.  The new server setup is the same as the server I'm migrating from.  I moved all the files in the webroot directory over to the new server and imported the database.  The homepage works just fine, just all links go to an Apache 404 and so does the admin panel.  Ideas?  Nothing is different from the other server.


texts: Select all entries with asset field attribute criteria

texts:
OK so I got entries articles with an asset field documents.
This asset field has an attribute called docType which is a dropdown with 5 values (A, B, C, D, E).

I d like to select all articles entries that have documents with docType=A criteria.

How can I dot that?
Should I make a relatedTo selection?
I tried multiple things but nothing works.


texts: From a template, how can you order entries by one field, and if that field is empty a different field?

texts:
Is it possible to put conditions on the ordering of a loop of entries?

I have two fields: title and alphaTitle. I want to order alphabetically, by alphaTitle if it has a value, otherwise by title. Title will always have a value but I only want to order by title if there is no alphaTitle. I've been having some trouble figuring out if this is possible or how to do it - any chance someone can point me in the right direction?


texts: Amending a lightswitch field value inside a matrix, from a plugin?

texts:
I have a plugin which is used to send a notification email when certain events happen.

I need to watch the contents of a Matrix field attached to a User, and when a Lightswitch field inside the Matrix is 'on', flip another Lightswitch field on the same matrix block. Here's the simplified code I have so far:

craft()->on('users.onBeforeSaveUser', function(Event $event) {
    foreach ($user->getContent()->myMatrixField as $matrixBlock) {
        if($matrixBlock->firstLightswitch){
            $matrixBlock->secondLightswitch = '1';
        }
    }
}

I am getting the following error though:

  Property “Craft\MatrixBlockModel.secondLightswitch” is not defined

It's very definitely defined. I presume I'm trying to set the field incorrectly, but can't find out how.


texts:
I'm having a weird issue trying to figure out which database my staging site (staging.domain.com) is connecting too. On my staging site, craft is up-to-date, but does not show the latest changes I made (added a new section and updated craft), which makes me think it's using the live database. However, if it's using the live DB, it should show craft as needing updates? All the other changes on the staging site are working fine (ie. tmpl & css updates).

So to troubleshoot, I added devMode to my staging site array to see if my keys were working properly. This added the devMode strip to the top of the CP. Next, I double checked both database on the server to make sure they were different. The staging DB has the new section I just added. Lastly, I cleared the cache to see if that made a difference.

Am I totally missing something here?

general.php:

return array(
    '*' => array(
        'cpTrigger' => 'cp-admin',
        'omitScriptNameInUrls' => true,
        'environmentVariables' => array(
            'basePath' => $base_path,
            'baseUrl'  => $base_url
        )
    ),
    '.dev' => array(
        'devMode' => true,
    ),
    'stage.' => array(
        'devMode' => true,
    ),
    '.com' => array(
        'cooldownDuration' => 0,
    )
);

db.php:

return array(

    '*' => array(
        'tablePrefix' => 'craft',
    ),

    '.dev' => array(
        'server' => 'localhost',
        'user' => 'root',
        'password' => 'root',
        'database' => '***pa_craft',
    ),

    'stage.' => array(
        'server' => 'localhost',
        'user' => '***pa',
        'password' => '***',
        'database' => '***pa_craft',
    ),

    '.com' => array(
        'server' => 'localhost',
        'user' => '***pa',
        'password' => '***',
        'database' => '***pa_craft_live',
    ),

);

Update

I just switched my local setup (dev) to point to the remote staging DB which connects and shows the updates. I also added a new entry to check to see if was writing to the correct DB.


texts:
I've got a site set up with the Patrol plugin, and it forces the HTTPS and www on most pages fine. I've got the sslRoutingBaseUrl, sslRoutingEnabled, and sslRoutingRestrictedUrls set in my general.php config file (just like in the github example). It works 99% of the time.

But it doesn't work right for 404s.

Normally, when I go to a page, it automatically changes from http://mysite.com/mypage to https://www.mysite.com/mypage

But when I got to a broken page, http://mysite.com/brokenpageurl, it doesn't redirect.

My 404.twig template lives in the root of the templates directory. So if I go to mysite.com/404, it automatically redirects to https://www.mysite.com/404 - because it's a real page.

But when another page exits to a 404, it doesn't redirect.

I'm wondering if the 'exit to 404' rendering bit happens before patrol gets a chance to do its redirect.

On Craft 3.3.19 and Patrol 3.1.3. But I can reproduce the issue on a couple of different sites.

Edit: I made a ticket on github too.


texts: Is using craft.config to access siteUrl possible?

texts: In the past I would comment out analytics code on my dev and staging sites then uncomment the code when it went live. I ran across this page in the Craft docs the other day and started thinking, can I use this to access the siteUrl from the environment variable array and specify a value in my conditional (i.e. {% craft.config.environmentVariable('siteUrl', 'http://www.example.com') %}? This way I can add the analytics code and only worry about it loading on the live site.


texts: Solspace Calendar For Craft CMS - Importing ICS Files

texts:
I'm using Solspace Calendar for Craft CMS for an upcoming project.

The client has asked if they can initially import all of their events from an .ics file from Outlook.

I can't see anything in the docs. It doesn't appear to be a feature, however has anyone else come up with a solution to this? I'm sure it's not the first time it's been asked.

Thanks :)


texts: Is there a twig filter to display decimal values as fractions?


texts: Craft Search looking for keywords contained in the query

texts:
Edited for clarity:

I do have a search form in the frontend where customers can enter keywords.
The way it searches now only returns exact matches. I'd like to tell Craft to look for works containing the keyword the look for.

I know I have to set the 'q' param to do this but I have no idea what I should do.

Search for results page:

{% set query = craft.request.getParam('q') %}
{% set entries = craft.entries.search(query).section('oeuvres').order('score') %}


texts: Content Modeling for Site Architecture Recommendations

texts:
I am doing some content modeling for a site with over 100 pages with a pretty deep tree. The site has a lot of what I refer to as "General Pages" as well as a collection of channel type content in the form of news, blogs, and such. In addition there are many unique pages such as contact and application form pages.

My main question is: How to section the over 100 general pages for best balance for client friendliness?

Do I create one "General Page" channel section and then use or build
some sort of nav add-on to create the appropriate heirarchy (This is
how we'd roll if we were building this in EECMS for example)?
Do I use multiple structures, one for each primary nav item? And then figure out how to mix in the other unique singles and entries?
Tons of singles? (my least favorite option)
Something else?

I know the answer to these questions given a CMS as flexible as Craft is simply "Yes"; however, would love to get some thoughts on how people have dealt with a well branched site map and lots of "General Pages".

Thanks!


texts: Is it possible to get another Craft's webApp from within a Craft plugin controller

texts: I have two instances of Craft on the same server. From within a plugin controller in Craft #1, I want to be able to get entries from Craft #2. Can this be done and if so, how?


texts: Type number form in textField for plugin

texts:
I haven't found any fields that deal with numbers for a plugin. I've changed a forms.textField into a type:number which has seemed to work fine for the most part. But I can't find a way to keep someone from going under 0 or over 100. I've looked in vendor\craftcms\cms\src\templates\_includes and have come up empty.

I'm assuming I'll need to make a custom field type for this but if there is something I'd rather not reinvent the wheel.

  {{ forms.textField({
      label: 'Blanket Discount Percent',
      instructions: 'Set this if you want to offer a blanket discount to all businesses. Do not put in letters or decimals. (10 = 10%)',
      id: 'blanketDiscount',
      name: 'settings[blanketDiscount]',
      value: settings.blanketDiscount,
      type: 'number',
   })}}

I do have a rule for validation setup, I would just prefer to keep people in range at the front as well.

['blanketDiscount', 'integer', 'min' => 0, 'max' => 100],


texts: This seems like an easy question to answer but I can't seem to figure it out... I'm sure we could do it in Craft 2. Anyway, I'm trying to figure out how to only display a certain entry type in an entry field. For example, I have an entry field labeled "Authors" and in my articles section I want to select and entry from that field to relate to an article, however if I add an entry field to the article entry type, all my entries can be selected... how do I limit it to only the entry type "authors"?


texts:
I'm new to Craft and need to add a link to the right side of the footer on this site http://britainthinks.com/

Can't see anything in the dashboard that holds the existing content or any obvious templates

There is a Global called footer but this doesn't have the links, just some contact info.

Would welcome any help!

Thanks


texts: Cannot access plugin controllers when plugin does not have a "cp section"

texts:
Due to a permission check in \Craft\WebApp::processRequest(), I cannot access my plugin controller through the control panel templates. Also I cannot grant the user access because the plugin does not have a "cp section".

I have a fieldtype that loads data through an ajax-request, but this does not work if the user looking at the pages does not have access to the plugin.

Simple solution would be to always show all plugins (with controllers) in the permission overview, so that I can grant access if needed.


texts: How to differentiate between positive and negative numbers in search

texts:
I discovered today that searching a custom field for a number will return results containing either the positive or negative versions of the number, even if I do an exact search. For example: fieldName::"-2" will give me entries where that field contains either "2" or "-2". Same result if I search for fieldName::"2". The field in question is a "number" field.

Is there any workaround for this?


texts: Craft 2.X Local setup error – Craft not connecting to MySQL (via Sequel Pro)

texts:
Novice dev here, really struggling to get my local setup functioning. After a couple of days of wrestling with Apache config settings, I finally have Craft connecting via a VHOST setup. The problem –

Craft can’t connect to the database with the credentials in craft/config/db.php.

This should all be tried and tested as it came from my lead dev on this project and had been working, so it is likely something silly I have done in the set up. I just can't figure out what.

Thus far, I have downloaded the repo, installed all dependencies and have successfully got the local server running with npm run start. I've configured a Virtual Host and that's all running fine. I downloaded a copy of the production db from the live site and uploaded it to my local db (connect via Sequel Pro). Both db's have the same name.

My db.php file is:

return array(

// The database server name or IP address. Usually this is 'localhost' or '127.0.0.1'.
'server' => $_SERVER['DATABASE_HOST'],

// The name of the database to select.
'database' => $_SERVER['DB_NAME'],

// The database username to connect with.
'user' => 'root',

// The database password to connect with.
'password' => $_SERVER['DB_PASSWORD'],

// The prefix to use when naming tables. This can be no more than 5 characters.
'tablePrefix' => 'craft',

);

My VHOST is:

<VirtualHost *:80>

SetEnv DATABASE_HOST localhost
  SetEnv DB_NAME dbName
  SetEnv DB_PASSWORD dbPassword
  SetEnv DEV_MODE true
  SetEnv SITE_URL sitename.local
  SetEnv DB_PORT 3306
  DocumentRoot "/Users/username/Sites/sitename/public"
  ServerName www.sitename.local
  ServerAlias www.sitename.local
  ErrorLog "/Users/username/Sites/sitename/error_log"
  CustomLog "/Users/username/Sites/sitename/access_log" common
  <Directory "/Users/username/Sites/sitename/public">
    Options Indexes FollowSymLinks Includes ExecCGI
    AllowOverride All
    Require all granted
  </Directory>
</VirtualHost>

I'm stumped. The only think I have been able to find on similar threads seems to point to db version issues (which might be the case but I don't know how to check).

Does anyone have any ideas?


texts: How to show details on linked entry in CP (another field inside related entry)

texts:
I'm using a row layout SuperTable to create a recipe (ingredients are entries). Is there a way to show another field inside the related entry (not just the title) together with the entry title? I need to specify the measure (like tbsp) otherwise it's hard to know the quantity for what you're editing.

I need to show Spinach (100g) in the ingredient row. The 100g is a field called ingredientMeasure inside the ingredient entry.

I was thinking about using a hook (modifyEntryTableAttributes) - but not sure how to do it with ST. This is my hook example (from Ben's plugin tutorial):

// ADD A HOOK - modify the contents of table cell on entry index page
public function getEntryTableAttributeHtml(EntryModel $entry, $attribute) {
    // check if setting is enabled and we're editing our column
    if ($this->getSettings()->showCountOnEntryIndex AND $attribute == 'count')
    {
        return 'C<b>' . craft()->entryCount->getCount($entry->id)->count . '</b>';
    }
}


texts: Access add and remove events with the Craft Element Selector?

texts:
Is there any way to access an event, and trigger some function, when an element is added / removed with the Craft Element Selector logic available in Garnish?

I am working on a custom field type and to keep everything tidy I only want to show a set of options when an asset is selected.


texts: Navigation Slug Issue (Structure Section)

texts:
I am trying to setup a navigation on a site. I am using a Structure Section called "pages", however, when I changed the "Top-Level Entries" to just {slug} and the nested levels to {parent.uri}/{slug}, I am getting URLs like about/profile-1 and about/biography-1.

I am guessing the reason why I am getting -1 is due to the fact that the entry already exists in my About channel.

Any thoughts on how to resolve this?


texts: Integrity constraint violation - Not null violation

texts:
Looking for some help here - I'm working on a site that is using a PostgreSQL db and am running into an issue. When saving a large Matrix field with multiple block types I was receiving the following error:

Integrity constraint violation
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "id" violates not-null constraint

At first, I thought there was something corrupted with the Matrix so I nuked it and rebuilt it - everything seemed to be working fine until I created a new channel section - when I tried to create an entry there, I got the following error:

Integrity constraint violation
SQLSTATE[23502]: Not null violation: 7 ERROR: null value in column "id" violates not-null constraint
The SQL being executed was: INSERT INTO "drafts" ("sourceId", "creatorId", "name", "notes") VALUES (NULL, 5772, 'First draft', NULL)).

Similar to the above, just a new table this time.

Everything I am reading points to an auto-increment issue, though in both cases there does seem to be the appropriate sequence in the db. I've barely used PostgreSQL and never with Craft, though I'm not 100% certain it has to do with the db.

Any thoughts on what could be causing this?


texts: Graphql total results / pageinfo when searching with pagination

texts:
I'm trying to build something to search my data that is stored in Craft with graphql.
To make pagination work I want to know how many results there are in total.

I'm doing a query like this:

query($search: String, $relatedTo: [Int]) {
  entries(section: "address", search: $search, orderBy: "companyName", relatedTo: $relatedTo, limit: 10, offset: 0) {
    searchScore,
    ... on address_address_Entry {
      sid,
      address_title,
    }
  }
}

Truncated for readability

I set a limit and an offset to see the first 10 results.
But i also need to know the total amount to determine how many pages there are

I've seen that there is a _count field of type Int on the entryInterface which says "Return a number of related elements for a field." But it seems to just give me the field's value itself, if I, for example, add it like this:

query($search: String, $relatedTo: [Int]) {
  entries(section: "address", search: $search, ... same) {
    _count:id,
  }
}

It just adds in the response {"_count": "8154"} (which is the id, so not very usefull)

I've looked at graphql docs:
https://graphql.org/learn/pagination/

But it doesn't work to just add 'pageInfo' or 'totalCount', neither does the cursor stuff.

Any help to get this working is welcome!