Unable to hide/disable custom metabox in attachment - wordpress

I have a stack with https://lumberjack.rareloop.com/ and use it to create a custom taxonomy for WP attachement. I use it to filter my media in admin panel and hide them to non-authorize account. I would like to hide meta box for the same account but can't find a way to make it work.
My custom taxonomy:
namespace App\Taxonomy;
use Rareloop\Lumberjack\Models\AbstractTerm;
class AttachmentType extends AbstractTerm
{
public static function getTaxonomyObjectTypes(): array
{
return [
'attachment',
];
}
public static function getTaxonomy(): string
{
return 'attachment_type';
}
protected static function getTaxonomyConfig(): array
{
return [
'hierarchical' => false,
'public' => false,
'publicly_queryable' => false,
'show_ui' => true,
'query_var' => 'media',
'meta_box' => 'radio',
'meta_box_cb' => false, // not working
];
}
Also try to use admin_menu hook in functions.php with no success :
add_action('admin_menu','remove_post_meta_boxes');
function remove_post_meta_boxes() {
remove_meta_box( 'submitdiv','attachment','normal' ); // working
remove_meta_box( 'attachment_typediv','attachment','normal' ); // not working
}
Metabox still visible with id attachment_typediv in html. Search for hours and tried many things but couldn't find a solution.
Any help is greatly appreciated!

Related

Adding graphql support for custom posts

I have installed WP GraphQL plugin and it works fine for pages and posts. However its not working for custom posts.
for example,
query getPages{
pages(first: 1000) {
edges {
node {
uri
}
}
}
}
works.
query getPastEvents{
past-events(first: 1000) {
edges {
node {
uri
}
}
}
}
not works.
I have read this doc https://www.wpgraphql.com/docs/custom-post-types/ but still not understood exact process.
update: i added the below code in wp-includes/plugin.php and its now showing careCenter, careCenterPages in WP GraphQL IDE but its returning no data
// WP GRAPH QL
add_action( 'init', function() {
register_post_type( 'care_center', [
'show_ui' => true,
'labels' => [
//#see https://developer.wordpress.org/themes/functionality/internationalization/
'menu_name' => __( 'CareCenter', 'care_center' ),
],
'show_in_graphql' => true,
'hierarchical' => true,
'graphql_single_name' => 'careCenter',
'graphql_plural_name' => 'careCenterPages',
] );
} );
add_filter( 'register_post_type_args', function( $args, $post_type ) {
// Change this to the post type you are adding support for
if ( 'care_center' === $post_type ) {
$args['show_in_graphql'] = true;
$args['graphql_single_name'] = 'careCenter';
$args['graphql_plural_name'] = 'careCenterPages';
}
return $args;
}, 10, 2 );
am attaching few screenshots below for more understanding...
I want graphql support for custom posts just like pages & posts.

How to execute a Drupal-view in a custom module and print the output (as html-markup)?

I want to print the output from a simple view in my custom module. But is doesnt work. I have tried many options from forums and stackoverflow. All of them print "array" instead of html-markup.
My controller:
class DefaultController extends ControllerBase {
public function myfunc1() {
$view = Views::getView('myfirstview');
$view->setDisplay('page_1');
$view->preExecute();
$view->execute();
// $myresults = $view->preview(); = array
// $myresults = $view->render(); = array
$myresults = $view->result; // = array
return array(
'#title' => 'Hello World!',
'#markup' => $myresults,
);
}
}
How can I print the result/output of a view programmatically?
I dont want to make it without "embed view" , because I want to set some exposed filters later.
get the view
$corresponding_view = Views::getView('myfirstview');
set exposed filters
$arguments = your arguments (exposed filter value);
$corresponding_view->setArguments($arguments);
embed your view
return [
'#type' => 'view',
'#name' => 'myfirstview',
'#view' => $corresponding_view,
'#display_id' => 'page_1',
'#embed' => TRUE,
];

How to remove category from sonata_type_model_list at url #admin_sonata_media_media_create

I'm using Media in User Entity(avatar).
At first I used sonata_media_type. It worked good.
The problem is I'm using ManyToOne - so the admin can select one from the list. To achieve this I have to use sonata_type_model_list - this has list,new,delete actions. I removed delete by 'btn_delete' => ''. Here the list action works good(up to now).
The real PROBLEM is at new action. The new action window load from ajax - and it has File/Reference, Category (Two fields).
Here I need to remove Category field entirely(list,new,delete). Why do we need this? Because it is useless!.
LIST - only display the 'context' => 'profile' from
'link_parameters'. So here the LIST action is useless.
NEW - New action can create new context, but it will not display in the
LIST(right now). So I don't need this. If I need I'll create from
ClassificationBundle.
DELETE - Delete action has no effect(right now - here).
MY-RESEARCH:
I tried to modify the TEMPLATE - but I can't find the correct twig file. It points to parent() - which is pointing to admin bundle!
To validation File/Reference - I created my own ImageProvider(as per doc) - It works(validate) good.
I tried to remove Category field(check image) - but failed.
My code is:
class ImageProvider extends BaseProvider{...}
public function buildCreateForm(FormMapper $formMapper) {
// This works - changed File/Reference to ok
$formMapper->add('binaryContent', 'file', array('label' => 'ok',
'constraints' => array(
new NotBlank(),
),
));
// This works - added a new text field
$formMapper->add('context', 'text', ['attr' => ['class' => 'fz_rocks']]);
// This not working - also ->add('category') - has no effect even when attr=hide and so on..
$formMapper->remove('category');
}
-
To remove category field from media popup
You need to override media admin's class by overriding class parameter sonata.media.admin.media.class
Create you own admin class and extend it with sonata media's base admin class.
Override configureFormFields() method by defining in your admin class
Remove category field from $formMapper
Override Sonata media class
parameters:
sonata.media.admin.media.class: Your\MediaBundle\Admin\ORM\MediaAdmin
Media Admin Class
namespace Your\MediaBundle\Admin\ORM;
use Sonata\MediaBundle\Admin\ORM\MediaAdmin as Admin;
// .. Other use statements
class MediaAdmin extends Admin {
/**
* {#inheritdoc}
*/
protected function configureFormFields( FormMapper $formMapper ) {
$media = $this->getSubject();
if ( ! $media ) {
$media = $this->getNewInstance();
}
if ( ! $media || ! $media->getProviderName() ) {
return;
}
$formMapper->add( 'providerName', 'hidden' );
$formMapper->getFormBuilder()->addModelTransformer( new ProviderDataTransformer( $this->pool, $this->getClass() ), true );
$provider = $this->pool->getProvider( $media->getProviderName() );
if ( $media->getId() ) {
$provider->buildEditForm( $formMapper );
} else {
$provider->buildCreateForm( $formMapper );
}
}
}
I solved by hiding the categoy field. If i removed completely it cause problem sometimes. Safe is to hide.
To achieve this i use custom providers, as per sonata-media doc creating_a_provider_class.rst
namespace Application\Sonata\MediaBundle\Provider;
class ImageProvider extends BaseProvider {
public function buildCreateForm(FormMapper $formMapper) {
$formMapper->add('binaryContent', 'file', ['label' => 'Upload a new file', 'constraints' => [new NotBlank(), new NotNull()]])->end();
$formMapper->with('General', ['class' => 'hidden'])->add('category');
}
public function buildEditForm(FormMapper $formMapper) {
parent::buildEditForm($formMapper);
$formMapper->add('binaryContent', 'file', ['label' => 'Upload a new file', 'required' => FALSE])->end();
$formMapper->with('General', ['class' => 'hidden'])->add('category');
}
}

SilverStripe and Display Logic fails with certain field types

I'm working on a SilverStripe 3.1.8 site. I have a DataExtension that defines some fields, and I'm trying to use Display Logic to modify the behavior of the CMS:
private static $db = array(
'Enabled' => 'Boolean',
'Title' => 'Text'
);
private static $has_one = array(
'Link' => 'SiteTree',
'Image' => 'Image'
);
/* this is a DataExtension */
public function updateCMSFields(FieldList $fields) {
$fields->addFieldsToTab('Root.Other', array(
CheckboxField::create('Enabled'),
TextField::create('Title', "Title")->displayIf('Enabled')->isChecked()->end(),
TreeDropdownField::create("LinkID", "Linked page", 'SiteTree')->displayIf('Enabled')->isChecked()->end(),
UploadField::create('Image', "Image")->displayIf('Enabled')->isChecked()->end()
));
}
When I check or uncheck the "Enabled" checkbox, the other three fields should appear or disappear correspondingly. Unfortunately, only the TextField does, the TreeDropdownField and UploadField are always shown.
Any ideas why Display Logic fails with these two field types, and how to solve it?
Thank you!
It appears that UploadField and DropdownField fall under the category of Dealing with non-standard forms and you need to wrap them in a DisplayLogicWrapper.
See the last 2 lines of the addFieldsToTab input array.
private static $db = array(
'Enabled' => 'Boolean',
'Title' => 'Text'
);
private static $has_one = array(
'Link' => 'SiteTree',
'Image' => 'Image'
);
/* this is a DataExtension */
public function updateCMSFields(FieldList $fields) {
$fields->addFieldsToTab('Root.Other', array(
CheckboxField::create('Enabled'),
TextField::create('Title', "Title")->displayIf('Enabled')->isChecked()->end(),
DisplayLogicWrapper::create(TreeDropdownField::create("LinkID", "Linked page", 'SiteTree'))->displayIf('Enabled')->isChecked()->end(),
DisplayLogicWrapper::create(UploadField::create('Image', "Image"))->displayIf('Enabled')->isChecked()->end()
));
}

Drupal validation solution when using file upload with other required form field

I am having problem while trying to upload a picture in a form that also has other required field. So if I dont enter anything on the required field and upload the picture, I lose the picture that's uploaded (during the form validation the picture is no longer there).
I can't print it anywhere in form_state and all. How can I have a file upload inside a form with other form elements which are required? I dont want user to upload the picture again if the user forgets to enter the info in the other required field.
Any ideas?
function form() {
$form['#attributes'] = array('enctype' => "multipart/form-data");
//'upload' will be used in file_check_upload()
$form['upload'] = array('#type' => 'file');
$form['my_require_field'] = array(
'#type' => 'textfield',
'#title' => t('Enter code here'),
'#default_value' => 1,
'#size' => 20,
'#required' => TRUE
);
}
function form_validate() {
if(!file_check_upload('upload')) {
form_set_error('upload', 'File missing for upload.');
}
}
function form_submit() {
$file = file_check_upload('upload');
}
You should use the managed_file type id you are using Drupal 7
$form['upload'] = array(
'#type' => 'managed_file',
'#title' => t('Upload Image'),
'#default_value' => '',
'#required' => TRUE,
'#description' => t("Upload Image description"),
);
In your submit handler you can write following:
// Load the file via file fid.
$file = file_load($form_state['values']['upload']);
// Change status to permanent and save.
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
Hope this will help!
For Drupal 8
It appears that such basic functionality as making field of type file (not managed_file) required is not supported out of the box.
One need to implement custom validator for this field in formValidate() method.
A rare example of such functionality can be found in ConfigImportForm.php file.
Here is a snippet of code to handle file field setup in the form, required validation and submission.
<?php
class YourForm extends FormBase {
public function buildForm(array $form, FormStateInterface $form_state) {
$form['myfile'] = [
'#title' => $this->t('Upload myfile'),
'#type' => 'file',
// DO NOT PROVILDE '#required' => TRUE or your form will always fail validation!
];
}
public function validateForm(array &$form, FormStateInterface $form_state) {
$all_files = $this->getRequest()->files->get('files', []);
if (!empty($all_files['myfile'])) {
$file_upload = $all_files['myfile'];
if ($file_upload->isValid()) {
$form_state->setValue('myfile', $file_upload->getRealPath());
return;
}
}
$form_state->setErrorByName('myfile', $this->t('The file could not be uploaded.'));
}
public function submitForm(array &$form, FormStateInterface $form_state) {
// Add validator for your file type etc.
$validators = ['file_validate_extensions' => ['csv']];
$file = file_save_upload('myfile', $validators, FALSE, 0);
if (!$file) {
return;
}
// The rest of submission processing.
// ...
}
}
From https://api.drupal.org/comment/63172#comment-63172

Resources