本文整理汇总了PHP中Drupal类的典型用法代码示例。如果您正苦于以下问题:PHP Drupal类的具体用法?PHP Drupal怎么用?PHP Drupal使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Drupal类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的PHP代码示例。
示例1: form
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state)
{
$view = $this->entity;
$form['#prefix'] = '<div id="views-preview-wrapper" class="views-admin clearfix">';
$form['#suffix'] = '</div>';
$form['#id'] = 'views-ui-preview-form';
$form_state->disableCache();
$form['controls']['#attributes'] = array('class' => array('clearfix'));
$form['controls']['title'] = array('#prefix' => '<h2 class="view-preview-form__title">', '#markup' => $this->t('Preview'), '#suffix' => '</h2>');
// Add a checkbox controlling whether or not this display auto-previews.
$form['controls']['live_preview'] = array('#type' => 'checkbox', '#id' => 'edit-displays-live-preview', '#title' => $this->t('Auto preview'), '#default_value' => \Drupal::config('views.settings')->get('ui.always_live_preview'));
// Add the arguments textfield
$form['controls']['view_args'] = array('#type' => 'textfield', '#title' => $this->t('Preview with contextual filters:'), '#description' => $this->t('Separate contextual filter values with a "/". For example, %example.', array('%example' => '40/12/10')), '#id' => 'preview-args');
$args = array();
if (!$form_state->isValueEmpty('view_args')) {
$args = explode('/', $form_state->getValue('view_args'));
}
$user_input = $form_state->getUserInput();
if ($form_state->get('show_preview') || !empty($user_input['js'])) {
$form['preview'] = array('#weight' => 110, '#theme_wrappers' => array('container'), '#attributes' => array('id' => 'views-live-preview'), 'preview' => $view->renderPreview($this->displayID, $args));
}
$uri = $view->urlInfo('preview-form');
$uri->setRouteParameter('display_id', $this->displayID);
$form['#action'] = $uri->toString();
return $form;
}
示例2: getEntityManager
/**
* Returns the entity manager.
*
* @return \Drupal\Core\Entity\EntityManagerInterface
* The entity manager service.
*/
protected function getEntityManager()
{
if (!isset($this->entityManager)) {
$this->entityManager = \Drupal::entityManager();
}
return $this->entityManager;
}
示例3: validateStub
/**
* Perform validation on a stub entity.
*
* @param string $entity_type_id
* The entity type we are stubbing.
* @param string $entity_id
* ID of the stubbed entity to validate.
*
* @return \Drupal\Core\Entity\EntityConstraintViolationListInterface
* List of constraint violations identified.
*/
protected function validateStub($entity_type_id, $entity_id)
{
$controller = \Drupal::entityManager()->getStorage($entity_type_id);
/** @var \Drupal\Core\Entity\ContentEntityInterface $stub_entity */
$stub_entity = $controller->load($entity_id);
return $stub_entity->validate();
}
示例4: nextMail
/**
* {@inheritdoc}
*/
public function nextMail()
{
// Get the current mail spool row and update the internal pointer to the
// next row.
$return = each($this->mails);
// If we're done, return false.
if (!$return) {
return FALSE;
}
$spool_data = $return['value'];
// Store this spool row as processed.
$this->processed[$spool_data->msid] = $spool_data;
$entity = entity_load($spool_data->entity_type, $spool_data->entity_id);
if (!$entity) {
// If the entity load failed, set the processed status done and proceed with
// the next mail.
$this->processed[$spool_data->msid]->result = array('status' => SpoolStorageInterface::STATUS_DONE, 'error' => TRUE);
return $this->nextMail();
}
if ($spool_data->data) {
$subscriber = $spool_data->data;
} else {
$subscriber = simplenews_subscriber_load_by_mail($spool_data->mail);
}
if (!$subscriber) {
// If loading the subscriber failed, set the processed status done and
// proceed with the next mail.
$this->processed[$spool_data->msid]->result = array('status' => SpoolStorageInterface::STATUS_DONE, 'error' => TRUE);
return $this->nextMail();
}
$mail = new MailEntity($entity, $subscriber, \Drupal::service('simplenews.mail_cache'));
// Set the langcode langcode.
$this->processed[$spool_data->msid]->langcode = $mail->getEntity()->language()->getId();
return $mail;
}
示例5: setUp
function setUp()
{
parent::setUp();
$this->drupalCreateContentType(array('type' => 'article', 'name' => 'Article'));
// Create and login user.
$admin_user = $this->drupalCreateUser(array('administer site configuration', 'administer languages', 'access administration pages', 'administer content types', 'administer comments', 'create article content', 'access comments', 'post comments', 'skip comment approval'));
$this->drupalLogin($admin_user);
// Add language.
$edit = array('predefined_langcode' => 'fr');
$this->drupalPostForm('admin/config/regional/language/add', $edit, t('Add language'));
// Set "Article" content type to use multilingual support.
$edit = array('language_configuration[language_show]' => TRUE);
$this->drupalPostForm('admin/structure/types/manage/article', $edit, t('Save content type'));
// Enable content language negotiation UI.
\Drupal::state()->set('language_test.content_language_type', TRUE);
// Set interface language detection to user and content language detection
// to URL. Disable inheritance from interface language to ensure content
// language will fall back to the default language if no URL language can be
// detected.
$edit = array('language_interface[enabled][language-user]' => TRUE, 'language_content[enabled][language-url]' => TRUE, 'language_content[enabled][language-interface]' => FALSE);
$this->drupalPostForm('admin/config/regional/language/detection', $edit, t('Save settings'));
// Change user language preference, this way interface language is always
// French no matter what path prefix the URLs have.
$edit = array('preferred_langcode' => 'fr');
$this->drupalPostForm("user/" . $admin_user->id() . "/edit", $edit, t('Save'));
// Create comment field on article.
$this->container->get('comment.manager')->addDefaultField('node', 'article');
// Make comment body translatable.
$field_storage = FieldStorageConfig::loadByName('comment', 'comment_body');
$field_storage->translatable = TRUE;
$field_storage->save();
$this->assertTrue($field_storage->isTranslatable(), 'Comment body is translatable.');
}
示例6: testConfigTranslationsExist
/**
* Confirm the config defaults show on the translations page.
*/
public function testConfigTranslationsExist()
{
// Ensure the config shows on the admin form.
$this->drupalGet('admin/config/regional/config-translation');
$this->assertResponse(200);
$this->assertText(t('Metatag defaults'));
// Load the main metatag_defaults config translation page.
$this->drupalGet('admin/config/regional/config-translation/metatag_defaults');
$this->assertResponse(200);
// @todo Update this to confirm the H1 is loaded.
$this->assertRaw(t('Metatag defaults'));
// Load all of the Metatag defaults.
$defaults = \Drupal::configFactory()->listAll('metatag.metatag_defaults');
/** @var \Drupal\Core\Config\ConfigManagerInterface $config_manager */
$config_manager = \Drupal::service('config.manager');
// Confirm each of the configs is available on the translation form.
foreach ($defaults as $config_name) {
if ($config_entity = $config_manager->loadConfigEntityByName($config_name)) {
$this->assertText($config_entity->label());
}
}
// Confirm that each config translation page can be loaded.
foreach ($defaults as $config_name) {
if ($config_entity = $config_manager->loadConfigEntityByName($config_name)) {
$this->drupalGet('admin/config/search/metatag/' . $config_entity->id() . '/translate');
$this->assertResponse(200);
} else {
$this->error('Unable to load a Metatag default config: ' . $config_name);
}
}
}
示例7: testDirectoryPrecedence
/**
* Tests that files in different directories take precedence as expected.
*/
function testDirectoryPrecedence()
{
// Define the module files we will search for, and the directory precedence
// we expect.
$expected_directories = array('drupal_system_listing_compatible_test' => array('core/profiles/testing/modules', 'core/modules/system/tests/modules'));
// This test relies on two versions of the same module existing in
// different places in the filesystem. Without that, the test has no
// meaning, so assert their presence first.
foreach ($expected_directories as $module => $directories) {
foreach ($directories as $directory) {
$filename = "{$directory}/{$module}/{$module}.info.yml";
$this->assertTrue(file_exists(\Drupal::root() . '/' . $filename), format_string('@filename exists.', array('@filename' => $filename)));
}
}
// Now scan the directories and check that the files take precedence as
// expected.
$listing = new ExtensionDiscovery(\Drupal::root());
$listing->setProfileDirectories(array('core/profiles/testing'));
$files = $listing->scan('module');
foreach ($expected_directories as $module => $directories) {
$expected_directory = array_shift($directories);
$expected_uri = "{$expected_directory}/{$module}/{$module}.info.yml";
$this->assertEqual($files[$module]->getPathname(), $expected_uri, format_string('Module @actual was found at @expected.', array('@actual' => $files[$module]->getPathname(), '@expected' => $expected_uri)));
}
}
示例8: testSyslogSettings
/**
* Tests migration of syslog variables to syslog.settings.yml.
*/
public function testSyslogSettings()
{
$config = $this->config('syslog.settings');
$this->assertIdentical('drupal', $config->get('identity'));
$this->assertIdentical('128', $config->get('facility'));
$this->assertConfigSchema(\Drupal::service('config.typed'), 'syslog.settings', $config->get());
}
示例9: testEmbedDialog
/**
* Test the WYSIWYG embed modal.
*/
public function testEmbedDialog()
{
// Use the modal to embed into a page.
$this->drupalGet('node/add/page');
$this->find('.cke_button__video_embed')->click();
$this->assertSession()->assertWaitOnAjaxRequest();
// Assert all the form fields appear on the modal.
$this->assertSession()->pageTextContains('Autoplay');
$this->assertSession()->pageTextContains('Responsive Video');
$this->assertSession()->pageTextContains('Width');
$this->assertSession()->pageTextContains('Height');
$this->assertSession()->pageTextContains('Video URL');
// Attempt to submit the modal with no values.
$this->find('input[name="video_url"]')->setValue('');
$this->find('button.form-submit')->click();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->pageTextContains('Video URL field is required.');
// Submit the form with an invalid video URL.
$this->find('input[name="video_url"]')->setValue('http://example.com/');
$this->find('button.form-submit')->click();
$this->assertSession()->assertWaitOnAjaxRequest();
$this->assertSession()->pageTextContains('Could not find a video provider to handle the given URL.');
$this->assertContains('http://example.com/', $this->getSession()->getPage()->getHtml());
// Submit a valid URL.
$this->find('input[name="video_url"]')->setValue('https://www.youtube.com/watch?v=iaf3Sl2r3jE&t=1553s');
$this->find('button.form-submit')->click();
$this->assertSession()->assertWaitOnAjaxRequest();
// View the source of the ckeditor and find the output.
$this->find('.cke_button__source_label')->click();
$base_path = \Drupal::request()->getBasePath();
$this->assertEquals('<p>{"preview_thumbnail":"' . rtrim($base_path, '/') . '/' . $this->publicFilesDirectory . '/styles/video_embed_wysiwyg_preview/public/video_thumbnails/iaf3Sl2r3jE.jpg","video_url":"https://www.youtube.com/watch?v=iaf3Sl2r3jE&t=1553s","settings":{"responsive":1,"width":"854","height":"480","autoplay":1},"settings_summary":["Embedded Video (Responsive, autoplaying)."]}</p>', trim($this->getSession()->getPage()->find('css', '.cke_source')->getValue()));
}
示例10: testSimpleAjaxFormValue
/**
* Submits forms with select and checkbox elements via Ajax.
*/
function testSimpleAjaxFormValue()
{
// Verify form values of a select element.
foreach (array('red', 'green', 'blue') as $item) {
$edit = array('select' => $item);
$commands = $this->drupalPostAjaxForm('ajax_forms_test_get_form', $edit, 'select');
$expected = new DataCommand('#ajax_selected_color', 'form_state_value_select', $item);
$this->assertCommand($commands, $expected->render(), 'Verification of AJAX form values from a selectbox issued with a correct value.');
}
// Verify form values of a checkbox element.
foreach (array(FALSE, TRUE) as $item) {
$edit = array('checkbox' => $item);
$commands = $this->drupalPostAjaxForm('ajax_forms_test_get_form', $edit, 'checkbox');
$expected = new DataCommand('#ajax_checkbox_value', 'form_state_value_select', (int) $item);
$this->assertCommand($commands, $expected->render(), 'Verification of AJAX form values from a checkbox issued with a correct value.');
}
// Verify that AJAX elements with invalid callbacks return error code 500.
// Ensure the test error log is empty before these tests.
$this->assertNoErrorsLogged();
// We don't need to check for the X-Drupal-Ajax-Token header with these
// invalid requests.
$this->assertAjaxHeader = FALSE;
foreach (array('null', 'empty', 'nonexistent') as $key) {
$element_name = 'select_' . $key . '_callback';
$edit = array($element_name => 'red');
$commands = $this->drupalPostAjaxForm('ajax_forms_test_get_form', $edit, $element_name);
$this->assertResponse(500);
}
// Switch this back to the default.
$this->assertAjaxHeader = TRUE;
// The exceptions are expected. Do not interpret them as a test failure.
// Not using File API; a potential error must trigger a PHP warning.
unlink(\Drupal::root() . '/' . $this->siteDirectory . '/error.log');
}
示例11: getPluginCollection
/**
* Encapsulates the creation of the action's LazyPluginCollection.
*
* @return \Drupal\Component\Plugin\LazyPluginCollection
* The action's plugin collection.
*/
protected function getPluginCollection()
{
if (!$this->pluginCollection) {
$this->pluginCollection = new ActionPluginCollection(\Drupal::service('plugin.manager.action'), $this->plugin, $this->configuration);
}
return $this->pluginCollection;
}
示例12: testTermRevisionNode
/**
* Tests the Drupal 6 term-node revision association to Drupal 8 migration.
*/
public function testTermRevisionNode()
{
$node = \Drupal::entityManager()->getStorage('node')->loadRevision(2);
$this->assertIdentical(2, count($node->vocabulary_3_i_2_));
$this->assertIdentical('4', $node->vocabulary_3_i_2_[0]->target_id);
$this->assertIdentical('5', $node->vocabulary_3_i_2_[1]->target_id);
}
示例13: getConstraints
/**
* {@inheritdoc}
*/
public function getConstraints()
{
$constraint_manager = \Drupal::typedDataManager()->getValidationConstraintManager();
$constraints = parent::getConstraints();
$constraints[] = $constraint_manager->create('ComplexData', array('value' => array('Regex' => array('pattern' => '/^[+-]?((\\d+(\\.\\d*)?)|(\\.\\d+))$/i'))));
return $constraints;
}
示例14: setUp
/**
* {@inheritdoc}
*/
public function setUp()
{
parent::setUp();
$cache_contexts_manager = $this->prophesize(CacheContextsManager::class);
$cache_contexts_manager->assertValidTokens()->willReturn(TRUE);
$cache_contexts_manager->reveal();
$container = new Container();
$container->set('cache_contexts_manager', $cache_contexts_manager);
\Drupal::setContainer($container);
$this->viewer = $this->getMock('\\Drupal\\Core\\Session\\AccountInterface');
$this->viewer->expects($this->any())->method('hasPermission')->will($this->returnValue(FALSE));
$this->viewer->expects($this->any())->method('id')->will($this->returnValue(1));
$this->owner = $this->getMock('\\Drupal\\Core\\Session\\AccountInterface');
$this->owner->expects($this->any())->method('hasPermission')->will($this->returnValueMap(array(array('administer users', FALSE), array('change own username', TRUE))));
$this->owner->expects($this->any())->method('id')->will($this->returnValue(2));
$this->admin = $this->getMock('\\Drupal\\Core\\Session\\AccountInterface');
$this->admin->expects($this->any())->method('hasPermission')->will($this->returnValue(TRUE));
$entity_type = $this->getMock('Drupal\\Core\\Entity\\EntityTypeInterface');
$this->accessControlHandler = new UserAccessControlHandler($entity_type);
$module_handler = $this->getMock('Drupal\\Core\\Extension\\ModuleHandlerInterface');
$module_handler->expects($this->any())->method('getImplementations')->will($this->returnValue(array()));
$this->accessControlHandler->setModuleHandler($module_handler);
$this->items = $this->getMockBuilder('Drupal\\Core\\Field\\FieldItemList')->disableOriginalConstructor()->getMock();
$this->items->expects($this->any())->method('defaultAccess')->will($this->returnValue(AccessResult::allowed()));
}
示例15: testDeleteGroup
/**
* Delete a group.
*/
function testDeleteGroup()
{
$data = array('format_type' => 'fieldset', 'label' => 'testing');
$group = $this->createGroup('node', $this->type, 'form', 'default', $data);
$config_name = 'node.' . $this->type . '.form.default.' . $group->group_name;
$this->drupalPostForm('admin/structure/types/manage/' . $this->type . '/groups/' . $config_name . '/delete', array(), t('Delete'));
$this->assertRaw(t('The group %label has been deleted from the %type content type.', array('%label' => $group->label, '%type' => $this->type)), t('Group removal message displayed on screen.'));
$display = EntityFormDisplay::load($group->entity_type . '.' . $group->bundle . '.' . $group->mode);
$data = $display->getThirdPartySettings('field_group');
debug($data);
// Test that group is not in the $groups array.
\Drupal::entityManager()->getStorage('entity_form_display')->resetCache();
$loaded_group = field_group_load_field_group($group->group_name, 'node', $this->type, 'form', 'default');
debug($loaded_group);
$this->assertNull($loaded_group, t('Group not found after deleting'));
$data = array('format_type' => 'fieldset', 'label' => 'testing');
$group = $this->createGroup('node', $this->type, 'view', 'default', $data);
$config_name = 'node.' . $this->type . '.view.default.' . $group->group_name;
$this->drupalPostForm('admin/structure/types/manage/' . $this->type . '/groups/' . $config_name . '/delete', array(), t('Delete'));
$this->assertRaw(t('The group %label has been deleted from the %type content type.', array('%label' => $group->label, '%type' => $this->type)), t('Group removal message displayed on screen.'));
// Test that group is not in the $groups array.
\Drupal::entityManager()->getStorage('entity_view_display')->resetCache();
$loaded_group = field_group_load_field_group($group->group_name, 'node', $this->type, 'view', 'default');
debug($loaded_group);
$this->assertNull($loaded_group, t('Group not found after deleting'));
}