Symfony 3 & Doctrine - Complex form with OnetoMany and ManyToMany relation - symfony-forms

I want to manage the rates of a product in multi-currency and keep historic of currency rates.
So onetomany relation:
A Rates can have many CurrencyRate.
A manyto many relation:
Many currencyRate have many currencies.
RATES :
+-----------------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| rate | double | YES | | NULL | |
| timeStamp | datetime | NO | | NULL | |
| currencyRate_id | int(11) | YES | MUL | NULL | |
+-----------------+----------+------+-----+---------+----------------+
CURRENCY RATES
+-----------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| rate | double | NO | | NULL | |
| timeStamp | datetime | NO | | NULL | |
+-----------+----------+------+-----+---------+----------------+
currencyrateshascurrencies (manytomany join table)
+-----------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+---------+------+-----+---------+-------+
| currency_id | int(11) | NO | PRI | NULL | |
| currencyRate_id | int(11) | NO | PRI | NULL | |
+-----------------+---------+------+-----+---------+-------+
currencies
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | UNI | NULL | |
| abreviation | varchar(5) | NO | UNI | NULL | |
+-------------+--------------+------+-----+---------+----------------+
I want to generate a form from all of this.
The html form would get all available currencies with a text field to indicate the CurrencyRate.
Ex :
USD <input type="text">
EUR <input type="text">
CNY <input type="text">
...
I saw the documentation on Symfony about manytomany form. But mine is more complex with an additional onetomany relation and text field. I am totaly lost.
Thanks if you can put me on the right direction.
Best regards,
Pierre

I found the response :
First I needed to correct my Schema which didn't need a ManytoMany relation :
Rates :
+-----------+----------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------+----------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| rate | double | YES | | NULL | |
| timeStamp | datetime | NO | | NULL | |
+-----------+----------+------+-----+---------+----------------+
CURRENCY RATES
+-------------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| ratio | double | NO | | NULL | |
| currency_id | int(11) | YES | MUL | NULL | |
| Rate_id | int(11) | YES | MUL | NULL | |
+-------------+---------+------+-----+---------+----------------+
Currencies
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | NO | UNI | NULL | |
| abreviation | varchar(5) | NO | UNI | NULL | |
+-------------+--------------+------+-----+---------+----------------+
Then One Form Type
class CurrencyRateType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('currency',EntityType::class, array(
'class'=>'AppBundle:Currencies',
'choice_label' => 'abreviation',
'disabled' => true,
))
->add('ratio', TextType::class);
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => CurrencyRates::class,
));
}
}
which is embedded in the final form type :
class RateType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder ->add('rate')
->add('CurrencyRate', CollectionType::class, array(
'entry_type' => CurrencyRateType::class,
'entry_options' => array('label' => false))
)
->add('save', SubmitType::class, array('label' => 'create'));
}
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => Rates::class,
));
}
}

Related

Active Record querying with joins and group by

I'm designing an API to get data from the following scenario :
brands table :
+------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+------------+--------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| name | varchar(255) | YES | | NULL | |
+------------+--------------+------+-----+---------+----------------+
items table :
+---------------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------------------+--------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| category_id | bigint(20) | YES | MUL | NULL | |
| brand_id | bigint(20) | YES | | NULL | |
+---------------------------+--------------+------+-----+---------+----------------+
item_skus table :
+---------------------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------------------------+--------------+------+-----+---------+----------------+
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| item_id | bigint(20) | YES | MUL | NULL | |
| number_of_stock | int(11) | YES | | NULL | |
+---------------------------+--------------+------+-----+---------+----------------+
Item model association with ItemSku and Brand
belongs_to :brand
has_many :skus, class_name: 'ItemSku'
Simply i want the counts of stock available items and all items for each brand.
{
"brandCounts":[
{
"id":7006,
"name":"Brand 01",
"stockAvailableItemCount":50,
"allItemCount":60
},
{
"id":20197,
"name":"Brand 02"
"availableItemCount":150,
"allItemCount":660
}
]
}
Implementation :
brand_counts = []
brand_counts_hash = Hash.new()
items = Item.left_outer_joins(:skus).where(category_id: params[:id]).pluck(:brand_id, :number_of_stock, :item_id)
items.each do |item|
brand_id = item[0]
stock = item[1]
if brand_counts_hash.has_key?(brand_id)
item_count_arry = brand_counts_hash[brand_id]
stock_available_item_count = item_count_arry[0]
all_item_count = item_count_arry[1]
if stock > 0
brand_counts_hash[brand_id] = [stock_available_item_count + 1, all_item_count + 1]
else
brand_counts_hash[brand_id] = [stock_available_item_count, all_item_count + 1]
end
else
stock_available_item_count = 0
all_item_count = 0
if stock > 0
stock_available_item_count += 1
all_item_count += 1
brand_counts_hash[brand_id] = [stock_available_item_count, all_item_count]
else
all_item_count += 1
brand_counts_hash[brand_id] = [stock_available_item_count, all_item_count]
end
end
end
brand_counts_hash.each do |key, value|
stock_available_item_count = value[0]
all_item_count = value[1]
brand_counts << {
id: key,
name: get_brand_name(key),
stock_available_item_count: stock_available_item_count,
all_item_count: all_item_count
}
end
#brand_counts = brand_counts
render 'brands/counts/index', formats: :json
end
def get_brand_name(brand_id)
brand = Brand.find_by(id: brand_id)
brand.name unless brand == nil
end
Is there a way to optimize this further without multiple loops maybe?
Assume your Brand model also has the following association defined
has_many :items
and the final result you want is like
{
"brandCounts":[
{
"id":7006,
"name":"Brand 01",
"stockAvailableItemCount":50,
"allItemCount":60
},
{
"id":20197,
"name":"Brand 02"
"availableItemCount":150,
"allItemCount":660
}
]
}
The following code may not work when you copy and paste to your project. But it demonstrate how this problem can be solved with less code
Brand.includes(items: :skus).all.map do |brand|
{
id: brand.id,
name: brand.name,
stockAvailableItemCount: brand.items.count,
allItemCount: brand.items.map {|item| item.skus.sum(:number_of_stock)}.sum
}
end
if you need json format, just use to_json to the result of above code.

Querying in Rails

How can I get the first name and last name from the table User through table Friend which is referenced by the user_id with the condition of user_id 5 and status is pending and place it in a each loop but i also need the contents of friend controller in rails. Thank a lot for the help
Controller
#add = Friend.where(user_id: 5, status: 'Pending')
User Database
+-----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-----------------+--------------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| first_name | text | YES | | NULL | |
| last_name | text | YES | | NULL | |
| email | text | YES | | NULL | |
| contact_number | varchar | YES | | NULL | |
| birth_date | date | YES | | NULL | |
| created_at | datetime | NO | | NULL | |
| updated_at | datetime | NO | | NULL | |
Friend
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| id | int | NO | PRI | NULL | auto_increment |
| request_date | date | YES | | NULL | |
| reason | text | YES | | NULL | |
| status | varchar(255) | YES | | NULL | |
| userid | int | YES | MUL | NULL | |
How about this:
#add = Friend.joins(:user).select("users.first_name, users.last_name").where(user_id: 5, status: 'Pending')
Seems like youre already fetching the id of the user, stored in the user_id field. In order to get the associated user, i would do
#user = User.find(#add.id)
This retrieves the user based on the id you pass, and from there you can do stuff like
#user.first_name
to get the values
All you need to do in Friend model belongs_to user and then
#add =Friend.where("user_id = ? AND status = ?", 5,"Pending")
and
<#add.each do |s|>
<%s.user.first_name%>
<%=<%s.user.last_name%>
// and so on..
<%end%>

MQL help required, how to generate key

I am struggling with one code line. It is a Key generation Line for a Expert Adviser. Can someone help me figure out how I can generate key by using this line:
int key=3*(StringToInteger(StringSubstr(IntegerToString(AccountNumber()), 0, 3)))+333333;
And what is the problem?
int accountNumber = AccountNumber();
string accountNumberString = IntegerToString(accountNumber);
string accountNumberStringFirst3Digits=
StringSubstr(accountNumberString,0,3);
int accountNumberFirstThreeDigits = StringToInteger(accountNumberStringFirst3Digits);
int accountNumberFirstThreeDigitsMultiplied = 3 * accountNumberFirstThreeDigits;
int key = accountNumberFirstThreeDigitsMultiplied + 333333;
Can someone help me figure out how to generate key by this line?
Welcome, certainly, let's look on that :
int key = 3*(StringToInteger(StringSubstr(IntegerToString(AccountNumber()), 0, 3)))+333333;
Your code actually means this:
// +------------------------------------------------------------------------------- type declaration
// | +--------------------------------------------------------------------------- variable name definition
// | | +------------------------------------------------------------------------- assignment operator
// | | | +----------------------------------------------------------------------- compile-time integer constant
// | | | | +--------------------------------------------------------------------- multiply operator
// | | | | | +-------------------------------------------------- MT4 system function: StringToInteger( aString )
// | | | | | | +------------------------------------ MT4 system function: StringSubstr( aString, aPosToStartSubstrFrom, aSubstrLength )
// | | | | | | | +------------------- MT4 system function: IntegerToString( aIntNum ) | |
// | | | | | | | | +---- MT4 system function: AccountNumber() | |
// | | | | | | | | | | |
// | | | | | | | | | +------------------------------------------------------------------+ |
// | | | | | | | | | | +------------------------------------------------------------------------------+
// | | | | | | | | | | |
int key = 3 * ( StringToInteger( StringSubstr( IntegerToString( AccountNumber() ), 0, 3 ) ) )
+ 333333;
// | ||
// +------||----------------------------------------------------------------- add operator
// +|----------------------------------------------------------------- compile-time integer constant
// +----------------------------------------------------------------- literal MQL4-language syntax-terminator
The code above both defines and generates a fair integer value, so wherever your Expert Advisor code refers to a value of key, this calculated value will be used ( see also the documentation about the New-MQL4 scope-of-validity, inside which this variable remains visible ).

Why does this before_save not update the verified date in rails?

My before_save doesn't update the verified_date field.
Why is that? Other processes can update the field ok.
Model:
class Link < ActiveRecord::Base
belongs_to :group
validates_presence_of :url_address
validates_presence_of :group_id
validates_size_of :version_number, :maximum => 10 #, :allow_nil => true
before_save :verify_this_link
acts_as_list
...
def verify_this_link
verified_date = Time.now
end
end
mysql> describe links;
+----------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| url_address | varchar(255) | NO | | NULL | |
| alt_text | varchar(255) | YES | | NULL | |
| group_id | int(11) | YES | | NULL | |
| position | int(11) | YES | | NULL | |
| created_at | datetime | YES | | NULL | |
| updated_at | datetime | YES | | NULL | |
| version_number | varchar(255) | YES | | NULL | |
| content_date | date | YES | | NULL | |
| verified_date | date | YES | | NULL | |
+----------------+--------------+------+-----+---------+----------------+
mysql> select id, substr(url_address,1,20),
verified_date from links where id > 350;
+-----+--------------------------+---------------+
| id | substr(url_address,1,20) | verified_date |
+-----+--------------------------+---------------+
| 351 | http://magicmodels.r | NULL |
| 352 | http://jsbin.com/#ja | 2014-07-12 |
| 353 | http://www.javascrip | 2014-07-12 |
| 354 | http://www.test.com | 2014-08-08 |
| 357 | http://www.t5.com | 2014-07-12 |
+-----+--------------------------+---------------+
5 rows in set (0.00 sec)
Try:
def verify_this_link
self.verified_date = Time.now
end
Reference https://stackoverflow.com/a/6326323/252671

hasMany relationship - deselecting set value from view - does not update DB accordingly

I have seen this behaviour on a few different locations lets say:
class fruits {
static hasMany=[preapples:Apples, apples: Apples, postapples: Apples ]
}
static mapping = {
preapples cascade: 'lock'
apples cascade: 'lock'
postapples cascade: 'lock'
}
static constraints = {
preapples nullable:true
apples nullable:true
postapples nullable:true
}
When the views are generated if on fruits I select many apples apple1 apple2 etc
If I return now and change from apple1 + apple2 to just apple1 - everything is ok
If I deselect all as in if there was only 1 selected and I choose ctrl to unhighlight it - which clearly shows nothing has been selected - when I submit form the value is not actually removed.
Is this something to do with nullable ? or am I missing something obvious
I have added nullable true as suggested which has made no difference from selecting values then unselecting it.
I have also modified actual sql table structure (naming to apples and fruits but before making change / dropping table and after making change having it recreate table - there was no difference to nullable (already nullable)
mysql> describe fruits_apples;
+-----------------------------------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------------------------+------------+------+-----+---------+-------+
| fruits_apples_id | bigint(20) | YES | MUL | NULL | |
| apples_id | bigint(20) | YES | MUL | NULL | |
| fruits_postapples_id | bigint(20) | YES | MUL | NULL | |
| fruits_preapples_id | bigint(20) | YES | MUL | NULL | |
|
mysql> describe fruits_shell_scripts;
+-----------------------------------+------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-----------------------------------+------------+------+-----+---------+-------+
| fruits_apples_id | bigint(20) | YES | MUL | NULL | |
| apples_id | bigint(20) | YES | MUL | NULL | |
| fruits_postapples_id | bigint(20) | YES | MUL | NULL | |
| fruits_preapples_id | bigint(20) | YES | MUL | NULL | |
+-----------------------------------+------------+------+-----+---------+-------+
Regards

Resources