texts:
I understand the implications of having a script tag in my redactor field.

But I am importing approx. 5k articles in to a Redactor field, some of which have various  tags from embedded Podcasts, Twitter cards etc.. These are obviously getting stripped out.

(It's not possible for me to go through all of the entries and break out those embeds in to a Matrix style set etc..)

So I need to be able to edit the HTML Purifier config to allow these tags.

My /config/htmlpurifier/config.json file looks like below but I am not having any luck.

{
    "Core.AggressivelyRemoveScript": false,
    "HTML.SafeScripting": ["script"]
}

And my Redactor config:

{
  "buttons": ["formatting", "bold", "italic", "unorderedlist", "orderedlist", "link", "image", "video", "html"],
  "plugins": ["fullscreen", "video", "clips", "table"],
  "linkNewTab": true,
  "toolbarFixed": true,
  "allowedTags": ["script"]
}

Has any ever managed to get Script tags to work and can offer some guidance here? There's a few other Script related configs here http://htmlpurifier.org/live/configdoc/plain.html I've tried all of them.

Example of an embed in one of my imported articles.

<script src="https://www.buzzsprout.com/xxxxxxxxxxx" type="text/javascript" charset="utf-8"></script>

I've seen other questions similar to this but no real solution other than put script tags in plain text etc.. but this is not an option in this case. Thanks!


texts:
I am using an entry's slug as the anchor for a page.

How do I grab the anchor from the request?
For example I want to get #article-one from /blog/#article-one

If it's not possible, is there a way to grab the full URI /blog/#article-one including the hash?


texts: Why are my profile pages not generating which I click on 'submit'?

texts:
does anyone know what I am doing wrong here? I am trying to create profile pages for each user, but when I click the submit button, it doesn't take me to the user's page.

This is my form code:

<form method="get" accept-charset="UTF-8" class="form"    action="/profile/{{ user }}"> <input type="hidden" name="action" value="users/login">

<input id="loginName" type="text" name="loginName" placeholder="username"
    value="{{ craft.session.rememberedUsername }}">

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

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

    <input type="checkbox" name="rememberMe" value="1" checked>
    Remember me

{% if errorMessage is defined %}

{{ errorMessage }}

{% endif %}

I have a profile folder and an _profile template. I also added a custom route in the admin panel with the following URI

    profile/*

And a link to the template

    profile/_profile

The profile index file looks like this:

{% set users = craft.users %}
{% for user in users %}
{{ user }}
{% endfor %}

And the _profile file looks like this

{% extends "_account_register_layout" %}
{% set title = "account" %}
{% set user = craft.users.username( craft.request.segment(2) ).first() %}


texts:
I'm working on a webshop that should have an integration with Mollie to provide the payment methods. Craft Commerce's docs mention that Mollie is already integrated by using the Omnipay interface.

Am I correct that Omnipay only provides a basic interface to communicate with various Payment Gateways (including Mollie) and does not include more concrete functionality, like getting the payment methods/issuing banks?

Basically, the code like below I still have to write myself? Or am I doing double work?

public function actionGetPaymentMethods()
{
    $this->requireAjaxRequest();

    $paymentResponse = $this->gateway->fetchPaymentMethods()->send();

    if ($paymentResponse->isSuccessful()) {
        $paymentMethods = array();
        foreach ($paymentResponse->getPaymentMethods() as $paymentMethod) {
            $paymentMethods[] = array(
                'id' => $paymentMethod->getId(),
                'name' => $paymentMethod->getName(),
            );
        }

        $this->returnJson($paymentMethods);
    }

    $this->returnErrorJson('error');
}


texts: How can I add a dynamic number of rows to a matrix via plugin?

texts: I would like to have a front-end profile form on my website that contains a matrix field. The matrix field will allow the user to add an infinite number of awards they have earned. How can I do this?


texts: How do you create a custom button field type (with js includes) for customizing the CP?

texts:
I'm trying to figure out how to integrate Stripe into the CMS more natively, and a thought occurred to me. Would it be possible to create a fieldtype that was just a button (i.e. no data being stored) with its own javascript?

This would potentially allow you to add a lot of customization and functionality just by adding the button fieldtype to the field layout (rather than having a global javascript file throughout the CP) — like silently submitting data to an external service, handling the response, dynamically rewriting the CP form submit action temporarily to point to a custom controller, etc.

Bad idea? Or worth investigating?


texts: Craft or Twig converting html tags to alt characters

texts:
Just starting with plugin development. I modified the code from pluginfactory.io for a custom tag:

public function navHTML()
{
    $result = '
Hello again
';
    return $result;
}

and I am getting output. The issue is the html tags are being converted to alt characters. Here is the actual source of my index page:

&lt;h2&gt;Testing&lt;/h2&gt;

IT looks like Craft or Twig is converting the tags to alt characters. I need to create an unordered list html using the plugin. How do I prevent Craft or Twig from converting the HTML to alt characters?


texts: Absoute urls for assets in rich text fields

texts: Is it possible to output asset urls, specifically an image url, as absolute from a rich text field? It looks like craft is automatically changing it back to a relative url.


texts:
I have a field in a channel called "weight" where the user can set a number between 0-1000. On page load I want to generate a random number between 0 and "weight" for each entry, and then sort the entries based on these numbers.

How can I do this with Craft 2/Twig?


texts: Default to only showing 'Live' entries in CP?

texts:
I'm finding that the structures view in CP is really slow with the amount of entries I have in it. The vast majority of these will be in draft for some time yet, however. I've had a look through the source of craft.js and hacked it a bit to just show the live entries by default just to see what would happen. The result is the CP is way more responsive in this view but obviously the status button doesn't reflect the right view any more and it's not a good idea to be doing this anyway.

Is there scope to make this configurable via a plugin or something?


texts: Search entries AND within associated assets fields

texts:
I have a large list of entries. Each entry has a a bunch of fields and a file-field with one or two files. Those files have related field (Author, Date, ..).

I have now implemented a search. All things are working so far. However, the search does not include the asset's fields. Only the asset's title is recognized.

Can I somehow search in asset fields? I tried something like

field1: *query* AND files.author: *query*

but this does not work :(

I have read that I can search all assets that are related to that section, but I would like to include this query in one query than in two queries..


texts: Click read more on a single and it takes you to items in a structure

texts:
Hey guys I was wondering if anyone could help me...

I am trying to link from a readmore button in a single( it's like a services page) to pages in a structure.

So instead of having a top level services page in the structure, having it as a single and all the services together in a structure and linking to them from the single is this possible? if so, how can i do it?


texts:
Part of our go live process is to put caching in place for the site. It is a great feature. But I am unsure on the best strategy, not from a technical perspective but from a non-technical cms editor perspective...

For example, we usually setup the cache on the header and footer includes on our templates. I like to set it up for 1 hour, that way it will clear reasonably often. That way if the editor changes some header or footer markup they just need to wait an hour for the new content to appear. Which brings me to the issue, our cms editors find this all a bit confusing, they are never sure what will be cached and what won't, if you show them how to clear the cache they end up doing it almost every edit just to be sure. Or they make edits and when it doesn't look they way they want they think it must be the cache and leave it looking odd for days before they admit something must be wrong.

So how do other people deal with this? I am thinking we might write a plugin to clear the entire cache on any entry save or structure modification. But this seems a bit crude.


texts: I have 900 entries that I have imported via the excellent import plugin. I need these to be set as draft (or 'disabled' status). Is there any way I can do this programatically? I don't fancy doing it manually.


texts: Craft queued tasks take up a lot of memory

texts:
Is it normal that my website crashes when a few background processes (think Feed me, but also image transformations after uploading images) use up so many resources that my app on Fortrabbit crashes and gives a 504?
Server specs are:
4 PHP processes
256 MB PHP Memory
5 GB Web storage
512 MB MySQL storage


texts: How do variables, services and models fit together?

texts:
I am new to Craft and have been attempting to write  a plugin but keep getting stuck on how to read and write to the database. I have been working through cocktailrecipesPlugin and am attemting to use it to better understand how to do database CRUD. In this attempt I am replacing coctailrecipes with projectmanager, ingredients with staff, and ingredient with staffMember. The Cocktail Recipe plugin is confusing because it uses objects and properties with the same name and I am unsure if this is the required. I am having difficulty understanding how services and variable and models interact. It appears that services is where the property ingredient is defined, but I am puzzled. I wish there was better documentation explaining the interaction of the various components. I have been banging my head against the wall trying to understand the Craft api and how the pieces work together. The documenation seem sparse and the code sample in the documenation are snippets which make it difficult to understand how everything fits together. I wish the cocktailRecipiesPlugin was better explained.

Cocktail Recipes <=> Project Manager

ingredients <=> staff

ingredient <=> staffmember


texts: Is it possible to increase the Title character limit?

texts:
Simple use case: I have a channel that is setup solely to be used in an entries field to relate goals that are used on multiple pages. The goals channel simply has the title field, as the goals themselves are all one sentence statement and need to be easily identifiable by content editors for the site. Unfortunately, one of them is 268 characters, and the Title field has a limit of 255 characters.

So my question is - is there a recommended way to change the character limit for the title field? If it's in the database structure, where is it? (I will continue to dig through the database for this). If it's in config, is there a configuration override to do this so it doesn't get changed back every update, or a plugin?

Thanks!


texts: How do I select a default in the Position Select field?

texts:
Just getting around to adding advanced layout features to our site, when I say advanced I just mean floated images left & right. The problem I seem to have though is that left is always the default position.

There is a way around it if I disable left & right and use drop-left & drop-right but I think it would be more usable if we were able to set a default.


texts:
I've added many fields in the past with success but today, on my local MAMP server, after adding a new field to a Matrix and saving, I'm getting a PHP error when I try to view the entry's admin page, the page preview, or try to add a new entry.

Thankfully removing that field and saving gets me back to where I was. The CMS is up to date. Here is the error when trying to view the entry's admin, I can post more if it helps (the stack trace has 70+ errors in it):

When creating a new entry, the error is also on BaseOptionsFieldType.php but line 362:

if ($option['value'] == $value)

Would anyone have any ideas for getting around this? The field I want to add is a Lightswitch but I get the same error when trying a Plain Text field.


texts: Craft CP showing plugin updates, but already updated

texts:
This morning there were new updates for Craft CMS, Contact Form and Simplemap on a Craft Pro site I host. I updated everything through the Craft CP. After the update, the CP still shows available plugin updates. When I check composer.json everything is already updated.

I tried running ./craft update all through SSH, deleted caches, checked the OPcache settings with my hosting provider and checked the logs. Can’t find any reason why the CP shows plugin updates while everything is already updated.

I also contacted Craft support, and they suggested putting the question here. I hope anyone does have an idea what’s going on.

The server environment:

PHP 7.0.33
MySQL 5.5.5
Craft Pro 3.1.21.1
Yii 2.0.17

My composer file:

{
  "name": "craftcms/craft",
  "description": "Craft CMS",
  "keywords": [
    "craft",
    "cms",
    "craftcms",
    "project"
  ],
  "license": "MIT",
  "homepage": "https://craftcms.com/",
  "type": "project",
  "support": {
    "email": "support@craftcms.com",
    "issues": "https://github.com/craftcms/cms/issues",
    "forum": "https://craftcms.stackexchange.com/",
    "source": "https://github.com/craftcms/cms",
    "docs": "https://craftcms.com/docs",
    "rss": "https://craftcms.com/changelog.rss"
  },
  "require": {
    "craftcms/cms": "3.1.21.1",
    "vlucas/phpdotenv": "^2.4.0",
    "craftcms/redactor": "2.3.2",
    "rias/craft-position-fieldtype": "1.0.14",
    "craftcms/contact-form": "2.2.4",
    "ether/seo": "3.5.4",
    "ether/simplemap": "3.4.10",
    "nystudio107/craft-typogrify": "1.1.17",
    "matt-west/craft-recaptcha": "1.3.0"
  },
  "autoload": {
    "psr-4": {
      "modules\\": "modules/"
    }
  },
  "config": {
    "optimize-autoloader": true,
    "platform": {
      "php": "7.0"
    }
  },
  "scripts": {
    "post-root-package-install": [
      "@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
    ],
    "post-create-project-cmd": [
      "@composer dump-autoload -o",
      "@php craft setup/welcome"
    ]
  }
}


texts: Asset Uploading via Assets Field Broken, please help

texts:
*Update: Installed MAMP Pro, reinstalled Craft, asset upload is working now. Not exactly a fix, but seemed like the simplest route of action due to my unfamiliarity with PHP. Thanks to those who responded to my question.

I'm a newcomer to web development and Craft CMS. I've downloaded and installed Craft CMS locally and I'm following along with an "Up and Running With Craft CMS" tutorial to get my bearings.

I am unable to upload assets via an asset field. The upload box appears and after selecting a file to upload the progress bar fills and freezes and the loading wheel spins on forever. Due to this I can't upload any images and therefore can't create my site properly. Please help!


texts: How to add assets field to control panel plugin template

texts:
So, a date field can be added to a plugin template within the control panel using:

{% from "_includes/forms" import date %}
{{ date({
        id: 'fields-invoiceDate',
        name: 'fields[invoiceDate]'
}) }}

But how do you go about adding an assets field a similar way?


texts: How to get Assets to remember last folder in file chooser?

texts:
In Assets for ExpressionEngine the file chooser will remember the folder from which an image was last selected, even if picking images from across instances of Assets fields in different Matrix rows. It saves a lot of time when populating large galleries such as in a photographic portfolio.

The same thing doesn't seem to be true of Assets in Craft though - each time I open the file chooser, unless it's the same Assets field I'm adding to or replacing into, I have to go from the root folder and find the correct sub-folder again.

I guess I'm hoping there's a nifty config item somewhere which will set 'remember last folder' to true...?


texts: Search results home page title not showing properly but other pages do?

texts:
Usually Google search results shows the <title> value as the title on the results, but with a CraftCMS website it shows the websites name with a colon and removes the last segment? I've checked on another CraftCMS website and the same thing is happening.

Code: <title>Book Store | City Name | Something</title>

Google Results: (Whats happening currently)

  MyBookCompany: | Book Store | City Name

Google Results: (What it should be)

  Book Store | City Name | Something

All other pages of the website meta title renders properly on their searched page. The DOM shows the code title correctly. Using no plugin and this dates latest CraftCMS version. How do I remove this default behaviour that is happening only on the home page?


texts:
On Craft 2.x, is it a known limitation that we must allow unsafe-inline for script-src in the Content-Security-Policy? My admin dashboard fails to load when I don't allow it.

...Trying to get a high grade on Mozilla Observatory :)


texts:
I'm trying to pull in the contents of a matrixField block and merge it with some default info —

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

{% for interview in interviews %}

    {% set blocks = interview.thumb %}
    {% for block in blocks %}

        {% set options = block|merge({
            'class': 'episode',
            'more': 'Listen to this interview...',
            'slug': craft.request.firstSegment,
            'linkUrl': interview.url,
        }) %}

        {% include '_includes/blocks/half-block.html' with { options: options } %}

    {% endfor %}
{% endfor %}

I get the error: Key "body" for array with keys "id, enabled, archived, locale, localeEnabled, slug, uri, dateCreated, dateUpdated, root, lft, rgt, level, searchScore, fieldId, ownerId, ownerLocale, typeId, sortOrder, collapsed, class, more, reverse, linkUrl" does not exist

Why am I getting block with the values of the entry instead of that single block of type thumb?

(where thumb has a field called body)

I had tried {% set block = interview.thumb.first() %} instead of {% set blocks = interview.thumb %}{% for block in blocks %} but was trying to be more explicit to see if it made a difference.


texts: Does craft have any build in function for countries like locales?

texts:
I'm wondering if there's a build in craft function for displaying countries (countryCode and/or name)?

Just like it is for displaying locales:

craft.i18n.getAllLocales()


texts: Is there a way to define my plugins Record start ID? Now it start with ID 1, and for various reasons I would like to define a starting number.


texts: Filtering list in CP index page for new ElementType

texts:
I've created my first new ElementType based on the Events example. The only thing which doesn't seem to be working is the search bar above the listing in the CP. When I type anything into it I just get a blank results returned.

I think it's something to do with me not using Titles, I'm using a property on the Model called name instead. I had to override the __toString method in the model to get it to populate the first column in the listing, so I'm guessing there is some way to also overriding what is used by default for the search as well. Is that the case, and if so how do it do it?


texts: Programmatically remove fields from a layout

texts: I've created a migration that copies the values of a few fields into a new matrix block. Once the migration is done, I'd like to remove the original fields from the layout. Is there a concise, documented way to do this? I found this example but it looks like it's a bit out of date since assembleLayout has been deprecated and I'm wondering if there's a better way to do it in 3.5.


texts: Is it safe to mass delete users from the database directly

texts:
We have a client site that has been getting a lot of spam registrations. We're turning on purgePendingUsersDuration to help deal  with some of these automatically, but I was planning to go into the database to delete a bunch in bulk directly (since there are almost 200 of them)

Is it safe to delete them just from craft_users and craft_usergroups_users tables? Are there other places I should watch out for?


texts:
404 page doesn't have a title. It shows "| Sitename" in my case.

I'm using Craft 3 with the SEOmatic plugin and would like to set the title in the 404 template.

{% set seomaticMeta = seomaticMeta | merge({ seoTitle: '404 page not found' }) %}

This gives a internal server error, looks like the seomaticMeta object is not available on the 404 page.


texts: $event->isNew not working as expected after Craft 3.2 update

texts:
Pre Craft 3.2, you could do something like this if you wanted to perform an action in the event you just saved a new entry:

use craft\elements\Entry;
use craft\events\ModelEvent;

Event::on(
    Entry::class,
    Entry::EVENT_AFTER_SAVE,
    function(ModelEvent $event) {
        $entry = $event->sender;
        $isNew = $event->isNew;

        if ($isNew) {
            // do something...
        }
    }
);

However, after the update, this code doesn't work as it used to. $isNew always gets evaluated to true whether resaving a pre existing entry or editing a yet-to-be-saved entry (the autosave kicks in after a couple of seconds while you're editing).

I've tried doing something like this to check if the entry is being resaved but it still gets evaluated to true:

$isBrandNew = false;
if ($event->isNew && ! $entry->propagating && ! $entry->resaving) {
    $isBrandNew = true;
}

if ($isBrandNew) {
    // do something
}

How do I fix this so that my code only runs after a brand new entry was just created, like it did before Craft 3.2?


texts: Craft 3 with Multi-Site: how to not set a primary site, or add a first segment to all primary site URLs?

texts:
I have a main domain, www.mycompany.com, which has several groups of sites, which are available in several languages:

www.mycompany.com/international

www.mycompany.com/sales/en
www.mycompany.com/sales/fr

www.mycompany.com/customers/en
www.mycompany.com/customers/fr

etc.

Once visitor access to www.mycompany.com, he will be auto-redirected to a Site version depending on his IP (probably using a third-party plugin like Country Redirect, once available for Craft 3).

The problem is that when I set up the Sites, Craft force to set a primary Site. So I choose the www.mycompany.com/international version.

But when Site is saved, the Base URL is displayed as www.mycompany.com instead of www.mycompany.com/international, and all URLs in this one are now like www.mycompany.com/my-slug instead of www.mycompany.com/international/my-slug.

This probably can be solved by pre-checking all links, adding the slug inside the URL if current Site id is the www.mycompany.com/international version, then adding a routing rule for all /international/* requests.

But it sounds a bit tricky in the some cases, so I wondered if there was a cleaner way to achieve this?


texts: Insert a url segment without creating sections

texts:
I have a very simple site split into sections. All pages use just one template.

The previous site had sections such as /section/subject.  I had thought I could have all entries in just one section and then alter the URL on each entry to include a 'pretend' section /section/{slug}, but this defaults to /section-subject.

Is there a way to have /settings/subject/ without creating new sections?

Many thanks

Martin


texts: Help! Craft issues after changing PHP version

texts:
We have an install of the latest Craft on a Nexcess shared account. By default, the account runs PHP 5.4.x. We were working on and configuring the site for about a week - no issues of any kind until today. We used the Nexcess control panel to update the PHP version to 5.6.3 (for a plugin we were going to use). After doing so, we found that saving entries or certain configuration elements in settings would take 5+ minutes to complete. We downgraded back to 5.4.x and still the behaviour persists. Unfortunately, it does not seem to be 100% consistent. I would say it happens about 90% of the time and cannot find any common thread as to when it happens and when it does not.

Saving one entry is generating about 1.4 MB of Craft log files:

Craft Log 1

Craft Log 2

Beyond the Craft logs, I don't see a php error in the PHP logs but there are these Apache errors when saving the entry:

[Fri May 05 07:28:46 2017] [error] [client xx.xx.xx.xx] FastCGI: incomplete headers (0 bytes) received from server "/dev/shm/cadexdev-php.fcgi", referer: http://www.cadex-dev.ca/shop/admin/entries/multiUse/new

I don't know if this is host-related. I do have a ticket open with Nexcess but am not certain if this is something specific to Craft instead?

EDIT:
Also, a curious behaviour around this issue. If I save an entry and only wait, say, 20 seconds, quit my browser and then re-open and go to the entries page, the entry is there with the saved changes. No 5+ minute wait.


texts: Is there a way to make conditional input fields in Craft CMS?

texts: I'd like to use conditional fields in my CMS instance. I found an old plugin called Reasons. I'm not sure it's compatible with Craft 3, so I'm looking for a workaround.


texts: Setup default Matrix blocks and default values for sub-fields?

texts:
Question is
what table can't achieve, can be achieve by matrix but problem is matrix cannot have default row value like table have.

Anyway to achieve it?
Thanks.


texts: Setting User's Groups - Integrity Constraint Error

texts:
$groupIds = [1, 2];
craft()->userGroups->assignUserToGroups($user, $groupIds);

When executed I get the following error:

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 (`letshacklondon2016`.`craft_usergroups_users`, CONSTRAINT `craft_usergroups_users_userId_fk` FOREIGN KEY (`userId`) REFERENCES `craft_users` (`id`) ON DELETE CASCADE). The SQL statement executed was: INSERT INTO `craft_usergroups_users` (`groupId`, `userId`, `dateCreated`, `dateUpdated`, `uid`) VALUES (:row0_col0, :row0_col1, :row0_col2, :row0_col3, :row0_col4), (:row1_col0, :row1_col1, :row1_col2, :row1_col3, :row1_col4). Bound with :row0_col0=1, :row0_col1=Craft\UserModel::__set_state(array('elementType' => 'User', ... (etc.)

Any Ideas?


texts: Missing entries if order of entries is changed

texts:
I'm having a very bizarre problem and was wondering if anyone else has had this happen. I have a page displaying thumbnails of product sheets.

My loop code starts with this:

{% for entry in craft.entries.section('resources').order('title asc') if entry.industry.label == "Healthcare" and entry.documentType.label == "Product Sheet" %}

If I leave it like this, I am missing the last three entries alphabetically (they start with V, W and Z).

If I change it to be descending order by title instead of ascending, I get all but one entry.

And if I change the order to be based on a field I have called lastUpdated, it will show all of the entries.

With the above loop code, if I change the names of the missing three entries to have earlier letters in front of them (i.e. changing Value Care to AValue Care), all entries will appear and no additional entries will fall off.

This is such a strange problem, and I feel like I'm crazy. Has anyone else seen something like this happen?


texts: How to remove the default cart notice after adding the line item?

texts:
I'd like to remove the default notice (Cart updated.) after adding the item into the cart. I have an event for checking the product with the warehouse system and have an error message for showing to the user, but It shows both notices (the default notice + my custom error), and here is the event:
Event::on(Order::class, Order::EVENT_AFTER_ADD_LINE_ITEM, function (LineItemEvent $event) {

    if(!$sarehouseStock) {

         Craft::$app->getSession()->removeAllFlashes();
         Craft::$app->getSession()->removeAll();
         Craft::$app->getSession()->setError(Craft::t('site', 'System error to get the stock from warehouse system, please contact administrator.'));

         Craft::$app->getResponse()->redirect(Craft::$app->getRequest()->getAbsoluteUrl())->send();

    }

});


texts:
I'm trying to create a structure using onBeforeInstall() that will be ready for a client to use after the plugin is installed.

Here's my code for onBeforeInstall():

public function onBeforeInstall()
{
    $section = new SectionModel();
    $section->name = 'Demo';
    $section->handle = 'demo';
    $section->type = 'structure';
    $section->hasUrls = 1;
    $section->template = 'demo/page';
    $section->enableVersioning = 1;
    $locale = craft()->sections->getSectionLocales(1)[0];
    $locale->urlFormat = 'demo/{slug}';
    $locale->nestedUrlFormat = '{parent.uri}/{slug}';
    $section->setLocales([ $locale ]);

    $response = craft()->sections->saveSection($section);
    if ($response) {
        var_dump("IT WORKED!");
        var_dump($response);
    } else {
        var_dump("nope.avi");
        var_dump($response);
    }
}

Unfortunately I get a 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 (`craft`.`craft_sections_i18n`, CONSTRAINT `craft_sections_i18n_locale_fk` FOREIGN KEY (`locale`) REFERENCES `craft_locales` (`locale`) ON DELETE CASCADE ON UPDATE CASCADE). The SQL statement executed was: INSERT INTO `craft_sections_i18n` (`sectionId`, `locale`, `enabledByDefault`, `urlFormat`, `nestedUrlFormat`, `dateCreated`, `dateUpdated`, `uid`) VALUES (:row0_col0, :row0_col1, :row0_col2, :row0_col3, :row0_col4, :row0_col5, :row0_col6, :row0_col7). Bound with :row0_col0='7', :row0_col1=0, :row0_col2=1, :row0_col3='demo/{slug}', :row0_col4='{parent.uri}/{slug}', :row0_col5='2015-06-09 20:33:00', :row0_col6='2015-06-09 20:33:00', :row0_col7='864207ba-6e43-46cf-9fdb-3a72cda4c2df'`

I was basing my code loosely on this Stack Exchange question and answer, but for some reason I can't get structures to cooperate.

I think I'm not setting the locale properly.  Is there a better way to set the locale, or am I overlooking something else?


texts: How to upload an asset from a front-end form

texts: I've found information on how to upload an asset as part of creating an entry. What I am trying to do is upload an asset from the frontend without creating an entry. I have a logged in user, and what I would like them to be able to do is upload an asset to a folder that is unique to that user (folder name = username). Help?


texts: GZIP seems to compress only HTML, not CSS or JavaScript

texts:
I'm not 100% sure this is a Craft specific problem, but I'll try here, as it relates to a Craft installation.

After running a number of tests, it seems that my CSS and JavaScript files are not getting GZIP-ed. I have a .htaccess file in my public folder, and no .htaccess files in the subfolders below. My CSS and JS files are stored in /assets/cssand /assets/js respectively (relative to the publicfolder).

My .htaccess file looks like this. Is there something I'm doing wrong? I thought the settings of the .htacces should work for subfolders when not overridden?

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteOptions InheritDown

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

<IfModule mod_deflate.c>
  AddOutputFilterByType DEFLATE application/javascript
  AddOutputFilterByType DEFLATE application/rss+xml
  AddOutputFilterByType DEFLATE application/vnd.ms-fontobject
  AddOutputFilterByType DEFLATE application/x-font
  AddOutputFilterByType DEFLATE application/x-font-opentype
  AddOutputFilterByType DEFLATE application/x-font-otf
  AddOutputFilterByType DEFLATE application/x-font-truetype
  AddOutputFilterByType DEFLATE application/x-font-ttf
  AddOutputFilterByType DEFLATE application/x-javascript
  AddOutputFilterByType DEFLATE application/xhtml+xml
  AddOutputFilterByType DEFLATE application/xml
  AddOutputFilterByType DEFLATE font/opentype
  AddOutputFilterByType DEFLATE font/otf
  AddOutputFilterByType DEFLATE font/ttf
  AddOutputFilterByType DEFLATE image/svg+xml
  AddOutputFilterByType DEFLATE image/x-icon
  AddOutputFilterByType DEFLATE text/css
  AddOutputFilterByType DEFLATE text/html
  AddOutputFilterByType DEFLATE text/javascript
  AddOutputFilterByType DEFLATE text/plain
  AddOutputFilterByType DEFLATE text/xml
</IfModule>


texts:
I'm setting up my first multilingual website with Craft. I'm struggling with multilingual slugs.

This is how I'd like the slugs to look like.

If I do this tough, I need to adapt my folder structure. To get it working I needed to create folder structure like this

/fr/nouvelles/
/en/news/

both containing the same templates.

Is it possible to get this working without needing to copy the templates? I'd like to always load the same template(/news/), without the language specific folder structure.


texts: How do I cache with the ElementAPI plugin?

texts:
I'm replacing some templates with the ElementAPI plugin.

In my templates, I would use the cache tag, and rely on Craft to handle invalidation when the elements changed.

How can I achieve a similar thing now that I'm using the ElementAPI plugin?


texts: Default Upload Location for asset fields on a User...?

texts:
when setting a Default Upload Location for a field that’s attached to a User, what’s the variable to use that would ensure the file is uploaded to the User I’m editing’s account in the back end, and not my admin user account - which is what {{currentUser.username}} does?

I haven't been able to find out and everything I've tried hasn't worked. e.g., Could not resolve the subpath “{user.username}”. And {{ user.username }} uploads to a folder for my admin account.


texts: How do you pull a entry field in a global out in a template

texts:
I am trying to create an easy way to make a sticky post on my blog and I am using an entry field within a global.

Not sure where to even start to pull this out in a template.


texts: Rich text field adding   and normal space char at random

texts: Is there any rhyme or reason to the adding of non-breaking spaces or traditional space? It seems to appear at random throughout the content in my rich text fields.


texts: How to structurize a multi-project documentation site?

texts:
I'm currently working on our new Docs website. This site should hold the documentation for all our projects.

I thought I could structurize the content like this:

Project 1 (<-- Section)
    Project section header 1 (<-- Structure)
        Menu item 1.1
        Menu item 1.2
        Menu item 1.3
        Menu item 1.4
        Menu item 1.5
    Project section header 2
        Menu item 2.1
        Menu item 2.2
        Menu item 2.3

Project 2 (<-- Section)
    Project section header 1 (<-- Structure for Project 2)
        Menu item 1.1
        Menu item 1.2
        Menu item 1.3
        Menu item 1.4
        Menu item 1.5
    Project section header 2
        Menu item 2.1
        Menu item 2.2
        Menu item 2.3

I'd also like to have a dropdown which should list all available projects (Project 1, Project 2, ... from the above sample). If the visitor selects his desired project, a menu tree should be rendered in the sidebar with the corresponding structure.

Is this the right way?


texts:
Craft Pro 2.4.2702

Experiencing an intermittent issue with a Craft site that randomly crops up. It always seems to occur randomly with the caching and the "www" prefix and URLs being cached.

In a Redactor WYSIWYG field, this is the markup.

Privacy Policy

Randomly at times the page, the page URL links will be cached like so. Notice the eww.mysite.org. I've seen other instances where it's been ww.mysite.org/page-url, eee.mysite.org/page-url, htp.mysite.org, wee.mysite.org for all URLs that are being cached in the craft_templatecaches table. The urls are generated by entry.getUrl(), but also are manually typed in using a WYSIWYG field.

With my previous example, this is how it's being cached in the database
Privacy Policy

Majority of the caching on the site is done like so.

{%- cache globally unless craft.config.devMode -%}
...
{%- endcache -%}

At first I thought this might have been the wildcard in the DNS (*.mysite.org) and the page was still resolving with any prefix value and the URLs were being cached like so. I since then have removed the wildcard from the DNS, the page no longer resolves with an incorrect prefix, and this issue seems to pop up randomly.

In my general.php config.

define('URI_SCHEME',  ( isset($_SERVER['HTTPS'] ) ) ? "https://" : "http://" );

define('SITE_URL',    URI_SCHEME . 'www.' . $_SERVER['SERVER_NAME'] . '/');

Htaccess file.

# ----------------------------------------------------------------------
# Rewrite Craft URLs to remove index.php
# ----------------------------------------------------------------------

    RewriteEngine On

    # ----------------------------------------------------------------------
    # Force "www." to beginning of URLs
    # http://stackoverflow.com/questions/4916222/htaccess-how-to-force-www-in-a-generic-way
    # ----------------------------------------------------------------------

        RewriteCond %{HTTP_HOST} !^www\. [NC]
        RewriteCond %{HTTP_HOST} ^mysite.org [NC]
        RewriteCond %{HTTPS}s ^on(s)|
        RewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [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]


texts: Performance of a categories list with post count

texts:
Let's say I'm outputting a list/nav of categories, with the count of entries in each category, as described in other questions:

{% nav category in craft.categories.group('...') %}
   {% set entryCount = craft.entries.relatedTo(category).total() %}
   {{ category.title}} ({{ entryCount }})
{% endnav %}

On a site with plenty of categories (more than 100 in this case), that seems like a lot of relatedTo queries. Is there a way I could accomplish the same thing with fewer queries / better performance?


texts: Caching Issue "unserialize(): Error at offset 0 of 24 bytes"

texts:
I have never gotten this before when using Craft cms this is the first.

When trying to load my site (locally), I am getting this message

unserialize(): Error at offset 0 of 24 bytes

I have attached some screenshots of what I am getting in more detail

What am I suppose to do to fix this?


texts: Does setting Enabled = 1 override postDate in front end forms?

texts:
I have a front end form where I set have

<input type="hidden" name="enabled" value="1">

I also need to set the postDate to a date in the future. Does setting enabled = 1 reset the postDate in all cases? Or should I just forego the enabled form field altogether in favor of Setting postDate?


texts: valet share, ngrok giving 404, CORS errors

texts:
I have a Craft instance running via Valet, per the instructions here.

Running the project via valet link works great, and valet share works, except when I try to access the admin side. I'm using valet share to try to access the site over a local network for a demo.

In Chrome from http://ad3f5068.ngrok.io/admin/login when I try to log in, I get:

OPTIONS http://craftycoffee.test:60/index.php?p=admin/actions/users/login 404 (Not Found)
Access to XMLHttpRequest at 'http://craftycoffee.test:60/index.php?p=admin/actions/users/login' from origin 'http://ad3f5068.ngrok.io' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

If I use HTTPS, I get net::ERR_SSL_PROTOCOL_ERROR across a bunch of requests.

What am I missing to get this to share over a local host?


texts: Easy way to stage template updates for a live site

texts:
Im curious if folks have found an easy way to stage template updates for a craft site thats already live.

Locally we have branch in the repo for the new version which works fine but on the server if we want to share them with the client ideally wed just use stage.sitedomain.com or something

Right now we are replicating the whole craft setup in a different location for a sub-domain and just sharing the database, is there a way to share a craft folder and just have a different templates folder?

Eventually looking to move some of this to vagrant cloud for staging environments but not quite there yet


texts: What's the easiest way to update an entry from the front end as a guest user and only post the data that needs to be updated?

texts:
I'm creating a multi-page form on the front end of a site where different data is added to the entry depending on the page they are on. Originally I was going to create the entries using P&T's guest entries, but that doesn't allow the user to edit an entry once it's submitted, so I created a plugin based on this question to handle saving the entry as a user with sufficient privileges.

The problem I'm having is that once a user submits new data from the front-end that doesn't include the data already saved to the entry, the previously saved information is erased. I am hoping to avoid including the existing data on each submission to keep things easy.

Is there a way to use something similar $entry->setContentFromPost('fields'); while updating existing entries?

Controller code:

class Plugin_Controller extends BaseController
{
    /**
     * @var Allows anonymous access to this controller's actions.
     * @access protected
     */
    protected $allowAnonymous = true;

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

        $entryId = craft()->userSession->getState('entryId');

        $entry = craft()->entries->getEntryById($entryId);

        if (!$entry)
        {
            // Fields
            $entry = new EntryModel();
            $entry->sectionId  = 1;
            $entry->locale     = 'en_us';
            $entry->postDate   = date('Y-m-d');
            $entry->authorId   = 1;
        }

        // Tell our content model where to look for custom fields
        $entry->setContentFromPost('fields');

        // Content
        $entry->getContent()->title = "Title";

        // Save the entry content
        craft()->entries->saveEntry($entry);

        $this->redirectToPostedUrl();

    }

}

Front-end Form

<form method="post" accept-charset="UTF-8">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="plugin/saveEntry">
    <input type="hidden" name="redirect" value="/builder?step={{ nextStep }}">
    <input type="hidden" name="title" value="{{ title }}" />
    <input type="hidden" name="sectionId" value="1">
    <input type="hidden" name="enabled" value="1">
    <input type="hidden" name="fields[matrix][new1][type]" value="service">
    <input type="hidden" name="fields[matrix][new1][enabled]" value="1">
    <input type="hidden" name="fields[matrix][new1][fields][entry]" value="">
    <input type="hidden" name="fields[matrix][new1][fields][entry][]" value="{{ entry.id }}">
    <button>Update</button>
</form>

Any thoughts on how I could accomplish this with the least amount of non-core code possible?


texts: Override the language-part in URL and add a region (en-fr / fr-fr)

texts:
I ran into a problem one year ago, but our we changed the specifications and so it was not neccessary anymore(another question here commented).
One year later now, the issue is back, harder as before and i have to solve this problem and do not know how or if it is even possible.

I am faced with the problem of integration regions into my url/entries. I thought i can use categories or lightswitches to set active regions in backend per entry. In the entry template, i check the languages for this entry and the active regions and i build up some correct links/urls.
Hard to understand, so here an example:
Entry 1 is available in 2 languages (en/fr) in 1 region(fr). So i need this Urls:

www.domain.tld/en-fr/entry1/
www.domain.tld/fr-fr/entry1/

I set up 2 sites/languages (en/fr). so entry 1 is now available as:

www.domain.tld/en/entry1/
www.domain.tld/fr/entry1/

Now i am stuck, because i do not know how to make "en-fr" possible instead of "en". The region in the URL should be available in template(so i can decide what is happening here based on the current region). This could be realized by getting the current URL and splitting, or by rewriting and parse the region-part as a parameter (www.domain.tld/en/entry1/?region=fr | www.domain.tld/fr/entry1/?region=fr), or by craft itself maybe (routing-hook).

I do not find a solution inside the craft configuration or hooking.

htaccess-rewrite is nor working like i expect.

And craft itself has no opportunity to define a siteUrl twice. ('fr' => getenv('CRAFTENV_BASE_URL') . 'fr' is set up, but i would need 2 definitions for the language "fr", so both urls would be possible:

[ 'fr' => getenv('CRAFTENV_BASE_URL') . 'fr', 'fr' => getenv('CRAFTENV_BASE_URL') . 'en-fr' ]

Setting up more sites so we can use the site-handle as "en-fr" / "fr-fr" was already tested, it should work, but we have to edit so much sites in an entry and would have so much identical content, this should not be neccessary, it is not a good solution to handle the content.

Has anyone an idea or tip for me how to solve this issue ?


texts: Loop index inside a switch content builder

texts:
How would one construct this? I have built a little content builder and wish now to change the layout HTML on the fly when there are more than one matrix block.

In the example below, this is just one section of the builder and the one I would like to change.

Basically 'move' the block.text part above the image every 2nd time in the loop. I have looked at batch and loopindex but having trouble for the last few hours. Can someone please help with this?

Builder code:

{% case "splitImageAndText" %}

        {% set images = block.imagePart %}

        {% if images and images|length %}
            {% set image = block.imagePart.all() %}

            {# Loop through the images #}
            {% for image in images.all() %}

            {% endfor %}
        {% endif %}

            {{ block.textPart }}


texts: Using element queries in general.php config file

texts:
Can i use element queries in general.php file? I wanted to set loginPath based on entry query, like this:

'loginPath' => Craft::$app->entries->section('login')->one()->url ?? false,

Hovewer, i get error:

( ! ) Fatal error: Uncaught Error: Class 'Craft' not found in C:\xampp\htdocs\xxx\config\general.php on line 40


texts: Entry element query missing user field data when user is suspended

texts:
I have a channel in which each channel entry has a "users" field type that is limited to one user. My code below works fine when the user is not suspended, however if I suspend the user, the then $entry->user field is null rather than set to the array of one user like its normally set to.

Here is my code:

        // do criteria code to get pending transfers from patients channel
    $account = $userIdentity->getFieldValue('account')->first();
    $entryQuery = Entry::find()
        ->section('networkAssets')
        ->relatedTo(['targetElement' => $account, "field" => "account"])
        ->orderBy('title asc');

    // Execute the query and get the results
    $entries = $entryQuery->anyStatus()->all();
    $assets = [];
    foreach($entries as $entry) {
        $user = $entry->user->one();
        $assets[] = [
            'id' => $entry->id,
            'slug' => $entry->slug,
            'title' => $entry->title,
            'email' => $user->email,
            'first_name' => $user->firstName,
            'last_name' => $user->lastName,
            'address1' => $entry->address1,
            'address2' => $entry->address2,
            'state_province' => $entry->stateProvince,
            'city' => $entry->city,
            'postal_code' => $entry->postalCode,
            'country' => $entry->country,
            'username' => $user->username,
            'password' => '',
            'status' => $user->getStatus(),
            'date_created' => $entry->dateCreated->format('m/d/Y') . "
" . $entry->dateCreated->format('H:i:s T'),
            'last_login' => $user->lastLoginDate ? $user->lastLoginDate->format('m/d/Y') . "
" . $user->lastLoginDate->format('H:i:s T') : 'Never',
            'phone' => $entry->phoneNumber
        ];
    }

    return $assets;

You can see in the foreach loop that Im getting the user from the looped entry result and storing it in a $user variable.

When I try to use $user I get a notice because $user is null.

How can I force this code to return the linked user in the user field even  when the user is suspended?


texts: Retrieve entries by random sort, then resort alphabetically

texts:
I need to pull X entries with

{% set randEntries = craft.entries.section('presenters').order('RAND()').limit(10) %}

But then sort them alphabetically on entry.lastName.

Do I need to Supersort for this, and if so, how do I apply it? Do I need to pull the entries first, and then run the sort?


texts: Still not able to manage tags in Craft 3?

texts: I have page where I display some items and there are filters by tag. So I make a list of all tags that are created. Then when the user click on some of the tag, he see only the product with that tag. Now I found out, that some of the tags are not used or written wrong. I want to delete them from the system. I found this question, that say it is not possible to done it in Craft 2. I am using Craft 3 is it possible to done it in the Craft 3?


texts: How to add time for repeats date with Solspace Calendar

texts:
I using Solspace Calendar on Craft 2. (I can upgrade for Craft 3 soon.)

How to add time for the recurring date?

My english not so good, sorry.

Thanks your help.


texts: How do I add next/prev controls to a blog?

texts:
I want to show the latest blog post on the blog/index.html page of my blog which I have done. I now want to display a link to the next post.

Likewise, when I click a blog entry's url I want to add next / prev controls to the blog/_detail.html page.

What is a simple way to accomplish this?


texts: Does Craft have an equivalent of EE's Custom Fields loop for front-end entry forms?

texts:
We're in the process of scoping out an online assessment form to be build in Craft CMS. We need to give the client the ability to add, edit and remove questions (custom fields) and would ideally like to handle all entries through a channel, rather than a dedicated form plugin. The thing I'm struggling with at the moment is how to render the field layout for a channel in my template. Expression Engine handles this using the {custom_fields} loop.

Is there an equivalent template tag for Craft CMS? Or would we be better of working with Freeform or SproutForms?

Any help would be much appreciated. Thanks.


texts: How to append 'Continue reading…' link within the last paragraph of the Excerpt

texts:
The code from the RichText documentation appends the 'Continue reading…' link in a new block and on a new line:

{% for entry in craft.entries.section('blog') %}
        {{ entry.title }}
        {{ entry.richTextFieldHandle.getPage(1) }}
        {% if entry.richTextFieldHandle.getTotalPages() > 1 %}
            Continue reading…
        {% endif %}
{% endfor %}

Any ideas how to append the 'Continue reading…' link inside the final
 tag generated by Redactor at the end of the final paragraph, i.e. as a continuation of the Excerpt text, and on the same line?


texts: Sprout SEO - Not all pages have a canonical tag

texts:
I'm using Sprout SEO on my site, and for some reason not all pages have a canonical url tag. Many pages have a canonical tag (the home page has one, for example), but a large number of pages are missing the canonical tag (many of my blog post pages, as an example).

I may be missing something, but I can't figure out how to get Sprout SEO to output a canonical tag for all pages. I tried adding:

{% do craft.sproutSeo.meta({
  canonical:  craft.request.url
}) %}

But this resulted in the same behavior - some pages had canonical tags while others didn't. I just need all my pages to output a canonical tag.

Thanks in advance for any help!


texts:
Im trying to do an OR filter for craft.entries and not sure of the syntax

so like this

{% set startedThisYear = craft.entries.find({ section: 'exhibitions', startDate: ">= " ~startDate, startDate: "<= " ~endDate, order:'startDate desc'}) %}

if i wanted it to be

startDate: ">= " ~startDate or startDate: "<= " ~endDate

??


texts:
I am brand new to Craft so excuse me if the question seems a little simple. Is this the best way to return the contents of a 'singles' section. Does everything end up in a for loop even if you are only returning a single entry.

{% for entry in craft.entries.section('sectionHandle').limit(1).find() %}
  {{ entry.title }}
{% endfor %}

Also I am curious if 'entry' in the for loop actually means anything or is just a good symantic name to use for example could you say

{% for oranges in ...%}{% oranges.title %}{% endfor %}


texts: Category Nav tag with control over the depth that {% children %} goes

texts:
Looking at the docs, i can see that the category {% nav %} loop uses the categoryGroup as the starting point. But, i want the first top level category within the category group as the starting point.

So, i want to do something like:

{% set categories = craft.categories.slug('my-first-top-level-cat).first().getChildren() %}

{% nav category in categories %}

        {{ category.title }}

 {% ifchildren %}

   {% children %}

 {% endifchildren %}
{% endnav %}

But, doing this only returns the top level, no sub levels.

Also, i want to be able to limit the amount of children output as the there are a few sub trees.


texts: Email template variables not rendering from plugin

texts:
I am loading an email template for custom registration via a plugin.
I reset the template path and load my template like this:

    $oldPath = craft()->path->getTemplatesPath();
    $newPath = craft()->path->getPluginsPath().'businesslogic/templates';
    craft()->path->setTemplatesPath($newPath);
    $bodyhtml = craft()->templates->render('emailreg.html', array(
        'user' => $user
    ));

In my html template ( an evil abomination of tables etc ) I am accessing the user variable {{user.firstname}} just fine. But the other variable $user->mycustomfield will not render - even though I can send it in the subject line, e.g.,

$email->subject = 'New User Registration: ' . $user->firstName . ' ' . $user->registrationNumber;

So whats up here?


texts: Passing optional variable values into an include template

texts:
Craft noob here. I have an include file which I'm calling a "component" so I can reuse it across the site.

The component is set up like this.

{{ heading }}

{{ bodyContent }}
{% if ctaUrl is defined %}
  Click
{% endif %}

Then on the template, I include it and pass some variables. In this case, the variables are from a Matrix field.

{% set matrixBlocks = entry.fullContentMatrix.all() %}

{% for block in matrixBlocks %}
    {% if block.type == 'imageRight' %}

        {% include '_components/imageRight' with {
            heading: block.heading,
            bodyContent: block.bodyContent,
            ctaUrl: block.ctaUrl
        } %}

...etc

This all works great. Until I have fields that are optional and have no value, in this case, the ctaUrl.

What is the best way to write this so that variables are only passed to the include if they are defined?


texts: Copy a Craft 3 site to my local machine (MAMP)

texts:
I have a client who started a Craft CMS site with another developer. I guess the other developer quit, and now the client wants me to make some changes to the site.

The site was created with Composer (which I haven't used before), and I'm stumped on how to get it installed on my local machine using MAMP. I ran Composer to install the dependencies, but there isn't a "Craft" folder and a "Public" folder like I'm used to seeing.

Here's a screenshot of the file structure.

Anyone have any advice on how to get this site installed locally so I can make the changes requested?

Thank you in advance!!


texts:
How can I display all entries in one page? I have a jobs Channel and inside of it there are 5 entries:

Title | Company  | Email
-------------------------
title1  company1   email1
title2  company2   email2
title3  company3   email3
title4  company4   email4
title5  company5   email5

I want it to be display in one page


texts:
I need to group and order member profiles alphabetically but I can't get it to work. Have a look here: http://ffsd.de.w0129b45.kasserver.com/mitglieder
(It's german but you should get the idea :))

In everything I tried either the groups are ordered correctly or the contents (profiles) of the group are… but never both. Here's the relevant code:

{% set allProfiles = craft.entries.section('members').order('profileLastname').limit(null) %}
{% for letter, profiles in allProfiles|group("profileAlphabet") %}

                    {{ letter }}

        {% for profile in profiles %}

{{ profile.title }}

        {% endfor %}

{% endfor %}

As you can see, I'd like to order the profiles by the custom field "profileLastname" and the groups by "profileAlphabet".

Any ideas?


texts:
Other than setting up a cron job, does Craft include any functionality for plugins to run a function at a specific time and/or date?

Some actions could include:

Bulk activate/deactivate entries
Messaging all users every monday (or once a week)
Hitting an API (account update, eCommerce, data updating etc.)

Let me know if a question like this already exists. I searched and couldn't find any related information.


texts:
I upgraded to Craft 2.1 and there is no Preview Button visible.

It must have something to do with the configuration I created for the different sections because when I use the same craft installation with a clean database the preview button is visible.


texts:
I uploaded a couple mp4 video files via FTP. One is 3.28GB, the other is 5.53GB. I updated Asset Indexes in Settings, but they are not showing up in Assets. I checked the DB and they do not show up there either. No errors are in the logs concerning them.

Any suggestions on how to get them to appear under Assets?


texts:
Is there an easy way in Craft 3 to get all missing translations for a certain language after they were piped through the translate TWIG filter?

{{ 'translate this text' | t }}


texts:
I tried to upgrade a website that I have to the latest version 2.6.2930 from an older 2.6.2804 and for an unknown reason the upgrade failed. I couldn't log in the administration area but the front end was working.

Now I tried to roll back to an old backup that I had 20 days ago. So I restored mysql database askitis.gr_160813_184933_v2.6.2804.sql and I uploaded only the folder /craft/app from the older version of craft Craft-2.6.2804

Now when I get to the website administration panel I get the button to finish up the installation like I'm updating the website. Any ideas what's going on? According to everything I read in order to roll back you need the db and files to be of the same version. I check the craft_info and this is the case


texts: Why does craft.request.getQueryStringWithoutPath return an empty string?

texts:
I'm trying to use craft.request.getQueryStringWithoutPath() to handle query strings on pagination, but for some reason it always seems to return an empty string. If I try craft.request.getQueryString() I get the query string as expected (eg. foo=bar), but with the exact same URL getQueryStringWithoutPath() gives me an empty string.

Am I doing something wrong? Could this be a server configuration issue (I'm using Apache 2.4 with a fairly default configuration)? Or could this be a Craft bug...? I'd be grateful for any help!


texts:
I am sending the set Password URL to a user to set their password after ADMIN create a user in CP.

I am using craft()->users->getPasswordResetUrl($user) to generate the URL for set password which is look like https://<my domain>/actions/users/setpassword?code=8MHKqfmt6Te%5C_dyuCouL4PMaT%7EE%7EV9jNO&id=8bf376ca-e260-44b9-9ad2-0cc623fe4c4c However, I got intermittent user report they get "Oops! Invalid verification code. Please login or reset your password." message pop up after click the link.

In general.php, I have 'verificationCodeDuration' => 'P7D' to make sure the code could last for 7 days.

Does anyone has idea how to verify the code in DB? Looks the verficationCode column in DB is encrypted. Does anyone know how to solve that issue? Thanks


texts: Log in as different users in backend front end at the same time?

texts:
Is it possible be logged in with different users in frontend and backend, and if so, how do I do that?

It would be very convenient being able to test logging in/out different users in frontend, without it affecting the logged in admin user in backend.


texts: How to check if an entry is enabled for a particular site?

texts:
Is there a way to find out if an entry is enabled for a particular site?

I know there's the enabledForSite property, but it doesn't look like it accepts any arguments. Ideally I'd like to do something like {% if entry.enabledForSite(2) %} or {% if entry.enabledForSite('siteHandle') %}.

Thanks!


texts:
This is my code I am using, but want to limit it to just one and possibly randomize it also.  Is it possible with Table, I looked at the example on Craft's site but did not see that option.

{% for row in block.example %}
    {{ row.examplerow }}
{% endfor %}


texts: Craft CMS - 3.6.11.1 - Why are Assets Backed Up to Temporary Storage?

texts:
Since updating Craft CMS to the latest version I noticed that our uploaded files get backed-up daily to temporary storage. Uploaded files live on DigitalOcean Spaces so we have no need to back up these files to the same server Craft CMS resides on.

Files are stored on the following path: storage/runtime/temp/tfxrsolmuf/images
This caused us to go over our allotted disk space and cause the server to go down
The backup is happening daily
Using Craft 3.6.10
We use the DigitalOcean spaces volume plugin


texts: "Unknown "craft" function" Error in Plugin Service Call

texts:
I'm just starting with plugins and I've downloaded the Business Logic plugin and am trying to call it from my template.

Here's the code in my template:

{% extends "_layout" %}

{% block content %}
{{craft()->businessLogic->exampleService()}}

{% endblock %}

And the code in the BusinessLogicService.php:

class BusinessLogicService extends BaseApplicationComponent

{

    /**
     * This function can literally be anything you want.
     *
     * HOW TO USE IT
     * From any other plugin file, call it like this:
     *
     *     craft()->businessLogic->exampleService()
     *
     */
    public function exampleService()
    {
        return "I've got your data right here!";
    }

}

It returns this error:

Unknown "craft" function.

Would I call it a different way?
Thanks for any help with this.


texts: Contact form plugin only sending the content of the textarea?

texts:
I'm working in a form with five fields, but I'm only receiving the content in the comments field; I'm not getting anything from the other four, please check my code
below.

{{ block.contactFormHeadline }}

    {% macro errorList(errors) %}
    {% if message is defined %}
        {% if errors %}
            {% for error in errors %}
                {{ error }}
            {% endfor %}
        {% endif %}
        {% endif %}
    {% endmacro %}
    {% from _self import errorList %}
    <form method="POST" action="">
        {{ getCsrfInput() }}
        <input type="hidden" name="action" value="contactForm/sendMessage">

            <input id="fromName" type="text" name="fromName" value="{% if message is defined %}{{ message.fromName }}{% endif %}" placeholder="Full Name">
            {{ message is defined and message ? errorList(message.getErrors('fromName')) }}

            <input type="email" name="fromEmail" id="from-email" class="form-control" placeholder="Email" value="{% if message is defined %}{{ message.fromEmail }}{% endif %}">
            {{ message is defined and message ? errorList(message.getErrors('fromEmail')) }}

            <input type="text" name="message[Company]" id="company" class="form-control" placeholder="Company Name" value="">

            <input id="phone" type="text" name="message[Phone]" value="" Placeholder="Phone Number">

            <textarea rows="3" cols="30" id="message" name="message" placeholder="Comments">{% if message is defined %}{{ message.message }}{% endif %}</textarea>
            {{ message is defined and message ? errorList(message.getErrors('message')) }}

        <input type="submit" class="Btn mini-form" value="Submit">

        <input type="text" name="sales" id="sales" class="hidden">
    </form>


texts: Assets Error: Unknown or bad format (years) at position 0 (y)

texts:
I am getting a new error, after no apparent updates from me or the client.
The error only appears on pages with this one particular field.

  "DateInterval::createFromDateString(): Unknown or bad format ( years) at position 0 (y): The timezone could not be found in the database"

(then a whole description of errors after it - the first from /craftcms/cms/src/helpers/DateTimeHelper.php)

The field in question is an asset field (within a Matrix field).
The files are uploaded / stored in an S3 bucket.

Everything was working fine for a few months, now any site or admin page with content from this particular field throws that error.

I have looked at the database and could not spot any obvious errors (to my eyes anyway).

I've also cleared caches and updated asset indexes

Any ideas as to what I am looking for / do next?


texts: Start a Loop at the nth Entry in a Structure and Loop to the End?

texts: I'm trying to start a loop at the 8th entry in a structure and then loop through the remaining entries in that structure and stop once I reach the end. How would I accomplish this in Craft?


texts: How can I make Craft's caching aware of fields used inside a plugin?

texts:
I have a complex template which uses various modules and sub-components for which I opted for handling all the logic and rendering directly in PHP, as it felt like it was too complex a job for twig.

Currently, when I change a field (e.g. swap out an image) inside one of the modules, the surrounding cache isn't busted, so the site doesn't update.

My question is: How can I make Craft aware of fields used inside a plugin within a {% cache %} tag, so that when a field is changed, the surrounding cache is busted?

I am aware of the TemplateCacheService, but unsure if / how I can use that in this case (I had a bit of an experiment with no success).

The modules represent a Neo field, but my assumption is that this would work very similarly if not identically to if this was a matrix field.

A super-reduced test case looks something like the following:

{% for module in modules %}
    {% cache using key module.id %}
        {{ craft.control.renderModule(module) }}
    {% endcache %}
{% endfor %}

_modules.twig

<?php

namespace Craft;

class ControlVariable
{

    public function renderModule($module)
    {
        return craft()->control_modules->renderModule($module);
    }
}

ControlVariable.php

<?php

namespace Craft;

class Control_ModulesService extends BaseApplicationComponent
{

public function __construct()
{}

public function renderModule($module)
{
    ?>

    <img src="<?= $module->myImageField->first()->getUrl(); ?>">

    <?php
}

Control_ModulesService.php

FWIW, in the following setup, the cache is successfully busted when changing the image field in the CMS:

{% for module in modules %}
    {% cache using key module.id %}

    {% endcache %}
{% endfor %}

_modules.twig


texts:
My hoster has i public html folder where all websites are lying. Different Websites are separeted by subfolders. Should i upload all Craft3 installation files to this public html folder and point the webserver to the /web folder?

Or should i upload only the /web folder to my webhoster's public html folder and place all other files ABOVE, like it's explained in the Craft 2 installation guide?
If yes, how do i configure the craft path in the index.php file?

Thank you very much for a explanation!


texts: Move Icon Disappears from Categories editor

texts:
The move symbol -  the one that allows you to move a category in the list up or down, etc. -- is gone from one of my category groups.  It's the one that appears just after the checkbox to select a category and right before the name of a category.

How do I get it back?

I know, stupid question. But I have no clue what I did to make it disappear.  The other category groups are okay.


texts: Many sections use one template: How do I get current section?

texts:
I have multiple sections (channels) that use the same index and _entry templates. In my index template, given that the section is dynamic, how do I define the current section and access it? Eg, I'd like to make the template's header dynamic: <h1>{{ section.name ~ " Blog" }}</h1>.

Here is my fragile, hacked solution that I hope I never have to use in production:

I start things off by grabbing a section of the current URL. This returns a string, eg: "southwest-mn", that I use to load the actual section.

{% set handle = craft.request.getSegment(2) %}

Next, I convert the string to one that reflects the section's handle format, eg: blog_southwest_mn (I changed it from blogSouthwestMn to make this string wizardry faster and easier)

{% set sectionHandle = handle|replace('-', '_') %}

Now we can patch together a dynamic section name based on our URL, so let's grab the entries

{% set blog = craft.entries.section('blog_' ~ sectionHandle) %}

This is the most embarrassing part of the code... I'm not sure how to get to the actual section model, so I used the following to display the correct header in the template

{% if handle == "southwest-mn" %}
    {% set blogTitle = "Southwest MN Blog" %}
{% endif %}

That's how I was able to at least get a prototype template working. But how can I load a dynamic section's model so I don't have to write such madness?

Thanks!


texts: When I try to upgrade to 3.2 on my site I get an error saying the drafts table already exists.  Does anyone know of any plugins that use such a table?  I'm trying to sort out what's going on.


texts: Reuse chosen dropdown field value on frontend

texts:
I would like to choose entry values from a frontend dropdown and reuse the chosen value directly.

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

<select name="year">
{% for entry in entries %}
  <option value={{ entry.year }}>{{ entry.year }}</option>
{% endfor %}

How can i get the chosen value and reuse it in the same template?
For example:

{% for entry in entries %}
  {% if entry.year == '2015' %} /* chosen value in dropdown field */
    {{ entry.title }}
  {% endif %}
{% endfor %}

Thanks for any help!


texts:
I would like to eagerload inverse relation. Business case:
I have stories, stories are connected to books over relatedBooks field. Now I would like to query those books only which not have any story.

I do not see any easy way to do it, so I thought that to using eagerload the related stories somehow, and filtering out the nulls
What also could help is to just using having count somehow

But I am not able to do it, because I am not able to lead the relatedBooks(inverse) from books perspective, only from stories.

Tried to use the manyToMany plugin, but it is not helping either, just giving a nice interface

Also I know I can query one-by-one but that is silly

(last workaround would be to use hardcoded sql, but I would like to avoid this one:) )


texts: Craft CMS: Data too long for column 'cacheKey' at row 1

texts:
We have Craft CMS v3 using multi-sites.
We are using cache to cache whole pages based on the absolute URL as some URLs have query parameters which seem to be ignored when not using a key.  So the absoluteUrl is working. Our cache code is:
{% cache using key craft.app.request.absoluteUrl unless craft.app.request.getSegment(1) == 'members' or craft.app.request.getSegment(1) == 'data-summary' %}

One of the sites, Korean, has a few pages that result in an Internal Server Error as follows.
Next Twig\Error\RuntimeError: An exception has been thrown during the rendering of a template ("SQLSTATE[22001]: String data, right truncated: 1406 Data too long for column 'cacheKey' at row 1

This leads me to believe the URL is longer than 255 characters as the database column templatecaches.cacheKey is varchar(255).
The SQL is:
The SQL being executed was: INSERT INTO `templatecaches` (`cacheKey`, `siteId`, `path`, `expiryDate`, `body`) VALUES ('https://www.mydomain.com/ko/%C3%AC%C2%86%C2%8C%C3%AA%C2%B0%C2%9C/%C3%AC%C2%9D%C2%B8%C3%AC%C2%A6%C2%9D-%C3%AB%C2%B0%C2%8F-%C3%AC%C2%88%C2%98%C3%AC%C2%83%C2%81-%C3%AB%C2%82%C2%B4%C3%AC%C2%97%C2%AD/%C3%AC%C2%B5%C2%9C%C3%AA%C2%B3%C2%A0-%C3%AA%C2%B8%C2%B0%C3%AC%C2%97%C2%85-%C3%AC%C2%88%C2%98%C3%AC%C2%83%C2%81?__geom=%E2%9C%AA', 26, 'site:ìê°/ì¸ì¦-ë°-ìì-ë´ì/ìµê³ -ê¸°ì-ìì', '2020-11-16 18:41:26', '[all the page content here]')"). in /home/mydomain/craftcms/templates/_layout.twig:84

The page URL in the browser has Korean symbols of course, so I guess its too many characters once converted to ascii.
I tried changing it to a Longtext as per another similar issue with a different column, but MySQL will not allow it due to the cacheKey being in the index.
Recommended solutions were to remove the column from the index but to be honest I dont want to start messing with things like this without guidance from Craft.
Is there a Craft recommended approach to this issue please?
Thanks


texts: Entry slug auto appends -1 even when the original slug is unique

texts:
I have an entry slug like this: cics-west-belden-1

the -1 seems to be auto appended to the slug, but there are no other entries with the project cics-west-belden in my project. When I remove the -1 from the end of the slug and save, the -1 always comes back. changing it to cics-west-belden-2 saves works. Even changing it to cics-west-belden- works.

But as soon as I try to save it as  cics-west-belden, it changes back to cics-west-belden-1 again.

Is this a bug with craft or maybe my database somehow got corrupted where it thinks this entry already exists when in fact it doesn't


texts: SOLVED: Best way to deploy Craft 3 to webserver?

texts:
I want to deploy a local craftCMS 3 website to a server, but I didn't manage to get answers to some of the questions I have rightnow on Google search. So I hope you can help me with this and can help me finding the right / a better workflow to do these things instead of me reinventing the wheel.

I have the website build locally and want to deploy it. I installed composer on the webserver via SSH by putty (Win) and installed Craft 3 on the server with composer and the craft webinstaller whithout any problems. But that's obviously just an empty craftcms and not the locally build cms.

These are the questions I have right now:

1) What's the preferred way to install a build craft website on the server? Do you use the craft installer or just copy all local files of the project to the server by FTP?

When creating a new craft project with composer the 'public' files are in 'web'. So if I install a new craft project with composer on the webserver inside public_html, the public files will be in domain.com/project/web or in domain/web if I use public_html as a path.
But in both cases some critical files, like the config files with passwords and all, will be in the public_html folder.

Of coarse I use htaccess to protect things, but I'm not sure this is the right and secure location to have this folderstructure on the server as meant to be and wonder if the project should go on a higher folder instead with only 'web' exposed on public_html.

2) What's the right location on the server to install the craft project to to keep everything secure, like having config, vendor and all 'out of sight'? Do you guys install craft directly in the public_html folder, or on a higher parent folder? And in case of the latter do you only have the 'web' folder inside public_html somehow (how to do that?)? So what's the right/preferred way/location to install Craft3 in a secure way?

With an older CMS/framework I used I just copied local files by ftp to deploy. But it seems like using composer is a better way to do this and like to improve my workflow.

3) If you make changes to the website locally, how do you deploy them once the website is setup on the server? Do you just use ftp to upload your changed files (and update the database) or is there a better way to do this with composer?

I like to do things in a way that works best and the CMS is meant for instead of reinventing the wheel and do things differently than the 'standard'. Hope you guys can help. Thanks in advance!


texts: Get all Categories with getGroupById in Element API plugin - Craft 3

texts:
I have an endpoint created and I am getting the groupID but I am unable to get all the categories associated with the group.

This is what I have right now:

$categoriesGroup = Craft::$app->categories->getGroupById($catId);

I can't seem to get an array of entries from that.


texts:
Our website has been live for more than a year with no issues, but today it seems the images have disappeared and are showing as a '?'

Any ideas why this might be?


texts: Why does my Twig for loop not get a Key?

texts:
I'm looping through a Matrix field called Documents. The matrix has three fields:

Document (an asset field)
Document Title (plain text field)
Document Type (a category field)

I need to loop through the matrix and output all the rows, but grouped by Document Type. This seems like it should work:

{% set grouped = entry.documents | group('documentType.title') %}

{% for categoryTitle, groupedRows in grouped %}
    TITLE HERE: {{ categoryTitle }}

    {% for document in groupedRows %}
        <br/>{{ document.documentTitle }}
    {% endfor %}
{% endfor %}

The problem is that {{ categoryTitle }} is blank. Nothing in it. The code runs, but the key is blank. The grouped rows are populated.

What's wrong?


texts: Update Asset Indexes gives "getFileList() is not implemented"

texts:
Thank you in advance for any tips on this.

Barely-related-background: I made a mistake on my development machine. In gparted, I chose "ignore" instead of "cancel". This is called 'choosing poorly'. Anyway, I now have freshly reinstalled my OS, apache, php, etc.

Now, as the title says, when I click "Update Asset Indexes" it gives a popup saying getFileList() is not implemented

Any suggestions what I need to do?


texts: List Only Child Categories Related to Entries

texts:
I need to show a list of Child Categories which only have Entries attached.

From about 6 different solutions here, I have assembled the following. It works perfectly on a Section that has < 200 Entries with a Category Group that contains 50 Parent Cats that each may have up to 10 Child Cats.

My concern is that with a larger Section (3,200 entries, yet to be imported into Craft) it will break down, timeout, etc. because in order for this to work, ALL the Entries from a Section must be present in the Array for the Categories to check Relations against.

For brevity and clarity, the following URL structure is required by the client for several reasons...

URL = /alpha/yadda/news
syntax = /[parent-category]/identifier/[section]

Section = News
Category Group = 1
Category Examples =
alpha
    alpha-1
    alpha-2
    alpha-3
beta
    beta-1
    beta-2
    beta-3
    beta-4
etc....

Based on that, here is what I've assembed that works great for 200 entries in News. It outputs a list of Child categories that only have News entries, based on the Parent's Category Slug in segment 1:

{# 1. find ALL the entry ids for a channel #}
{% set entryIds = craft.entries.section('news').limit(null).ids() %}

{# 2. find all the cats in Group 1 related to those entries #}
{% set categories = craft.categories.relatedTo({ sourceElement: entryIds }).groupId(1).limit(null).find() %}

{# 3. set var from URL seg1 and use to get CatModel Object: catParent #}
{% set parentSlug = craft.request.getSegment(1) %}
{% set catParent = craft.categories.slug(parentSlug).first() %}

{# 4. using catParent, get child cats #}
{% set subCategories = craft.categories.descendantOf(catParent) %}

{# 5. loop through cats found matching entries in step 2
        then subloop through this Parent Cat's descendants for match #}
{% for category in categories %}
    {% set currentCat = category.title %}
    {% for subCat in subCategories %}
        {% if subCat.title == currentCat %}
            <li>{{ subCat.title }}</li>
        {% endif %}
    {% endfor %}
{% endfor %}

Again, this all works...for 200 entries in News. But I don't see how it's scalable for the 3,200 blog entries that will be imported.

Just seems like there must be a better, more efficient way to display a list of Categories (or only descendants of a specific Parent Cat) that have Entries attached?


texts: Every time I perform updates on Craft 3, I get errors

texts:
What is going on in Craft 3, seems like Composer has caused more problems than good. Every time I have had to update a dev/staging environment I run into issues and have to go and manually update the composer.json file to get updates to work.

This doesn't seem like how things should work.

Anyway on to the latest error trying to update to Craft 3.1.14

Composer output: Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

Problem 1
- Can only install one of: yiisoft/yii2[2.0.16, 2.0.15.1].
- Can only install one of: yiisoft/yii2[2.0.16, 2.0.15.1].
- craftcms/cms 3.1.14 requires yiisoft/yii2 ~2.0.16.0 -> satisfiable by yiisoft/yii2[2.0.16].
- Installation request for craftcms/cms 3.1.14 -> satisfiable by craftcms/cms[3.1.14].
- Installation request for yiisoft/yii2 (installed at 2.0.15.1) -> satisfiable by yiisoft/yii2[2.0.15.1].

Running update with --no-dev does not mean require-dev is ignored, it just means the packages will not be installed. If dev requirements are blocking the update you have to resolve those problems.


texts: Impossible to access an attribute (title) on a string variable

texts:
I have a Video section with a field called videoCategory. I'm trying to pull in the first category on the _entry.html template.

I'm pretty much following the the last example in the documentation at: http://buildwithcraft.com/docs/categories-fields

...with this code:

 {% set entryCategory = entry.videoCategory.first() %}
 {% if entryCategory %}

{% for category in entryCategory %}{{ category.title }} {% endfor %}

 {% endif %}

But I can't get around this error message:

  Impossible to access an attribute ("title") on a string variable ("19")

What is it that I'm missing?


texts: Add a shippingCost per lineItem rather than per Order

texts:
Each Product is associated with a Merchant (a standard Craft User), who has 2-3 flat-rate Shipping Prices. There could be any number of Merchants and Products.

What I would like to do is on the Shipping page of Checkout, allow the Customer to select a Shipping method from a drop-down per LineItem. Then when they progress to the Payment Page, these Shipping Costs are Totalled and applied to the overall Order.

I've got everything up to the drop-downs on the Shipping page and I'm able to save the value the Customer has chosen to the LineItem via the Options collection, but that's where I've hit a brick wall.

I've had a look at Adjusters and I don't think that's the solution. It was suggested on the Craft Slack that Custom Shipping Methods might be a way forward, but they are very heavily geared towards applying the Shipping Method to the whole Order rather than having separate ones for each lineItem.

Does anyone have any ideas on a suitable approach? Any help gratefully received.


texts: List both parent entry and its child entry

texts:
I am trying to display a list of entries.  Specifically the parent entry and it's children's entry.

I started off using this:

{% nav page in craft.entries.section('forms').isChildOf.slug('applicant-form') %}

        {{ page.getLink() }}

        {% ifchildren %}

{% children %}

        {% endifchildren %}

{% endnav %}

But this only displays the Parent.

I found this solution on Stack here, and all the children display but not the parent.  I also wonder if this is the best solution to display the children as it seems a bit more lines than what is in the Craft docs.

Many thanks.

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

{% if topLevel.hasDescendants %}

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

        {% nav page in nav  %}
            {% if page.id != entry.id %}

{{ page.getLink() }}

            {%else%}

{{page}}

            {%endif%}

        {% ifchildren %}

                {% children %}

        {% endifchildren %}

        {% endnav %}

{% endif %}


texts: How to add an alpha ordered list option in Redactor?

texts:
In addition to a bulleted unordered list and a numbered ordered list, I'd like to add an option to format text as an ordered list with upper-alpha letters, like this:

A.

B.

C.

D.

Can I add this to the list formatting menu somehow? If now, how would I create a custom formatting option that creates an ol?

EDIT 9/4

I am able to add custom formatting (with formattingAdd) to create

, but I haven't found a way to allow li elements to be created inside it.


texts:
I am using Lindsey's Language Link plugin for my language switcher.

Everything works well, as long as the url is not a category url.

Here it is:

{% set element = (entry is defined ? entry : null) %}

{% for locale in craft.i18n.getSiteLocales %}
    {{ locale.nativeName|capitalize }}
{% endfor %}

Where can I tell Craft to used the translated slug in my language switcher?


texts:
Currently each time we make changes to our dev instance of our Craft install (add fields, plugins, change settings in CP), we dump the database and upload it to the production database server. This gets messy now that our production database is accepting guest entries. We obviously do not want to overwrite those changes.

Is there a recommend workflow for this situation.


texts: How to change the Entry status to enabled from Disabled

texts:
I have created a page where user creates an entry but its status is disabled. This page then redirects to a page where the user gets to see a preview of his entry. On this preview page there are two publish button when clicked the status of the entry has to be enabled. The code I have used is:

<form method="post" accept-charset="UTF-8">
    {{ getCsrfInput() }}
    <input type="hidden" name="action" value="entries/saveEntry">
    <input type="hidden" name="redirect" value="/user/thanks/{{slug}}">
    <input type="hidden" name="sectionId" value="4">
    <input type="hidden" name="entryId" value="{{entry.id}}">
    <input type="hidden" name="enabled" value="1">
    <button type="submit" class="btn-save">Publish</button>
</form>

But after submitting the form it reloads the same page. I checked the craft.log, it has the following errors:

2017/06/08 13:17:53 [warning] [application] Craft\ContentModel->dailyPlan failed validation: Daily Plans cannot be blank. ( a matrix field )
2017/06/08 13:17:53 [warning] [application] Craft\ContentModel->banner failed validation: Banner cannot be blank. ( an asset field )
2017/06/08 13:17:53 [warning] [application] Craft\ContentModel->Included failed validation: Included cannot be blank. ( a table field )
2017/06/08 13:17:53 [warning] [application] Craft\ContentModel->Excluded failed validation: Excluded cannot be blank. ( a table field )

Can't I change the status of entry simply with the above form? Do I have to load all the required fields with its value? Well I don't want to do that as it would take lot of extra lines of code and also the execution time will be longer, as there are two publish button on the page.


texts: Displaying Craft templates in external apps

texts:
I'm working on a site that is running Craft v2 and also has an installation of Simple Machines Forum (SMF). This has been fine using the approach outlined in this answer, i.e.
$craft = include '/craft/app/bootstrap.php';
echo $craft->templates->render('includes/nav');

Now the site is being upgraded to v3 and this isn't working anymore. I've tried this:
$craft = include '/craft/vendor/craftcms/cms/bootstrap/web.php';
echo Craft::$app->getView()->renderTemplate('includes/nav');

but with that I get:

Uncaught Error: Class 'craft\services\Config' not found in /craft/vendor/craftcms/cms/bootstrap/bootstrap.php on line 165

What else is missing to get this to work for Craft 3?


texts: Trying to access 'title' attribute via getEntryTableAttributeHtml. Any idea how?

texts:
I am trying to get access to the attribute title using this, but does not work. If I switch out 'title' for slug, uri, etc. It works. But not title. Anyway I can do this?

public function getEntryTableAttributeHtml(EntryModel $entry, $attribute)
{
    switch ($attribute) {
        case 'title':
            return $entry->title . ': Something appended to title';
            break;
    }
}

Update

Added in return $entry->title . ': Something appended to title'; to the case to show I want to append something to the title.

I want to be able to just append some text, icon, or html to the titles in the entries list in the CP.


texts: Link to the next Entry Type in a Structure level

texts:
I have a Structure with three Entry Types:

entypeOne
entypeTwo
entypeThree

When a user is viewing entries saved as entypeThree I want to add 'Next' and 'Previous' links which only link to the next/previous entry also saved as entypeThree.

I know this doesn't work but something like this?

{% if entry.getPrevSibling.type('entypeThree') %}
 {{entry.getPrevSibling.title}}
{% endif %}

{% if entry.getNextSibling.type('entypeThree') %}
 {{entry.getNextSibling.title}}
{% endif %}

Thanks


texts: Craft Commerce 3 calling commerce/payments/pay from Axios returns errors

texts:
I have headless Craft CMS + Craft Commerce 3 + Mollie for Craft Commerce as backend and decoupled Nuxt.js frontend
I'm trying to use POST request to "?action=commerce/payments/pay&note=from+ajax" to submit payment.
I have two different scenarios in which I'm receiving an error from backend:

Passing the following body:
 "email": "mail@example.com",
 "gatewayId": 4,
 "paymentMethod": "ideal",
 "issuer": "ideal_ABNANL2A",
 "redirect": "/checkout/success",
 "cancelUrl": "/checkout/payment",
 "orderNumber": "050dfb9df12054210f7171270b77dd83",
 "cartUpdatedNotice": "Pay the order"

returns me the 400 error "Request contained an invalid body param"

Passing the body without "cancelUrl" and "redirect" gives me the 500 error:Argument 1 passed to craft\helpers\UrlHelper::siteUrl() must be of the type string, null given, called in /home/kooij/domains/kooij.com/craft/vendor/craftcms/commerce-omnipay/src/base/Gateway.php on line 506

Can you tell me what is wrong/missing there ? Thank you


texts: Craft plugin controller for batch update users break with empty page

texts:
I made a plugin to update my 3000 users. It is kind of a toolbox to manage and update some users fields.

I am calling the controller directly through its url action.
It is working basically but it stops after 20 seconds when updating too many users, and display a white page in browser, no results.

I can see in my plugin log it updated some few lines before stopping.
I checked php and craft logs and cannot see any error information.

public function actionUsersFix() {

    // Delete all the entry caches
    craft()->templateCache->deleteCachesByElementType('User');

    // Now find the entry IDs
    $criteria = craft()->elements->getCriteria('User', array('group' => 'migMembers', 'limit' => null, 'status' => null, 'localeEnabled' => null));
    $criteria->group = 'migMembers';
    $criteria->limit = null;
    $criteria->status = null;
    $criteria->localeEnabled = null;
    $criteria->accent = '2';

    $userIds = $criteria->ids();
    //$totalEntries = count($userIds);

    //
    foreach ($userIds as $userId)
    {
        $user = craft()->users->getUserById($userId);

        $oldAccent = $user->accent;
        $newAccent = '3';

        $user->getContent()->accent = $newAccent;
        $success = craft()->users->saveUser($user);
        MigPlugin::log('User '.$user->email.' - accent = '. $oldAccent .' - modified = '.$newAccent, LogLevel::Warning);
    }

}


texts: How can I override the Response status text from a controller?

texts:
I'm trying to set the statusText in a response, from a module controller.

E.g.:

<?php

namespace modules\appmodule\controllers;

use Craft;
use craft\web\Response;

class StatusController extends \craft\web\Controller
{
  protected $allowAnonymous = true;

  public function actionCheck(): Response
  {
    $response = Craft::$app->getResponse();
    $response->format = $response::FORMAT_RAW;
    $response->setStatusCode(204, 'Healthy');

    return $response;
  }
}

However, the result still uses the default statusText "No Content", and still sets the format to text/html:

❯ curl  -I http://localhost:8089/actions/appmodule/status/check
HTTP/1.1 204 No Content
Cache-Control: no-cache, no-store, must-revalidate
Content-Type: text/html; charset=UTF-8
Date: Thu, 26 Sep 2019 18:49:31 GMT
Server: nginx/1.10.3
X-Powered-By: Craft CMS


texts: How do I change the default front-end language in Craft Personal?

texts: Our client wants to have an English back-end, but a German front-end (for now, other languages later). Any idea how to handle this?


texts: Eager load elements from Solspace Plugin

texts:
I'm using Solspace plugin. I've related each event to a show. I want to get the event with its related show (Entry type).

I'v tried (Among others):

$calendarEvent = Event::find([
            'id' => $id,
        ])->with(['shows'])->all();

But, that gives me the event(✅) but in the show, I don't get the entry per se but I get like an unexecuted query. Looks something like:

        {
            "id": 22,
            "url": null,
            "title": "The Way You Sound",
            "slug": "the-way-you-sound",
            "start": "2018-12-14T18:00:00+00:00",
            "end": "2018-12-14T20:00:00+00:00",
            "allDay": false,
            "multiDay": false,
            "repeats": true,
            "readableRepeatRule": "Weekly on Friday, starting from Dec 14, 2018, forever",
            "calendar": {
                "id": 1,
                "name": "Shows",
                "handle": "default"
            },
            "site": {
                "id": "1",
                "name": "English",
                "handle": "default",
                "language": "en-US"
            },
            "editable": false,
            "enabled": true,
            "backgroundColor": "#C0BE11",
            "borderColor": "#868900",
            "textColor": "black",

    ======> "show": {
                "editable": false,
                "orderBy": {
                    "relations.sortOrder": 4
                },
                  ...
                "join": [
                    [
                        "INNER JOIN",
                        "{{%relations}} relations", [
                            "and",
                            "[[relations.targetId]] = [[elements.id]]",
                            {
                                "relations.sourceId": "22",
                                "relations.fieldId": "42"
                            },
                            [
                                "or",
                                {
                                    "relations.sourceSiteId": null
                                },
                                {
                                    "relations.sourceSiteId": "1"
                                }
                            ]
                        ]
                    ]
                ],
                "having": null,
                "union": null
            }
        }


texts: ERROR: relation "assetindexdata_id_seq" already exists on new database

texts:
I'm using PostgreSQL locally and everything is working as expected. However, when I decided to move/restore the database to the staging environment I am getting this error (even through the tables do not exist).

Has anyone experienced this before?

restore_pg_11.0: [archiver (db)] could not execute query: ERROR:  relation "assetindexdata_id_seq" already exists
    Command was: CREATE SEQUENCE public.assetindexdata_id_seq
    AS integer
    START WITH 1
    INCREMENT BY 1
    NO MINVALUE
    NO MAXVALUE
    CACHE 1;


texts: Impossible to access an attribute ("created_at") on a boolean variable ("1")

texts:
I have read a number of related threads but am still puzzled what this error actually means or how to fix it.

This triggers the error:

                {% set tweets = craft.twitter.get('statuses/user_timeline', {count:2}) %}

               {% if tweets %}

Latest Tweets

                    {% for tweet in tweets %}
                    {% set tweetDate = date(tweet.created_at).diff(now).format('%a') %}
                    {% if tweetDate == 0 %}
                    {% set tweetTimeAgo = 'today' %}
                    {% else %}
                    {% set tweetTimeAgo = tweetDate ~ ' days ago' %}
                    {% endif %}

                          {{ tweet.text|autoLinkTweet }}

                          @{{ tweet.user.screen_name|raw }} /
                          Posted {{ tweetTimeAgo }}

                    {% endfor %}

                  {% endif %}

What would fix this?