How to preselect the radiobutton when 'data' is entity - symfony

Normally,form shows the select code though,
I have two tables which has Many-to-one relation.
for example
MainTable
ID | name |job
1 | Mr.A |1
2 | Mr.D |1
3 | Mr.C |3
jobTable
ID | name
1 | doctor
2 | engineer
3 | teacher
then ,I am making the form to input Maintable,normally
symfony uses select box for this kind of choice,but I use radio button like this.
$form = $this->createFormBuilder($mainTable)
->add('job','entity',array(
'class' => 'AcmeTopBundle:jobTable','expanded' => true))
Then I would like to preselect the one button.
There I found hint.
How to pre-select a form radio item with Symfony 2?
it says to use
'data' => 1
But my choices is jobTable entity.
How can I put the jobtable entity?
'data' => ???

You have to pass the entity record it self as data. So, from a Controller :
$em = $this->getDoctrine()->getEntityManager();
// If you want to preselect record with ID #1
$preselectedData = $em->getReference('AcmeTopBundle:jobTable', 1);
$form = $this->createFormBuilder($mainTable)
->add(
'job','entity',array(
'class' => 'AcmeTopBundle:jobTable','expanded' => true,
'data' => $preselectedData
)
)
// ...
;

Its easier to set the default value in your entity/value object. The form component take care of them and preselect it.

Related

How to insert 100k entries into 3 tables with foreign key Laravel

I have an array where each element contains array
$arryItem = [
'surname' => 'user_surname',
'name' => 'user_name',
'sex' => 'user_sex',
'ratio' => 'player_ratio'
];
Also I have 3 tables. Users, Players and users_roles
users
id | name | surname | sex
players
id | user_id | ratio
users_roles
user_id | role_id
On each iteration I have to
Create user and get inserted ID
Create player and insert user_id as inserted user ID
Create new entry into users_roles, where user_id will inserted user ID
The problem is that there will 100k+ iterations with 3 inserts and other logic such as srtolower, generate random email and password. I think that my script will fail with timeout or memory limit.
Are there ways to do this fast? DB - PostgreSQL

Symfony OneToMany persisting data

I am using Symfony3.4 and have the following relationship in the database between House and Type entities:
house
+----------------------------------------------+
| id | title | description |
+----------------------------------------------+
| 1 | some title 1 | some description 1 |
+----------------------------------------------+
| 2 | some title 2 | some description 2 |
+----------------------------------------------+
type
+----------------+
| id | name |
+----------------+
| 1 | shortstay |
+----------------+
| 2 | rent |
+----------------+
| 4 | sell |
+----------------+
house_types
+-----------------------------------+
| id | house_id | type_id | price |
+-----------------------------------+
| 1 | 1 | 2 | 1000 |
+-----------------------------------+
| 2 | 1 | 3 | 1000000 |
+-----------------------------------+
| 3 | 2 | 1 | 100 |
+-----------------------------------+
| 4 | 2 | 3 | 200000 |
+-----------------------------------+
Here are my entities:
House entity
class House extends EntityBase
{
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\HouseHasTypes", mappedBy="houses", cascade={"persist","remove"})
*/
protected $hasTypes;
Type entity
class Type extends EntityBase
{
/**
* #ORM\OneToMany(targetEntity="AppBundle\Entity\HouseHasTypes", mappedBy="types", cascade={"persist","remove"})
*/
protected $hasHouses;
HouseHasTypes entity
class HouseHasTypes extends EntityBase
{
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\House", cascade={"persist"}, fetch="EAGER")
* #ORM\JoinColumn(name="house_id", referencedColumnName="id", nullable=true)
*/
protected $houses;
/**
* #ORM\ManyToOne(targetEntity="AppBundle\Entity\Type", cascade={"persist","remove"}, fetch="EAGER" )
* #ORM\JoinColumn(name="type_id", referencedColumnName="id",nullable=true)
*/
protected $types;
/**
* #var int
*
* #ORM\Column(name="price", type="integer")
*/
protected $price;
I did not quite get the difference between ManyToOne and OneToOne relationship. Which one should mine be?
Also, what would be the easiest way to handle inserting new data into the 2 entities (House and HouseHasTypes). Right now I can render the checkboxes for each row in type table as follows:
$builder
...
->add('hasTypes', EntityType::class, array(
'required' => true,
'class' => Type::class,
'expanded' => true,
'multiple' => true,
))
And the in the controller I am planning to make a foreach(){} for each of the checked Types and setHouse() and setPrice() there. Is there any other more efficient way to do this?
How can I render as many textboxes as there are the abovementioned EntityType checkboxes to define a price for each Type selected? I am currently hardcoding three html input text elements and hiding them with javascript based on checked checkboxes. If I make a custom form, how can I tell it to render 3 text inputs (since there're 3 rows in the entity table)
Sorry for asking so many questions. Any help would be much appreciated
Your database model seems correct.
To define you the OneToMany, ManyToOne and OneToOne relationship, I made you little examples:
Imagine we have two entities: USER and ORDER.
OneToMany:
An user can do 0, 1 or many orders right ? It means that One user can be linked To 0, 1 or Many orders.
USER(id:1) --> ORDER(id:1)
--> ORDER(id:3)
--> ORDER(id:8)
ManyToOne:
An order can be done by one and only one user right ? It means that Many orders can be linked To One user.
ORDER(id:1) --> USER(id:1)
ORDER(id:3) --> USER(id:1)
ORDER(id:8) --> USER(id:1)
OneToOne:
Now imagine we have two others entities: USER and EMAIL.
An user can have one and only one email address and an email address can have one an only one user right ? It means that One user can be linked To One email address and One email address can be linked To One user.
USER(id:1) --> EMAIL(id:6)
USER(id:3) --> EMAIL(id:7)
USER(id:8) --> EMAIL(id:1)
Hope I was clear.
For your others questions, Symfony will automatically insert data on form submit if you have correctly defined your getter and setter in entities no needs to do a foreach

symfony2 adjacency list model use with Forms

I have a self referencing table as covered in the doctrine documentation (which is already in heavy use throughout the application and therefore changing to nested tree isn't a current option).
http://docs.doctrine-project.org/projects/doctrine-orm/en/2.0.x/reference/association-mapping.html#one-to-many-self-referencing
The table structure looks like this:
+----+----------+--------+
| id | parentID | Name |
+----+----------+--------+
| 1 | null | Name 1 |
| 2 | 1 | Name 2 |
| 3 | 1 | Name 3 |
| 4 | 2 | Name 4 |
| 5 | 1 | Name 5 |
--------------------------
Up until now in our forms we've been using the entire entities content our form, ie
$builder->add('hierarchyid', 'entity', array(
'class' => 'AcmeTestBundle:Hierarchies')
Which works fine, but now I want to be able to amend this to set points in the table, ie something like:
->add('hierarchyid', 'entity', array(
'class' => 'AcmeTestBundle:HierarchiesTest',
'query_builder' => function(HierarchiesTestRepository $repo)
{return $repo->findBy??????}
But I've hit a mental block how to complete this, any ideas?
One option I've considered is I already have code that builds an array collection of these entities, which is used elsewhere, but I'm unfamiliar with how I should go about implement a doctrine arraycollection in a form type.
private function createNodeArray($node)
{
$this->hierarchyArrayCollection->add($node);
foreach ($node->getChildren() as $hierarchy)
{
$this->createNodeArray($hierarchy);
}
}
query_builder option should return QueryBuilder object and I assume your findAllById() method returns actual data. You need to change that ;)
Other than that, you should probably add property option to indicate which field is to be displayed in list...
For anyone interested the solution I went with in the end was to generate an array and use choice field type rather than entity,such as this:
->add('hierarchyid', 'choice', array(
'choices' => $hierarchy)

D7 Pager Query - Too many pages in the pager

I have 3 nodes of content type 'mycontenttype'. I'm trying to setup a sortable/pagable table with a limit of 10 items per page.
In this code, $nids only returns 3 nodes. I'm actually runnng node_load_multiple($nids) then looping through those nodes to build the $rows variable. Only 3 appear.
Problem: The pager is rendering with 4 pages.
Expectation: There should be no pager rendering because I do not have 10 nodes in the query or the count query.
Any insight would be greatly appreciated.
<?php
function mymodule_create_a_pager_table() {
$query = db_select('node', 'n')->extend('PagerDefault')->extend('TableSort')->element('my_custom_id');
$query->fields('n', array('nid'));
$query->condition('n.type', 'mycontenttype');
$query->condition('n.status', 1);
$count_query = clone $query;
$query->setCountQuery($count_query);
$query->limit(10);
$header = array(array('data' => 'Title', 'sort' => 'asc', 'field' => 'n.title'), 'column 2', 'column 3');
$query->orderByHeader($header);
$nids = $query->execute()->fetchCol();
// ... building $rows array for display only here
$output = theme('table', array('header'=> $header, 'rows' => $rows));
$output .= theme('pager', array('element' => 'my_custom_id', 'quantity' => 10));
return $output;
}
?>
Output
Node 1 Title | col2 val | col3 val
Node 2 Title | col2 val | col3 val
Node 3 Title | col2 val | col3 val
1 2 3 4 next › last »
I think element should be an integer.
Try to leave both the ->element() call and any arguments to theme('pager') away.
Also, your count query is wrong. Just don't define it either, that will be done automatically for you. This is probably the actual reason for your problem, not the element thing.
The count query get's executed and the first returned value (fetchField()) is assumed to be the number of elements. Your query probably returns a nid and that is mistaken as the number. So just leave that away, and Drupal will build a correct count query automatically for you.

Views relationship with multiple files

I have a content types with 3 file fields, all of them can have an unlimited number of images. I need to make a view that returns the title of the content and the images name inside an array (I'm using amfphp with services). The problem is that when I add the relationship to the content field_pics fid I get as many duplicate nodes as the number of the images in the field:
EG:
[10] => stdClass Object
(
[nid] => 56
[node_title] => asd asd asd
[node_language] =>
[node_nid] => 56
)
[11] => stdClass Object
(
[nid] => 56
[node_title] => asd asd asd
[node_language] =>
[node_nid] => 56
)
This is the query:
SELECT node.nid AS nid, node.title AS node_title, node.language AS node_language, node.nid AS node_nid
FROM node node
LEFT JOIN content_field_colori node_data_field_colori ON node.vid = node_data_field_colori.vid
LEFT JOIN files files_node_data_field_colori ON node_data_field_colori.field_colori_fid = files_node_data_field_colori.fid
WHERE (node.status <> 0 OR (node.uid = ***CURRENT_USER*** AND ***CURRENT_USER*** <> 0) OR ***ADMINISTER_NODES*** = 1) AND (node.type in ('prodotto'))
ORDER BY node_nid ASC
I don't know how to fix this.
ANy help is appreciated.
Thanks
I think I understand what you're trying to do now. Unfortunately, Services's views support isn't all that great when it comes to CCK. There are a lot of different issues (e.g. one, two, three) with a lot of different patches and comments, but based on my understanding, to capture what you want is to not use relationships and to use the Node row style. If you use relationships, you get the output you're seeing, and if you use the Fields row style, the ImageField fields never load.

Resources