Guião para criar aplicações simples em APEX
(parte II)
Guide to create simple Apex applications
(part II)
Vamos criar duas funções: uma que devolve quantos alugueres foram feitos por sócio; outra que calcula a média do número de alugueres por mês de um sócio.
Let us create two functions: one that returns how many rents (alugueres) were made per sócio (member); another one that calculates the average number of rentals per month of a sócio.
Ambas as funcões são criadas em SQL workshop/ Sqldeveloper Both functions are created in SQL worshop/ Sqldeveloper like this:
create or replace function num_alugueres(n_socio number) return number is n_alugueres number;
begin
select count(*) into n_alugueres from aluguer where num_socio = n_socio;
return n_alugueres; end num_alugueres;
create or replace function media_mes(n_socio number) return number is
media number;
begin
with socio_cont_mes as (select count(*) as cnt from aluguer where num_socio = n_socio group by to_char(data_aluguer,'MON-‐YYYY'))
select avg(cnt) into media from socio_cont_mes;
return media; end media_mes;
Agora clique em SQL script onde escreverá os comandos para criar a função; sempre que a edição de um comando tem um número de caracteres suficiente para que seja provável a ocorrência de erros sintáticos é preferível criar um script porque nele é mais cómodo corrigir o erro.
Now click on the SQL script where you will write the commands to create the functions; whenever editing a command has a sufficient number of characters so that syntactic er-rors are likely to occur, it is preferable to create a script because it is more convenient to correct the error in the script.
Edite o script e dê-lhe um nome (ex:MyFunctions); entre os dois comandos escreva uma barra “/” (sem as aspas)
Edit the script and give it a name (ex: MyFunctions); between the commands write a bar “/” (without “”).
Depois clique em save e depois em run / then clique save and then Run.
Depois clique em View Results (à direira na linha do script MyFunctions) e verifique se o script correu com zero (0) erros. Se houver erros corrija e corra de novo.
Then click at View Results (right in the MyFunctions script line) if the script ran with zero (0) errors. In case of errors, correct it and run it again.
Agora vamos acrescentar duas colunas ao Relatório do sócio Now we are going to add two columns in the Relatório do socio.
Para tal, na zona Page Rendering, Content Body, clique em Report 1 e em seguida, à direira clique no canto superior direito junto ao código SQL de forma a obter uma janela de edição mais conveniente (seta vermelha).
To do so, in the Page Rendering, Content Body zone, click on Report 1 and then on the right click in the upper right corner next to the SQL code in order to obtain a more con-venient editing window (red arrow).
Depois, editar na janela o seguinte / Then edit the following in windown zone:
select NUM_SOCIO as numero, NOME_SOCIO as nome, BI_SOCIO as BI
,DATA_NSC_SOCIO as "Nasceu em", MORADA_SOCIO as Morada, TLF_SOCIO as Tlf, SEXO_SOCIO as Sexo, num_alugueres(num_socio) as "Tot Alugueres",
media_mes(num_socio) as "Media mensal" from socio
Usar List of Values para esconder códigos
Using List of Values to hide codes
Vamos criar um form para manipulação dos dados em Filme mas sem ter que conhecer os códidos de editora e de género
We are going to create a form to manipulate data in Filme but without the need of knowing the codes of editora and genero.
Vamos então criar uma nova página (Create Page) / Let us creat ea new Page (Create Page)
Do tipo Form / of type Form
Depois de Next, indique que quer aceder a esta página a partir da página inicial Home After Next, indicate that you want to access this page from the home page Home
Depois de Next, indique que cod_filme é chave e que os valores da chave serão obtidos por
Existing Sequence. Pode indicar já a sequência seq_filme, como está na figura. Use o botão >> para incluir no form todos os campos da tabela.
After Next, indicate that cod_filme is key and that key values are obtained by Existing Sequence. You can already indicate the sequence seq_filme, as it is in the figure. Use >> to include all table columns in the form.
Faça Create e corra a página / Do Create and run the page.
Para além de ver códidos de editora e de genero, como era de esperar, se clicar à esquerda num dos lápis de edição, verá novamente os mesmos códigos. O que se pretende é evitar que o utilizador tenha que conhecer os códigos, por isso, vamos alterar este form.
In addition to viewing editora and genero codes, as you would expect, if you left-click one of the edit pencils, you'll see the same codes again. What is intended is to prevent the user from having to know the codes, so we will change this form.
Assim, volte a editar a página 11 (do form) e na zona Shared Components clique em List Of
Values.
Nota: o número da página pode eventualmente ser outro que não o 11; depende do número de remoções de páginas feitas / criadas no contexto do desenvolvimento de uma aplicação. Note: the page number may possibly be other than 11; it depends on the number of page removals made / created in the context of developing an application.
So, go back to edit page 11 (of the form) and in the Shared Components zone click on List Of Values.
Escolha From Scratch / Now select From Scratch
Indique o nome Editoras para o nome da lista e selecione Dynamic porque a lista de valores poderá eventualmente alterar-se ao longo do tempo
Enter the Editoras as name for the List of Values and select Dynamic because the list of values may eventually change over time
Agora preencha como na figura; este é o código gerador da lista de valores. Now fill in as in the figure; this is the generator code of the list.
Em seguida crie outra List Of Values com o nome generos com o código gerador como se indica / Then create another List Of Values with the name generos with the generator code as indicated
Agora vamos ligar os cógidos (de editora e de genero) do form a estas listas Now let's connect the form codes (of editora and genero) to these lists.
Agora na mesma página clique à esquerda no attributo p11_cod_editora e altere do lado esquerdo as características deste campo: No type escolha Select List; na Label escreva
Editora; depois clique em Shared Components e selecione EDITORAS, que é o nome da List of Value criada. Em seguida faça o equivalente para o atributo p11_cod_genero e escolha
para tal a List of Values generos (setas vermelhas).
Now, on the same page, click on the p11_cod_editora attribute on the left side and change the characteristics of this field: In the type choose Select List; in Label type Ed-itora; then click Shared Components and select EDITORAS, which is the name of the created List of Values. Then do the equivalent for the attribute p11_cod_genero and choose for this the List of Values generos (red arrows)
Em seguida corra a página e repare que os códigos de editora e género estão escondidos e, em vez disso, pode aceder aos nomes.
Then run the page and notice that the editora and genero codes are hidden and you can instead access the names.
No entanto, falta alterar o código SQL do Report (página 10) de forma a que se vejam os nomes em vez dos códigos das editora e genero. Para tal edite a página 10 e, na zona Page
Rendering, Content Body, clique em Report 1 e altere o SQL comona figura abaixo.
However, it is necessary to change the SQL code of the Report (page 10) in order to see the names instead of the editora and genero codes. To do this, edit page 10 and, in the Page Rendering, Content Body area, click on Report 1 and change the SQL as below.
Experimente agora inserir um novo filme: clique em Create / Try inserting a new Filme now: click Create
De
Depois preencha os campos como quiser e usando as listas de valores já disponíveis (veja o exemplo)
Then fill in the fields as you wish and using the lists of values already available (see example)
Clique em Create/ Click Create
Depois clique no lapis de edição, altere um dos campos; faça Apply Changes e confirme a alteração. Em seguida volte a clicar no lápis de edição e faça Delete para apagar o filme. Then click on the edit pencil, change one of the fields; make Apply Changes and confirm the change. Then click again on the edit pencil and Delete to delete that filme.
Como criar um Form & Report Apex para uma relação de
Muitos para Muitos
Apex How to create an Apex Form & Report for an
Many to Many relationship
Vamos considerer a relação filme_actor que corresponde a uma relação Muitos para Muitos. Crie um Report with Form on a Table e preencha os campos de acordo com a figura seguinte: Let's consider the filme_actor relationship that corresponds to a Many to Many rela-tionship. Create a Report with Form on a Table and fill in the fields according to the fol-lowing figure:
Depois crie a ligação da página Home para esta página, assim: Then create the Home page link for this page, like this:
A tabela sobre a qual vai funcionar este form é a filme_actor, que deve indicar.
Agora, dado que a chave da tabela (composta pelos dois atributos cod_filme e cod_actor) não vai ser gerada automaticamente mas sim escolhida a partir do domínio de valores possíveis para cada caso (cod_filme e cod_actor), vamos escolher Managed by Database (Rowid). Desta maneira não seremos obrigados a escolher trigger nem sequence, que neste contexto são mecanismos para gerar a chave automaticamente.
Now, since the table key (composed of the two attributes cod_filme and cod_actor) will not be generated automatically but chosen from the possible domain values for each case (cod_filme and cod_actor), we will choose Managed by Database (Rowid). This way we will not be forced to choose trigger or sequence, which in this context are mecha-nisms to generate the key automatically.
Agora se correr a página do Report verá apenas os códigos de Filme e de Actor, o que não é desejável, já que não queremos ter que saber códigos de cor.
Now if you run the Report page you will only see the Filme and Actor codes, which is not desirable, since we are not supposed to know each particular code value.
Vamos então melhorar esta página e a do form de inserção/edição correspondente. Para tal vamos criar duas List of Values na página do form.
We will then improve this page and the corresponding insert/edit form. For this we will create two List of Values in the form page.
Assim, e recordando como se declara uma List of Values: Thus, and remembering how to declare a List of Values:
E outra List of Values de nome Filmes: And another List of Values of Films:
De seguida é preciso ligar o campo (item) p13_cod_filme à List of Values Filmes e o item
p13_cod_actor à List of Values Actores, à semelhança do que já foi feito noutro exercício.
Then you need to connect the field (item) p13_cod_filme to the List of Values Filmes and the item p13_cod_actor to the List of Values Actors, similar to what has already been done in another exercise.
Para tal, no type do item (à direita) é preciso alterar o valor de hidden para select list, e em
shared components (à direita, onde está assinalada uma cruz vermelha), é necessário
selecionar a List of Values Filmes; na label escreva Filme Fazer de modo semelhante relativamente ao item p13_cod_actor.
To do this, in the item type (on the right) you need to change the value of hidden to se-lect list, and in shared components (to the right, where a red cross is marked), it is nec-essary to select the List of Values Filmes; on the label write Filme.
Do similarly to item p13_cod_actor.
Corra a página do Form e confirme que já tem acesso às listas dos filmes e dos actores para preenchimento.
Run the Form page and confirm that you already have access to the lists of Filmes and Actores to fill out.
Agora há que melhorar o Report, isto é, facultar os nomes dos actores e dos filmes que correspondem aos códicos respectivos.
Para tal edite a página do Report (12). Assim, na zona Page Rendering, Content Body, clique em Report 1 e edite o código SQL como indicado na figura abaixo.
Now it is necessary to improve the Report, that is, to give the names of the actors and the filmes that correspond to the respective codes.
To do this, edit the Report page (12). So, in the Page Rendering, Content Body zone, click Report 1 and edit the SQL code as indicated in the figure below.
Corra a página e deverá ver algo semelhante a:
Run the page and you should see something similar to:
Experimente editar um tuplo; crie outro e confime que a interface funciona.
Tente também inserir um tuplo que já existe e verá que isso não é possível por tentativa de violação da chave primária, como aqui se mostra:
Try editing a tuple; create another one and confirm that the interface works.
Also try inserting a tuple that already exists and you will see that this is not possible by attempting to violate the primary key, as shown here: