vctls / select2entity-extension-bundle
是 TetranzSelect2EntityBundle 的一个扩展,包含一些辅助类。
1.0
2019-04-02 12:05 UTC
Requires
- php: >=5.4.0
- doctrine/orm: >=2.4
This package is auto-updated.
Last update: 2024-09-29 05:42:15 UTC
README
此包为使用 Tetranz Select2EntityBundle 提供辅助功能。
Searcher
类定义了在 Select2 字段中使用的实体配置。
配置
向默认控制器添加路由
# routes.yml vctls_select2_entity_extension: resource: '@VctlsSelect2EntityExtensionBundle/Resources/config/routing.yaml'
在 config.yml
中添加您的 Searcher
类命名空间。默认为 App\Util
# config.yml vctls_select2_entity_extension: searcher_namespace: 'App\Tools\Select2\'
创建 Select2 字段
首先,为您的字段中要使用的实体创建一个 Searcher
类。
<?php namespace App\Util; use Vctls\Select2EntityExtensionBundle\Util\Searcher; class ExampleSearcher extends Searcher { public $alias = 'example'; public $idMethod = 'getId'; public $textMethod = '__toString'; public $searchfileds = ['example.name']; }
然后,在您的表单中添加一个 Select2 字段
<?php namespace App\Form\Example; use App\Entity\Example; use Vctls\Select2EntityExtensionBundle\Util\S2; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; class ExampleType extends AbstractType { /** * {@inheritdoc} */ public function buildForm(FormBuilderInterface $builder, array $options) { // with the helper class... $builder->add(...S2::build('example', Example::class)); // or without it $builder->add('example2', Select2EntityType::class, [ 'remote_route' => 'generic_autocomplete', 'remote_params' => [ 'classname' => Example::class ], 'class' => Example::class, 'primary_key' => 'id', 'text_property' => 'name', 'minimum_input_length' => 2, 'delay' => 250, 'cache' => true, 'placeholder' => 'Select an example', ]); } }
保护默认控制器访问
您可以创建一个 Voter
来控制对不同实体的访问。
<?php // App\Security\EntityVoter.php namespace App\Security; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\Voter\Voter; use App\Entity; class EntityVoter extends Voter { const ENTITIES_BY_ROLE = [ 'ROLE_USER' => [ Entity\Example::class ], 'ROLE_ADMIN' => [ Entity\User::class ] ]; protected function supports($access, $subject) { return $access === 'view' && gettype($subject) === 'string'; } protected function voteOnAttribute($access, $subject, TokenInterface $token) { $roles = $token->getRoles(); foreach ($roles as $role) { if (in_array($subject, self::ENTITIES_BY_ROLE[$role->getRole()])) { return true; } } return false; } }