texts: Environment specific siteUrl settings not working

texts:
I followed the advice from this and this post, but I just can't get my environment specific siteUrls to work.
This is what my config file looks like:
return array(

    '*' => array(
      'errorTemplatePrefix' => "pages/",
    ),

    '.dev' => array(
      'environmentVariables' => array(
        'userSessionDuration' => false,
        'devMode' => true,
        'siteUrl ' => 'http://myurl.dev',
      )
    ),

    '.com' => array(
      'environmentVariables' => array(
        'userSessionDuration' => false,
        'devMode' => true,
        'siteUrl ' => 'http://myurl.com',
      )
    ),

    '.org' => array(
      'environmentVariables' => array(
        'siteUrl'  => 'http://myurl.org',
      )
    )
);

These do not take precedence over any URL specified in Settings > General in the CP as outlined in the docs. If I set the Site URL field to {siteUrl} in the CP, then my links are broken and look like this: {siteUrl}/link-to-a-page.
Am I missing something else to get the siteUrl settings to work?

Update
Fixed the additional space in 'siteUrl ', thanks to Lindsey.
My config settings now look like this:
'*' => array(
  'errorTemplatePrefix' => "pages/",
),
// local
'.dev' => array(
  'devMode' => true,
  'userSessionDuration' => false,
  'environmentVariables' => array(
    'siteUrl' => 'http://myurl.dev',
  )
),
// staging
'.com' => array(
  'devMode' => true,
  'userSessionDuration' => false,
  'environmentVariables' => array(
    'siteUrl' => 'http://myurl.com',
  )
),
// live
'.org' => array(
  'environmentVariables' => array(
    'siteUrl'  => 'http://myurl.org',
  )
)

With this and adding {siteUrl} in the CP, everything works as expected - hooray!
It does however not reflect what the Craft docs say, as they state that the config settings "will take precedence over the Site URL setting in Settings → General". I've contacted the Craft team to let them know about this.

Update #2
Got this response from Brandon:

“I'm guessing that when you added 'siteUrl' to your config, you put it inside the environmentVariables array? (which would explain why adding {siteUrl} to the CP setting made it work.)
When the documentation is referring to the siteUrl config setting, it's referring to an actual top-level config setting, not some custom "siteUrl" environmentVariable that happens to have the same name.”

So I've taken the setting out of environmentVariables, and hey presto, it all works as expected. You even get a helpful message in the CP:

Final working code:
'*' => array(
  'errorTemplatePrefix' => "pages/",
),
// local
'.dev' => array(
  'devMode' => true,
  'userSessionDuration' => false,
  'siteUrl' => 'http://myurl.dev',
),
// staging
'.com' => array(
  'devMode' => true,
  'userSessionDuration' => false,
  'siteUrl' => 'http://myurl.com',
),
// live
'.org' => array(
  'siteUrl'  => 'http://myurl.org',
)

Got there in the end - phew!


texts: Control Panel URLs being rewritten to use index.php?p=admin/

texts:
All of our control panel URLs are being rewritten to show index.php?p=admin/***

While this isn't a problem in itself we can't determine why it's happening when the frontend of the website itself is writing the URLs cleanly and correctly without the index.php?p=

We have in our .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>

There are no other Rewrites happening.

A possibly related issue we're seeing is that there are no entries, assets or categories listing in the control panel. Looking through the logs I can see the following

2015/09/22 16:55:23 [error] [exception.Craft\HttpException.400] exception 'Craft\HttpException' with message 'Param “elementType” doesn’t exist.' in /var/www/vhosts/mysite.org/httpdocs/craft/app/services/HttpRequestService.php:586
Stack trace:
#0 /var/www/vhosts/mysite.org/httpdocs/craft/app/controllers/BaseElementsController.php(50): Craft\HttpRequestService->getRequiredParam('elementType')
#1 /var/www/vhosts/mysite.org/httpdocs/craft/app/controllers/ElementIndexController.php(68): Craft\BaseElementsController->getElementType()
#2 /var/www/vhosts/mysite.org/httpdocs/craft/app/framework/web/CWebApplication.php(281): Craft\ElementIndexController->init()
#3 /var/www/vhosts/mysite.org/httpdocs/craft/app/etc/web/WebApp.php(784): CWebApplication->runController('elementIndex/ge...')
#4 /var/www/vhosts/mysite.org/httpdocs/craft/app/etc/web/WebApp.php(276): Craft\WebApp->_processActionRequest()
#5 /var/www/vhosts/mysite.org/httpdocs/craft/app/framework/base/CApplication.php(184): Craft\WebApp->processRequest()
#6 /var/www/vhosts/mysite.org/httpdocs/craft/app/index.php(62): CApplication->run()
#7 /var/www/vhosts/mysite.org/httpdocs/index.php(40): require_once('/var/www/vhosts...')
#8 {main}
REQUEST_URI=/index.php?p=admin/actions/elementIndex/getElements
HTTP_REFERER=http://mysite.org/index.php?p=admin/entries/pages
---
2015/09/22 16:55:23 [error] [application] Param “elementType” doesn’t exist.

******************************************************************************************************

We do have PATH_INFO installed and enabled on the server.

Craft Pro 2.4.2692

Any help would be much appreciated.
Many thanks


texts:
What are all the available options that products can be ordered by?

craft.commerce.products({ order: '???' })

I have found this reference https://craftcommerce.com/docs/products-fields#templating but it does not list the available options.

Bonus points if it includes the key that sorts by sales (aka popularity).


texts: Output values from all entries in a specific section EXCEPT those with a specific category id

texts:
Currently, this is NEARLY doing what I want except instead of the output being entries that do NOT have the id, it's output is ONLY the entries with the id.  I'm not sure why, since I've included the 'not' keyword within the parameter.

{% set entries =
craft.entries.section('driverPositions').limit(null).relatedTo('not' , 7192) %}

{% for entry in entries.order('state, city').limit(null) %}

<option value="{{entry.url}}">{{ entry.state }} - {{ entry.city }}</option>

{% endfor %}

thanks in advance!


texts: Image transform with either width or height

texts:
I'm looking to create an image transformation where either the height is (e.g.) 180px, or the width is 180px depending on whether the image is portrait or landscape.

So, if the image is landscape the dimensions should be (WxH): 180 x AUTO
If the Image is portrait, the dimensions should be (WxH): AUTO x 180

Maybe I'm missing something obvious. Or maybe this could be a CSS issue?

Thanks!


texts:
Good Evening.
Im looking for a way to regularly check a full section of entries to see if a date has been passed.  If it has I want to place a checkbox marker within that entry.  Has anyone come across a plugin or something that an achieve this?


texts: Is it possible to change the default text for a Charge plugin checkout button

texts:
I'm trying to set up a simple subscription based site using the Awesome Charge plugin and am wondering if I can change the button text using Stripe Checkout.

There doesn't seem to be any documentation around Checkout Options on the Squarebit site that indicates I can pass a value, through the options list, that changes the text 'Pay with card' to something else.

I understand I could customise the whole process using the Strip.js method but was hoping to just use the out of the box version.

Thanks.


texts: Twig replace filter - use part of regex match

texts: Using replace filter we can match pattern using regular expressions, but can we use part of the matched string in the second argument of filter? For example, I want to match all numbers and replace each matched number with a matched number enclosed in parentheses.


texts:
The image tag shown below prevents my {% cache %} tag from caching the loop it's in. If I remove the image tag or change the data-resource attribut to a normal src, it works fine. The class="lazy" and data-original are from the jQuery plugin Lazy Load 1.9.3. Regardless, the page still renders fine. Does anyone have any ideas what's wrong?

Thank you for your help for a first-time poster.

<img class="lazy" data-original="{{ image.getUrl(transform) }}" alt="{{ project.title }}" />

EDIT: Now showing just the code that seems to be the problem rather than the whole loop.


texts: Run a localized site using one Craft install on 2 servers

texts:
Is it possible to share one craft install across 2 servers?  Say I have a US site (en only) hosted in the US and a Canadian site (en and fr) hosted in Canada.

E.g.

usa-site.com (english)
ca-site.ca (english)
ca-site.ca/fr (french)


texts: How to model a multiple relation situation?

texts:
I have a site that has these different types of content:

Candidates
Questions
Answers

So there's a list of questions, that have answers that are related to a candidate. I imagine the models look like:

Question

Question Info

Answers

relatedCandidate
relatedQuestion

Candidate

Candidate Info

The main question is is this the best setup for this particular situation? Or should  I have a matrix in Questions with all the answers and then a related field for the candidate and the answer?

While this works if the question section works on it's own, if I ever need to display candidates and then their corresponding answers, I don't know if I can run through the Questions' matrix field and find only that candidate's answer.


texts: I have over 9000 photos that I need to add to my site however using the upload feature in assets is taking an extremely long time. I have tried to just simply add the images to the correct folder in public but they are not showing up on craft. Is there something additional I must do for them to show up or is using the upload feature the only way for photos to show in assets?


texts:
We're using the Digital Products plugin from Pixel and Tonic to sell 6 different types of products. I've set up a macro with matching icons for each of the product types (image, video, etc). On our user account page, I want to show recent purchases with the icon of the product type underneath it.

Usually, I would write {{ icons.image }} or {{ icons.video}} to call the icon macro. But the variable needs to be dynamic if I want to display it under a dynamic list of products.

In order to make it dynamic, of course, I need to be able to inject different macro variables image, video, etc when they're called.

I found the {{ attribute() }} function, which looks like the preferred way of accessing dynamic attributes.

So I tried this:

{{ attribute(icons, license.product.type) }}

And get this error:

Illegal offset type in isset or empty

So I researched a bit and found that I could try {{ attribute(icons, license.product.type[0]) }}

But that led to this error: Property "Craft\DigitalProducts_ProductTypeModel.0" is not defined.

So, basically now I'm stuck. My lack of PHP knowledge may be holding me back here.


texts:
Hopefully simple variable / concatenation question: What is the best way to retrieve the url of a specific asset the name of which should be concatenated from an asset field variable and a text string?

I need to end accessing the url of an asset like so – {{asset.portraitThumbSmall.url}}, but I am in a loop where “portrait” could also be “landscape” ...or “square”, and is derived from an asset field variable on an asset called “thumbnailCrop”. With me so far?

So something like...

    {{asset.thumbnailCrop ~ "ThumbSmall" ~ .url}}

…only, unlike this, it should actually work.

I did read this -> How can I incorporate a variable into a string? …but I’m trying to incorporate a string into a variable. Not sure it applies.

Someone in the Slack channel suggested...

    {% set thumbnail = attribute(asset, thumbnailCrop ~ "ThumbSmall") %}
    {{ thumbnail.url }}

But it doesn't work, and I was also wondering if it wasn't possible to make something more compact.

Any help would be appreciated!


texts: How get entries between mutiple dates, ordered by date?

texts:
I'll import (event) entries with feedme in craftcms 2 from an API who I'll can't change. The api gives the startdate off the events in a dateTime object. The allDay events have a date without time. Because the api also names those date elements different (start/dateTime, start/date) I'll have to import the data separate in to two fields for start and for end.
The question is how I'll get all those events (entries) together ordered by date? From the current date to the currentdate plus 6 months. The entries with the allDay date have an empty field for startDate and endDate and visa versa.
This is what I'll have but that didn't work.
  'api/calendar' => function() {

            // Fetch global set 'agenda'

            return [
                'elementType' => 'Entry',
                'criteria' => [
                    'limit' => 0,
                    'startDate' => ['and', '>=' . date('U') . ""],
                    'endDate' => ['and', '<=' . date('U', strtotime("+6 months")) . ""],

                    'startDateAllDay' => ['and', '>=' . date('U') . ""],
                    'endDateAllDay' => ['and', '<=' . date('U', strtotime("+6 months")) . ""],
                    'order'     => 'startDatum asc'
                ],


texts: Craft 2: New locale introduction not affecting old entries

texts:
I just introduced a new (2nd) locale to my site. It now seems I can easily set up translated versions for "single" and "channel" pages that I set up new.

The old entries, which existed prior to introducing the new locale, are not translatable however:

The little (green) dot after the language switch in these entries’ individual editor is only a grey circle instead of a green one like with the newly setup pages. If I click the new language I get a native "Page not found" error.

I have set the specific legacy pages to be fully translatable though in the Sections settings, set them to be available in both locales but I get the feeling that Craft is not able to handle "legacy" singles & entries that were introduced during a one-locale setup of the page, is that correct?

Is there any way of working around the hassle of having to delete all the pre-multi-locale pages and re-setting them up to have them available in both locales (which would solve my problem but is a pain with so many pages/entries)?


texts: How do you set a different icon per entry in SmartMap?

texts:
And how do you set a different icon and infoWindow when a lightswitch or entry type?

{% set locations = craft.entries.section('section').find() %}

{% set options = {
    'zoom': 5,
    'height': 750,
    'markerInfo': '_includes/infoBubble',
    markerOptions: {
        icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png'
    },
} %}

{{ craft.smartMap.map(locations, options) }}


texts: Adding cache headers to Nginx configuation file breaks the /admin area

texts:
When I add this to my Nginx Confirguration file:

location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
    expires 7d;
    add_header Pragma "public";
    add_header Cache-Control "public, must-revalidate, proxy-revalidate";
}

In the admin area I get all 404 responses on those assets (js, css, png, etc).

Without that in my configuration, for example, settings.css is OK:

Request URL:http://{site}admin/resources/css/settings.css?d=1411426522
Request Method:GET
Status Code:200 OK
Cache-Control:max-age=31536000
Connection:keep-alive
Expires:Sun, 11 Oct 2015 02:25:24 GMT
Last-Modified:Mon, 22 Sep 2014 22:55:22 GMT
Pragma:cache

And then with the code, the settings.css is 404 Not Found

Request URL:http://{site}/admin/resources/css/settings.css?d=1411426522
Request Method:GET
Status Code:404 Not Found
Cache-Control:no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection:keep-alive
Expires:Sat, 04 Oct 2014 02:31:56 GMT
Pragma:no-cache


texts: Can I have multiple comparisons within a single criteria parameter?

texts:
The Craft site shows an example using a single comparison

Building upon this example from that page:

craft.entries.width('>= 100')

Can I do something similar but where 'width' is ALSO less than or equal to 200?

Conceptually:

craft.entries.width('>= 100 && <= 200')


texts:
I've got a staging environment where in need to install Craft 3 in the web root rather than above the root as in normally recommended. Like so:

my-project.test/web
    config/
    storage/
    templates/
    vendor/
    .env
    .env.example
    composer.json
    craft.bat
    index.php

I'm struggling to set the correct CRAFT_BASE_PATH for this configuration. I've tried using the full path to the web root with no success in addition to some variations on using DIR. Can anyone point me in the right direction?


texts: Changing an entries data in onBeforeSaveEntry event depending on data set in saved entry

texts:
Ok I'm buliding a plugin which changes the category of a news article if another article is set to the same category so that only one article is set as the featured category.

So far I have the onSaveBeforeEntry event working ok I'm just stuck on the updating the existing featured article. This is the flow so far followed by the code I'm having an issue with.

First check the article being saved to see if the category is set.
If it is check it has not changed.
If it has changed and it has changed to 'Featured' use getCriteria to find the entry that is currently set to 'Featured'
(the sticking point) set the existing featured entry category to 'Latest' and save it.
Finish off saving the entry.

Point 4 is not changing the existing featured article data.

The code I have is:

// Get the current featured news entry
$entry_criteria = craft()->elements->getCriteria(ElementType::Entry);
$entry_criteria->section = 'news';
$entry_criteria->search = 'category:Featured';
$featuredEntry = $entry_criteria->first();

// update exiting featured article and mark as latest
$featuredEntry->setContentFromPost(array('category' => 'Latest'));
$success = craft()->entries->saveEntry($featuredEntry);

Getting the existing entry works, changing the category and re-saving does not.

What am I missing?

Any help appreciated.

Ta


texts: Live Preview: Hide tabs from live preview

texts:
I've noticed that Live Preview mode includes fields from all tabs. Is it possible to specify tabs to be left out of the Live Preview display?

For example, if you have an 'SEO' tab which consists of meta data it's not relevant to include this in the Live Preview mode whilst constructing the page. With lots of tabs this just becomes confusing for the user when only a few of them are relevant.

Is there a way to exclude set tabs or fields?


texts:
I set up my first Craft site on my shared hosting and I can't get it to work for the life of me. Whatever I do, I run into a 404 error. .htaccess is there and named correctly, craft folder is one level up as it should be.
What I noticed is that it briefly works after setting the correct permissions on the craft files and folders. A couple of clicks later the permissions seem to reset again back to 755.
I haven't had this problem with my hosting before, so I am unsure if this is a craft problem? Or if the permissions even are the cause?

Edit: It doesn't appear to be a permission problem after all. Filezilla shows 755, although the permissions are set to 744. So now I'm at a total loss what the issue could be.... I can't even complete the installation because it stops working beforehand.
Tried several times more and got it installed. Just before it goes wrong again, I can see that it doesn't load the site properly, e.g. the login screen looks weird. Has anyone seen this before?


texts: Namespace issues when calling a plugin variable

texts:
Making a plugin.

I can't seem to get this {% set leads = craft.lead_infopack.getPacks() %} to fire from within a template.

Plugin name: lead

Here's a look inside my variables class.

Lead_InfopackVariable.php:

class Lead_InfopackVariable
{
    public function getPacks()
    {
        return craft()->lead_infopack->leads();
    }

The leads function calls a service that outputs all entries within my 'infopack' table.

If I write it like this it works {% set leads = craft.lead.getPacks() %}

LeadVariable.php:

class LeadVariable
{
    public function getPacks()
    {
        return craft()->lead_infopack->leads();
    }
}


texts: Craft 3 multisite - are entries accessible between sites?

texts: In multi-site is it possible to access entries between sites in the templates.  Like a feed?   ie. entry "a" on site "A" shows up in an index on site "B", and links back to the entry on site A, not a duplicate of the entry on site "B"?


texts: Displaying images from a matrix field from a related field

texts:
I have a section that is a single type. On this page there is a relation ship ('entries') field where the user can select a related photo gallery. Photo gallery is its own section with a matrix field on it that contains image files and image names. How when I am displaying the single page pull in the matrix field to display an image gallery. This is what I have tried but not with much luck.

I have tried

  {% if entry.associatedGallery is not null %}
    {% set theGallery = craft.entries.section('bb').relatedTo(entry.associatedGallery) %}

        {% for matrixBlock in theGallery.albumImages %}
          {% set asset = matrixBlock.imageFile.first() %}
            {% if asset %}

            {% endif %}
        {% endfor %}

    {% else %}

 Apparently its null

  {% endif %}

and

  {% if entry.associatedGallery is not null %}
    {% set theGallery = entry.associatedGallery %}

        {% for matrixBlock in theGallery.albumImages %}
          {% set asset = matrixBlock.imageFile.first() %}
            {% if asset %}

            {% endif %}
        {% endfor %}

    {% else %}

 Apparently its null

  {% endif %}

I think I am missing something fundamental about how relationships are defined.


texts: Is there a way to add a url(not to the file itself) to assets?

texts:
I am testing Craft to see if it would be a good fit for sites I build.  At this point, I do feel it is great and might fit most of the work I do.  The only thing I can't figure out is how I could add a url to images to build a logo gallery (ie: list of logos that link to the partners websites).

Is there a way to do this by default?  I can't find any information on it.


texts:
I've got a problem with some tasks. Craft tells me 'Deleting Stale Template Caches Failed' multiple times.

When I look in the Deprecated Warnings, it tells me two things:

Ordering tags by ‘name’ has been deprecated. Order by ‘title’ instead.
The Tag ‘name’ property has been deprecated. Use ‘title’ instead.

I don't know if this will fix my task errors, but it would be nice to solve this problem as well.

This warning is strange to me because I don't ordering my tags by name, I order them by title:

        <select class="multiselect multiselect-activitytype" multiple="multiple" data-search-filter="activityType" name="activityType">
            {% for tag in tags.order('title') %}
                {% set selected = (filters['activityType'] is defined and tag.title in filters['activityType']) ? 'selected': ''  %}
                <option value="{{ tag.title }}" {{ selected }}>{{ tag.title }}</option>
            {% endfor %}
        </select>

        <select class="multiselect multiselect-place" multiple="multiple" data-search-filter="activityLocation" name="activityLocation">
            {% for location in locations.order('title') %}
                {% set selected = (filters['activityLocation'] is defined and location.title in filters['activityLocation']) ? 'selected': '' %}
                <option value="{{ location.title }}" {{ selected }}>{{ location.title }}</option>
            {% endfor %}
        </select>

Any ideas?


texts: Using static translations for the primary site / site.php being ignored

texts:
I'm having trouble outputting static translations for the primary site, and only the primary site.
Translations structure:

translations

en-US

site.php

site.php
<?php

return [
  'UNIQUE_KEY_NAME' => `This is the string I'd like to appear.`,
];

Template
{{ 'UNIQUE_KEY_NAME' | t }}

Output
UNIQUE_KEY_NAME

Is there a way to make this pattern work?
The advantage of storing microcopy and site furniture in a single location is that it is much easier to update and share with copywriters.
If there is a second site, then it appears the site.php for that language will be respected, but when there is just one site, the primary site, its corresponding site.php translation file appears to be ignored. Is this intended?
Thanks


texts: Can you delete rows from a table field on the front end?

texts:
I have a table field which is attached to users, before I go ahead and create the logic for adding rows on the front end via ajax, I need to know if I am going to be able to easily add the facility to delete specific rows (ideally without saving all the data again each time)?

It may well be that depending on complexity that this is more suited to a matrix field or custom database tables via a plugin.

Either way can it be done?


texts: Craft Commerce: Imagick stops PDF order downloads

texts:
We needed to use Imagick so that our users could upload .bmp files to Craft - this works fine, however we noticed this directly stops users downloading PDFs orders from the website and a server errors gets applied.

Has anyone had any similar issues or advice on how to remedy?

Here is our original issue with .bmp files: Error uploading .bmp file format - gets rejected


texts: Is it possible to restrict access to an asset to logged in users?

texts:
i.e. is there a type of loginRequired functionality for assets?

Or even better - can I restrict access to a single group, or a require a certain permission?

In the "permissions" tab for users/groups I can only give access to uploading/deleting assets.


texts: Does Craft Commerce support One Time Password and Social Login features?

texts:
I have just started reviewing this plugin for e-commerce development. Fully featured though it is, I wanted to know if Craft Commerce can also support custom auth (login and registration) features such as One Time Password using a mobile cell number and Social Login through facebook and twitter?

Is it possible to build or use an existing plugin around these features?


texts: How to catch errors in a service and return to a controller?

texts:
How do you handle “catching” errors in a plugin service and return the error to
the plugins controller?

To be more specific... I am sending an Ajax request to a controller, that controller is performing a few checks (is the user logged in for example, if not logged in - return a json response).

See the below controller code:

public function actionMyController($elementId)
{
    if ($this->notLoggedIn()) {
        return;
    }
}

protected function notLoggedIn()
{
    if (!craft()->userSession) {
        return $this->returnJson('You must be logged in!');
    }
}

However, when those conditions are met the data is passed to the plugin service. In this case $elementId and $userId. Before creating the record, I'm performing additional checks on the data. When those checks fail, it should return additional JSON responses to the controller to display on the front-end.

See the below service code:

public function saveThing($elementId, $userId)
{
    $this->validateUser($userId);

    $this->validateElement($elementId);

    // populate the model

    // save the record and etc.

}

protected function validateUser($userId)
{
    if ($userId == craft()->getUser()->id) {
        return true;
    }

    // return json to the controller?
}

protected function validateElement($elementId)
{
    $element = craft()->elements->getElementById($elementId);

    if (is_null($element)) {
        // return json to the controller?
    }

}

So when the conditionals fail on the service, we need to return a response to the controller. Thoughts?


texts: Problems with tasks and max execution time

texts:
We've set up a task that's supposed to run through an external folder with images and resize them into 3 sizes each. This results in about 13000 tasks (one task per image). I thought each task was on a separate thread? But now the tasks are running for only 60 seconds (max_execution_time), then stopping. The task says running in the database, but it has just stopped, and the error log says max execution time was exceeded.

Is there a way around this? Would sub tasks change any behaviour?


texts: How do I adjust the page title for different Section and Entry pages?

texts:
Inside the default template that comes installed with Craft, the title of a page is set as:

<title>{% if title is defined %}{{ title }} - {% endif %}{{ siteName }}</title>

This works perfectly for the homepage and on pages where the {{ title }} variable is set. However for individual entries inside a channel, only the site name is used for the title.

I've tried to use the {{ entry.title }} variable instead, however in that case the title of the homepage is rendered as 'Homepage - {{ siteName }}'.

What's the best way to achieve the following page titles for the different sections?

Homepage: {{ siteName }}
Page: {{ title }} - {{ siteName }}
Entry: {{ entry.title }} - {{ siteName }}


texts:
I have a Craft site I am building that will be selling about 20 templates with private password protected content (each a product basically). I need to allow people to "buy" access to each page. These purchases are one time and not a recurring subscription. Customers would have lifetime access to each product page content.

I have use plugins like Charge on other sites with Stripe. This works great for single product sites, but we want to allow people to buy access to more than one product. Is there any way to just build a simple cart with Craft to work with Stripe? Is there any cart code samples for Stripe? My needs are simple but I have been having a hard time finding an option without using a 3rd party solution like Foxy or Snipcart. Any ideas or suggestions.


texts: If other languages are not defined show english

texts:
Is it possible to get the english content on the, for example, Spanish site if the Text for the specific language is not defined yet?

I do not mean a redirect! The English version should be displayed until the Spanish content has been inserted.

It would be great if someone has a Idea! Thanks!


texts: I cannot create any more admin user accounts

texts:
Can it be that I have hit a limit for amount of admin users? I have only 6 now and I would like to add 3 more. But when I try to set a new one up, it cannot send the verification email.

If I try to resend verification, then an internal server error pops up with the message "Could not instantiate mail function."

Does this mean my server is the issue?

Any support is greatly appreciated.

Thanks in advance!

josh


texts: Is there a quick way to check a server for Craft's minimum requirements?

texts: Is there a quick way (or some sort of wizard) that can be run on a server in order to establish whether it fulfils Craft's minimum requirements without uploading all of the Craft files? Finding out PHP and MySQL versions is easy enough but sometimes it's hard to get the finer details from clients.


texts: Can entries disabled by default in Guest Entries plugin and in section be enabled from the front-end?

texts:
So I have the switch for Enable entries by Default set to OFF for Guest Entries and a channel.

Given this value="1" for input field name="enabled" on Guest Entry submission I always get entry not updated in corresponding field with desired value.

{# Enable entry #}
<input type="hidden" name="enabled" value="1">

I think the channel switch for Enable entries by default should be on as guest entries doesn't have control over that?


texts: Creating entries from JSON feed - plugin?

texts:
I'm wondering if this plugin already exists and I'm just not finding it on Github or via Google. Essentially looking for a CraftCMS version of the ExpressionEngine plugin called "Data Grab" - http://brandnewbox.co.uk/products/details/datagrab

This plugin basically lets you define a feed and run automated imports to create entries. Hoping someone has done this in Craft or has some pointers to a preexisting plugin!

Thanks!


texts:
I understand there's a lot of work being done on the Update Asset Indexes feature. I believe I've run into another issue related to MySQL, whereas other issues have been related to PHP's memory_limit.

Would appreciate some feedback on trying to address this issue.

Thanks!

2016/12/31 22:45:19 [error] [system.db.CDbCommand] CDbCommand::execute() failed: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`homeaidoc`.`craft_assetfolders`, CONSTRAINT `craft_assetfolders_parentId_fk` FOREIGN KEY (`parentId`) REFERENCES `craft_assetfolders` (`id`) ON DELETE CASCADE). The SQL statement executed was: INSERT INTO `craft_assetfolders` (`uid`, `parentId`, `sourceId`, `name`, `path`, `dateUpdated`, `dateCreated`) VALUES (:yp0, :yp1, :yp2, :yp3, :yp4, :yp5, :yp6).
2016/12/31 22:45:19 [error] [exception.CDbException] CDbException: CDbCommand failed to execute the SQL statement: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`homeaidoc`.`craft_assetfolders`, CONSTRAINT `craft_assetfolders_parentId_fk` FOREIGN KEY (`parentId`) REFERENCES `craft_assetfolders` (`id`) ON DELETE CASCADE) in /var/www/craft/app/framework/db/CDbCommand.php:358
Stack trace:
#0 /var/www/craft/app/framework/db/ar/CActiveRecord.php(1081): CDbCommand->execute()
#1 /var/www/craft/app/framework/db/ar/CActiveRecord.php(810): CActiveRecord->insert(NULL)
#2 /var/www/craft/app/services/AssetsService.php(263): CActiveRecord->save()
#3 /var/www/craft/app/assetsourcetypes/BaseAssetSourceType.php(1022): Craft\AssetsService->storeFolder(Object(Craft\AssetFolderModel))
#4 /var/www/craft/app/assetsourcetypes/LocalAssetSourceType.php(121): Craft\BaseAssetSourceType->ensureFolderByFullPath('development/emm...')
#5 /var/www/craft/app/services/AssetIndexingService.php(40): Craft\LocalAssetSourceType->startIndex('cf59adea-fe2b-4...')
#6 /var/www/craft/app/tools/AssetIndexTool.php(94): Craft\AssetIndexingService->getIndexListForSource('cf59adea-fe2b-4...', '1')
#7 /var/www/craft/app/controllers/ToolsController.php(50): Craft\AssetIndexTool->performAction(Array)
#8 /var/www/craft/app/framework/web/actions/CInlineAction.php(49): Craft\ToolsController->actionPerformAction()
#9 /var/www/craft/app/framework/web/CController.php(308): CInlineAction->runWithParams(Array)
#10 /var/www/craft/app/framework/web/CController.php(286): CController->runAction(Object(CInlineAction))
#11 /var/www/craft/app/framework/web/CController.php(265): CController->runActionWithFilters(Object(CInlineAction), Array)
#12 /var/www/craft/app/framework/web/CWebApplication.php(282): CController->run('performAction')
#13 /var/www/craft/app/etc/web/WebApp.php(817): CWebApplication->runController('tools/performAc...')
#14 /var/www/craft/app/etc/web/WebApp.php(287): Craft\WebApp->_processActionRequest()
#15 /var/www/craft/app/framework/base/CApplication.php(185): Craft\WebApp->processRequest()
#16 /var/www/craft/app/index.php(62): CApplication->run()
#17 /var/www/public/index.php(19): require_once('/var/www/craft/...')
#18 {main}
REQUEST_URI=/index.php/admin/actions/tools/performAction
HTTP_REFERER=http://homeaidoc.craft.dev/admin/settings
---


texts: Output specific entry from entries field based on position

texts:
I have an entries field in a section, I am looking to output a certain selected entry from this field based on its position.

For example I want to out the 2nd or 3rd entry only from this entry field, what is the best way to do this without calling all the entries and looping through them all?


texts: Does anyone know how to query the database to find entry data based on a slug? The only table field I see that contains slug data is in craft_entryversions.data  in json format. Anyone ever tried querying for matches?


texts: Can I use a Block inside an Include file?

texts:
I have a _layout.html template which has both an include partial {% include '_partials/_header.html' %} and a block section (e.g. Content) for other templates to extend it.

Can I put another block section (e.g. Breadcrumb) inside the include file and use that in a template which extends _layout.html? So far it doesn't seem to work. If I move the Breadcrumb block from the include template into _layout.html it works fine, and when I move it back the content in the template extension does not show.


texts: Structure parent root - entry type or category urls?

texts:
Been rolling around with this for the last 36hrs trying to decide most useful option. The dilemma is how to preserve a structure and use categories - or not. Below is my structure:

Food (section structure)

fruit (branch parent)

apples (entry)
pears
oranges

Bread (branch parent)

wholemeal
white
bloomer

Goal:
Part of the goal here is to use the structure in the admin panel so that entrie are reflected like the above.

The branch parent contains contains a description of that branches content. So 'fruit' and 'bread' are what i call branch parents ( possibly even root parents etc)
The branch parent content can be either stored as its own entry type at the top of the branch in the structure, and preserve the admin structural view. Or I can store the branch description as a field in the category for the entries in the section.

If I store the branch description as an entry type at the top of the branch structure, I cant use the category urls because they will conflict with the branch:
e..g category url = 'food/fruit'
entry type url 'food/fruit-1'

But if I ditch the top of the branch parent entry type then the admin for that section is just a flat list - it loses is hierarchical structure and a little bit of its meaning and find-ability for admins.

So I could just turn off the category urls and render the structure in templates without categories but it doesn't feel right.

How have others solved / implemented this?


texts: How to move entries from one channel to another

texts:
I have a channel that has three different entry types. The client has decided that two of those post types should be in a separate channel. This is an existing site with a few dozen entries currently in the channel, so I'm wondering if there's any easy way of splitting a channel like this that won't require me to manually set up a duplicate of the channel and then manually copy entries across, one by one.

Is there some way of duplicating a channel with all its entries, so I can then just batch delete some entries within each channel? Or is there a way (a plugin, perhaps?) of moving entries of a particular type into a new channel? ...or would it be easier to keep the existing structure and via templates and routing create the appearance of two channels on the front end? (That's the best solution I've been able to come up with so far)

I'd be very grateful for any advice / suggestions!


texts: migrating from Linux to Windows, but my templates aren't loading

texts:
Hello I am migrating our craft install from a Linux server to a Windows IIS based server.

So far all is working, however the default template is not loading. Any idea why?

Linux: http:// 70 .32 .84 .65/home
Windows: https://brownbis.com/primer/home

Is there a PHP module on Windows that I need to enable?

Thank you very much for your help


texts: Visitor drop off since moving over to Craft CMS

texts:
Hi I've been managing my clients Wordpress site for over 7 years now and redesigned it a few times. Recently, I convinced my client to move over to Craft CMS and 4 months ago we went live with a new design. This was my first build in Craft, the development went well having studied some good tutorials. Since then, in the 4 months that the site has been live the visitor sessions in Google Analytics have halved and have stayed at half continuously. They pretty much halved around the day or the week the site went live.

Bounce rate has increased by 10% and the average session duration has increased by 20%, which would suggest that the site is slow to respond?

I have run the site through Google Site Speed and there is some action to take regarding compression etc, minor stuff though.

So my question is:

Does Craft perform more slowly than Wordpress, or probably a better question: does Craft require more server resources than Wordpress?

Server is a dedicated server and has 2gb of RAM for 15 active domains and 256mb of memory is allocated to PHP for this particular domain.

Pictures do seem to render a little more slowly than before especially on a slide show on the home page.

I did have a lot of 404's which I was a bit slow to notice and clear up but have been dealt with in the .htaccess file.

We also moved the website onto SSL for added security so don't know if there is anything that I should look into there.

All meta tags were ported over correctly.

Have I been penalised in some way by Google for the change in website design or structure?

Other than that, I don't know why my site visitors would halve like this.

Any other tips or suggestions would be really helpful thanks.


texts: Redactor table plugin broken in Craft 2.3.2620?

texts:
I'm running Craft 2.3.2620 and installed the Redactor table plugin to /craft/app/resources/lib/redactor/plugins

And this is my json:

{
    buttons: ['html','formatting','bold','italic','unorderedlist','orderedlist','link','image','table','video'],
    plugins: ['fullscreen','table','video'],
    toolbarFixedBox: true,
    paragraphize: false,
    linebreaks: true
}

But the table button is not showing up. The video and fullscreen plugins are working fine.

Is this a bug - or is Craft's redactor implementation not compatible with their table plugin?


texts: Is there a native function or plugin to allow admins to email all users?

texts:
I want to be able to provide the admin with a function so that they can email all registered users of the site.

Is there a native function or plugin that would make this possible?


texts:
We are building a multilingual site.

We have different domains and slugs for German and English pages/sections  i.e. projects is called projekte...

Right now the template used is called "projects.html" which we want to use for all languages, but Craft is looking for each slug's language template and not the English one?

Do we need to duplicate each template or?

Thanks in advance.


texts: Display number based on position in structure hierarchy

texts:
I'm stuck. For a new site I need to display numbers before the main h1 title and in the submenu's.

Example:

1 Home
2 About

01 history
02 strategy (active page)
03 profile
etc. etc.

In the active page (strategy) the title needs to be 02 strategy.
So the number is based on the position inside the parent. If I reorder strategy to the first position, the number needs to be 1.

Can someone help me please?

preview http://durk.com/example.png


texts: Setting structure section entry titles dynamically based on the entry level

texts:
I'm trying to set a title for a STRUCTURE entry dynamically based on the structure level within the section hierarchy.

{% if entry.level('not 1') %}{ postDate|date('M') }{% else %}{ postDate|date('Y') }{% endif %}

I've tried using the above for the title format of my entry type but it only appears to work for setting YYYY for the parent entry and doesn't add the month for child entries.


texts: Updating plugins from the admin doesn't work

texts:
Suddenly getting this strange error every time I try to update Craft or any plugins through the admin;

Status: Internal Server Error

Response:
PHP Fatal Error &#039;yii\base\ErrorException&#039; with message &#039;Allowed memory size of 134217728 bytes exhausted (tried to allocate 4096 bytes)&#039;

in /Users/a/Sites/askrembla/vendor/composer/composer/src/Composer/DependencyResolver/Solver.php:220

Stack trace:
#0 [internal function]: yii\base\ErrorHandler-&gt;handleFatalError()
#1 {main}

Memory and all that is fine as far as I can tell, so not sure why this error is thrown. Will continue investigating on my end.


texts: Setting User Permission to hide products of other user

texts: I have a model where there will be many users. Each user has dashboard access and can add there products.. this all is done, but what I want is one user doesn't see other user products. Right now a user can see all products uploaded by all users. Currently Craft CMS doesn't have permission settings to hide entries of other user as they have for channel entries.. but I need that. Can anyone help me how can I achieve that. Any ideas would be helpful. Thanks in advance


texts: Hiding Craft's admin folder from search engines

texts:
I am trying to hide our website's admin directory from public view as best as possible and have read the Securing Craft article. I am pleased at how easy it is to make a directory that isn't easy to guess using the cpTrigger setting in the config file.

My next thought was to disallow the directory on the robot.txt file, keeping crawlers from indexing the login page. The obvious issue with that is that now the "hidden" admin directory is in public view from our robot.txt file, not exactly what I want to do.

Is there something in the metatags or HTML of the Craft admin pages that blocks crawlers from indexing the admin pages? I was hoping to see the following on the admin pages:

But they are not present. Is there a reason we would not want these by default on the Craft admin pages?

Please advise on the best practice here, perhaps I am overthinking things, or there is another way altogether to accomplish this.


texts: Worldpay Gateway not redirecting to Customer Order screen on successful transaction

texts:
I have live site with PayPal payment Gateway and works flawless. Problem appears when I want to use also WorldPay.
Payment is going throught but after payment browser is not redirecting to Order Summary Screen and order doesn't appear as placed order in CP.
I set up everything as stated in Craft Commerce doc. I really don't know what I can do else :(

Orders only appears in ACTIVE CARTwith status REDIRECT.

Another order is adding to the same order that's the problem to identify what has been bought.


texts: Setting a variable to a Matrix field with additional parameters

texts:
I'm trying to set a variable to a Matrix field and apply additional query parameters like so:

{% set monthDates = entry.scanDates.type('dates').date('and', '>= ' ~ currMonthFirst|date('Y-m-d'), '< ' ~ nextMonthFirst|date('Y-m-d')) %}

I want to have a set of dates based on a date range, but I'm getting a "Calling unknown method: craft\behaviors\ElementQueryBehavior::date()"

The name of the Matrix field is scanDates with block type dates and field name date.

The following code with just one parameter works just fine, so it must be the syntax that is wrong in the first example.

{% set monthDates = entry.scanDates.type('dates').date('>= ' ~ nextMonthFirst|date('Y-m-d')) %}

What is the correct syntax to narrow down the results based on multiple conditions?  `


texts: Element API: PHP Error: Fatal error: Allowed memory size of 33554432 bytes exhausted

texts:
Trying to get this json api to work for us and keep running into issues. Here, when trying to list all items, it throws the following PHP error:

  Fatal error:  Allowed memory size of 33554432 bytes exhausted (tried to allocate 65552 bytes) in /home/accesstrucks/craft/app/framework/YiiBase.php on line 618

There are only 100 listings currently, but this is just for testing. Which is nothing compared to how many listings there will be when live.

Here's my code:

return [
  'endpoints' => [
    'alltrucks.json' => [
      'elementType' => 'Entry',
      'criteria' => ['section' => 'trucks'],
      'paginate' => false,
      'transformer' => function(EntryModel $entry) {
        return [
          $entry->year.' '.$entry->manufacturer.' '.$entry->model,
          (string)$entry->author,
          !empty((string)$entry->category[0]) ? (string)$entry->category[0] : null,
          !empty($entry->listingPhotos[0]->url) ? str_replace('/images/uploads/listings/', '', $entry->listingPhotos[0]->url) : null,
          ($entry->saleType=='new') ? '0' : '1',
          (string)$entry->featured,
          ($entry->saleType->label=='new') ? '0' : '1',
          $entry->transmission,
          (string)$entry->dateUpdated,
          $entry->mileage,
          $entry->price


texts: Best way to organise sections and templates

texts:
I'm hoping this isn't too broad or long! I have two questions. I'm trying to streamline the organisation of my site.

Firstly: Currently, for every section of my website (e.g. website.com/housing , website.com/skiing, website.com/guitar) i have created separate structures for each one, with an index page in it with content entries being children of that index. The index template loops through children and displays links to each page.

Housing structure
  - index
    - entry
    - entry

I have seen some people saying they are putting all entries of the site in a single structure with hierarchy, e.g. one structure that has:

- Single Structure
  - housing
    - entry
    - entry
    - entry
  - guitar
    - entry
    - entry
  - skiing
    - entry
    - entry etc.

Is this a good idea? Is there any drawkbacks to the way i've done it? or is it a case of 'whatever works best for you'. It does make my Entries area of the CMS full of lots of structures, but it is clear which to access to edit which pages.

Second question: template organisation. In light of my separate structure approach, my templates folder has a folder in it for each structure type with an _entry that routes to the correct template based on entry type e.g.

templates folder
  > housing
    - _entry.html
    - index.html
    - content-page.html
  > guitar
    - _entry.html
    - index.html
    - content-page.html

_entry.html in each folder has something like this:

{% include "housing/" ~ entry.type %}

The index page on nearly all my structures is exactly the same, and the content page is often pretty similar (although varies slightly), so it feels like i should really point each structure to a single folder to load templates (e.g._pages/), where i'd realistically have maybe 6 or 7 templates total, as opposed to 10+ folders in /templates/ (one for guitar, one for skiing etc.).

I've abstracted all of the repeated logic in each structure template folder to a macro file to make it easy to manage updates to templates but is a single folder a better approach? Would i be best off still keeping a separate folder for /news/ in the templates folder? Or is it again 'what works best for you'.

I'd love to hear how others are doing things so i can improve my future craft builds.


texts: Element API - UrlHelper generates backwards slashes (regex)

texts:
I am generating a url within Element API:

'profile' => UrlHelper::getUrl("directory/company/{$member->id}/{$urlslug}"),

which outputs:

http:\/\/craft.fira\/directory\/company\/1501\/abet-limited

What do I need to do to turn this into a real url without the backwards slashes "\"? As far as I understand this is a regular expression (regex) version of the url?

I will be using javascript to put this on the page, so it could either be fixed at source in the Element api php code, or alternatively when scraping through the JSON with Javascript.

Thanks in advance guys! :-)


texts: Using search criteria in modifyEntrySources plugin

texts:
I have articles with a multi-select named theme.

This works fine in a template:

{% set entries = craft.entries.section('article').search('theme:themeFoobar') %}
<p>{{ entries | length }}</p>

I'm working on a plugin to create a custom source containing only those articles that have themeFoobar selected in their multi-select, this is what I have:

public function modifyEntrySources(&$sources, $context)
{
  $sources[] = array('heading' => 'Themes');

  $sources['theme:foobar'] = array(
    'label' => 'Theme: Foobar',
    'criteria' => array(
      'section' => 'article',
      'search' => 'theme:themeFoobar'
    )
  );
}

The result of this is that the source contains all articles, it looks like the search criteria is completely ignored.

Is search not the correct criteria to use here? Is there another criteria I can use to find only the articles with themeFoobar selected in the multi-select?

Further information

The multi-select used to be just a dropdown. When it was a dropdown, this plugin worked fine:

public function modifyEntrySources(&$sources, $context)
{
  $sources[] = array('heading' => 'Themes');

  $sources['theme:foobar'] = array(
    'label' => 'Theme: Foobar',
    'criteria' => array(
      'section' => 'article',
      'theme' => 'themeFoobar'
    )
  );
}


texts:
I am having an issue where the activation link sent to a user has expired and when they click the 'resend activation link' on the warning message a new activation link is never sent.

I have added logging into the userservice->sendActivationEmail method to see if it's called and it never gets called.

Any help would be appreciated.


texts: How to display a specific image from Assets field

texts:
I have an Assets field with a set of images. What is the best way to find one image that has 'featured' checkbox checked? This is the code I put together to check which of the images is marked 'featured' but I'm not sure how to modify this so to display just the 'featured' image without looping through the entire set. In my use case I need to display a page of entries with featured image for each of them.

{% for image in entry.image %}

   {% if image.featured | length %}(Featured Image){% endif %}
{% endfor %}


texts: How to filter entries by tags array using ['or'] and by category not using or

texts:
This works for filtering by tag array

{% set relatedToParam = ['or'] %}

{% for id in selectedTagIds %}
    {% set relatedToParam = relatedToParam|merge([{
        targetElement: id
    }]) %}
{% endfor %}

{% set entries = craft.entries.relatedTo(relatedToParam) %}

But how can we add another relatedTo param for category so the results only show the selected tag entries from a category?

For example to achieve this:

...WHERE categoryid = 'myid' AND (tag1 LIKE 'green' OR tag2 LIKE 'red' OR tag3 LIKE 'yellow' etc)


texts: ElementAPI : Excluding terms from search criteria

texts:
I am trying to exclude terms in my search when using the element api. I have successfully managed to include terms and search them by fields in my entries. I would now like to be able to exclude different terms in those fields.

In this case 'recipeIngredients' is a matrix field.

Here is my criteria search so far :

//Get search query text
$searchQuery = Craft::$app->request->getQueryParam('searchQuery');
//Search in either title or ingredients
if ($searchQuery) $criteria['search'] = "title:'".$searchQuery."' OR recipeIngredients:'".$searchQuery."'";

//Get excluded ingredients query
$excludedQuery = Craft::$app->request->getQueryParam('xq');
if ($excludedQuery) {
    if (!isset($criteria['search'])) {
        $criteria['search'] = '';
    } else {
        $criteria['search'] = $criteria['search'].' AND ';
    }
    $criteria['search'] = $criteria['search']."recipeIngredients: not '".$excludedQuery."'";
}

//Get result count
$count = Craft::$app->request->getQueryParam( 'count' );
$count = $count ? $count : 10;//Default to ten if no parameter

return [
    'elementType'     => Entry::class,
    'criteria'        => $criteria,
    'elementsPerPage' => $count,
    'transformer'     => function ( Entry $entry ) {
        return [
            'name'      => $entry->title,
            'url'        => $entry->url,
            //'json_url'    => UrlHelper::url( "recipe/{$entry->id}.json" ),
            'picture_url' => $entry->recipeImage->one()->getUrl(),
            'portions'   => (float)$entry->recipePortions,
            'time'       => [
                'total' => (float)$entry->recipeTotalTime
            ]
        ];
    },
];

I can't figure out if I should be trying to append the excluded terms to the search query, and my syntax is wrong, or if there is another criteria property available to exclude results.

Also, the ElementQuery page mentionned in the docs no longer exists. I assume, it's this page, but I'm not certain.


texts:
I'm using image transforms and getUrl() method to display an image.
I'm using Blitz to export my site as a static website.
My problem is that .html pages get cached with images that have full urls like this: http://localhost:8888/assets/pages/_medium/image.jpg
There must be an obvious solution that i'm missing... I've tried getPath but it doesn't support image transforms. Removing http://localhost:8888 should do the job.. but how?


texts:
I might be over-engineering this a bit, but I'm looking for a clean way to set up my homepage, for as few database queries and maintaining a DRY setup. The homepage is:

Hero introduction

Fields in a homepage single.

News & Events

Simple blog-like query

And then the two parts I'm confused about. Both of these are pulled from other singles.

About Us summary
Membership info

Is it fine to just query these pages individually? It feels so over the top to do something like

{% set aboutQuery = craft.entries().section('about') %}
{% set aboutPage = aboutQuery.all() %}
{% for page in aboutPage %}

{{ page.title }}

{{ page.summary }}

{% endfor %}

I'm sure this is a fairly common setup, so I just want to know what other people do in cases like this.


texts: Can I build a 100,000 pages website with Craft?

texts:
I want to build a fairly large website (over 1000,000 pages and even more users) and I was wandering if Craft was made for large websites or should I look somewhere else?

Do you know any examples of large websites built with Craft CMS?


texts: Put simple content into Craft and grab it in JavaScript

texts:
I want to put a few simple text fields into Craft CP and then be able to retrieve them with JavaScript.

What is the best way to structure this in Craft? I'd like to be able to create/edit an "entry" and then do something like this:

<script type="text/javascript">
    var homepageContent = {{ craft.entries.homepageContent }};
    console.log('details: ', homepageContent);
</script>

The homepage content entry in Craft needs to have ~2-3 fields attached to it.

I created the 3 fields that I think I will need to be editable on the homepage. Now I'm unsure how to get these tied to be able to enter an "entry" into something like a Homepage Content group?


texts: After transferring local to server, Twig Runtime Error: Impossible to invoke a method all() on an array

texts:
I transferred site from MAMP to Arcustech server and the Admin panel works fine, I even updated to 3.6.6, but the front-facing site throws an error:
Twig Runtime Error: Impossible to invoke a method all() on an array.
This is the code, but it throws it anywhere all() is used:
{% set myEntryQuery = craft.entries()
    .section('informationPages')
    .all() %}

{% set entries = myEntryQuery.all() %}

I'm new to Craft so I'm probably doing something dumb, but the site works fine in MAMP so I'm not sure where to start in running this down.
I checked all the file/folder permissions, updated all the .env and config items, etc.


texts: How can I make make the class of an entry link "active" if entry is the current url?

texts:
I'm currently using the below jQuery but it's buggy as it relies on looking for 'similar' URL and not the exact URL.
Is there a way it can be done just using Twig?
{% set mainNavigation = craft.entries.section('mainNavigation').all() %}

    {% nav page in mainNavigation %}

            {% if page.customUrl|length %}
                {{ page.title }}
            {% else %}
                {{ page.title }}
            {% endif %}

            {% ifchildren %}

                    {% children %}

            {% endifchildren %}

    {% endnav %}


texts:
I have a RichText field using a standard config. "Clean up HTML" and "Purify HTML" are OFF.

I have a page with a paragraph of text, then an unordered list. After that list, I try to insert another paragraph and add a line with a mailto link in it.

No matter what, the link gets removed/stripped out. If I move the paragraph up before the UL, it works. But being after the UL list, it's getting stripped out.

Essentially the text in the editor looks like:

text

title line of text

title line of text

Send us a message

I did try checking both purify and clean HTML options ON, but that didn't work either. I've tried inserting the text via html view as well as visual view. Still can't get it to stick. I've tried adding multiple paragraphs after the UL list, but HTML is getting stripped out of everything after the list.

Anyone have any ideas?

My standard config json is:

{ buttons: ['html','formatting','bold','italic','unorderedlist','orderedlist','link','image','video'],
plugins: ['fullscreen'],
toolbarFixedBox: true }

Craft Client 2.4.2692


texts: Returning a "is currently unable to handle this request. 500 Error" when client posts

texts:
I'm working with a client to resolve an issue that has appeared recently with a Craft site. Up until recently there were no issues with the site for my client, but she is now getting a 500 Error:

  site.com is currently unable to handle this request. HTTP ERROR 500

This happens whenever my client tried to create a new entry post. Uploading an image is okay, but posting is not. We're running Craft 1.3.2487.

Any help or direction on this would be greatly appreciated.


texts:
apologies if this has been asked, I don’t seem to be able to find the solution.
What is the correct way to call craft.app.session.set in a Twig template (or any other setter function for that matter)? I can’t find a working example in the docs for anything other than getters.
To expand, this causes an error:
{# grab initial value, it is empty #}
{% set mySession = craft.app.session.get("mySession") %}
{{ "mySession = #{mySession}" }}

{# set value to 'someValue' - this will cause the error #}
{% craft.app.session.set("mySession", "someValue") %}

{# grab value again, it should now be 'someValue' #}
{% set mySession = craft.app.session.get("mySession") %}
{{ "mySession = #{mySession}" }}

However this works as expected:
{# grab initial value, it is empty #}
{% set mySession = craft.app.session.get("mySession") %}
{{ "mySession = #{mySession}" }}

{# set value to 'someValue' #}
{% set somePointlessVariable = craft.app.session.set("mySession", "someValue") %}

{# grab value again, it’s now 'someValue' #}
{% set mySession = craft.app.session.get("mySession") %}
{{ "mySession = #{mySession}" }}

Surely I don’t need to create some pointless variable just to use the setter function?


texts: Craft front-end forms not working with Angularjs app

texts:
I'm making a site with Craft CMS/Angularjs. I'm using angular to filter and display entries on the index page and it's working good so far except for one thing. The login/register/entry form's all don't function at all. If I remove ng-app from the html tag they work just fine so it's definitely angular that's causing this issue.

Here's my login form on the main page:

{% if currentUser %}
        You are logged in as {{ currentUser.friendlyName }}
        logout

    {% else %}

    <form method="post" action="" accept-charset="UTF-8">
        <input type="hidden" name="action" value="users/login">

Username

        <input id="loginName" type="text" name="loginName">

Password

        <input id="password" type="password" name="password">

        <input type="submit" value="Login">

        {% if errorMessage is defined %}

{{ errorMessage }}

        {% endif %}

Please login or register

    </form>

    {% endif %}

If anyone with experience using angular and craft together can chime in that'll be great.


texts:
Is there a way to have multiple entry templates per entry?

I'd like to create two different templates that display the same content/data in different ways.


texts: Using the Group filter with Squarebit Charge plugin

texts:
Has anyone had success using the Group filter with Squarebit Charge?

I tried a few different approaches, in each case getting array errors. Here is code:

{% set allCharges = craft.charge.charges.limit(3)|group('cardName') %}

{% for cardName, details in allCharges %}

{{ cardName }}

{% for details in allCharges %}
    {{ details.dateCreated }}...and more fields
{% endfor %}

{% endfor %}

This throws an error message "Key "dateCreated" for array with keys "0" does not exist."

If I dump(details) I see an array that looks like all the fields you would expect, including "dateCreated"

Any help would be appreciated!


texts:
I have these to arrays that I need to merge into one array, but can't figure it out.

Please advise

{% set entries = craft.entries.section('publications').search('nonMembers:0') %}

{% set entries = craft.entries.section('improveYourClub').search('membersExclusive:1') %}


texts: Finding Super Table field in matrix field

texts:
I am writing an importer that pulls from a separate MySQL database into Craft 3, and for the most part it's been quite simple to do.

However, I set myself up for some complication by having a Super Table field inside a Matrix field, which required some acrobatics to retrieve the field information to use when saving the entry.

The code below does work, but I wanted to check if it could be simpler, or if there are any obvious problems with this approach. It could also be helpful to someone else trying to achieve the same thing, as I didn't find anything similar when searching around.

// Get our "quotes" Super Table field (inside "mediaBlocks" matrix field)
if (empty($this->superTableQuotesField)) {
    $mediaBlockField = Craft::$app->getFields()->getFieldByHandle('mediaBlocks');
    $blockTypes = Craft::$app->getMatrix()->getBlockTypesByFieldId($mediaBlockField->id);
    foreach($blockTypes as $blockType) {
        if ($blockType->handle=='quotes') {
            $matrixFields = Craft::$app->fields->getFieldsByLayoutId($blockType->fieldLayoutId);
            // Cache this for future use
            $this->superTableQuotesField = SuperTable::$plugin->service->getBlockTypesByFieldId($matrixFields[0]->id);
        }
    }
}
// For some reason we couldn't find the Super Table field
if (empty($this->superTableQuotesField)) {
    Craft::warning('Could not find Super Table field for quotes in mediaBlocks!');
    return [];
}

$blockType = $this->superTableQuotesField[0]; // There will only ever be one SuperTable_BlockType

... then a for loop with $q++ on each item from the other db:

$related_quotes['new'.$q] = [
    'type' => $blockType->id,
    'fields' => [
        'quote'         => $quote,
        'personName'    => $personName,
        'personCompany' => $personCompany,
    ]
];

... and then if any found, merge with matrix array:

if (!empty($related_quotes)) {
    $i++;
    $media_blocks = array_merge(['new'.$i => [
        'type' => 'quotes',
        'fields' => [
            'quotes' => $related_quotes,
        ]
    ]], $media_blocks);
}

Is there a better way to do this?

Update:

For comparison, this is the (much simpler) code I'm using to find the $blockType for a Super Table field when it's not an embedded field:

// Get our Super Table field
$field = Craft::$app->getFields()->getFieldByHandle('quotes');
$blockTypes = SuperTable::$plugin->service->getBlockTypesByFieldId($field->id);
$blockType = $blockTypes[0];

... but since this is inside a Matrix field, it doesn't work.

Here's a snapshot of what the field looks like in CP:


texts: Are there callbacks for elementSelect macro?

texts: I am writing a custom field type that makes use of Craft's asset selector, and saw that there is an elementSelector macro (in includes/_forms). I want to be able to do some things onSelect, but I cannot tell if that is possible with the elementSelector macro. I know the element select modals can be extended using Craft.createElementSelectorModal(). Is this the only way to access element select modal callbacks?


texts: Is there a way to get supportedSites for a category page?

texts:
I'm working on a site that is available in multiple languages and I would like to build a language switcher that will work for both category pages and single entries.

In Craft v2 that was possible but once I switched to Craft v3, I can't find a way to do get the current category page.

For single entries I do the following (simplified):

{% for siteForEntry in entry.getSupportedSites %}
    {% set site = craft.app.getSites.getSiteById(siteForEntry.siteId) %}
    {% if site.id == entry.siteId %}

           {{ site.language }}

    {% else %}
        {% set entryForOtherSite = craft.entries.id(entry.id).site(site).one() %}

                {{ site.language }}

        {% endif %}
 {% endfor %}

Is there a way to do the same thing for categories?


texts:
Probably this one is repeated, but I couldn't find an answer for it yet.
I have a multi-site in Craft CMS 3.15, one that is in English and another one in Japanese.
So the English page, which is the default, is www.mysite.com, and my other site, is working fine if the domain is www.mysite.com/jp
However, I want to change the domain for the Japanese site to be www.myjapanesesite.com/home and is not working as I expected as the browser says that there have been too many redirects.
How can I make this possible on Craft? Is there anything else I should config in Craft or in the htaccess file?
The redirects section from my htaccess looks like this:
<IfModule mod_rewrite.c>
   RewriteEngine On

   RewriteCond %{HTTP:X-Forwarded-Proto} !https
   RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

   RewriteRule ^(autodiscover) - [L]

   RewriteCond %{HTTP_HOST} !mysite.com$ [NC]
   RewriteRule ^(.*)$ https://www.mysite.com/$1 [L,R=301]

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

   # 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>

While the Base URL for my English site is https://www.mysite.com and the Japanese one is https://www.mysite.com/jp (I have tried to change it to www.myjapanesesite.com/home but that's when it doesn't work).
Thanks in advance
Note: I have set the alias for this site www.myjapanesesite.com in SiteHost (the hosting service)


texts: Is there a way to hide Matrix blocks based on the Selected Entry Type?

texts:
I have 2 primary entry types, one for a full width page, and one for a sidebar page. The sidebar page shares about 90% of the same block types as the full width page.  The other 10% do not apply to the sidebar page at all.

Instead of going to the trouble of duplicating (and maintaining) an additional Matrix set for the sidebar page, sans the non-applicable block types, I have decided to use the same Matrix for both pages.

I am looking for a way to disable / hide the unused block types on the sidebar page entry type. Just as with the normal fields which can be assigned or not to the entry types, shouldn't the matrix block types also work in the same manner?

Any ideas?


texts: "Custom" validation for plugin settings page

texts:
I have a plugin that has a few settings. One of which is a start date and and end date. Everything is set up and working fine. I'd like to validate the start/end dates a a bit though.

I am able to use compare to check that the end isn't before the start, but I'd also like to check that the start (or end) isn't in the past as well.

Using this awesome page on validation I've seen how to set custom validation via rules. But, since I'm in a settings file, I'm not exactly sure how this translates over.

MyPlugin.php

defineSettings(){
    return array(
        'myStartDate' => array(
             AttributeType::DateTime,
             'required': true,
             'compare': '<= myEndDate'
         ),
         'myEndDate' => array(
             AttributeType::DateTime,
             'required': true,
             'compare': '>= myStartDate'
         ),
    )
}

What I think I'm trying to get is something like this:

....
'myStartDate' => array(
     AttributeType::DateTime,
     'required': true,
     'something': array(
          'rule': myValidation,
          'message': 'The start date can not be after the finish date.'
      )
 )
....

function myValidation() {
    // Do something here
}

Or, maybe I'm way off.


texts: Is there a way to get the URL of the localised version of a product variant?

texts:
I have a website that uses Craft Commerce and I'm trying to add a language menu that points to the localised version of each product variant as follows:

  {% set variantID = craft.request.getParam('variant') %}
  {% set locales = craft.i18n.getSiteLocales() %}

  {% for locale in locales %}
     {% set localisedEntryUrl = craft.commerce.variants.id(variantID).locale(locale.id).first().url() %}
     {{ localisedEntryUrl }}
  {% endfor %}

The problem is that the code above always produces the variant url for one language. eg.

/en/shop/ornaments/melisa?variant=9356
/en/shop/ornaments/melisa?variant=9356
/en/shop/ornaments/melisa?variant=9356

whereas I would expect something like:

/en/shop/ornaments/melisa?variant=9356
/de/shop/ornaments/melisa?variant=9356
/es/shop/ornaments/melisa?variant=9356

What am I doing wrong?


texts:
Has anyone had issues with Craft parsing a .env on Windows Server?   Dotenv is throwing an exception (FileException - invalid name) when parsing the first line of my .env, which is just a comment. I can remove that line and then i complains about the next line.
My .env simple starts with:
# The environment Craft is currently running in (dev, staging, production, etc.)
ENVIRONMENT=dev

basically, Dotenv/Parser/isValidName's Regex call is failing.
Full Stack...
Fatal error: Uncaught Dotenv\Exception\InvalidFileException: Failed to parse dotenv file due to an invalid name. Failed at [ENVIRONMENT]. in C:\WebRoot\WebApplications\advantage-rebate-portal-v4.0\vendor\vlucas\phpdotenv\src\Parser.php:74

Stack trace:
#0 C:\WebRoot\WebApplications\advantage-rebate-portal-v4.0\vendor\vlucas\phpdotenv\src\Parser.php(30): Dotenv\Parser::parseName()

#1 C:\WebRoot\WebApplications\advantage-rebate-portal-v4.0\vendor\vlucas\phpdotenv\src\Loader.php(169): Dotenv\Parser::parse()

#2 C:\WebRoot\WebApplications\advantage-rebate-portal-v4.0\vendor\vlucas\phpdotenv\src\Loader.php(107): Dotenv\Loader->processEntries()

#3 C:\WebRoot\WebApplications\advantage-rebate-portal-v4.0\vendor\vlucas\phpdotenv\src\Loader.php(91): Dotenv\Loader->loadDirect()

#4 C:\WebRoot\WebApplications\advantage-rebate-portal-v4.0\vendor\vlucas\phpdotenv\src\Dotenv.php(123): Dotenv\Loader->load()

#5 C:\WebRoot\WebApplications\advantage-rebate-portal-v4.0\vendor\vlucas\phpdotenv\src\Dotenv.php(80): Dotenv\Dotenv->loadData()

#6 in C:\WebRoot\WebApplications\advantage-rebate-portal-v4.0\vendor\vlucas\phpdotenv\src\Parser.php on line 74


texts: Option and notes fields after cart at checkout for order, not just line items

texts:
My client has gift wrapping services but they apply to the entire order, not one single line item.

How would I add notes or custom fields to the entire order, at the shipping stage of checkout? is this possible without a plugin?

I tried to apply notes and giftwrapping options to the first line item by using the commerce/cart/updateLineItem form, on the cart.lineItems.first() but it didn't work. I presume that after the user proceeds to checkout the line Items no longer exist?


texts:
After moving a Craft website from Apache server to Nginx, the admin css\js assets url-s stopped resolving.
For example, on /admin/login page Craft CMS tries connecting to the /admin/resources/lib/jquery.min.js - even though that directory structure doesn't exist, it still connects fine on Apache server, but results in a 404 page on nginx.

How are these routes generated? What need to be added to vhosts file in order for it to work?

Note that Craft is used to generate only the part of the website - e.g. www.example.com/craftpages is my Craft homepage.


texts: How to check if matrix block type is empty or not

texts:
I have a matrix field with two different block types and I want create a conditional to check if one of the blocks is not empty show it and if it is show the other.  This is not working:

{% for block in entry.page.type('text, intro') %}
    {% if block.type.text != "" %}
        <h3>{{ block.text }}</h3>
    {% else %}
        {{ block.intro }}
    {% endif %}
{% endfor %}

Thanks!


texts: Question regarding member-owned shared assets

texts:
Complicated question regarding asset sharing for a client proposal.

The website to be built will contain reports uploaded by a super-admin. These reports will be PDFs, tagged by year and be about specific users. The users that the reports relate to will be registered members of the site, and will be able to view reports regarding themselves.

Users will be able to log in to their members area of the website (front-end), and send requests to view other users' reports, and approve requests from other users to view their own reports.

Example

User1 has a login to the site, and has access to user_1_report.pdf
User2 logs in and sends a request to User1 to view user_1_report.pdf
User1 receives a notification in their members area and can click Approve / Deny
User2 gains access to the user_1_report.pdf as a download link in their members area.

Can anyone suggest how this might be implemented? I'm assuming that it needs to be done with a custom built plugin but I'd love to know if it's possible without.

If it is plugin-only and there are any Craft plugin developers available, let me know as there is a budget available for someone to build that area of the site if necessary.


texts: Creating a date filtered archive template

texts:
I'm trying to create an archive list template that lists entries from a News or Blog Channel based on year/month/day combinations.

However, I get no entries and can't see where I'm going wrong...I'm running the latest build of Craft.

{% if year is not defined %}
    {% redirect "news/archives/"~now.year %}
{% endif %}

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

Year: {{ year }}

Month: {{ month }}

Day: {{ day }}

{% if (year | length) and (month | length) and (day | length) %}
    {% set entryDate = year ~ '-' ~ month ~ '-' ~ day %}
{% elseif (year | length) and (month | length) %}
    {% set entryDate = year ~ '-' ~ month %}
{% elseif (year | length) %}
    {% set entryDate = year %}
{% endif %}

Entry Date: {{ entryDate }}

{% set entries = craft.entries.find({section: "news", postDate: entryDate}) %}

{% if entries | length %}
    Entries found.
{% else %}
    No entries found.
{% endif %}


texts: Use subdomain for S3 assets in multi-site Craft installation

texts:
I have found the section in settings where I can set the URL Prefix for an asset source using a CNAME and pointing to the relative S3 bucket where the file actually lives but I am using a multi site environment so I need the value of the URL Prefix to be dynamic.

I have tried setting it to assets.{{ craft()->request->getServerName() }}, also have tried assets.{% craft()->request->getServerName() %}but that is what's getting spit out on the page (asset url as rendered on page looks like assets.{% craft()->request->getServerName() %}images/home-banner.jpg.

How can I make Craft parse this field's dynamic value? The statement isn't parsed as it would be if it was in a Twig template.


texts:
I am trying to paginate grouped entries as follows...

{% set searchParam = craft.request.getParam('q') %}

{% set groups = craft.entries({
    search: searchParam
})|group('section') %}

{% for entries in groups %}
    {% paginate entries.limit(10) as pageEntries %}

    {% endpaginate %}
{% endfor %}

However it is throwing this error on the paginate line: Array to string conversion

How else can I achieve this functionality?


texts:
I am pretty new to craft (just came from EE) and trying to output the last entry from a matrix field in my template:

{% for block in entry.gallery.last() %}
    {% set image = block.image.first() %}
    <img class="lazy" src="{{ siteUrl }}img/assets/loader.gif" data-src="{{ image.getUrl('galleryThumb') }}" data-src-retina="{{ image.getUrl('galleryThumbRetina') }}" alt="{{ image.title }}">
{% endfor %}

So this isn't working as I thought, i've done some snooping but have had no luck, any ideas?

Thanks
-Graham


texts:
I'm trying to include different markup if a blog post is featured.
This is done via a Lightswitch. If there's is no featured entry then the latest entry uses this different markup instead.
The rest of the entries follow this but need to exclude showing the featured entry if it is shown above.

This is something like what I'm trying to achieve

{% set featured = craft.entries.section('blog').featured(1).limit(1) %}
{% paginate craft.entries.section('blog').limit(12) as entriesOnPage %}
{% for entry in entriesOnPage %}
    {% if entry is featured or loop.first and not featured|length %}

       [markup A]

    {% else %}

       [markup B excluding featured item]

    {% endif %}
{% endfor %}


texts:
Would it be possible that when you create a new entry, it's not activated by default?

I know there is a "Draft" option...  But is there an option for this?

Best,
Marcel


texts:
Trying to add entries in a visual array on my homepage.
Problem is that I need a special class on the last item in every row.
col_last

Trying to get my head around how to automate this, in order to avoid "special entries" for these.

Any ideas?

{% for item in craft.entries.section('services').orderBy('postDate asc').all() %}

{{ item.title }}

{{ item.serviceTagline }}

{% endfor %}


texts: Redirects or Routing for Landing Page URL's?

texts:
I am trying to set up a channel that uses different content for a series of Google Adwords landing pages.

I set up the channel template as /landing-pages/_entry

I'd like to remove the /landing-pages/ piece of the title

Ideally, I'd like short simple url, which is effectively the slug title, which would be something like /chef-jobs for this client.

What is the best way to achieve this with Craft? Redirects or Routing.

The routing method doesn't call the entry and just shows a blank template, how can I feed the route address across if I use this method?

Any help, much appreciated :)


texts: 'An unknown error occurred.' when trying to add new custom widget

texts:
I am hoping that somebody can help with this issue.

I followed this excellent tutorial on creating a custom widget in Craft. On completion, I uploaded the plugin to the /craft/plugins/ directory, visited the page at /admin/settings/plugins and installed the plugin. All fine so far. Then, on returning to the dashboard, I clicked on New Widget, and selected the name of the widget. Following this, a message flashed up saying 'An unknown error occurred.' and little else happened.

It's probably user error, but if you could point out what I might have done incorrectly, that'd be useful.

My Plugin Structure

The plugin's called Adlister and the widget's called Alu, so in /craft/plugins/adlister/ I have two folders ( templates/ and widgets/ ), and a file: AdListerPlugin.php. Within templates/ is a file: AluWidget.html and within widgets/ is AdLister_AluWidget.php.

File Contents

AdListerPlugin.php

<?php
namespace Craft;

class AdListerPlugin extends BasePlugin
{
    function getName()
    {
         return Craft::t('AdLister');
    }

    function getVersion()
    {
        return '1.0';
    }

    function getDeveloper()
    {
        return 'Mark Syred';
    }

    function getDeveloperUrl()
    {
        return 'http://www.sypo.uk';
    }
}

AluWidget.html

Click to perform a daily update.

Click to perform an update on a Monday.

Click to perform a weekly update.

Click to perform a monthly update.

AdLister_AluWidget.php

<?php
namespace Craft;

class Adlister_AluWidget extends BaseWidget
{
    public function getName()
    {
        return Craft::t('Adlister Update');
    }

    public function getBodyHtml()
    {
        return craft()->templates->render('adlister/AluWidget');
    }
}

Any help that anyone could provide would be much appreciated.

With kind regards,

Mark

UPDATE

I don't know if this has any bearing, but the version of Craft I'm running is 2.6.2911.


texts: How to list the latest 5 entries per entry type?

texts: Let's say I have 4 entry types (Article, Video, Photo & Quote). What's the best way to list the latest 5 entries by each entry type?


texts: How to link to an anchor on an entry page from within Rich Text editor

texts:
I need to link to a particular #anchor on a page from within the WYSIWYG editor.

However, if I start by using Link to Entry in the Rich Text editor, Redactor adds its own 'anchor' (with the same syntax as the Reference Tag for the entry page), and any additional anchors I add to the URL using the Edit Source functionality are ignored.

How would you suggest creating enabling users to create links to specific parts of Entry pages from within the Rich Text editor?


texts: How can I get an entry's child category, and not the parent category?

texts:
I have a category page that lists all of the entries related to that category. And then I want to display the selected child category for the entry... in brief like so:

Entry Title 1
Entry 1's Child-Category

Entry Title 2
Entry 2's Child-Category

Entry Title 3
Entry 3's Child-Category

My category field handle is chooseLocation

Here is what I have in my template:
(snippet taken from here)

{% for entry in entries %}
    {% if entry.chooseLocation | length %}
    {% for category in entry.chooseLocation %}
         {{ category }}
            {% if not loop.last %}, {% endif %}
        {% endfor %}
    {% endif %}
{% endfor %}

The problem is, this get's the parent category (which is the category page we're on) but not the child category. I need to show just the child category and not the parent.

I've looked through the docs but I can't find anything on how to do this.


texts: How can I grant front-end access to an entry that belongs to the current user?

texts:
How would one go about showing a link on the front end if this entry belongs to the current user? I was thinking it had something to do with the UserModel's can(), but I don't see any documentation of it.

Right now I'm showing an "Edit Page" link once someone is logged in, but I don't want to show a that link on a page that the current user doesn't have access to edit.

Any thoughts on this?

Edit

I was hoping something like this would work but it doesn't :( :

{% if entry.author == currentUser %}
    Edit Page
{% endif %}


texts: What is the best way of managing multisite propagation post setup phase?

texts:
I have a multisite setup with a pages section.
In the future we want to add additional sites but there seem to be some caveats.
When we first setup pages we set the section propagation to 'all other sites in this group'. This creates the pages we want in another site without having to recreate the content. Great :)

Once this has been done, I then change the section settings to 'only save sites they were created in'. Otherwise the content edited overwrites each site page.
However, I am trying to achieve a cookie cutter approach going forward that lets us set up a new site and then allows us to copy initial pages in the section rather than recreate the existing pages for the new site.

However there is an inherent danger in swapping propagation methods as this seems to sometimes remove content and or create failed tasks where I can't tell what craft is trying to do (maybe a bug - I'll check github later)

Is there a better way of achieving this process over time when adding sites or is best to just complete initial setup then leave and add new site and content from scratch?


texts: Structure Navigation with 3 possible Link Types using Nav tag

texts:
I'd like to build a Structure that can be used to output the main site navigation; each "entry" in the Structure would have three custom fields (types): Category, Entries, URL
This question is close to what I want, except it's not using Nav; I want children, so I think I need Nav? Plus I couldn't get that code to work anyway.
Based on other questions and the docs, I have this:
{% set pages = craft.entries.section('navDropDownMenu').all() %}

    {% nav page in pages %}

            {% if page.entriesFieldLink %}
                {{ page.title }}
            {% elseif page.urlFieldLink %}
                {{ page.title }}
            {% else %}
                {{ page.title }}
         {% endif %}
            {% ifchildren %}

                    {% children %}

            {% endifchildren %}

    {% endnav %}

The only thing that works here is the Category link, except it should be a child but it isn't. I'm new to Craft so I'm probably doing something basic wrong, but any help is appreciated.


texts: Pushing to an array within a class doesn't work

texts:
Apologies if this ends up being a silly syntax oversight.

My services file looks like this:

class MyPluginService extends BaseApplicationComponent {
  public $myArray = array('test1', 'test2');

  public function someFunction() {
    $someText = "This should end up in myArray";
    array_push($this->myArray, $someText);
  }
}

Assuming the "someFunction" has been called, I later try to dump the array.

{{ dump(craft.myPlugin.myArray) }}

Expected output:

  array(2) { [0]=> string(5) "test1" 1=> string(5) "test2" [2]=>
  string(29) "This should end up in myArray" }

Actual output:

  array(2) { [0]=> string(5) "test1" 1=> string(5) "test2" }

The solution seems to be pretty unanimous across many PHP related forums. However, this just isn't working in my Craft project. Have I overlooked something obvious, or is Craft protecting the public array in some way?


texts: Craft entries related on a category page

texts:
So i'm trying to output blog entries related to a category.

I first created a category group ('categories')
I added several categories to the group ('innovation', 'teams', etc)
I added a category field to my blog post matrix field (post.category)
On my blog index page (example.com/blog) I have excerpts of posts and a sidebar which has the categories and their urls

 {% set categories = craft.categories.group('categories') %}

 {% for category in categories %}

{{ category.title }}

 {% endfor %}

When I click on the link it goes to the page I expect (example.com/categories/teams) and is using the template i specified for the template group (categories.html)
In the template for the category I can list the title and name but I want to get the entries so I:

{{ category.title }}
 <--- just this works
{% set posts = craft.entries.relatedTo(category) %}
{% for post in posts %}

{{ post.title }}

{% endfor %}

But this didn't work

following http://buildwithcraft.com/help/entries-related-to-category

then I tried this, thinking specifying the field was necessary

{{ category.title }}
 <--- again, this works
{% set posts = craft.entries({
section: 'blog',
relatedTo: {
targetElement: category,
field: 'posts.categories'
}
}) %}

{% for post in posts %}

{{ post.title }}

{% endfor %}

and this doesn't work either.

Anyways, i'm not sure where I am going wrong and any help would be appreciated.


texts:
I have two modals with embedded video on this page…
http://staging.wenzelspine.com/products

Everything was working fine until I started converting the HTML to Craft templates, but now they are not playing the correct videos… depending on which you click first.

For example, if you load the page and click Play Video under VariLift-LX it is correct, but if you then click Play Video under VariLift-C it plays the VariLift-LX video. If you reload the page and click for VariLift-C first, it plays the correct video.


texts:
Is there a way to print all of the available parameters/handles when I set a variable?

For example if I put {% set orders = craft.commerce.orders.find() %} is there a way to list out the available parameters/handles depending on what I set, without having to go to the docs? So a way of checking that my code is right from the templates.


texts: Assets problem (/cpresources/transforms/) after update to Craft Client 2.5.2750

texts:
Hi I've just updated to Craft 2.5 but ran into a problem. All my assets are now broken (also showen broken assets icons). I've cleared my cache, went to my craft_tasks table and adjusted the running task there but still it won't show me my assets again...

Any suggestions someone?


texts:
is it possible to change the name of the "New Entry" button?

In my case the user can add a new program part. And so the button should call "New program" or something like that.


texts: How to add more options to the 'Restrict allowed file types' settings?

texts:
I am wondering what would be the best approach to add another file type to the 'Restrict allowed file types' asset field settings?

For our website specification we need to have .zip files and .pdf files only for this field, however I can only restrict to .pdf.


texts:
i'm running centos 6.6, nginx 1.7.7, mysql and php-fpm (i believe 5.5.3) and craft 2.4.2669.

i enable a new language and let all the background tasks complete (the default data copied to the templates is english) and followed the steps here: http://buildwithcraft.com/docs/localization-guide

the localized home page works fine.

i've tried this, with a little luck:
Locales sub directories on Nginx

my language picker doesn't work right: where i send users to the localized version of the page if it exists (otherwise they go to the home page). same code works fine on my local dev (mamp). similar to: How can I build a language switcher?

anyone have any luck using localization on craft with nginx? help asap please.

thanks,
jeremy


texts:
I want to filter data based on category, I would prefer to do this using a join statement, but I can't figure out how an entry is related to its category. I had the same problem with matrix field, but figured it out after hours of research, the code for this is below. A similar statement to filter based on category would be great.

$criteria = craft()->elements->getCriteria(ElementType::Entry);
$criteria->section = 'affiliates';
$criteria->limit = null;
$query = craft()->elements->buildElementsQuery($criteria);
$query->join('matrixblocks matrixblocks', 'matrixblocks.ownerId = entries.id');
$mat_name = 'field_handle';
$query->join('matrixcontent_'.$mat_name.' matrixcontent_'.$mat_name, 'matrixcontent_'.$mat_name.'.elementId = matrixblocks.id');
$query->join('relations relations', 'relations.sourceId = matrixcontent_'.$mat_name.'.elementId');
$query->join('content '.$mat_name, $mat_name.'.elementId = relations.targetId');
$query->andWhere($mat_name.".title"." IN ('abc', 'def')");


texts: Upon updating CraftCMS via CP > Utilities or Terminal, does this update only the vendor folder? Or does it also change structure in the DB and other files outside the vendor?


texts: relatedTo working for one category group but not another

texts:
I'm trying to show a list of entries related to the same category on a page that contains a single entry. I have two category separate category fields in the entry, both with one category each selected in them. The two category groups are named eventType and venue. The code below successfully shows a list of entry titles for one category group but not the other, and I can't seem to find out what's going wrong.

The code below works for the eventType category group (it shows all the entries related to eventType). But when I swap out eventType for venue, it returns my else statement.

I'm new to Craft (it's great!), so maybe I'm going about this all wrong, or missing something obvious.

{% for thisCategory in entry.eventType %}

Other Events in {{ thisCategory.title }}

    {% set category = craft.categories.slug(thisCategory.title) %}
    {% set entries = craft.entries.section('events').relatedTo(category).find() %}

    {# If there are any entries, loop through them #}
    {% if entries | length %}
        {# For each entry we find, do this #}
        {% for entry in entries %}

{{ entry.title }}

        {% endfor %}
    {% else %}

Found no entries

    {% endif %}
{% endfor %}


texts: Can't link to entries or assets via a Redactor field

texts:
When using a Redactor field for a section, I can’t upload assets or link to entries. I just get an empty modal with no ability to select a section or asset folder. Thoughts on what I’m doing wrong?

[UPDATED] See video: https://drive.google.com/file/d/1hKKKKizSfmr1-QeblzfSbQ1B3Pf6Bybv/view?usp=sharing


texts: Default locale in console commands is always en_us rather than the site default

texts:
The default (and only) locale for my site is en, however, when trying to query the ElementService from a console command without specifying the locale in the criteria, the locale used in the query is en_us. As such, the query returns no results. For example:

<?php
namespace Craft;

class ShoppingCommand extends BaseCommand {

    public function actionListOrders() {
        $c = craft()->elements->getCriteria(ElementType::Entry);
        $c->section = 'orders';
        $c->limit = 5;
        foreach($c as $o) {
            print $o->id . ": " . $o->title . "\n";
        }
    }
}

prints nothing, even though there are entries present for the default locale en.

Printing out the query object print_r(craft()->elements->buildElementsQuery($c)); shows the :locale parameter being passed to the sql query as en_us. But this locale doesn't even exist for the site (select * from craft_locales shows only en).

The only way I could find to work around this is by adding the site's default locale to the criteria manually with:

$c->locale = craft()->i18n->getPrimarySiteLocale();

However, since the query works find without this when run in a controller, I'm skeptical that it should be needed. Is this is a bug, or is there some extra configuration i'm missing? Having some parameter to specify the locale to use for commands would make sense in mutli-locale environments, but I would still expect the default to be the site's default rather than en_us.


texts: Is it possible to reassign an existing event from one Solspace Calendar to another ?

texts:
Let's say I have an existing event called "My Event" on a Solspace calendar called "Social".

Is it possible to reassign "My Event" to a different calendar eg: "Sports" - without deleting "My Event" from "Social" & recreating it on "Sport" ?