Giter Club home page Giter Club logo

craft-linkfield's Introduction

Link field plugin for Craft

This plugin adds a new link field type to the Craft CMS. The link field allows content editors to choose from a list of link types and offers individual input fields for each of them.

Requirements

This plugin requires Craft CMS 4.0.0 or later.

Installation

The plugin can be installed from the integrated plugin store by searching for "Typed Link Field" or using Composer:

  1. Open your terminal and navigate to your Craft project:

    cd /path/to/project
    
  2. Then tell Composer to load the plugin:

    composer require sebastianlenz/linkfield
    
  3. Finally, install and enable the plugin:

    ./craft plugin/install typedlinkfield
    ./craft plugin/enable typedlinkfield
    

Usage

After the plugin has been installed, link fields can be created using the field settings within the control panel. All field settings can be found within the field manager.

Templating

Link fields can be rendered directly in Twig, they return the url the link is pointing to, or an empty string if they are unset:

<a href="{{ entry.myLinkField }}">Link</a>

The field value is actually an instance of lenz\linkfield\models\Link which exposes additional properties and methods that can be used in templates. Depending on the link type, a more specific subclass will be returned.

Render methods

getLink($attributesOrText = null)

Renders a full html link using the attribute and content data of the field.

{{ entry.myLinkField.getLink() }}

To modify the inner text of the link tag, the desired content can be passed:

{{ entry.myLinkField.getLink('Imprint') }}

To modify the attributes of the link, an object can be passed. The special attribute text will be used as the inner text.

{{ entry.myLinkField.getLink({
  class: 'my-link-class',
  target: '_blank',
  text: 'Imprint',
}) }}

getLinkAttributes($extraAttributes = null)

Renders only the link attributes. Attributes can be modified or appended by passing an object to the first argument.

<a{{ entry.myLinkField.getLinkAttributes() }}>
  <span>Custom markup</span>
</a>

getRawLinkAttributes($extraAttributes = null)

Returns the attributes of the link as an array. Can be used in junction with the attr or tag helpers exposed by Craft.

{% tag 'a' with entry.myLinkField.getRawLinkAttributes() %}
  <span>Custom markup</span>
{% endtag %}

Helper methods

getAllowCustomText()

Returns whether the field allows users to enter custom texts.

{{ entry.myLinkField.getAllowCustomText() }}

getAllowTarget()

Returns whether the field shows the option for opening links in a new window.

{{ entry.myLinkField.getAllowTarget() }}

getAriaLabel()

Returns the aria label of the link.

{{ entry.myLinkField.getAriaLabel() }}

getCustomText($fallbackText = '')

Returns the custom text of the link. The first non-empty text from the following possibilities will be picked:

  1. Custom text of the link.
  2. Default text defined in the field settings.
  3. Fallback text as passed to the function.
{{ entry.myLinkField.getCustomText('My fallback text') }}

getDefaultText()

Returns the default text set in the link field settings of this link.

{{ entry.myLinkField.getDefaultText() }}

getElement($ignoreStatus = false)

Returns the linked element (entry, asset, etc.) or NULL if no element is linked.

By default, only published elements are returned. Set $ignoreStatus to TRUE to retrieve unpublished elements.

{{ entry.myLinkField.getElement() }}

getEnableAriaLabel()

Returns whether the field allows users to enter aria labels.

{{ entry.myLinkField.getEnableAriaLabel() }}

getEnableTitle()

Returns whether the field allows users to enter link titles.

{{ entry.myLinkField.getEnableTitle() }}

getIntrinsicText()

Returns the text that is declared by the link itself (e.g. the title of the linked entry or asset).

{{ entry.myLinkField.getIntrinsicText() }}

getIntrinsicUrl()

Returns the url that is declared by the link itself (e.g. the url of the linked entry or asset). Custom queries or hashes are taken into account and will be appended to the result.

{{ entry.myLinkField.getIntrinsicUrl() }}

getTarget()

Returns the link target (e.g. _blank).

{{ entry.myLinkField.getTarget() }}

getText($fallbackText = "Learn More")

Returns the link text. The first non-empty text from the following possibilities will be picked:

  1. Custom text of the link.
  2. Intrinsic text defined by the linked element.
  3. Default text defined in the field settings.
  4. Fallback text as passed to the function.
{{ entry.myLinkField.getText($fallbackText = "Learn More") }}

getType()

Returns a string that indicates the type of the link. The plugin ships with the following link types: asset, category, custom, email, entry, site, tel, url and user.

{{ entry.myLinkField.getType() }}

getUrl($options = null)

Returns the url of the link.

{{ entry.myLinkField.getUrl() }}

Allows the link to be modified by overwriting url attributes as returned by the php function parse_url. The following options are supported: fragment, host, pass, path, port, query, scheme and user.

  • All options require a string value to be passed.
  • The query option accepts an array or hash map. If an array is passed, the query parameters of the original url will be merged by default. To disable this behaviour, the option queryMode must be set to replace.

This example enforces the https scheme and replaces all query parameters of the original url:

{{ entry.myLinkField.getUrl({
  scheme: 'https',
  queryMode: 'replace',
  query: {
    param: 'value'
  },
}) }}

hasElement($ignoreStatus = false)

Returns whether the link points to an element (e.g. entry or asset).

{{ entry.myLinkField.hasElement() }}

isEmpty()

Returns whether the link is empty. An empty link is a link that has no url.

{{ entry.myLinkField.isEmpty() }}

Properties

The properties generally expose the raw underlying data of the link.

ariaLabel

The aria label as entered in th cp.

<a aria-label="{{ entry.myLinkField.ariaLabel }}">...</a>

customText

The custom text as entered in th cp.

<a>{{ entry.myLinkField.customText }}</a>

target

The link target as text. Can be either _blank or an empty string.

<a target="{{ entry.myLinkField.target }}">...</a>

title

The title as entered in th cp.

<a title="{{ entry.myLinkField.title }}">...</a>

Eager-Loading

Link fields can be eager-loaded using Crafts with query parameter. Eager-loading can greatly improve the performance when fetching many entries, e.g. when rendering menus.

{% set entries = craft.entries({
  section: 'pages',
  with: 'myLinkField',
}).all() %}

API

You can register additional link types by listening to the EVENT_REGISTER_LINK_TYPES event of the plugin. If you just want to add another element type, you can do it like this in your module:

use craft\commerce\elements\Product;
use lenz\linkfield\Plugin as LinkPlugin;
use lenz\linkfield\events\LinkTypeEvent;
use lenz\linkfield\models\element\ElementLinkType;
use yii\base\Event;

/**
 * Custom module class.
 */
class Module extends \yii\base\Module
{
  public function init() {
    parent::init();
    Event::on(
      LinkPlugin::class,
      LinkPlugin::EVENT_REGISTER_LINK_TYPES,
      function(LinkTypeEvent $event) {
        $event->linkTypes['product'] = new ElementLinkType(Product::class);
      }
    );
  }
}

Each link type must have an unique name and a definition object extending lenz\linkfield\models\LinkType. Take a look at the bundled link types ElementLinkType and InputLinkType to get an idea of how to write your own link type definitions.

Remarks

Upgrading from Fruit Link It

If wish to migrate a field created using "Fruit Link It", please follow the discussion and directions here:

#51 (comment)

craft-linkfield's People

Contributors

angrybrad avatar apt-thomas avatar arthur-akufen avatar bartrylant avatar boboldehampsink avatar ctangney-tulip avatar d--j avatar holmey avatar internetztube avatar jeroenlammerts avatar jeroenonstuimig avatar jorgeanzola avatar kevinbeckers avatar leecrosdale avatar mia-tpa avatar michtio avatar mitch-rickman avatar nfourtythree avatar nstcactus avatar pascalminator avatar r0615219 avatar sanderpotjer avatar sebastian-lenz avatar timkelty avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

craft-linkfield's Issues

Add title tag to the link

Can it be made possible that the rendered tag gets a title object too? Would come in handy for SEO's sake :-)

GraphQL: use element field, instead of each

Right now the element field gets added its named type, entry, asset, category, etc.

I think it would be more usable to always add it as element.
So a query might look like:

linkField {
        url
        element {
            id
            ...on EntryInterface {
                title
             }
            ...on CategoryInterface {
                title
            }
        }
}

Relative links don't work

Hi I would like to add a url link type with the value /blog as a link but the validation doesn't let me save the field.

Invalid Call on Entry Save

I'm getting the following error whenever saving an entry that has a linkfield field:

Setting read-only property: typedlinkfield\models\Link::url

Additional Information:

Craft CMS 3.0.17.1
Typed link field 1.0.14
PHP 7.0.22

Add an icon

Consider adding an icon, makes the plugin look better in the plugin store and gives a sense of trust to people installing it that everything is working. An empty icon seems like something went wrong.

Consolidate to two rows

I think Linkfield takes up one too many rows. It's really noticeable upon placing into other fields like Matrix or SuperTable. Could we reduce as much margin between fields as possible & reduce it to two rows?

"Open link in new window?" and relationship/url input fields could really go into the same row.

Fields’ isEmpty() method has been deprecated. Use isValueEmpty() instead.

Getting the above error when trying to save entries uses the Link field on Craft CMS 3.0.0-RC15.

Here is the stack trace:

25 | Deprecation error: Fields’ isEmpty() method has been deprecated. Use isValueEmpty() instead. Called from /Users/seandelaney/Sites/ims/vendor/craftcms/cms/src/base/Field.php:315
-- | --
typedlinkfield\fields\LinkField::isValueEmpty(typedlinkfield\models\Link, craft\elements\MatrixBlock) Called from /Users/seandelaney/Sites/ims/vendor/craftcms/cms/src/base/Element.php:1037
craft\elements\MatrixBlock::isFieldEmpty("href") Called from /Users/seandelaney/Sites/ims/vendor/craftcms/cms/src/base/Element.php:776
craft\elements\MatrixBlock::__call("isFieldEmpty:href", [typedlinkfield\models\Link])
call_user_func([craft\elements\MatrixBlock, "isFieldEmpty:href"], typedlinkfield\models\Link) Called from /Users/seandelaney/Sites/ims/vendor/yiisoft/yii2/validators/Validator.php:444
typedlinkfield\validators\LinkFieldValidator::isEmpty(typedlinkfield\models\Link) Called from /Users/seandelaney/Sites/ims/vendor/yiisoft/yii2/validators/Validator.php:264
typedlinkfield\validators\LinkFieldValidator::validateAttributes(craft\elements\MatrixBlock, ["field:href"]) Called from /Users/seandelaney/Sites/ims/vendor/yiisoft/yii2/base/Model.php:367
craft\elements\MatrixBlock::validate() Called from /Users/seandelaney/Sites/ims/vendor/craftcms/cms/src/fields/Matrix.php:527
craft\fields\Matrix::validateBlocks(craft\elements\Entry, null) Called from /Users/seandelaney/Sites/ims/vendor/craftcms/cms/src/base/Element.php:1019
craft\elements\Entry::validateCustomFieldAttribute("field:slider", [craft\fields\Matrix, "validateBlocks", null], yii\validators\InlineValidator)
call_user_func([craft\elements\Entry, "validateCustomFieldAttribute"], "field:slider", [craft\fields\Matrix, "validateBlocks", null], yii\validators\InlineValidator) Called from /Users/seandelaney/Sites/ims/vendor/yiisoft/yii2/validators/InlineValidator.php:72
yii\validators\InlineValidator::validateAttribute(craft\elements\Entry, "field:slider") Called from /Users/seandelaney/Sites/ims/vendor/yiisoft/yii2/validators/Validator.php:267
yii\validators\InlineValidator::validateAttributes(craft\elements\Entry, ["field:slider"]) Called from /Users/seandelaney/Sites/ims/vendor/yiisoft/yii2/base/Model.php:367
craft\elements\Entry::validate() Called from /Users/seandelaney/Sites/ims/vendor/craftcms/cms/src/services/Elements.php:373
craft\services\Elements::saveElement(craft\elements\Entry) Called from /Users/seandelaney/Sites/ims/vendor/craftcms/cms/src/controllers/EntriesController.php:539
craft\controllers\EntriesController::actionSaveEntry()
call_user_func_array([craft\controllers\EntriesController, "actionSaveEntry"], []) Called from /Users/seandelaney/Sites/ims/vendor/yiisoft/yii2/base/InlineAction.php:57
yii\base\InlineAction::runWithParams(["p" => "admin/entries/homepage/2-homepage"]) Called from /Users/seandelaney/Sites/ims/vendor/yiisoft/yii2/base/Controller.php:157
craft\controllers\EntriesController::runAction("save-entry", ["p" => "admin/entries/homepage/2-homepage"]) Called from /Users/seandelaney/Sites/ims/vendor/craftcms/cms/src/web/Controller.php:74
craft\controllers\EntriesController::runAction("save-entry", ["p" => "admin/entries/homepage/2-homepage"]) Called from /Users/seandelaney/Sites/ims/vendor/yiisoft/yii2/base/Module.php:528
craft\web\Application::runAction("entries/save-entry", ["p" => "admin/entries/homepage/2-homepage"]) Called from /Users/seandelaney/Sites/ims/vendor/craftcms/cms/src/web/Application.php:237
craft\web\Application::runAction("entries/save-entry", ["p" => "admin/entries/homepage/2-homepage"]) Called from /Users/seandelaney/Sites/ims/vendor/craftcms/cms/src/web/Application.php:445
craft\web\Application::_processActionRequest(craft\web\Request) Called from /Users/seandelaney/Sites/ims/vendor/craftcms/cms/src/web/Application.php:221
craft\web\Application::handleRequest(craft\web\Request) Called from /Users/seandelaney/Sites/ims/vendor/yiisoft/yii2/base/Application.php:386
craft\web\Application::run() Called from /Users/seandelaney/Sites/ims/web/index.php:26

Using a Global Link Field

Hello, Is there an easy way to select Global link fields I have under Globals > links
I have them in globals because they are external links I use and reuse all around the site. ex.: in the header, footer, contact page, pricing page. So would be nice to only use one link that would change all around the site.
I thought I'd be able to do something in the link field by using custom and entering for the URL {{ links.freeTrialLink }} and {{ links.freeTrialLink.getText() }} for the button text, but no luck :(

Is this something that might be of value to others?
Thanks for a great plugin, nonetheless.

Error when using versioning

When trying to return an entry to a previous version I get the following error:

2018-09-20 03:53:06 [-][1][pakuuvvlhmqd9ahfrrfm1vs8tl][error][yii\base\InvalidCallException] yii\base\InvalidCallException: Setting read-only property: typedlinkfield\models\Link::allowCustomText in /var/www/vhosts/example.com/httpdocs/releases/5eb3789b881caf21961db2849b3a4f54216b11d7/vendor/yiisoft/yii2/base/Component.php:206

Undefined index: entry on version restore

If I select an older version of an entry:

entry

The following error appears, related to the linkfield plugin

screenshot at marz 06 13-06-26

PHP 7.2.3 / Craft 3.0.0-RC13 / Plugin Version 1.0.4

Let me know, If you need further informations.
Thanks!

Undefined index "owner" on link field when saving draft evokes php notice

When saving a draft, the owner is null and results in a PHP Notice of an undefined index on the Link.php constructor.

yii\base\ErrorException: Undefined index: owner in /var/app/current/vendor/sebastianlenz/linkfield/src/models/Link.php:64
Stack trace:
#0 /var/app/current/vendor/craftcms/cms/src/web/ErrorHandler.php(84): yii\base\ErrorHandler->handleError(8, 'Undefined index...', '/var/app/curren...', 64)
#1 /var/app/current/vendor/sebastianlenz/linkfield/src/models/Link.php(64): craft\web\ErrorHandler->handleError(8, 'Undefined index...', '/var/app/curren...', 64, Array)
#2 /var/app/current/vendor/sebastianlenz/linkfield/src/fields/LinkField.php(105): typedlinkfield\models\Link->__construct(Array)
#3 /var/app/current/vendor/craftcms/cms/src/base/Element.php(1904): typedlinkfield\fields\LinkField->normalizeValue(Array, Object(craft\models\EntryDraft))
#4 /var/app/current/vendor/craftcms/cms/src/base/Element.php(761): craft\base\Element->normalizeFieldValue('linkTest')
#5 /var/app/current/vendor/yiisoft/yii2/base/ArrayableTrait.php(126): craft\base\Element->__get('linkTest')
#6 /var/app/current/vendor/craftcms/cms/src/web/View.php(466): yii\base\Model->toArray(Array, Array, false)
#7 /var/app/current/vendor/craftcms/cms/src/helpers/ElementHelper.php(149): craft\web\View->renderObjectTemplate('{% if object.le...', Object(craft\models\EntryDraft))
#8 /var/app/current/vendor/craftcms/cms/src/helpers/ElementHelper.php(92): craft\helpers\ElementHelper::_renderUriFormat('{% if object.le...', Object(craft\models\EntryDraft))
#9 /var/app/current/vendor/craftcms/cms/src/models/BaseEntryRevisionModel.php(103): craft\helpers\ElementHelper::setUniqueUri(Object(craft\models\EntryDraft))
#10 /var/app/current/vendor/craftcms/cms/src/controllers/EntriesController.php(302): craft\models\BaseEntryRevisionModel->getUrl()
#11 [internal function]: craft\controllers\EntriesController->actionEditEntry('pages', 1841, 2, NULL, NULL, Object(craft\models\EntryDraft))
#12 /var/app/current/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#13 /var/app/current/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams(Array)
#14 /var/app/current/vendor/craftcms/cms/src/web/Controller.php(76): yii\base\Controller->runAction('edit-entry', Array)
#15 /var/app/current/vendor/yiisoft/yii2/base/Module.php(528): craft\web\Controller->runAction('edit-entry', Array)
#16 /var/app/current/vendor/craftcms/cms/src/web/Application.php(267): yii\base\Module->runAction('entries/edit-en...', Array)
#17 /var/app/current/vendor/yiisoft/yii2/web/Application.php(103): craft\web\Application->runAction('entries/edit-en...', Array)
#18 /var/app/current/vendor/craftcms/cms/src/web/Application.php(256): yii\web\Application->handleRequest(Object(craft\web\Request))
#19 /var/app/current/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
#20 /var/app/current/web/index.php(21): yii\base\Application->run()
#21 {main}

Settings are lost on 3.1

Any section/category type field settings seem to be lost after a 3.1 upgrade.

Inspecting the HTML source on the field settings page, it would seem it is now expecting a UID, not an ID.

Not sure, but maybe related to this line from the 3.1 release notes:

System user permissions now reference things by their UIDs rather than IDs (e.g. editEntries: rather than editEntries:).

Seems problematic, and probably not just isolated to this plugin.

Using conditionals with link properties

Is there a way to use a conditional on a property of a link? For example, I'd like to first check if the getTarget() is defined and do something like this:

{% if item.myLinkField.getTarget() | length %}
target="{{ item.myLinkField.getTarget() }}"
{% endif %}

This way, I don't need to have my target output empty (like this target="") when it's not defined.

Facing some issues when previewing links with custom link text in a page saved as a Draft

I’m facing some issues when previewing links with custom link text in a page saved as a Draft. Happens when I click Share button to preview. When I click on the Share button (next to Live Preview button), Instead of showing the custom text, it shows the default text. For Entry, it shows only the entry title. Please refer the attached images.

When click on Share button to preview changes:

screen shot 2019-02-14 at 12 47 03 pm

screen shot 2019-02-14 at 12 48 11 pm

In Live Preview:

screen shot 2019-02-14 at 12 49 03 pm

screen shot 2019-02-14 at 12 49 53 pm

Allow global link source

It would be great if there were a way to link to a global somehow.

For example, I have a site that references an external url several times, which I have in a global "URL" field.

I want to use Link Field, and be able to select that global as the link URL.

Feature Request: getAttrs

Right now when using the field in templates there are methods for grabbing each of the available fields, which is great. But I'm wondering if we could maybe have a shortcut method to get all of them at once.

The biggest thing this would help with is the scenario where you need the anchor tag to wrap some other elements. You can grab all of the fields one by one, but it can get a little verbose. For example

<a
    class="nav-link"
    href="{{ entry.customLink }}"
    {% if entry.customLink.getTarget %}
        target="{{ entry.customLink.getTarget }}"
    {% endif %}
    {% if entry.customLink.getTitle %}
        title="{{ entry.customLink.getTitle }}"
    {% endif %}
    {% if entry.customLink.getAriaLabel %}
        aria-label="{{ entry.customLink.getAriaLabel }}"
    {% endif %}
>
    <p>
        {{ entry.customLink.getText }}
    </p>
</a>

But I'm thinking this logic could be extracted into a getAttrs method that would behave something like

<a {{ entry.customLink.getAttrs }}>
    <p>
        {{ entry.customLink.getText }}
    </p>
</a>

If this feature sounds like it would be a good fit to add to this plugin, I'm totally willing to jump in and submit a PR for it. I just wanted to run the idea past everyone first and potentially get some feedback before jumping straight into code.

Linking to pending entries

I've discovered getElement returns null when the linked entry is pending, I feel like I should at least be able to pass status(null) or similar to get at it. Is this something I can't figure out or is this not yet supported?

Visually group fields together

I think it would help if you visually grouped all the fields…right now additional fields ("Custom link text", "Open link in new window") look like totally separate fields, when they should be grouped with the main link input.

screen shot 2018-03-07 at 12 18 02 pm

Fields are not visible on load

After load, he link type "URL" is preselected, but the url value field is only visible after selecting another link type (for example "Mail" and toggling back to "URL".

url

Additionally, the Target and Link Text Option ("Eigener Linktext") is only visible after save the control panel entry and reopen it.

Thanks for fixing and for creating this plugin!

Content inside a "linkfield" is not accessible via Crafts `find()->relatedTo`

I, for example, have an entry "Contact" and it is linked on various other entries via the linkfield and entries field.

Now im trying to get all the entries the "Contact" entry is linked on via the following code:

return Entry::find()->relatedTo([
            'targetElement' => $contactEntryId,
            'field' => [
               'entriesCollection' , //<-- entries field
               'linkedfield', <-- linkfield
            ],
        ])->all();

Only using the entriesCollection i get all entries the "Contact" entry was linked inside a entries field.

Using it in combination or only the campaignsiteCallToAction i get no response. It should return all entries where the "Contact" entry was linked inside a linkfield and/or entries field

I hope i explained my issue clearly. If not, im happy to explain further.

Relative URLs

Can you switch the URL Field type to text that we can use stuff like /contact/ or maybe add a custom option?

Get link type functionality

Hey @sebastian-lenz THANK YOU for this plugin. It's just what I need for my project.

Question: Is there a way to return the type of the field (entry, category, url, etc)? I'm not seeing it in the documentation and when I try link.myLinkField.getType() it errors out.

Sorry to ask a question in an issue, couldn't find you on Craft Slack.

Linking to Asset is Broken

Getting a file not found.

It looks like only the file name (instead of the whole file path) is getting passed in. Thought it might have been my asset settings, tried an absolute path as well instead but still no dice.

Stack Trace:

yii\base\ErrorException: finfo_file(Aglime-Key-to-Increased-Yield-and-Profits1.pdf): failed to open stream: No such file or directory in /Volumes/ProBeast/Users/dave/Sites/W/vendor/yiisoft/yii2/helpers/BaseFileHelper.php:158
Stack trace:
#0 /Volumes/ProBeast/Users/dave/Sites/W/vendor/craftcms/cms/src/web/ErrorHandler.php(84): yii\base\ErrorHandler->handleError(2, 'finfo_file(Agli...', '/Volumes/ProBea...', 158)
#1 [internal function]: craft\web\ErrorHandler->handleError(2, 'finfo_file(Agli...', '/Volumes/ProBea...', 158, Array)
#2 /Volumes/ProBeast/Users/dave/Sites/W/vendor/yiisoft/yii2/helpers/BaseFileHelper.php(158): finfo_file(Resource id #468, 'Aglime-Key-to-I...')
#3 /Volumes/ProBeast/Users/dave/Sites/W/vendor/craftcms/cms/src/helpers/FileHelper.php(260): yii\helpers\BaseFileHelper::getMimeType('Aglime-Key-to-I...', NULL, true)
#4 /Volumes/ProBeast/Users/dave/Sites/W/vendor/craftcms/cms/src/helpers/FileHelper.php(308): craft\helpers\FileHelper::getMimeType('Aglime-Key-to-I...', NULL, true)
#5 /Volumes/ProBeast/Users/dave/Sites/W/vendor/craftcms/cms/src/elements/Asset.php(708): craft\helpers\FileHelper::isGif('Aglime-Key-to-I...')
#6 /Volumes/ProBeast/Users/dave/Sites/W/vendor/sebastianlenz/linkfield/src/models/ElementLinkType.php(206): craft\elements\Asset->getUrl()
#7 /Volumes/ProBeast/Users/dave/Sites/W/vendor/sebastianlenz/linkfield/src/models/Link.php(191): typedlinkfield\models\ElementLinkType->getUrl(Object(typedlinkfield\models\Link))
#8 /Volumes/ProBeast/Users/dave/Sites/W/vendor/sebastianlenz/linkfield/src/models/Link.php(214): typedlinkfield\models\Link->getUrl()
#9 /Volumes/ProBeast/Users/dave/Sites/W/vendor/craftcms/cms/src/helpers/StringHelper.php(758): typedlinkfield\models\Link->__toString()
#10 /Volumes/ProBeast/Users/dave/Sites/W/vendor/craftcms/cms/src/base/Field.php(337): craft\helpers\StringHelper::toString(Object(typedlinkfield\models\Link), ' ')
#11 /Volumes/ProBeast/Users/dave/Sites/W/vendor/craftcms/cms/src/fields/Matrix.php(555): craft\base\Field->getSearchKeywords(Object(typedlinkfield\models\Link), Object(craft\elements\Entry))
#12 /Volumes/ProBeast/Users/dave/Sites/W/vendor/craftcms/cms/src/services/Content.php(236): craft\fields\Matrix->getSearchKeywords(Object(craft\elements\db\MatrixBlockQuery), Object(craft\elements\Entry))
#13 /Volumes/ProBeast/Users/dave/Sites/W/vendor/craftcms/cms/src/services/Content.php(201): craft\services\Content->_updateSearchIndexes(Object(craft\elements\Entry), Object(craft\models\FieldLayout))
#14 /Volumes/ProBeast/Users/dave/Sites/W/vendor/craftcms/cms/src/services/Elements.php(459): craft\services\Content->saveContent(Object(craft\elements\Entry))
#15 /Volumes/ProBeast/Users/dave/Sites/W/vendor/craftcms/cms/src/controllers/EntriesController.php(543): craft\services\Elements->saveElement(Object(craft\elements\Entry))
#16 [internal function]: craft\controllers\EntriesController->actionSaveEntry()
#17 /Volumes/ProBeast/Users/dave/Sites/W/vendor/yiisoft/yii2/base/InlineAction.php(57): call_user_func_array(Array, Array)
#18 /Volumes/ProBeast/Users/dave/Sites/W/vendor/yiisoft/yii2/base/Controller.php(157): yii\base\InlineAction->runWithParams(Array)
#19 /Volumes/ProBeast/Users/dave/Sites/W/vendor/craftcms/cms/src/web/Controller.php(76): yii\base\Controller->runAction('save-entry', Array)
#20 /Volumes/ProBeast/Users/dave/Sites/W/vendor/yiisoft/yii2/base/Module.php(528): craft\web\Controller->runAction('save-entry', Array)
#21 /Volumes/ProBeast/Users/dave/Sites/W/vendor/craftcms/cms/src/web/Application.php(273): yii\base\Module->runAction('entries/save-en...', Array)
#22 /Volumes/ProBeast/Users/dave/Sites/W/vendor/craftcms/cms/src/web/Application.php(521): craft\web\Application->runAction('entries/save-en...', Array)
#23 /Volumes/ProBeast/Users/dave/Sites/W/vendor/craftcms/cms/src/web/Application.php(257): craft\web\Application->_processActionRequest(Object(craft\web\Request))
#24 /Volumes/ProBeast/Users/dave/Sites/W/vendor/yiisoft/yii2/base/Application.php(386): craft\web\Application->handleRequest(Object(craft\web\Request))
#25 /Volumes/ProBeast/Users/dave/Sites/W/public_html/index.php(21): yii\base\Application->run()
#26 {main}

Links to entries always point to default site

We're currently developing a multi-site in Craft, and we're using this plugin to give the user the opportunity to link to URLs as well as entries. However, we seem to be running into two problems:

  • When adding a disabled entry as a link, it is gone upon saving (is that intentional or not?)
  • When adding an entry as a link in a site that is not the default one (e.g. "A"), the entry of the default site (e.g. Entry of "A") is taken instead of the entry of the non-default site (e.g. Entry of "B") that we are editing

When adding an entry that exists in both sites to a non-default site ("B") and the entry is disabled in the default site ("A") but enabled in the non-default site ("B"), it is gone because of the first and second bullet point playing together. However, it only seems to be gone in the backend, but not in the frontend (you can see it on the website).

Maybe you can help us out with this bug? That'd be much appreciated!

More compact display

I'm really enjoying LinkField, but I think it's taking a bit too much space in my field list for an entry, especially for big entries.

Here are screenshots of what I mean:
https://imgur.com/a/y3PlA2I

I achieved the second result by changing some styling in Chrome, and I'll probably do it permanently through a CP CSS plugin, but it'd be great to have this built in I think!

Linking Entries to itself

For example editing the entry "Contact", i would like to add a link that points to the entry itself but with an additional anker. /contact#anker.

But the plugin greys out the entry you are currently editing.

Am i missing something in the settings?

Unable to install via composer

When attempting to install via

composer require sebastianlenz/linkfield

Composer returns the following error:

[InvalidArgumentException]                                                                                                                                                                                               
  Could not find a matching version of package sebastianlenz/linkfield. Check the package spelling, your version constraint and that the package is available in a stability which matches your minimum-stability (beta).

Choosing default link type

Currently the plugin displays the first activated link type when the field type is used. This could be improved by allowing the user to choose the default link type, instead.

Use case example

I am creating a navigation builder using Craft’s Structure section type. 9 times out of 10 I will want to use an entries link, but there are times where the client will want to include a link to an external site, too. It would be helpful if the fieldtype allowed me to just default to the entry link instead.

Allow localized custom link text

Is it possible that you can add a setting so we can specify if the "Custom link text" should be specific to site/languages?

I know I can set the whole field to «Translateable», but I actually don't want customers to add different links in every language, but simply add a different Link text.

So for example if you add a Link with the Text «Read more», you should be able to add a localized Link Text like «Mehr lesen» in german, without localizing the whole field and the link itself.

Thank you!

Ability to choose the entry type in a structure

A feature request:
Wouldn't it be handy to be able to select a specific entry type in a structure? So if you choose a structure, you get the entry types to select from too? Or something like that? I'd love to see that happen - I've bumped into a problem in the past (and now) in which that possibility would've saves me quite a lot of work.

Pass custom link text to getLink

In the same spirit as #4, when using a Craft structure to build a navigation, it could be a nice addition to have the getLink function accept a parameter for link text. We could use the entry title instead of the link text prop.

Issue with channels

When trying to select an entry, I'm not seeing any entries in Channel-type sections. Structures and singles seem to work fine.

I thought it might be an issue with multisite, but Channel-type section entries don't show up whether or not they are set to "propagate across all sites".

Thanks for the plugin!

Feature Request: Add ability to define reusable field settings

We often use entry types to handle data to help with content translations, define reusable content blocks, set scheduled announcements, etc.

Link fields need to have these removed, so the user is only presented with entries that they should be linking to.

As soon as we uncheck all (from Categories, Entries, etc) and define our available sources, we end up with a project management nightmare. The next time a new entry type is added, we have to remember to go into every field, sometimes deeply nested in Matrix or Super Tables, and ensure that we add that type as an available source.

Outside of handling sources, being able to define our other options would also be a welcome improvement. Currently, every time I add a new link field, I have to go through the whole setup process again.

If we could define all of our unique link types in a settings panel, then optionally select from them when creating a link field (much like related entries), this would greatly reduce the chance for errors and save us a lot of hassle.

Support aliases (@web)

Right now there seems to be no way of linking relative to the site's URL, which is cumbersome for multiple testing environments.

For instance, /store is recognized as an invalid URL, so is @web/store.

Get children of a linked entry/structure

I am trying to achieve a multi level navigation with the use of craft-linkfield.

E.g. I do use craft-linkfield to create my site navigation and simply link to a entry or category.
However for a specific site i need to create a multilevel menu that would create links for the children of an entry, is it even possible to get the children of an entry through craft-linkfield.

Thanks for the awesome work!

FR: Add migration from Fruit Link It field

Those of us coming from Craft 2 probably used the Fruit Studio's Link It plugin, which was free at the time. While I think it's fair for developers to want to be paid, I think their price point is pretty silly (and honestly in my opinion, it ought to be free if we're trying to invest in Craft CMS as a community). We should add a CLI option or utility to convert Link It fields to typed link fields from either Craft 2 or Craft 3.

Announcement: Version 2

Hi everyone! Over the last weeks we've been working on a bigger update for the link field. The new update comes with several requested features but the biggest change will be the fact that we will be storing links to a dedicated table instead of a chunk of json like before. This unlocks a whole lot of new possibilities for querying and updating links with simple db commands.

As this requires us to update all your stored links we would like to make sure the update process is as smooth as possible for everyone. Therefore we kindly invite everyone eager enough to try out the v2 beta version to provide feedback.

Updating

In order to use the beta version of the link field in your project, first make sure you have a backup of your database, then make the following changes to your composer.json before running composer update:

  "minimum-stability": "beta",
  "require": {
    "sebastianlenz/linkfield": "^2.0-beta",
  },

New stuff

Eager loading of linked elements

Starting with v2 you can now eager load linked elements. This can save a lot of time e.g. when displaying content that must access the linked elements. You may activate the eager loading by specifying the name of the link field in the with argument of element queries:

{% set pages = craft.entries.section('footer').with('linkField').all() %}

Caching linked element urls and titles

If you don't need to access the linked elements the field might still need to load the element as we need to know the url or title of the linked element. With v2 this lookup can be avoided by caching the linked elements url and title. Open the settings of your link field and tick the checkbox Enable element url and title cache on the common settings page.

The link field stores urls and titles of linked elements within the link record. The plugin watches for element changes and updates these values accordingly. You'll find a new cache option in Tools > Clear caches named Link field element cache allowing you to rebuild all cached element links. This might be handy when moving your site between hosts or when the base url / slug format of your entries change.

New link type and link models

In previous versions links where able to simply store one value, which turned out to be very limiting. The new version therefore adds distinctive link models for the different link types allowing us to store more data with each link type. This makes authoring link types much more flexible and allows us to integrate more features in the future.

Out of the box v2 comes with the ability to link to elements across different sites within your Craft installation, just ticke the new option Allow links to reference a different site on element link types on the field settings. When selecting elements users now can change the target site in the element popup.

New namespace

The plugin namespace has moved to lenz\linkfield. This is just some houskeeping in preparation of the release of another plugin.

Feedback

We would like you to try out these new features and especially provide feedback for the upgrade experience, both positive and negative. Please leave a comment or emote right here to let us know how things played out for you.

Tel Link

It would be great to allow for telephone formatting for instance (xxx) xxx-xxxx so that users are only entering numbers where the x's are in the back end and then I can reformat how I want on the front end. Currently the value is also stored with "tel:" which is helpful for the url portion but not how I want the number to display.

Thanks!

Entry selection doesnt work

I have matrix field, each block has link field with entry and category selection allowed.
When i want to select entry, window apperars, but it just shows preloader. When i close window and click it second time, it wont appear at all.
Category selection window works ok.

These is browser console error that appears after first click (i have devmode enabled):

jquery.js:9566 POST http://address/web/index.php?p=admin/actions/elements/get-modal-body 500 (Internal Server Error)

This is error that appears after second click:

Craft.js:4281 Uncaught TypeError: Cannot read property 'getSelectedElements' of null
    at s.constructor.updateSelectBtnState (Craft.js:4281)
    at s.constructor.show (Craft.js:4354)
    at s.constructor.e [as show] (garnish.js:79)
    at s.constructor.showModal (Craft.js:4053)
    at s.constructor.i (jquery.js:496)
    at s.constructor.<anonymous> (garnish.js:893)
    at HTMLDivElement.i (jquery.js:496)
    at HTMLDivElement.dispatch (jquery.js:5206)
    at HTMLDivElement.v.handle (jquery.js:5014)
    at Object.trigger (jquery.js:8201)

I have similar versions of this field in matrix in other parts of page and they work OK.

This probably appeared after updating to craft 3.1. My current version is Craft CMS 3.1.5 and typed link field version is 1.0.16.

Can't get Module to load.

I'm trying to extend the Link Field plugin as specified in https://github.com/sebastian-lenz/craft-linkfield#api but it doesn't seem to be loading my module.

I have the module in /modules/VideoModalModule.php and have registered it in my autoload with

"autoload": {
    "psr-4": {
      "modules\\": "modules/"
    }
  },

I have it loading in my app config in /config/app.php like so:

    'modules' => [
        'video-modal' => \modules\VideoModalModule::class,
    ],

And the module looks like so:

<?php
namespace modules;

use Craft;

use typedlinkfield\Plugin as LinkPlugin;
use typedlinkfield\events\LinkTypeEvent;
use typedlinkfield\models\InputLinkType;
use yii\base\Event;

/**
 * Custom module class.
 */
class VideoModalModule extends \yii\base\Module
{
  public function init() {
    parent::init();
    Event::on(
      LinkPlugin::class,
      LinkPlugin::EVENT_REGISTER_LINK_TYPES,
      function(LinkTypeEvent $event) {
        $event->linkTypes['videoModalModule'] = new InputLinkType([
          'displayName'  => 'Video Modal',
          'displayGroup' => 'Input fields',
          'inputType'    => 'url'
        ]);
      }
    );
  }
}

I also ran composer dumpautoload.

No errors but its not loading.

Adding relative links

Is there a way to add a relative link to a linkfield, ie /product/test instead of http://mysite.com/product/test? Right now any relative url is rejected. It would also be nice to add a token like {siteUrl}/product/test that would replace the siteUrl with the current domain being used.

Remove site dependency on element select field

Would you consider removing the hardcoded relation criteria to elements within the current site, to enable selecting elements across sites?

Looking into the code, it appears even if this were to be accepted, it would require a change in core that would allow the _includes/forms/elementSelect macro to respect the showSiteMenu setting in the Craft.BaseElementSelectInput JS function.

I've filed a pull request for that anyway, as it seems like an oversight: craftcms/cms#3494. If this were to be accepted it would pave the way to implementing something like this in the plugin.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.