How to add multiple images to edit form using MongoDB in Sonata? - sonata-admin

I'm trying to find out how I can have the edit action of a Document (Entity) that is using an array of Object IDs to store the ID of an image stored using GridFS. This is a one-to-many but using an array inside the Document, instead of a middle table.
So far I was able to add the following to my edit action:
Here is the code I've used in the NewsAdmin configureFormFields():
$formMapper
->with('Images Manager')
->add(
'cover_images',
CollectionType::class,
['required' => true, 'label' => 'Cover Images'],
[ 'admin_code' => 'admin.file' ]
)
I have a controller and an action (#Route("/image/{id}", name="show_image")) that handles the display of images in the frontend using MongoDB GridFS. It uses the IDs stored in this array:

Related

TYPO3 saving Backend content in another database

I want to store content from my Backend in another database.
So let's say i have this in my Backend:
How can i save the value (e.g. the float value in the picture) in another database?
The reason why i need this, is, because i have another database, which is being used for some dynamic content loaded onto my Website with PHP.
Hopefully, someone has an idea and can help me :)
I would use either a hook which updates the foreign database with the value which is triggered if something is changed in the TYPO3 backend or I would use a scheduler task / command controller which is triggered by CLI and runs all x minutes and changes the values in the database.
There are several ways to achieve that. I just assume that you want to create relations between the tt_content table of TYPO3 and some external table in a different database or even different storage engine (web-service, file-system, ...).
In that case you could extend the TCA of the tt_content table by an additional property, let's call it external_reference. The backend form then should provide an additional selector field that allows to chose entities of the external data-source.
The following example assumes that your extension key is called my_extension, this has to be adjusted of course to the actual naming.
You can do so by putting the following configuration to your extension in the folder typo3conf/ext/my_extension/Configuration/TCA/Overrides/tt_content.php:
<?php
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addTCAcolumns(
'tt_content',
[
'external_reference' => [
'exclude' => 1,
'label' => 'External Source',
'config' => [
'type' => 'select',
'items' => [
['-- none --', 0]
],
'itemsProcFunc' => ExternalReferenceSelection::class . '->render',
'default' => 0,
]
],
]
);
\TYPO3\CMS\Core\Utility\ExtensionManagementUtility::addToAllTCAtypes(
'tt_content',
'external_reference'
);
Then you have to implement the selector and the retrieval from the external source, like e.g.
<?php
class ExternalReferenceSelection
{
public function render(array $parameters)
{
$references = ExternalReferenceRepository::instance()->findAll();
foreach ($references as $reference) {
$parameters['items'][] = [
$reference->getTitle(),
$reference->getIdentifier()
];
}
}
}
To be able to persist the selected reference, you have to extend the SQL schema of tt_content as well in typo3conf/ext/my_extension/ext_tables.sql
#
# Table structure for table 'tt_content'
#
CREATE TABLE tt_content (
external_reference int(11) unsigned DEFAULT '0' NOT NULL
);
The database schema is updated by invoking the database analyzer in the TYPO3 Install Tool, or by (re-)installing the extension in the Extension Manager.

How to insert into database Drupal Custom Fields

I retrieve content types with the following code
$form['ct'] = array(
'#type' => 'checkboxes',
'#options' => node_type_get_names(),
'#title' => t('Hangi tür içerikler hakkında bilgi almak istersiniz?'),
);
And It gives the following output
http://i.stack.imgur.com/TOfS6.png
And when I press Create new Account button, the POST Array is so :
http://i.stack.imgur.com/BtxhC.png
My Question is How can I insert into database these values and read?
There are two ways of saving this data and associates with user ID ($user->uid).
Adding a new field for users from 'admin/config/people/accounts/fields'. Say the new field name is 'ct' and it is a list type field. In hook form_alter you can assign this options to 'ct'. Drupal will take care of saving the data.
You can create separate table to keep this information and use db_insert function in hook hook_user_update. To retrieve this information you need to use db_query in hook_user_load.

Saving a model with no data in CakePHP (just create id in db)

My CakePHP Cart model/table has only one field: id.
It hasMany LineItems.
I am not having success saving the Cart model alone:
$this->Cart->create();
$this->Cart->save();
Or, by passing it a $data array structured as follows and using saveAssociated():
$data = array(
'Cart' => array(),
'LineItem' => array(
array(
'item_id' => $item_id,
'qty' => $qty,
'price_option_id' => $price_option_id
)
)
);
If I add a useless_field to the Cart table/model, and pass some data in it saves. So obviously the problem lies in my having a model with a table with just a single id field and not passing in any other data to save. It won't create what it must be assuming is an 'empty' record.
I have passed 'validate' => false into the saveAssociated call but it doesn't make a difference (and there are no validations for this model to ignore).
Is there a way to do this? Am I missing something? Please enlighten me!
CakePHP tables require created and modified fields, or for you to define your own fields (ie you can call them whatever you want but they do the same thing).
In this instance you would use
$this->Cart->set($data);
$this->Cart->saveAll();

how to save one-to-many relationships to the database using zend form and doctrine

I'm writing an application that uses Zend Framework 2 and Doctrine (both the latest stable version).
There is much documenation (mainly tutorials and blog posts) that deal with saving doctrine entities to the database in combination with Zend Form. Unfortunately they only deal with simple entities that do not have one-to-many or many-to-many relationships.
This is one of those examples that i have adopted into my own code.
http://www.jasongrimes.org/2012/01/using-doctrine-2-in-zend-framework-2/
I understand that in the Album Entity of this example, the artist is a string to keep the (already lengthy) tutorial as simple as possible. But in a real world situation this would of course be a one-to-many releationship with an Artist Entity (or even a many-to-many). In the view, a select-box could be displayed where the artist can be selected, listing all the artist-entities that could be found in the database, so the right one can be selected.
Following the example with the album, this is how i've set up an 'edit' Action in my controller:
public function editAction()
{
// determine the id of the album we're editing
$id = $this->params()->fromRoute("id", false);
$request = $this->getRequest();
// load and set up form
$form = new AlbumForm();
$form->prepareElements();
$form->get("submit")->setAttribute("label", "Edit");
// retrieve album from the service layer
$album = $this->getSl()->get("Application\Service\AlbumService")->findOneByAlbumId($id);
$form->setBindOnValidate(false);
$form->bind($album);
if ($request->isPost()) {
$form->setData($request->getPost());
if ($form->isValid()) {
// bind formvalues to entity and save it
$form->bindValues();
$this->getEm()->flush();
// redirect to album
return $this->redirect()->toRoute("index/album/view", array("id"=>$id));
}
}
$data = array(
"album" => $album,
"form" => $form
);
return new ViewModel($data);
}
How would this example need to be altered if the artist wasn't a string, but an Artist Entity?
And suppose the album also has multiple Track Entities, how would those be processed?
The example would not need to be changed at all, the changes will happen with your entity and your form.
This is a good reference: Doctrine Orm Mapping
So to save yourself a lot of extra work, your OnToMany relationship would use: cascade = persist:
/**
* #ORM\OneToMany(targetEntity="Artist" , mappedBy="album" , cascade={"persist"})
*/
private $artist;
When it comes to persisting the form object, the entity knows it must save the associated entity as well. If you did not include this, then you would have to do it manually using a collection.
To make like easier with your form, you can use Doctrines Object Select like this:
$this->add(
[
'type' => 'DoctrineModule\Form\Element\ObjectSelect',
'name' => 'artist',
'options' => [
'object_manager' => $this->objectManager,
'target_class' => 'Artist\Entity\Artist',
'property' => 'name', //the name field in Artist, can be any field
'label' => 'Artist',
'instructions' => 'Artists connected to this album'
],
'attributes' => [
'class' => '', //Add any classes you want in your form here
'multiple' => true, //You can select more than one artist
'required' => 'required',
]
]
);
So now your form takes care of the collection for you, the controller as per your example does not need to change since the entity will take care of the persisting...
Hope this gets you on track.

How to diaplay other tables attributes in single view form and also insert values in corresponding tables

I have two tables QBQuestion(Questionid,Question,OptionId) and Option(OptionId,Option). I want to display option form on view form of QBQuestion? I want to create multiple choice question. i.e.for single question we can add multiple options.For such purpose i want to cretae option field with add button si that when we click add button,we can insert more options and also want to display that all inserted options in table using grid.
So what should i do? please help me....
1) Add relations in the model for this two stuff.
public function relations() {
return array(
'valOptions' => array(self::BELONGS_TO, 'Option', 'OptionId'),
);
}
2) Use lazy loading in CGridView.
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider' => new CActiveDataProvider('QBQuestion'),
'columns' => array(
'Questionid',
'Question',
'valOptions.Option',
),
));
I think that's what you need.

Resources