Compare commits

..
9 Commits
Author SHA1 Message Date
bachy 4fc8e542c3 fixed i18n_taxonomy missing
added module_exists('i18n_taxonomy')

Signed-off-by: bachy <git@g-u-i.net>
2012-02-04 11:47:59 +01:00
bachy 8690f4a165 càrrectif bug : term created even if node form validation fail
- remove taxonomy term save from tod, let taxonomy handle the term
- move all toed process from hook_node_validate to hook_node_submit
- handle node creation with hook_node_presave
- handle node update (with term form) in hook_node_submit

Signed-off-by: bachy <git@g-u-i.net>
2012-02-02 18:48:13 +01:00
bachy 66ff837039 RC
Signed-off-by: bachy <git@g-u-i.net>
2012-01-17 16:14:17 +01:00
bachy 626ec7eabc Parent term options
Signed-off-by: bachy <git@g-u-i.net>
2012-01-07 22:59:15 +01:00
bachy 691ecd7d61 add gui icon
Signed-off-by: bachy <git@g-u-i.net>
2011-10-04 11:37:57 +02:00
bachy 930913e764 term is saved (created) and node tagged with, but then term name will not be updated yet. module can't add term form in the node form yet.
Signed-off-by: bachy <git@g-u-i.net>
2011-09-29 20:36:46 +02:00
bachy ad30a381f9 no message 2011-08-28 11:09:59 +02:00
bachy 951be207ab add readme 2011-08-25 21:32:15 +02:00
bachy 8ec280d5fa project creation 2011-08-25 21:26:47 +02:00
34 changed files with 971 additions and 3866 deletions
+228 -293
View File
@@ -1,339 +1,274 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
GNU GENERAL PUBLIC LICENSE
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Version 2, June 1991
Preamble
Copyright (C) 1989, 1991 Free Software Foundation, Inc. 675 Mass Ave,
Cambridge, MA 02139, USA. Everyone is permitted to copy and distribute
verbatim copies of this license document, but changing it is not allowed.
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
Preamble
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
The licenses for most software are designed to take away your freedom to
share and change it. By contrast, the GNU General Public License is
intended to guarantee your freedom to share and change free software--to
make sure the software is free for all its users. This General Public License
applies to most of the Free Software Foundation's software and to any other
program whose authors commit to using it. (Some other Free Software
Foundation software is covered by the GNU Library General Public License
instead.) You can apply it to your programs, too.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
When we speak of free software, we are referring to freedom, not price. Our
General Public Licenses are designed to make sure that you have the
freedom to distribute copies of free software (and charge for this service if
you wish), that you receive source code or can get it if you want it, that you
can change the software or use pieces of it in new free programs; and that
you know you can do these things.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
To protect your rights, we need to make restrictions that forbid anyone to
deny you these rights or to ask you to surrender the rights. These restrictions
translate to certain responsibilities for you if you distribute copies of the
software, or if you modify it.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
For example, if you distribute copies of such a program, whether gratis or for
a fee, you must give the recipients all the rights that you have. You must make
sure that they, too, receive or can get the source code. And you must show
them these terms so they know their rights.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
We protect your rights with two steps: (1) copyright the software, and (2)
offer you this license which gives you legal permission to copy, distribute
and/or modify the software.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
Also, for each author's protection and ours, we want to make certain that
everyone understands that there is no warranty for this free software. If the
software is modified by someone else and passed on, we want its recipients
to know that what they have is not the original, so that any problems
introduced by others will not reflect on the original authors' reputations.
The precise terms and conditions for copying, distribution and
modification follow.
Finally, any free program is threatened constantly by software patents. We
wish to avoid the danger that redistributors of a free program will individually
obtain patent licenses, in effect making the program proprietary. To prevent
this, we have made it clear that any patent must be licensed for everyone's
free use or not licensed at all.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
The precise terms and conditions for copying, distribution and modification
follow.
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND
MODIFICATION
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
0. This License applies to any program or other work which contains a notice
placed by the copyright holder saying it may be distributed under the terms
of this General Public License. The "Program", below, refers to any such
program or work, and a "work based on the Program" means either the
Program or any derivative work under copyright law: that is to say, a work
containing the Program or a portion of it, either verbatim or with
modifications and/or translated into another language. (Hereinafter, translation
is included without limitation in the term "modification".) Each licensee is
addressed as "you".
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
Activities other than copying, distribution and modification are not covered
by this License; they are outside its scope. The act of running the Program is
not restricted, and the output from the Program is covered only if its contents
constitute a work based on the Program (independent of having been made
by running the Program). Whether that is true depends on what the Program
does.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
1. You may copy and distribute verbatim copies of the Program's source
code as you receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice and
disclaimer of warranty; keep intact all the notices that refer to this License
and to the absence of any warranty; and give any other recipients of the
Program a copy of this License along with the Program.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
You may charge a fee for the physical act of transferring a copy, and you
may at your option offer warranty protection in exchange for a fee.
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
2. You may modify your copy or copies of the Program or any portion of it,
thus forming a work based on the Program, and copy and distribute such
modifications or work under the terms of Section 1 above, provided that you
also meet all of these conditions:
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
a) You must cause the modified files to carry prominent notices stating that
you changed the files and the date of any change.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
b) You must cause any work that you distribute or publish, that in whole or in
part contains or is derived from the Program or any part thereof, to be
licensed as a whole at no charge to all third parties under the terms of this
License.
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
c) If the modified program normally reads commands interactively when run,
you must cause it, when started running for such interactive use in the most
ordinary way, to print or display an announcement including an appropriate
copyright notice and a notice that there is no warranty (or else, saying that
you provide a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this License.
(Exception: if the Program itself is interactive but does not normally print such
an announcement, your work based on the Program is not required to print
an announcement.)
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
These requirements apply to the modified work as a whole. If identifiable
sections of that work are not derived from the Program, and can be
reasonably considered independent and separate works in themselves, then
this License, and its terms, do not apply to those sections when you distribute
them as separate works. But when you distribute the same sections as part
of a whole which is a work based on the Program, the distribution of the
whole must be on the terms of this License, whose permissions for other
licensees extend to the entire whole, and thus to each and every part
regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest your rights to
work written entirely by you; rather, the intent is to exercise the right to
control the distribution of derivative or collective works based on the
Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
with the Program (or with a work based on the Program) on a volume of a
storage or distribution medium does not bring the other work under the scope
of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
3. You may copy and distribute the Program (or a work based on it, under
Section 2) in object code or executable form under the terms of Sections 1
and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
a) Accompany it with the complete corresponding machine-readable source
code, which must be distributed under the terms of Sections 1 and 2 above
on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three years, to give
any third party, for a charge no more than your cost of physically performing
source distribution, a complete machine-readable copy of the corresponding
source code, to be distributed under the terms of Sections 1 and 2 above on
a medium customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
c) Accompany it with the information you received as to the offer to distribute
corresponding source code. (This alternative is allowed only for
noncommercial distribution and only if you received the program in object
code or executable form with such an offer, in accord with Subsection b
above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
making modifications to it. For an executable work, complete source code
means all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation and
installation of the executable. However, as a special exception, the source
code distributed need not include anything that is normally distributed (in
either source or binary form) with the major components (compiler, kernel,
and so on) of the operating system on which the executable runs, unless that
component itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
If distribution of executable or object code is made by offering access to
copy from a designated place, then offering equivalent access to copy the
source code from the same place counts as distribution of the source code,
even though third parties are not compelled to copy the source along with the
object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
4. You may not copy, modify, sublicense, or distribute the Program except as
expressly provided under this License. Any attempt otherwise to copy,
modify, sublicense or distribute the Program is void, and will automatically
terminate your rights under this License. However, parties who have received
copies, or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
5. You are not required to accept this License, since you have not signed it.
However, nothing else grants you permission to modify or distribute the
Program or its derivative works. These actions are prohibited by law if you
do not accept this License. Therefore, by modifying or distributing the
Program (or any work based on the Program), you indicate your acceptance
of this License to do so, and all its terms and conditions for copying,
distributing or modifying the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the original
licensor to copy, distribute or modify the Program subject to these terms and
conditions. You may not impose any further restrictions on the recipients'
exercise of the rights granted herein. You are not responsible for enforcing
compliance by third parties to this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues), conditions
are imposed on you (whether by court order, agreement or otherwise) that
contradict the conditions of this License, they do not excuse you from the
conditions of this License. If you cannot distribute so as to satisfy
simultaneously your obligations under this License and any other pertinent
obligations, then as a consequence you may not distribute the Program at all.
For example, if a patent license would not permit royalty-free redistribution
of the Program by all those who receive copies directly or indirectly through
you, then the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply and
the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
It is not the purpose of this section to induce you to infringe any patents or
other property right claims or to contest validity of any such claims; this
section has the sole purpose of protecting the integrity of the free software
distribution system, which is implemented by public license practices. Many
people have made generous contributions to the wide range of software
distributed through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing to
distribute software through any other system and a licensee cannot impose
that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
This section is intended to make thoroughly clear what is believed to be a
consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
8. If the distribution and/or use of the Program is restricted in certain
countries either by patents or by copyrighted interfaces, the original copyright
holder who places the Program under this License may add an explicit
geographical distribution limitation excluding those countries, so that
distribution is permitted only in or among countries not thus excluded. In such
case, this License incorporates the limitation as if written in the body of this
License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will be
similar in spirit to the present version, but may differ in detail to address new
problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
Each version is given a distinguishing version number. If the Program specifies
a version number of this License which applies to it and "any later version",
you have the option of following the terms and conditions either of that
version or of any later version published by the Free Software Foundation. If
the Program does not specify a version number of this License, you may
choose any version ever published by the Free Software Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
10. If you wish to incorporate parts of the Program into other free programs
whose distribution conditions are different, write to the author to ask for
permission. For software which is copyrighted by the Free Software
Foundation, write to the Free Software Foundation; we sometimes make
exceptions for this. Our decision will be guided by the two goals of
preserving the free status of all derivatives of our free software and of
promoting the sharing and reuse of software generally.
NO WARRANTY
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE,
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT
PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE
STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL
NECESSARY SERVICING, REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR
AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR
ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE
LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL,
SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OR INABILITY TO USE THE
PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA
OR DATA BEING RENDERED INACCURATE OR LOSSES
SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE
PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN
IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF
THE POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
END OF TERMS AND CONDITIONS
+1 -16
View File
@@ -1,16 +1 @@
DESCRIPTION
===========
Provides a field type that can reference arbitrary entities.
SITE BUILDERS
=============
Note that when using a select widget, Entity reference loads all the
entities in that list in order to get the entity's label. If there are
too many loaded entities that site might reach its memory limit and crash
(also known as WSOD). In such a case you are advised to change the widget
to "autocomplete". If you get a WSOD when trying to edit the field
settings, you can reach the widget settings directly by navigation to
admin/structure/types/manage/[ENTITY-TYPE]/fields/[FIELD-NAME]/widget-type
Replace ENTITY-TYPE and FIELD_NAME with the correct values.
!!! this module is not ready tu use !!!
-4
View File
@@ -1,4 +0,0 @@
.entityreference-settings {
margin-left: 1.5em;
}
-26
View File
@@ -1,26 +0,0 @@
<?php
/**
* @file
* Support for processing entity reference fields in devel generate.
*/
function entityreference_devel_generate($object, $field, $instance, $bundle) {
if (field_behaviors_widget('multiple values', $instance) == FIELD_BEHAVIOR_CUSTOM) {
return devel_generate_multiple('_entityreference_devel_generate', $object, $field, $instance, $bundle);
}
else {
return _entityreference_devel_generate($object, $field, $instance, $bundle);
}
}
function _entityreference_devel_generate($object, $field, $instance, $bundle) {
$object_field = array();
// Get all the entity that are referencable here.
$referencable_entity = entityreference_get_selection_handler($field, $instance)->getReferencableEntities();
if (is_array($referencable_entity) && !empty($referencable_entity)) {
// Get a random key.
$object_field['target_id'] = array_rand($referencable_entity);
}
return $object_field;
}
-121
View File
@@ -1,121 +0,0 @@
<?php
/**
* @file
* Feeds mapping implementation for the Entity reference module
*/
/**
* Implements hook_feeds_processor_targets_alter().
*
* @see FeedsNodeProcessor::getMappingTargets().
*/
function entityreference_feeds_processor_targets_alter(&$targets, $entity_type, $bundle_name) {
foreach (field_info_instances($entity_type, $bundle_name) as $name => $instance) {
$info = field_info_field($name);
if ($info['type'] == 'entityreference') {
$targets[$name] = array(
'name' => check_plain($instance['label']),
'callback' => 'entityreference_feeds_set_target',
'description' => t('The field instance @label of @id', array(
'@label' => $instance['label'],
'@id' => $name,
)),
);
}
}
}
/**
* Entity reference callback for mapping.
*
* When the callback is invoked, $target contains the name of the field the
* user has decided to map to and $value contains the value of the feed item
* element the user has picked as a source.
*
* @param $source
* A FeedsSource object.
* @param $entity
* The entity to map to.
* @param $target
* The target key on $entity to map to.
* @param $value
* The value to map. MUST be an array.
* @param $mapping
* Array of mapping settings for current value.
* @param $input_format
* TRUE if an input format should be applied.
*/
function entityreference_feeds_set_target($source, $entity, $target, $value, $mapping, $input_format = FALSE) {
// Don't do anything if we weren't given any data.
if (empty($value)) {
return;
}
// Assume that the passed in value could really be any number of values.
if (is_array($value)) {
$values = $value;
}
else {
$values = array($value);
}
// Get some useful field information.
$info = field_info_field($target);
// Set the language of the field depending on the mapping.
$language = isset($mapping['language']) ? $mapping['language'] : LANGUAGE_NONE;
// Iterate over all values.
$iterator = 0;
$field = isset($entity->$target) ? $entity->$target : array();
foreach ($values as $value) {
// Only process if this value was set for this instance.
if ($value) {
// Fetch the entity ID resulting from the mapping table look-up.
$entity_id = db_query(
'SELECT entity_id FROM {feeds_item} WHERE guid = :guid',
array(':guid' => $value)
)->fetchField();
/*
* Only add a reference to an existing entity ID if there exists a
* mapping between it and the provided GUID. In cases where no such
* mapping exists (yet), don't do anything here. There may be a mapping
* defined later in the CSV file. If so, and the user re-runs the import
* (as a second pass), we can add this reference then. (The "Update
* existing nodes" option must be selected during the second pass.)
*/
if ($entity_id) {
// Assign the target ID.
$field[$language][$iterator]['target_id'] = $entity_id;
}
else /* there is no $entity_id, no mapping */ {
/*
* Feeds stores a hash of every line imported from CSVs in order to
* make the import process more efficient by ignoring lines it's
* already seen. We need to short-circuit this process in this case
* because users may want to re-import the same line as an update later
* when (and if) a map to a reference exists. So in order to provide
* this opportunity later, we need to destroy the hash.
*/
unset($entity->feeds_item->hash);
}
}
// Break out of the loop if this field is single-valued.
if ($info['cardinality'] == 1) {
break;
}
$iterator++;
}
// Add the field to the entity definition.
$entity->{$target} = $field;
}
-29
View File
@@ -1,29 +0,0 @@
name = Entity Reference
description = Provides a field that can reference other entities.
core = 7.x
package = Fields
dependencies[] = entity
dependencies[] = ctools
; Migrate handler.
files[] = entityreference.migrate.inc
; Our plugins interfaces and abstract implementations.
files[] = plugins/selection/abstract.inc
files[] = plugins/selection/views.inc
files[] = plugins/behavior/abstract.inc
files[] = views/entityreference_plugin_display.inc
files[] = views/entityreference_plugin_style.inc
files[] = views/entityreference_plugin_row_fields.inc
; Tests.
files[] = tests/entityreference.handlers.test
files[] = tests/entityreference.admin.test
; Information added by drupal.org packaging script on 2012-09-25
version = "7.x-1.0-rc5"
core = "7.x"
project = "entityreference"
datestamp = "1348565045"
-164
View File
@@ -1,164 +0,0 @@
<?php
/**
* Implements hook_uninstall().
*/
function entityreference_uninstall() {
variable_del('entityreference:base-tables');
}
/**
* Implements hook_field_schema().
*/
function entityreference_field_schema($field) {
if ($field['type'] == 'entityreference') {
// Load the base table configuration from the cache.
$base_tables = variable_get('entityreference:base-tables', array());
$schema = array(
'columns' => array(
'target_id' => array(
'description' => 'The id of the target entity.',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
),
),
'indexes' => array(
'target_id' => array('target_id'),
),
'foreign keys' => array(),
);
// Create a foreign key to the target entity type base type, if available.
$entity_type = $field['settings']['target_type'];
if (isset($base_tables[$entity_type])) {
list($base_table, $id_column) = $base_tables[$entity_type];
$schema['foreign keys'][$base_table] = array(
'table' => $base_table,
'columns' => array('target_id' => $id_column),
);
}
// Invoke the behaviors to allow them to change the schema.
foreach (entityreference_get_behavior_handlers($field) as $handler) {
$handler->schema_alter($schema, $field);
}
return $schema;
}
}
/**
* Update the field configuration to the new plugin structure.
*/
function entityreference_update_7000() {
// Enable ctools.
if (!module_enable(array('ctools'))) {
throw new DrupalUpdateException('This version of Entity Reference requires ctools, but it could not be enabled.');
}
// Get the list of fields of type 'entityreference'.
$fields = array();
foreach (field_info_fields() as $field_name => $field) {
// Update the field configuration.
if ($field['type'] == 'entityreference') {
$settings = &$field['settings'];
if (!isset($settings['handler'])) {
$settings['handler'] = 'base';
$settings['handler_settings']['target_bundles'] = $settings['target_bundles'];
unset($settings['target_bundles']);
field_update_field($field);
}
}
// Update the instance configurations.
foreach ($field['bundles'] as $entity_type => $bundles) {
foreach ($bundles as $bundle) {
$instance = field_info_instance($entity_type, $field_name, $bundle);
$save = FALSE;
if ($instance['widget']['type'] == 'entityreference_autocomplete') {
$instance['widget']['type'] = 'entityreference_autocomplete_tags';
$save = TRUE;
}
// When the autocomplete path is the default value, remove it from
// the configuration.
if (isset($instance['widget']['settings']['path']) && $instance['widget']['settings']['path'] == 'entityreference/autocomplete') {
unset($instance['widget']['settings']['path']);
$save = TRUE;
}
if ($save) {
field_update_instance($instance);
}
}
}
}
}
/**
* Drop "target_type" from the field schema.
*/
function entityreference_update_7001() {
if (!module_exists('field_sql_storage')) {
return;
}
foreach (field_info_fields() as $field_name => $field) {
if ($field['type'] != 'entityreference') {
// Not an entity reference field.
continue;
}
// Update the field settings.
$field = field_info_field($field_name);
unset($field['indexes']['target_entity']);
$field['indexes']['target_id'] = array('target_id');
field_update_field($field);
if ($field['storage']['type'] !== 'field_sql_storage') {
// Field doesn't use SQL storage, we cannot modify the schema.
continue;
}
$table_name = _field_sql_storage_tablename($field);
$revision_name = _field_sql_storage_revision_tablename($field);
db_drop_index($table_name, $field_name . '_target_entity');
db_drop_index($table_name, $field_name . '_target_id');
db_drop_field($table_name, $field_name . '_target_type');
db_add_index($table_name, $field_name . '_target_id', array($field_name . '_target_id'));
db_drop_index($revision_name, $field_name . '_target_entity');
db_drop_index($revision_name, $field_name . '_target_id');
db_drop_field($revision_name, $field_name . '_target_type');
db_add_index($revision_name, $field_name . '_target_id', array($field_name . '_target_id'));
}
}
/**
* Make the target_id column NOT NULL.
*/
function entityreference_update_7002() {
if (!module_exists('field_sql_storage')) {
return;
}
foreach (field_info_fields() as $field_name => $field) {
if ($field['type'] != 'entityreference') {
// Not an entity reference field.
continue;
}
if ($field['storage']['type'] !== 'field_sql_storage') {
// Field doesn't use SQL storage, we cannot modify the schema.
continue;
}
$table_name = _field_sql_storage_tablename($field);
$revision_name = _field_sql_storage_revision_tablename($field);
db_change_field($table_name, $field_name . '_target_id', $field_name . '_target_id', array(
'description' => 'The id of the target entity.',
'type' => 'int',
'unsigned' => TRUE,
'not null' => TRUE,
));
}
}
-24
View File
@@ -1,24 +0,0 @@
<?php
/**
* @file
* Support for processing entity reference fields in Migrate.
*/
/**
* Implement hook_migrate_api().
*/
function entityreference_migrate_api() {
return array('api' => 2);
}
class MigrateEntityReferenceFieldHandler extends MigrateSimpleFieldHandler {
public function __construct() {
parent::__construct(array(
'value_key' => 'target_id',
'skip_empty' => TRUE,
));
$this->registerTypes(array('entityreference'));
}
}
File diff suppressed because it is too large Load Diff
@@ -1,12 +0,0 @@
name = Entity Reference Behavior Example
description = Provides some example code for implementing Entity Reference behaviors.
core = 7.x
package = Fields
dependencies[] = entityreference
; Information added by drupal.org packaging script on 2012-09-25
version = "7.x-1.0-rc5"
core = "7.x"
project = "entityreference"
datestamp = "1348565045"
@@ -1,15 +0,0 @@
<?php
/**
* @file
* Example module to demonstrate Entity reference behavior handlers.
*/
/**
* Implements hook_ctools_plugin_directory().
*/
function entityreference_behavior_example_ctools_plugin_directory($module, $plugin) {
if ($module == 'entityreference') {
return 'plugins/' . $plugin;
}
}
@@ -1,31 +0,0 @@
<?php
class EntityReferenceFieldBehaviorExample extends EntityReference_BehaviorHandler_Abstract {
public function load($entity_type, $entities, $field, $instances, $langcode, &$items) {
drupal_set_message(t('Do something on load!'));
}
public function insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
drupal_set_message(t('Do something on insert!'));
}
public function update($entity_type, $entity, $field, $instance, $langcode, &$items) {
drupal_set_message(t('Do something on update!'));
}
public function delete($entity_type, $entity, $field, $instance, $langcode, &$items) {
drupal_set_message(t('Do something on delete!'));
}
/**
* Generate a settings form for this handler.
*/
public function settingsForm($field, $instance) {
$form['test_field'] = array(
'#type' => 'checkbox',
'#title' => t('Field behavior setting'),
);
return $form;
}
}
@@ -1,31 +0,0 @@
<?php
class EntityReferenceInstanceBehaviorExample extends EntityReference_BehaviorHandler_Abstract {
public function load($entity_type, $entities, $field, $instances, $langcode, &$items) {
drupal_set_message(t('Do something on load, on the instance level!'));
}
public function insert($entity_type, $entity, $field, $instance, $langcode, &$items) {
drupal_set_message(t('Do something on insert, on the instance level!'));
}
public function update($entity_type, $entity, $field, $instance, $langcode, &$items) {
drupal_set_message(t('Do something on update, on the instance level!'));
}
public function delete($entity_type, $entity, $field, $instance, $langcode, &$items) {
drupal_set_message(t('Do something on delete, on the instance level!'));
}
/**
* Generate a settings form for this handler.
*/
public function settingsForm($field, $instance) {
$form['test_instance'] = array(
'#type' => 'checkbox',
'#title' => t('Instance behavior setting'),
);
return $form;
}
}
@@ -1,8 +0,0 @@
<?php
$plugin = array(
'title' => t('Test behavior'),
'class' => 'EntityReferenceFieldBehaviorExample',
'weight' => 10,
'behavior type' => 'field',
);
@@ -1,8 +0,0 @@
<?php
$plugin = array(
'title' => t('Test instance behavior'),
'class' => 'EntityReferenceInstanceBehaviorExample',
'weight' => 10,
'behavior type' => 'instance',
);
BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 690 B

@@ -1,18 +0,0 @@
<?php
class EntityReferenceBehavior_ViewsFilterSelect extends EntityReference_BehaviorHandler_Abstract {
public function views_data_alter(&$data, $field) {
$entity_info = entity_get_info($field['settings']['target_type']);
$field_name = $field['field_name'] . '_target_id';
foreach ($data as $table_name => &$table_data) {
if (isset($table_data[$field_name])) {
// Set the entity id filter to use the in_operator handler with our
// own callback to return the values.
$table_data[$field_name]['filter']['handler'] = 'views_handler_filter_in_operator';
$table_data[$field_name]['filter']['options callback'] = 'entityreference_views_handler_options_list';
$table_data[$field_name]['filter']['options arguments'] = array($field['field_name']);
}
}
}
}
-187
View File
@@ -1,187 +0,0 @@
<?php
/**
* Additional behaviors for a Entity Reference field.
*
* Implementations that wish to provide an implementation of this should
* register it using CTools' plugin system.
*/
interface EntityReference_BehaviorHandler {
/**
* Constructor for the behavior.
*
* @param $behavior
* The name of the behavior plugin.
*/
public function __construct($behavior);
/**
* Alter the field schema.
*
* @see hook_field_schema()
*/
public function schema_alter(&$schema, $field);
/**
* Alter the properties information of a field instance.
*
* @see entity_hook_field_info()
*/
public function property_info_alter(&$info, $entity_type, $field, $instance, $field_type);
/**
* Alter the views data of a field.
*
* @see entityreference_field_views_data()
*/
public function views_data_alter(&$data, $field);
/**
* Act on loading entity reference fields of entities.
*
* @see hook_field_load()
*/
public function load($entity_type, $entities, $field, $instances, $langcode, &$items);
/**
* Alter the empty status of a field item.
*
* @see hook_field_is_empty()
*/
public function is_empty_alter(&$empty, $item, $field);
/**
* Act on validating an entity reference field.
*
* @see hook_field_validate()
*/
public function validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors);
/**
* Act on presaving an entity reference field.
*
* @see hook_field_presave()
*/
public function presave($entity_type, $entity, $field, $instance, $langcode, &$items);
/**
* Act before inserting an entity reference field.
*
* @see hook_field_insert()
*/
public function insert($entity_type, $entity, $field, $instance, $langcode, &$items);
/**
* Act after inserting an entity reference field.
*
* @see hook_field_attach_insert()
*/
public function postInsert($entity_type, $entity, $field, $instance);
/**
* Act before updating an entity reference field.
*
* @see hook_field_update()
*/
public function update($entity_type, $entity, $field, $instance, $langcode, &$items);
/**
* Act after updating an entity reference field.
*
* @see hook_field_attach_update()
*/
public function postUpdate($entity_type, $entity, $field, $instance);
/**
* Act before deleting an entity with an entity reference field.
*
* @see hook_field_delete()
*/
public function delete($entity_type, $entity, $field, $instance, $langcode, &$items);
/**
* Act after deleting an entity with an entity reference field.
*
* @see hook_field_attach_delete()
*/
public function postDelete($entity_type, $entity, $field, $instance);
/**
* Generate a settings form for this handler.
*/
public function settingsForm($field, $instance);
/**
* Determine if handler should appear.
*/
public function access($field, $instance);
}
/**
* An abstract implementation of EntityReference_BehaviorHandler.
*/
abstract class EntityReference_BehaviorHandler_Abstract implements EntityReference_BehaviorHandler {
/**
* The name of the behavior plugin.
*/
protected $behavior;
/**
* The plugin definition.
*/
protected $plugin;
public function __construct($behavior) {
$this->behavior = $behavior;
ctools_include('plugins');
$plugin = ctools_get_plugins('entityreference', 'behavior', $behavior);
$this->plugin = $plugin;
}
public function schema_alter(&$schema, $field) {}
public function property_info_alter(&$info, $entity_type, $field, $instance, $field_type) {}
public function views_data_alter(&$data, $field) {}
public function load($entity_type, $entities, $field, $instances, $langcode, &$items) {}
public function is_empty_alter(&$empty, $item, $field) {}
public function validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) {}
public function presave($entity_type, $entity, $field, $instance, $langcode, &$items) {}
public function insert($entity_type, $entity, $field, $instance, $langcode, &$items) {}
public function postInsert($entity_type, $entity, $field, $instance) {}
public function update($entity_type, $entity, $field, $instance, $langcode, &$items) {}
public function postUpdate($entity_type, $entity, $field, $instance) {}
public function delete($entity_type, $entity, $field, $instance, $langcode, &$items) {}
public function postDelete($entity_type, $entity, $field, $instance) {}
public function settingsForm($field, $instance) {}
public function access($field, $instance) {
return TRUE;
}
}
/**
* A broken implementation of EntityReference_BehaviorHandler.
*/
class EntityReference_BehaviorHandler_Broken extends EntityReference_BehaviorHandler_Abstract {
public function settingsForm($field, $instance) {
$form['behavior_handler'] = array(
'#markup' => t('The selected behavior handler is broken.'),
);
return $form;
}
}
-10
View File
@@ -1,10 +0,0 @@
<?php
if (module_exists('views')) {
$plugin = array(
'title' => t('Render Views filters as select list'),
'description' => t('Provides a select list for Views filters on this field. This should not be used when there are over 100 entities, as it might cause an out of memory error.'),
'class' => 'EntityReferenceBehavior_ViewsFilterSelect',
'behavior type' => 'field',
);
}
@@ -1,489 +0,0 @@
<?php
/**
* A generic Entity handler.
*
* The generic base implementation has a variety of overrides to workaround
* core's largely deficient entity handling.
*/
class EntityReference_SelectionHandler_Generic implements EntityReference_SelectionHandler {
/**
* Implements EntityReferenceHandler::getInstance().
*/
public static function getInstance($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
$target_entity_type = $field['settings']['target_type'];
// Check if the entity type does exist and has a base table.
$entity_info = entity_get_info($target_entity_type);
if (empty($entity_info['base table'])) {
return EntityReference_SelectionHandler_Broken::getInstance($field, $instance);
}
if (class_exists($class_name = 'EntityReference_SelectionHandler_Generic_' . $target_entity_type)) {
return new $class_name($field, $instance, $entity_type, $entity);
}
else {
return new EntityReference_SelectionHandler_Generic($field, $instance, $entity_type, $entity);
}
}
protected function __construct($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
$this->field = $field;
$this->instance = $instance;
$this->entity_type = $entity_type;
$this->entity = $entity;
}
/**
* Implements EntityReferenceHandler::settingsForm().
*/
public static function settingsForm($field, $instance) {
$entity_info = entity_get_info($field['settings']['target_type']);
// Merge-in default values.
$field['settings']['handler_settings'] += array(
'target_bundles' => array(),
'sort' => array(
'type' => 'none',
)
);
if (!empty($entity_info['entity keys']['bundle'])) {
$bundles = array();
foreach ($entity_info['bundles'] as $bundle_name => $bundle_info) {
$bundles[$bundle_name] = $bundle_info['label'];
}
$form['target_bundles'] = array(
'#type' => 'checkboxes',
'#title' => t('Target bundles'),
'#options' => $bundles,
'#default_value' => $field['settings']['handler_settings']['target_bundles'],
'#size' => 6,
'#multiple' => TRUE,
'#description' => t('The bundles of the entity type that can be referenced. Optional, leave empty for all bundles.'),
'#element_validate' => array('_entityreference_element_validate_filter'),
);
}
else {
$form['target_bundles'] = array(
'#type' => 'value',
'#value' => array(),
);
}
$form['sort']['type'] = array(
'#type' => 'select',
'#title' => t('Sort by'),
'#options' => array(
'none' => t("Don't sort"),
'property' => t('A property of the base table of the entity'),
'field' => t('A field attached to this entity'),
),
'#ajax' => TRUE,
'#limit_validation_errors' => array(),
'#default_value' => $field['settings']['handler_settings']['sort']['type'],
);
$form['sort']['settings'] = array(
'#type' => 'container',
'#attributes' => array('class' => array('entityreference-settings')),
'#process' => array('_entityreference_form_process_merge_parent'),
);
if ($field['settings']['handler_settings']['sort']['type'] == 'property') {
// Merge-in default values.
$field['settings']['handler_settings']['sort'] += array(
'property' => NULL,
);
$form['sort']['settings']['property'] = array(
'#type' => 'select',
'#title' => t('Sort property'),
'#required' => TRUE,
'#options' => drupal_map_assoc($entity_info['schema_fields_sql']['base table']),
'#default_value' => $field['settings']['handler_settings']['sort']['property'],
);
}
elseif ($field['settings']['handler_settings']['sort']['type'] == 'field') {
// Merge-in default values.
$field['settings']['handler_settings']['sort'] += array(
'field' => NULL,
);
$fields = array();
foreach (field_info_instances($field['settings']['target_type']) as $bundle_name => $bundle_instances) {
foreach ($bundle_instances as $instance_name => $instance_info) {
$field_info = field_info_field($instance_name);
foreach ($field_info['columns'] as $column_name => $column_info) {
$fields[$instance_name . ':' . $column_name] = t('@label (column @column)', array('@label' => $instance_info['label'], '@column' => $column_name));
}
}
}
$form['sort']['settings']['field'] = array(
'#type' => 'select',
'#title' => t('Sort field'),
'#required' => TRUE,
'#options' => $fields,
'#default_value' => $field['settings']['handler_settings']['sort']['field'],
);
}
if ($field['settings']['handler_settings']['sort']['type'] != 'none') {
// Merge-in default values.
$field['settings']['handler_settings']['sort'] += array(
'direction' => 'ASC',
);
$form['sort']['settings']['direction'] = array(
'#type' => 'select',
'#title' => t('Sort direction'),
'#required' => TRUE,
'#options' => array(
'ASC' => t('Ascending'),
'DESC' => t('Descending'),
),
'#default_value' => $field['settings']['handler_settings']['sort']['direction'],
);
}
return $form;
}
/**
* Implements EntityReferenceHandler::getReferencableEntities().
*/
public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
$options = array();
$entity_type = $this->field['settings']['target_type'];
$query = $this->buildEntityFieldQuery($match, $match_operator);
if ($limit > 0) {
$query->range(0, $limit);
}
$results = $query->execute();
if (!empty($results[$entity_type])) {
$entities = entity_load($entity_type, array_keys($results[$entity_type]));
foreach ($entities as $entity_id => $entity) {
$options[$entity_id] = check_plain($this->getLabel($entity));
}
}
return $options;
}
/**
* Implements EntityReferenceHandler::countReferencableEntities().
*/
public function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS') {
$query = $this->buildEntityFieldQuery($match, $match_operator);
return $query
->count()
->execute();
}
/**
* Implements EntityReferenceHandler::validateReferencableEntities().
*/
public function validateReferencableEntities(array $ids) {
if ($ids) {
$entity_type = $this->field['settings']['target_type'];
$query = $this->buildEntityFieldQuery();
$query->entityCondition('entity_id', $ids, 'IN');
$result = $query->execute();
if (!empty($result[$entity_type])) {
return array_keys($result[$entity_type]);
}
}
return array();
}
/**
* Implements EntityReferenceHandler::validateAutocompleteInput().
*/
public function validateAutocompleteInput($input, &$element, &$form_state, $form) {
$entities = $this->getReferencableEntities($input, '=', 6);
if (empty($entities)) {
// Error if there are no entities available for a required field.
form_error($element, t('There are no entities matching "%value"', array('%value' => $input)));
}
elseif (count($entities) > 5) {
// Error if there are more than 5 matching entities.
form_error($element, t('Many entities are called %value. Specify the one you want by appending the id in parentheses, like "@value (@id)"', array(
'%value' => $input,
'@value' => $input,
'@id' => key($entities),
)));
}
elseif (count($entities) > 1) {
// More helpful error if there are only a few matching entities.
$multiples = array();
foreach ($entities as $id => $name) {
$multiples[] = $name . ' (' . $id . ')';
}
form_error($element, t('Multiple entities match this reference; "%multiple"', array('%multiple' => implode('", "', $multiples))));
}
else {
// Take the one and only matching entity.
return key($entities);
}
}
/**
* Build an EntityFieldQuery to get referencable entities.
*/
protected function buildEntityFieldQuery($match = NULL, $match_operator = 'CONTAINS') {
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', $this->field['settings']['target_type']);
if (!empty($this->field['settings']['handler_settings']['target_bundles'])) {
$query->entityCondition('bundle', $this->field['settings']['handler_settings']['target_bundles'], 'IN');
}
if (isset($match)) {
$entity_info = entity_get_info($this->field['settings']['target_type']);
if (isset($entity_info['entity keys']['label'])) {
$query->propertyCondition($entity_info['entity keys']['label'], $match, $match_operator);
}
}
// Add a generic entity access tag to the query.
$query->addTag($this->field['settings']['target_type'] . '_access');
$query->addTag('entityreference');
$query->addMetaData('field', $this->field);
$query->addMetaData('entityreference_selection_handler', $this);
// Add the sort option.
if (!empty($this->field['settings']['handler_settings']['sort'])) {
$sort_settings = $this->field['settings']['handler_settings']['sort'];
if ($sort_settings['type'] == 'property') {
$query->propertyOrderBy($sort_settings['property'], $sort_settings['direction']);
}
elseif ($sort_settings['type'] == 'field') {
list($field, $column) = explode(':', $sort_settings['field'], 2);
$query->fieldOrderBy($field, $column, $sort_settings['direction']);
}
}
return $query;
}
/**
* Implements EntityReferenceHandler::entityFieldQueryAlter().
*/
public function entityFieldQueryAlter(SelectQueryInterface $query) {
}
/**
* Helper method: pass a query to the alteration system again.
*
* This allow Entity Reference to add a tag to an existing query, to ask
* access control mechanisms to alter it again.
*/
protected function reAlterQuery(SelectQueryInterface $query, $tag, $base_table) {
// Save the old tags and metadata.
// For some reason, those are public.
$old_tags = $query->alterTags;
$old_metadata = $query->alterMetaData;
$query->alterTags = array($tag => TRUE);
$query->alterMetaData['base_table'] = $base_table;
drupal_alter(array('query', 'query_' . $tag), $query);
// Restore the tags and metadata.
$query->alterTags = $old_tags;
$query->alterMetaData = $old_metadata;
}
/**
* Implements EntityReferenceHandler::getLabel().
*/
public function getLabel($entity) {
return entity_label($this->field['settings']['target_type'], $entity);
}
}
/**
* Override for the Node type.
*
* This only exists to workaround core bugs.
*/
class EntityReference_SelectionHandler_Generic_node extends EntityReference_SelectionHandler_Generic {
public function entityFieldQueryAlter(SelectQueryInterface $query) {
// Adding the 'node_access' tag is sadly insufficient for nodes: core
// requires us to also know about the concept of 'published' and
// 'unpublished'. We need to do that as long as there are no access control
// modules in use on the site. As long as one access control module is there,
// it is supposed to handle this check.
if (!user_access('bypass node access') && !count(module_implements('node_grants'))) {
$tables = $query->getTables();
$query->condition(key($tables) . '.status', NODE_PUBLISHED);
}
}
}
/**
* Override for the User type.
*
* This only exists to workaround core bugs.
*/
class EntityReference_SelectionHandler_Generic_user extends EntityReference_SelectionHandler_Generic {
public function buildEntityFieldQuery($match = NULL, $match_operator = 'CONTAINS') {
$query = parent::buildEntityFieldQuery($match, $match_operator);
// The user entity doesn't have a label column.
if (isset($match)) {
$query->propertyCondition('name', $match, $match_operator);
}
// Adding the 'user_access' tag is sadly insufficient for users: core
// requires us to also know about the concept of 'blocked' and
// 'active'.
if (!user_access('administer users')) {
$query->propertyCondition('status', 1);
}
return $query;
}
public function entityFieldQueryAlter(SelectQueryInterface $query) {
if (user_access('administer users')) {
// In addition, if the user is administrator, we need to make sure to
// match the anonymous user, that doesn't actually have a name in the
// database.
$conditions = &$query->conditions();
foreach ($conditions as $key => $condition) {
if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'users.name') {
// Remove the condition.
unset($conditions[$key]);
// Re-add the condition and a condition on uid = 0 so that we end up
// with a query in the form:
// WHERE (name LIKE :name) OR (:anonymous_name LIKE :name AND uid = 0)
$or = db_or();
$or->condition($condition['field'], $condition['value'], $condition['operator']);
// Sadly, the Database layer doesn't allow us to build a condition
// in the form ':placeholder = :placeholder2', because the 'field'
// part of a condition is always escaped.
// As a (cheap) workaround, we separately build a condition with no
// field, and concatenate the field and the condition separately.
$value_part = db_and();
$value_part->condition('anonymous_name', $condition['value'], $condition['operator']);
$value_part->compile(Database::getConnection(), $query);
$or->condition(db_and()
->where(str_replace('anonymous_name', ':anonymous_name', (string) $value_part), $value_part->arguments() + array(':anonymous_name' => format_username(user_load(0))))
->condition('users.uid', 0)
);
$query->condition($or);
}
}
}
}
}
/**
* Override for the Comment type.
*
* This only exists to workaround core bugs.
*/
class EntityReference_SelectionHandler_Generic_comment extends EntityReference_SelectionHandler_Generic {
public function entityFieldQueryAlter(SelectQueryInterface $query) {
// Adding the 'comment_access' tag is sadly insufficient for comments: core
// requires us to also know about the concept of 'published' and
// 'unpublished'.
if (!user_access('administer comments')) {
$tables = $query->getTables();
$query->condition(key($tables) . '.status', COMMENT_PUBLISHED);
}
// The Comment module doesn't implement any proper comment access,
// and as a consequence doesn't make sure that comments cannot be viewed
// when the user doesn't have access to the node.
$tables = $query->getTables();
$base_table = key($tables);
$node_alias = $query->innerJoin('node', 'n', '%alias.nid = ' . $base_table . '.nid');
// Pass the query to the node access control.
$this->reAlterQuery($query, 'node_access', $node_alias);
// Alas, the comment entity exposes a bundle, but doesn't have a bundle column
// in the database. We have to alter the query ourself to go fetch the
// bundle.
$conditions = &$query->conditions();
foreach ($conditions as $key => &$condition) {
if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'node_type') {
$condition['field'] = $node_alias . '.type';
foreach ($condition['value'] as &$value) {
if (substr($value, 0, 13) == 'comment_node_') {
$value = substr($value, 13);
}
}
break;
}
}
// Passing the query to node_query_node_access_alter() is sadly
// insufficient for nodes.
// @see EntityReferenceHandler_node::entityFieldQueryAlter()
if (!user_access('bypass node access') && !count(module_implements('node_grants'))) {
$query->condition($node_alias . '.status', 1);
}
}
}
/**
* Override for the File type.
*
* This only exists to workaround core bugs.
*/
class EntityReference_SelectionHandler_Generic_file extends EntityReference_SelectionHandler_Generic {
public function entityFieldQueryAlter(SelectQueryInterface $query) {
// Core forces us to know about 'permanent' vs. 'temporary' files.
$tables = $query->getTables();
$base_table = key($tables);
$query->condition('status', FILE_STATUS_PERMANENT);
// Access control to files is a very difficult business. For now, we are not
// going to give it a shot.
// @todo: fix this when core access control is less insane.
return $query;
}
public function getLabel($entity) {
// The file entity doesn't have a label. More over, the filename is
// sometimes empty, so use the basename in that case.
return $entity->filename !== '' ? $entity->filename : basename($entity->uri);
}
}
/**
* Override for the Taxonomy term type.
*
* This only exists to workaround core bugs.
*/
class EntityReference_SelectionHandler_Generic_taxonomy_term extends EntityReference_SelectionHandler_Generic {
public function entityFieldQueryAlter(SelectQueryInterface $query) {
// The Taxonomy module doesn't implement any proper taxonomy term access,
// and as a consequence doesn't make sure that taxonomy terms cannot be viewed
// when the user doesn't have access to the vocabulary.
$tables = $query->getTables();
$base_table = key($tables);
$vocabulary_alias = $query->innerJoin('taxonomy_vocabulary', 'n', '%alias.vid = ' . $base_table . '.vid');
$query->addMetadata('base_table', $vocabulary_alias);
// Pass the query to the taxonomy access control.
$this->reAlterQuery($query, 'taxonomy_vocabulary_access', $vocabulary_alias);
// Also, the taxonomy term entity exposes a bundle, but doesn't have a bundle
// column in the database. We have to alter the query ourself to go fetch
// the bundle.
$conditions = &$query->conditions();
foreach ($conditions as $key => &$condition) {
if ($key !== '#conjunction' && is_string($condition['field']) && $condition['field'] === 'vocabulary_machine_name') {
$condition['field'] = $vocabulary_alias . '.machine_name';
break;
}
}
}
}
@@ -1,183 +0,0 @@
<?php
/**
* Entity handler for Views.
*/
class EntityReference_SelectionHandler_Views implements EntityReference_SelectionHandler {
/**
* Implements EntityReferenceHandler::getInstance().
*/
public static function getInstance($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
return new EntityReference_SelectionHandler_Views($field, $instance);
}
protected function __construct($field, $instance) {
$this->field = $field;
$this->instance = $instance;
}
/**
* Implements EntityReferenceHandler::settingsForm().
*/
public static function settingsForm($field, $instance) {
$view_settings = empty($field['settings']['handler_settings']['view']) ? '' : $field['settings']['handler_settings']['view'];
$displays = views_get_applicable_views('entityreference display');
// Filter views that list the entity type we want, and group the separate
// displays by view.
$entity_info = entity_get_info($field['settings']['target_type']);
$options = array();
foreach ($displays as $data) {
list($view, $display_id) = $data;
if ($view->base_table == $entity_info['base table']) {
$options[$view->name . ':' . $display_id] = $view->name . ' - ' . $view->display[$display_id]->display_title;
}
}
// The value of the 'view_and_display' select below will need to be split
// into 'view_name' and 'view_display' in the final submitted values, so
// we massage the data at validate time on the wrapping element (not
// ideal).
$form['view']['#element_validate'] = array('entityreference_view_settings_validate');
if ($options) {
$default = !empty($view_settings['view_name']) ? $view_settings['view_name'] . ':' . $view_settings['display_name'] : NULL;
$form['view']['view_and_display'] = array(
'#type' => 'select',
'#title' => t('View used to select the entities'),
'#required' => TRUE,
'#options' => $options,
'#default_value' => $default,
'#description' => '<p>' . t('Choose the view and display that select the entities that can be referenced.<br />Only views with a display of type "Entity Reference" are eligible.') . '</p>',
);
$default = !empty($view_settings['args']) ? implode(', ', $view_settings['args']) : '';
$form['view']['args'] = array(
'#type' => 'textfield',
'#title' => t('View arguments'),
'#default_value' => $default,
'#required' => FALSE,
'#description' => t('Provide a comma separated list of arguments to pass to the view.'),
);
}
else {
$form['view']['no_view_help'] = array(
'#markup' => '<p>' . t('No eligible views were found. <a href="@create">Create a view</a> with an <em>Entity Reference</em> display, or add such a display to an <a href="@existing">existing view</a>.', array(
'@create' => url('admin/structure/views/add'),
'@existing' => url('admin/structure/views'),
)) . '</p>',
);
}
return $form;
}
protected function initializeView($match = NULL, $match_operator = 'CONTAINS', $limit = 0, $ids = NULL) {
$view_name = $this->field['settings']['handler_settings']['view']['view_name'];
$display_name = $this->field['settings']['handler_settings']['view']['display_name'];
$args = $this->field['settings']['handler_settings']['view']['args'];
$entity_type = $this->field['settings']['target_type'];
// Check that the view is valid and the display still exists.
$this->view = views_get_view($view_name);
if (!$this->view || !isset($this->view->display[$display_name]) || !$this->view->access($display_name)) {
watchdog('entityreference', 'The view %view_name is no longer eligible for the %field_name field.', array('%view_name' => $view_name, '%field_name' => $this->instance['label']), WATCHDOG_WARNING);
return FALSE;
}
$this->view->set_display($display_name);
// Make sure the query is not cached.
$this->view->is_cacheable = FALSE;
// Pass options to the display handler to make them available later.
$entityreference_options = array(
'match' => $match,
'match_operator' => $match_operator,
'limit' => $limit,
'ids' => $ids,
);
$this->view->display_handler->set_option('entityreference_options', $entityreference_options);
return TRUE;
}
/**
* Implements EntityReferenceHandler::getReferencableEntities().
*/
public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
$display_name = $this->field['settings']['handler_settings']['view']['display_name'];
$args = $this->field['settings']['handler_settings']['view']['args'];
$result = array();
if ($this->initializeView($match, $match_operator, $limit)) {
// Get the results.
$result = $this->view->execute_display($display_name, $args);
}
return $result;
}
/**
* Implements EntityReferenceHandler::countReferencableEntities().
*/
function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS') {
$this->getReferencableEntities($match, $match_operator);
return $this->view->total_items;
}
function validateReferencableEntities(array $ids) {
$display_name = $this->field['settings']['handler_settings']['view']['display_name'];
$args = $this->field['settings']['handler_settings']['view']['args'];
$result = array();
if ($this->initializeView(NULL, 'CONTAINS', 0, $ids)) {
// Get the results.
$entities = $this->view->execute_display($display_name, $args);
$result = array_keys($entities);
}
return $result;
}
/**
* Implements EntityReferenceHandler::validateAutocompleteInput().
*/
public function validateAutocompleteInput($input, &$element, &$form_state, $form) {
return NULL;
}
/**
* Implements EntityReferenceHandler::getLabel().
*/
public function getLabel($entity) {
return entity_label($this->field['settings']['target_type'], $entity);
}
/**
* Implements EntityReferenceHandler::entityFieldQueryAlter().
*/
public function entityFieldQueryAlter(SelectQueryInterface $query) {
}
}
function entityreference_view_settings_validate($element, &$form_state, $form) {
// Split view name and display name from the 'view_and_display' value.
if (!empty($element['view_and_display']['#value'])) {
list($view, $display) = explode(':', $element['view_and_display']['#value']);
}
else {
form_error($element, t('The views entity selection mode requires a view.'));
return;
}
// Explode the 'args' string into an actual array. Beware, explode() turns an
// empty string into an array with one empty string. We'll need an empty array
// instead.
$args_string = trim($element['args']['#value']);
if ($args_string === '') {
$args = array();
}
else {
// array_map is called to trim whitespaces from the arguments.
$args = array_map('trim', explode(',', $args_string));
}
$value = array('view_name' => $view, 'display_name' => $display, 'args' => $args);
form_set_value($element, $value, $form_state);
}
-113
View File
@@ -1,113 +0,0 @@
<?php
/**
* @file
* Abstraction of the selection logic of an entity reference field.
*
* Implementations that wish to provide an implementation of this should
* register it using CTools' plugin system.
*/
interface EntityReference_SelectionHandler {
/**
* Factory function: create a new instance of this handler for a given field.
*
* @param $field
* A field datastructure.
* @return EntityReferenceHandler
*/
public static function getInstance($field, $instance = NULL, $entity_type = NULL, $entity = NULL);
/**
* Return a list of referencable entities.
*
* @return
* An array of referencable entities, which keys are entity ids and
* values (safe HTML) labels to be displayed to the user.
*/
public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0);
/**
* Count entities that are referencable by a given field.
*/
public function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS');
/**
* Validate that entities can be referenced by this field.
*
* @return
* An array of entity ids that are valid.
*/
public function validateReferencableEntities(array $ids);
/**
* Validate Input from autocomplete widget that has no Id.
*
* @see _entityreference_autocomplete_validate()
*
* @param $input
* Single string from autocomplete widget.
* @param $element
* The form element to set a form error.
* @return
* Value of a matching entity id, or NULL if none.
*/
public function validateAutocompleteInput($input, &$element, &$form_state, $form);
/**
* Give the handler a chance to alter the SelectQuery generated by EntityFieldQuery.
*/
public function entityFieldQueryAlter(SelectQueryInterface $query);
/**
* Return the label of a given entity.
*/
public function getLabel($entity);
/**
* Generate a settings form for this handler.
*/
public static function settingsForm($field, $instance);
}
/**
* A null implementation of EntityReference_SelectionHandler.
*/
class EntityReference_SelectionHandler_Broken implements EntityReference_SelectionHandler {
public static function getInstance($field, $instance = NULL, $entity_type = NULL, $entity = NULL) {
return new EntityReference_SelectionHandler_Broken($field, $instance, $entity_type, $entity);
}
protected function __construct($field, $instance) {
$this->field = $field;
$this->instance = $instance;
}
public static function settingsForm($field, $instance) {
$form['selection_handler'] = array(
'#markup' => t('The selected selection handler is broken.'),
);
return $form;
}
public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) {
return array();
}
public function countReferencableEntities($match = NULL, $match_operator = 'CONTAINS') {
return 0;
}
public function validateReferencableEntities(array $ids) {
return array();
}
public function validateAutocompleteInput($input, &$element, &$form_state, $form) {
return NULL;
}
public function entityFieldQueryAlter(SelectQueryInterface $query) {}
public function getLabel($entity) {
return '';
}
}
-7
View File
@@ -1,7 +0,0 @@
<?php
$plugin = array(
'title' => t('Simple (with optional filter by bundle)'),
'class' => 'EntityReference_SelectionHandler_Generic',
'weight' => -100,
);
-9
View File
@@ -1,9 +0,0 @@
<?php
if (module_exists('views')) {
$plugin = array(
'title' => t('Views: Filter by an entity reference view'),
'class' => 'EntityReference_SelectionHandler_Views',
'weight' => 0,
);
}
+1
View File
@@ -0,0 +1 @@
!!! this module is not ready tu use !!!
-114
View File
@@ -1,114 +0,0 @@
<?php
/**
* @file
* Contains EntityReferenceHandlersTestCase
*/
/**
* Test for Entity Reference admin UI.
*/
class EntityReferenceAdminTestCase extends DrupalWebTestCase {
public static function getInfo() {
return array(
'name' => 'Entity Reference UI',
'description' => 'Tests for the administrative UI.',
'group' => 'Entity Reference',
);
}
public function setUp() {
parent::setUp(array('field_ui', 'entity', 'ctools', 'entityreference'));
// Create test user.
$this->admin_user = $this->drupalCreateUser(array('access content', 'administer content types'));
$this->drupalLogin($this->admin_user);
// Create content type, with underscores.
$type_name = strtolower($this->randomName(8)) . '_test';
$type = $this->drupalCreateContentType(array('name' => $type_name, 'type' => $type_name));
$this->type = $type->type;
// Store a valid URL name, with hyphens instead of underscores.
$this->hyphen_type = str_replace('_', '-', $this->type);
}
protected function assertFieldSelectOptions($name, $expected_options) {
$xpath = $this->buildXPathQuery('//select[@name=:name]', array(':name' => $name));
$fields = $this->xpath($xpath);
if ($fields) {
$field = $fields[0];
$options = $this->getAllOptionsList($field);
return $this->assertIdentical($options, $expected_options);
}
else {
return $this->fail(t('Unable to find field @name', array('@name' => $name)));
}
}
/**
* Extract all the options of a select element.
*/
protected function getAllOptionsList($element) {
$options = array();
// Add all options items.
foreach ($element->option as $option) {
$options[] = (string) $option['value'];
}
// TODO: support optgroup.
return $options;
}
public function testFieldAdminHandler() {
$bundle_path = 'admin/structure/types/manage/' . $this->hyphen_type;
// First step: 'Add new field' on the 'Manage fields' page.
$this->drupalPost($bundle_path . '/fields', array(
'fields[_add_new_field][label]' => 'Test label',
'fields[_add_new_field][field_name]' => 'test',
'fields[_add_new_field][type]' => 'entityreference',
'fields[_add_new_field][widget_type]' => 'entityreference_autocomplete',
), t('Save'));
// Node should be selected by default.
$this->assertFieldByName('field[settings][target_type]', 'node');
// The base handler should be selected by default.
$this->assertFieldByName('field[settings][handler]', 'base');
// The base handler settings should be diplayed.
$entity_type = 'node';
$entity_info = entity_get_info($entity_type);
foreach ($entity_info['bundles'] as $bundle_name => $bundle_info) {
$this->assertFieldByName('field[settings][handler_settings][target_bundles][' . $bundle_name . ']');
}
// Test the sort settings.
$options = array('none', 'property', 'field');
$this->assertFieldSelectOptions('field[settings][handler_settings][sort][type]', $options);
// Option 0: no sort.
$this->assertFieldByName('field[settings][handler_settings][sort][type]', 'none');
$this->assertNoFieldByName('field[settings][handler_settings][sort][property]');
$this->assertNoFieldByName('field[settings][handler_settings][sort][field]');
$this->assertNoFieldByName('field[settings][handler_settings][sort][direction]');
// Option 1: sort by property.
$this->drupalPostAJAX(NULL, array('field[settings][handler_settings][sort][type]' => 'property'), 'field[settings][handler_settings][sort][type]');
$this->assertFieldByName('field[settings][handler_settings][sort][property]', '');
$this->assertNoFieldByName('field[settings][handler_settings][sort][field]');
$this->assertFieldByName('field[settings][handler_settings][sort][direction]', 'ASC');
// Option 2: sort by field.
$this->drupalPostAJAX(NULL, array('field[settings][handler_settings][sort][type]' => 'field'), 'field[settings][handler_settings][sort][type]');
$this->assertNoFieldByName('field[settings][handler_settings][sort][property]');
$this->assertFieldByName('field[settings][handler_settings][sort][field]', '');
$this->assertFieldByName('field[settings][handler_settings][sort][direction]', 'ASC');
// Set back to no sort.
$this->drupalPostAJAX(NULL, array('field[settings][handler_settings][sort][type]' => 'none'), 'field[settings][handler_settings][sort][type]');
// Second step: 'Instance settings' form.
$this->drupalPost(NULL, array(), t('Save field settings'));
// Third step: confirm.
$this->drupalPost(NULL, array(), t('Save settings'));
// Check that the field appears in the overview form.
$this->assertFieldByXPath('//table[@id="field-overview"]//td[1]', 'Test label', t('Field was created and appears in the overview page.'));
}
}
-426
View File
@@ -1,426 +0,0 @@
<?php
/**
* @file
* Contains EntityReferenceHandlersTestCase
*/
/**
* Test for Entity Reference handlers.
*/
class EntityReferenceHandlersTestCase extends DrupalWebTestCase {
public static function getInfo() {
return array(
'name' => 'Entity Reference Handlers',
'description' => 'Tests for the base handlers provided by Entity Reference.',
'group' => 'Entity Reference',
);
}
public function setUp() {
parent::setUp('entityreference');
}
protected function assertReferencable($field, $tests, $handler_name) {
$handler = entityreference_get_selection_handler($field);
foreach ($tests as $test) {
foreach ($test['arguments'] as $arguments) {
$result = call_user_func_array(array($handler, 'getReferencableEntities'), $arguments);
$this->assertEqual($result, $test['result'], t('Valid result set returned by @handler.', array('@handler' => $handler_name)));
$result = call_user_func_array(array($handler, 'countReferencableEntities'), $arguments);
$this->assertEqual($result, count($test['result']), t('Valid count returned by @handler.', array('@handler' => $handler_name)));
}
}
}
/**
* Test the node-specific overrides of the entity handler.
*/
public function testNodeHandler() {
// Build a fake field instance.
$field = array(
'translatable' => FALSE,
'entity_types' => array(),
'settings' => array(
'handler' => 'base',
'target_type' => 'node',
'handler_settings' => array(
'target_bundles' => array(),
),
),
'field_name' => 'test_field',
'type' => 'entityreference',
'cardinality' => '1',
);
// Build a set of test data.
// Titles contain HTML-special characters to test escaping.
$nodes = array(
'published1' => (object) array(
'type' => 'article',
'status' => 1,
'title' => 'Node published1 (<&>)',
'uid' => 1,
),
'published2' => (object) array(
'type' => 'article',
'status' => 1,
'title' => 'Node published2 (<&>)',
'uid' => 1,
),
'unpublished' => (object) array(
'type' => 'article',
'status' => 0,
'title' => 'Node unpublished (<&>)',
'uid' => 1,
),
);
$node_labels = array();
foreach ($nodes as $key => $node) {
node_save($node);
$node_labels[$key] = check_plain($node->title);
}
// Test as a non-admin.
$normal_user = $this->drupalCreateUser(array('access content'));
$GLOBALS['user'] = $normal_user;
$referencable_tests = array(
array(
'arguments' => array(
array(NULL, 'CONTAINS'),
),
'result' => array(
$nodes['published1']->nid => $node_labels['published1'],
$nodes['published2']->nid => $node_labels['published2'],
),
),
array(
'arguments' => array(
array('published1', 'CONTAINS'),
array('Published1', 'CONTAINS'),
),
'result' => array(
$nodes['published1']->nid => $node_labels['published1'],
),
),
array(
'arguments' => array(
array('published2', 'CONTAINS'),
array('Published2', 'CONTAINS'),
),
'result' => array(
$nodes['published2']->nid => $node_labels['published2'],
),
),
array(
'arguments' => array(
array('invalid node', 'CONTAINS'),
),
'result' => array(),
),
array(
'arguments' => array(
array('Node unpublished', 'CONTAINS'),
),
'result' => array(),
),
);
$this->assertReferencable($field, $referencable_tests, 'Node handler');
// Test as an admin.
$admin_user = $this->drupalCreateUser(array('access content', 'bypass node access'));
$GLOBALS['user'] = $admin_user;
$referencable_tests = array(
array(
'arguments' => array(
array(NULL, 'CONTAINS'),
),
'result' => array(
$nodes['published1']->nid => $node_labels['published1'],
$nodes['published2']->nid => $node_labels['published2'],
$nodes['unpublished']->nid => $node_labels['unpublished'],
),
),
array(
'arguments' => array(
array('Node unpublished', 'CONTAINS'),
),
'result' => array(
$nodes['unpublished']->nid => $node_labels['unpublished'],
),
),
);
$this->assertReferencable($field, $referencable_tests, 'Node handler (admin)');
}
/**
* Test the user-specific overrides of the entity handler.
*/
public function testUserHandler() {
// Build a fake field instance.
$field = array(
'translatable' => FALSE,
'entity_types' => array(),
'settings' => array(
'handler' => 'base',
'target_type' => 'user',
'handler_settings' => array(
'target_bundles' => array(),
),
),
'field_name' => 'test_field',
'type' => 'entityreference',
'cardinality' => '1',
);
// Build a set of test data.
$users = array(
'anonymous' => user_load(0),
'admin' => user_load(1),
'non_admin' => (object) array(
'name' => 'non_admin <&>',
'mail' => 'non_admin@example.com',
'roles' => array(),
'pass' => user_password(),
'status' => 1,
),
'blocked' => (object) array(
'name' => 'blocked <&>',
'mail' => 'blocked@example.com',
'roles' => array(),
'pass' => user_password(),
'status' => 0,
),
);
// The label of the anonymous user is variable_get('anonymous').
$users['anonymous']->name = variable_get('anonymous', t('Anonymous'));
$user_labels = array();
foreach ($users as $key => $user) {
if (!isset($user->uid)) {
$users[$key] = $user = user_save(drupal_anonymous_user(), (array) $user);
}
$user_labels[$key] = check_plain($user->name);
}
// Test as a non-admin.
$GLOBALS['user'] = $users['non_admin'];
$referencable_tests = array(
array(
'arguments' => array(
array(NULL, 'CONTAINS'),
),
'result' => array(
$users['admin']->uid => $user_labels['admin'],
$users['non_admin']->uid => $user_labels['non_admin'],
),
),
array(
'arguments' => array(
array('non_admin', 'CONTAINS'),
array('NON_ADMIN', 'CONTAINS'),
),
'result' => array(
$users['non_admin']->uid => $user_labels['non_admin'],
),
),
array(
'arguments' => array(
array('invalid user', 'CONTAINS'),
),
'result' => array(),
),
array(
'arguments' => array(
array('blocked', 'CONTAINS'),
),
'result' => array(),
),
);
$this->assertReferencable($field, $referencable_tests, 'User handler');
$GLOBALS['user'] = $users['admin'];
$referencable_tests = array(
array(
'arguments' => array(
array(NULL, 'CONTAINS'),
),
'result' => array(
$users['anonymous']->uid => $user_labels['anonymous'],
$users['admin']->uid => $user_labels['admin'],
$users['non_admin']->uid => $user_labels['non_admin'],
$users['blocked']->uid => $user_labels['blocked'],
),
),
array(
'arguments' => array(
array('blocked', 'CONTAINS'),
),
'result' => array(
$users['blocked']->uid => $user_labels['blocked'],
),
),
array(
'arguments' => array(
array('Anonymous', 'CONTAINS'),
array('anonymous', 'CONTAINS'),
),
'result' => array(
$users['anonymous']->uid => $user_labels['anonymous'],
),
),
);
$this->assertReferencable($field, $referencable_tests, 'User handler (admin)');
}
/**
* Test the comment-specific overrides of the entity handler.
*/
public function testCommentHandler() {
// Build a fake field instance.
$field = array(
'translatable' => FALSE,
'entity_types' => array(),
'settings' => array(
'handler' => 'base',
'target_type' => 'comment',
'handler_settings' => array(
'target_bundles' => array(),
),
),
'field_name' => 'test_field',
'type' => 'entityreference',
'cardinality' => '1',
);
// Build a set of test data.
$nodes = array(
'published' => (object) array(
'type' => 'article',
'status' => 1,
'title' => 'Node published',
'uid' => 1,
),
'unpublished' => (object) array(
'type' => 'article',
'status' => 0,
'title' => 'Node unpublished',
'uid' => 1,
),
);
foreach ($nodes as $node) {
node_save($node);
}
$comments = array(
'published_published' => (object) array(
'nid' => $nodes['published']->nid,
'uid' => 1,
'cid' => NULL,
'pid' => 0,
'status' => COMMENT_PUBLISHED,
'subject' => 'Comment Published <&>',
'hostname' => ip_address(),
'language' => LANGUAGE_NONE,
),
'published_unpublished' => (object) array(
'nid' => $nodes['published']->nid,
'uid' => 1,
'cid' => NULL,
'pid' => 0,
'status' => COMMENT_NOT_PUBLISHED,
'subject' => 'Comment Unpublished <&>',
'hostname' => ip_address(),
'language' => LANGUAGE_NONE,
),
'unpublished_published' => (object) array(
'nid' => $nodes['unpublished']->nid,
'uid' => 1,
'cid' => NULL,
'pid' => 0,
'status' => COMMENT_NOT_PUBLISHED,
'subject' => 'Comment Published on Unpublished node <&>',
'hostname' => ip_address(),
'language' => LANGUAGE_NONE,
),
);
$comment_labels = array();
foreach ($comments as $key => $comment) {
comment_save($comment);
$comment_labels[$key] = check_plain($comment->subject);
}
// Test as a non-admin.
$normal_user = $this->drupalCreateUser(array('access content', 'access comments'));
$GLOBALS['user'] = $normal_user;
$referencable_tests = array(
array(
'arguments' => array(
array(NULL, 'CONTAINS'),
),
'result' => array(
$comments['published_published']->cid => $comment_labels['published_published'],
),
),
array(
'arguments' => array(
array('Published', 'CONTAINS'),
),
'result' => array(
$comments['published_published']->cid => $comment_labels['published_published'],
),
),
array(
'arguments' => array(
array('invalid comment', 'CONTAINS'),
),
'result' => array(),
),
array(
'arguments' => array(
array('Comment Unpublished', 'CONTAINS'),
),
'result' => array(),
),
);
$this->assertReferencable($field, $referencable_tests, 'Comment handler');
// Test as a comment admin.
$admin_user = $this->drupalCreateUser(array('access content', 'access comments', 'administer comments'));
$GLOBALS['user'] = $admin_user;
$referencable_tests = array(
array(
'arguments' => array(
array(NULL, 'CONTAINS'),
),
'result' => array(
$comments['published_published']->cid => $comment_labels['published_published'],
$comments['published_unpublished']->cid => $comment_labels['published_unpublished'],
),
),
);
$this->assertReferencable($field, $referencable_tests, 'Comment handler (comment admin)');
// Test as a node and comment admin.
$admin_user = $this->drupalCreateUser(array('access content', 'access comments', 'administer comments', 'bypass node access'));
$GLOBALS['user'] = $admin_user;
$referencable_tests = array(
array(
'arguments' => array(
array(NULL, 'CONTAINS'),
),
'result' => array(
$comments['published_published']->cid => $comment_labels['published_published'],
$comments['published_unpublished']->cid => $comment_labels['published_unpublished'],
$comments['unpublished_published']->cid => $comment_labels['unpublished_published'],
),
),
);
$this->assertReferencable($field, $referencable_tests, 'Comment handler (comment + node admin)');
}
}
+3
View File
@@ -0,0 +1,3 @@
.ctu-term-edit-form-box{border: 1px solid #ddd; padding:0.5em;}
#node-form fieldset.tcu-advanced-options,
#node-form fieldset.tcu-term-fields{width:45%; display:inline-block; vertical-align: top;}
+9
View File
@@ -0,0 +1,9 @@
name = Tode
description = First time this field will be used, it will create a new term with the value inserted in the textfield, after that, the term (tid) will always be the same, just update term name by updating the value of the field. You can keep synchronized a fixe term with a node, you can set an auto title from this field, The required, number of value at 1 and term_node synch of global field are required
project = "Tode"
dependencies[] = taxonomy
dependencies[] = field
package = gui
version = "7.x-0.dev"
core = "7.x"
+729
View File
@@ -0,0 +1,729 @@
<?php
/**
* developed by www.g-u-i.net
* 2011
* First time this field will be used, it will create a new term with the value inserted in the textfield,
* after that, the term (tid) will always be the same, just update term name by updating the value of the field.
* You can keep synchronized a fixe term with a node,
* you can set an auto title from this field, The required,
* number of value at 1 and term_node synch of global field are required
*
*
*/
/**
* Implementation of hook_menu().
*/
/*
function tode_menu() {
$items = array();
// $items['node/%node/tode/%term'] = array(
// 'title' => 'Taxonomy Term',
// 'type' => MENU_LOCAL_TASK,
// 'access callback' => 'tode_node_tab_access',
// 'access arguments' => array(2),
// 'page callback' => 'tode_tab_page',
// 'page arguments' => array(2),
// 'file' => 'tode.pages.inc',
// 'weight' => 2,
// );
return $items;
}
*/
/**
* Implementation of hook_theme().
*/
function tode_theme() {
return array(
'tode' => array(
'arguments' => array('element' => NULL),
),
);
}
/**
* Implementation of hook_init().
*/
function tode_init() {
// File hooks and callbacks may be used by any module.
drupal_add_css(drupal_get_path('module', 'tode') .'/tode.css');
}
/**
* Implementation of hook_field_widget_info().
*/
function tode_field_widget_info() {
return array(
'tode' => array(
'label' => t('Tode (create then update one unique term)'),
'field types' => array('taxonomy_term_reference'),
'behaviors' => array(
'multiple values' => FIELD_BEHAVIOR_DEFAULT,
'default value' => FIELD_BEHAVIOR_NONE,
),
'settings' => array(
'size' => 60,
'show_term_form'=> -1,
'choose_term_parent'=> -1,
'maxlength'=> 255,
),
),
);
}
/**
* Implementation of hook_widget_settings
*/
function tode_field_widget_settings_form($field, $instance){
// dsm($instance, 'tode_field_widget_settings_form : $instance');
// dsm($field, 'field');
$widget = $instance['widget'];
$settings = $widget['settings'];
// '#description' => t('First time this field will be used, it will create a new term with the value inserted in the textfield, after that, the term (tid) will always be the same, just update term name by updating the value of the field. You can keep synchronized a fixe term with a node, you can set an auto title from this field, The required, number of value at 1 and term_node synch of global field are required')
$form['maxlength'] = array(
'#type' => 'textfield',
'#title' => t('Maximum length of term'),
'#default_value' => $settings['maxlength'],
'#element_validate' => array('_tode_widget_settings_maxlength_validate'),
'#required' => TRUE,
'#description' => t('Defines how many characters can be typed into the text field. For values higher than 255, remember that one term name can not be longer than 255 (would be cutted).'),
);
/*
TODO complete the all flow of this
*/
$form['show_term_form'] = array(
'#type' => 'checkbox',
'#title' => t('Show taxonomy term edit form ?'),
'#default_value' => $settings['show_term_form'],
);
$form['choose_term_parent'] = array(
'#type' => 'checkbox',
'#title' => t('Enable taxonomy term parent selection ?'),
'#default_value' => $settings['choose_term_parent'],
);
return $form;
}
function _tode_widget_settings_maxlength_validate($element, &$form_state) {
// dsm('_tode_widget_settings_maxlength_validate');
// dsm($element, '$element');
// dsm($form_state, '$form_state');
$widget = $form_state['values']['instance']['widget'];
$value = $widget['settings']['maxlength'];
if (!is_numeric($value) || intval($value) != $value || $value <= 0) {
form_error($element, t('"Maximum length" must be a positive integer.'));
}
}
/**
* Implementation of FAPI hook_elements().
*
* Any FAPI callbacks needed for individual widgets can be declared here,
* and the element will be passed to those callbacks for processing.
*
* Drupal will automatically theme the element using a theme with
* the same name as the hook_elements key.
*
* Autocomplete_path is not used by text_widget but other widgets can use it
* (see nodereference and userreference).
*
* http://drupal.org/node/224333#hook_element_info
*
*/
#hook_element_info() WHY ??
/*
function tode_element_info(){
return array(
'tode' => array(
'#input' => TRUE,
'#columns' => array('value'),
'#delta' => 0,
'#process' => array('tode_element_process'),
),
);
}
*/
/**
* Implementation of hook_field_widget_form().
*/
function tode_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
// dsm('- - - - tode_field_widget_form');
// dsm($form, '&$form');
// dsm($form_state, '&$form_state');
// dsm($items, 'items');
// dsm($element, '$element');
// dsm($field, '$field');
// dsm($instance, '$instance');
$node = $form_state['node'];
// dsm($node, '$node');
if(isset($items[$delta])){
$term = taxonomy_term_load($items[$delta]['tid']);
// $term = i18n_taxonomy_term_get_translation($term, $node->language); // marche pas avec localized term
// dsm($term, '$term');
$term_parents = taxonomy_get_parents($term->tid);
// dsm($term_parents, '$term_parents');
$term_parent = array_pop($term_parents);
}
# no need of $node->translation_source because with node translation (not entity fields translation) tid remains
# just have to translate term name on submit
// if( !isset($node->id) && isset($node->translation_source) ){
// }
$form['tode_tid'] = array('#type' => 'hidden', '#value' => isset($term) ? $term->tid : 0,'#delta' => $element['#delta'],);
# parent
if( $instance['widget']['settings']['choose_term_parent'] ){
// add parent form autocomplete if activated
$vocabularies = array();
foreach ($field['settings']['allowed_values'] as $tree)
if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary']))
$vocabularies[$vocabulary->vid] = $vocabulary;
$vocabulary = reset($vocabularies);
// dsm($vocabulary, '$vocabulary');
$form['tode_vid'] = array('#type' => 'hidden', '#value' => $vocabulary->vid,'#delta' => $element['#delta'],);
$form['tode_parent_term'] = array(
'#title' => 'Parent ' . $vocabulary->name . ' (optional)',
'#type' => 'textfield',
'#default_value' => isset($term_parent) ? $term_parent->name : '',
'#autocomplete_path' => 'taxonomy/autocomplete' . '/' . $field['field_name'],
'#size' => 60,
'#maxlength' => 1024,
'#element_validate' => array('tode_parent_autocomplete_validate'),
);
}else{
// if parent selection not enabled set the current parent as hidden input
$form['tode_parent_term'] = array(
'#type' => 'hidden',
'#value' => isset($term_parent) ? $term_parent->name : '',
'#delta' => $element['#delta'],
);
}
// set element form item
$element += array(
'#type' => 'textfield',
'#default_value' => isset($term) ? ( if(module_exists('i18n_taxonomy')) ? i18n_taxonomy_term_name($term, $node->language) : $term->name ) : '',
'#size' => $instance['widget']['settings']['size'],
'#maxlength' => $instance['widget']['settings']['maxlength'],
'#element_validate' => array('tode_widget_validate'),
// '#element_submit' => array('tode_widget_submit'),
);
# add the term edit form
if(isset($term))
_tode_add_term_form($form, $term, $instance, $element['#delta']);
// dsm($form, 'end tode_field_widget_form :: $form');
return $element;
}
/**
* _tode_add_term_form($term)
*
* show the complete taxonomy term form if feature is enabled
*
*/
function _tode_add_term_form(&$form, $term, $instance, $delta){
// dsm('- - - - _tode_add_term_form');
module_load_include('inc', 'taxonomy', 'taxonomy.admin');
$term_form = _tode_term_form($term);
// dsm($term_form, 'term_form');
if($term_form){
unset($term_form['actions']);
unset($term_form['#action']);
unset($term_form['#method']);
#unset vid info 'cause is in conflict with the node's vid field
unset($term_form['vid']);
$term_form = _tode_clean_form($term_form);
$prefix = 'tode_termform_'.$instance['field_name'];
$term_form = _tode_prefix_form($term_form, $prefix.'_');
$visible = $instance['widget']['settings']['show_term_form'];
$form[$prefix] = array(
'#type' => 'fieldset',
'#title' => t('Term edit'),
'#tree' => TRUE,
'#collapsible' => TRUE,
'#collapsed' => FALSE,
'#weight'=>1,
// '#group'=>'additional_settings',
'#prefix' => $visible ? null : '<div style="display:none;">',
'#suffix' => $visible ? null : '</div>',
);
$form[$prefix] += $term_form;
// $form['tode_termform'] = array('#type' => 'hidden', '#value' => 'true','#delta' => $delta,);
}
}
/**
* Form element validate handler for tode parent term autocomplete element.
*/
function tode_parent_autocomplete_validate($element, &$form_state) {
// dsm('- - - - tode_autocomplete_validate');
// dsm($element, '$element');
// dsm($form_state, '$form_state');
$value = array();
if ($typed_term = $element['#value']) {
// Translate term names into actual terms.
// See if the term exists in the chosen vocabulary and return the tid;
// otherwise, set error.
if ($possibilities = taxonomy_term_load_multiple(array(), array('name' => trim($typed_term), 'vid' => $form_state['values']['tode_vid']))) {
$term = array_pop($possibilities);
$value = (array)$term;
}
else {
form_error($element, t('Parent term can only be an existing term.'));
}
}
//
// dsm('form_set_value');
form_set_value($element, $value, $form_state);
}
/**
* Validation function for the tode element
*
* parses input and sets the values as needed (tid) for storing the data
*/
function tode_widget_validate($element, &$form_state){
// dsm('- - - - tode_widget_validate');
// dsm($form_state, 'form_state');
// dsm($element, 'element');
$node = $form_state['node'];
$value = array();
if ($typed_term = $element['#value']) {
$field = field_widget_field($element, $form_state);
// dsm($field, 'field');
$vocabularies = array();
foreach ($field['settings']['allowed_values'] as $tree) {
if ($vocabulary = taxonomy_vocabulary_machine_name_load($tree['vocabulary'])) {
$vocabularies[$vocabulary->vid] = $vocabulary;
}
}
// get the parent term tid or 0 (no parents)
$parent_tid = isset($form_state['values']['tode_parent_term']['tid']) ? $form_state['values']['tode_parent_term']['tid'] : 0;
// See if the term already exists and load the term
// otherwise, create a new 'autocreate' term for insert.
if($tid = $form_state['values']['tode_tid']){
$term = taxonomy_term_load($tid);
$term->name = $typed_term;
$term->parent = $parent_tid;
}else{
$vocabulary = reset($vocabularies);
$term = (object)array(
'tid' => 'autocreate', // autocreate not needed with direct taxonomy_term_save [EDIT] autocreate needed because of the hook_submit insted of hook_validate
'vid' => $vocabulary->vid,
'name' => $typed_term,
'vocabulary_machine_name' => $vocabulary->machine_name,
'parent' => $parent_tid,
);
// taxonomy_term_save($term); // save here the new term to directly get the tid on hook_node_validate
// [EDIT] do not save the term here because it will be save even if node form is not validate
// results term without node or mutiple orfan term
// moving all process on node submit
}
// dsm($term, '$term');
$value = (array)$term;
}
// dsm($value, '$value');
form_set_value($element, $value, $form_state);
}
/**
* Implements hook_field_widget_error().
*/
function tode_field_widget_error($element, $error, $form, &$form_state) {
# use this to set errors
form_error($element['value'], $error['message']);
}
/**
* Implements hook_node_submit().
*/
function tode_node_submit($node, $form, &$form_state) {
// dsm('- - - tode_node_submit');
// dsm($node, '$node');
// dsm($form, '$form');
// dsm($form_state, '$form_state');
module_load_include('inc', 'taxonomy', 'taxonomy.admin');
// module_load_include('inc', 'i18n_string', 'i18n_string.pages');
//
$tode_fields = _tode_get_tode_fields_def($node);
// dsm($tode_fields, '$tode_fields');
if(!count($tode_fields))
return;
$language = $node->language;
$default_language = language_default('language');
// dsm($default_language, '$default_language');
foreach ($tode_fields as $field_name => $field) {
// retreive the prefixed termfom values (hidden or visible)
$prefix = 'tode_termform_'.$field_name;
// if term_form is not available
// it meens that we are on the creation of a node
// hook_node_presave will handle this case
if( !isset($form_state['values'][$prefix]) )
continue;
// else
// we are on the update or on the translation (from initial node)
// so we can go forward
// retreive the initial tode_field language
$init_language = $form[$field_name]['#language'];
// retreive the value of term field, to get the typed term name
$tode_field_term_value = $form_state['values'][$field_name][$init_language][0];
// dsm($tode_field_term_value, '$tode_field_term_value');
$values = _tode_prefix_form($form_state['values'][$prefix], $prefix.'_', FALSE);
// dsm($values, 'values');
if(!module_exists('i18n_taxonomy') || $language == 'und' || $language == $default_language){
// define the form_state for term_form submit
$new_term_form_state = array(
'build_info'=>array(
'args'=>array(0=>(object)$tode_field_term_value),
),
"values"=>array(
'name'=> $tode_field_term_value['name'], // replace the original (hidden) term name value by the typed in the the entity field
'op'=> t('Save'),
)
);
// add new values to form_state
$new_term_form_state['values'] += $values;
// dsm($new_term_form_state, 'form_state');
drupal_form_submit('taxonomy_form_term', $new_term_form_state);
}else{
$context= array('term',$values['tid'],'name');
i18n_string_textgroup('taxonomy')->update_translation($context, $language, $tode_field_term_value['name']);
}
}
}
/**
* Implements hook_node_presave().
*/
function tode_node_presave($node) {
// dsm('- - - tode_node_presave');
// dsm($node, 'node');
if($node->nid)
return;
$tode_fields = _tode_get_tode_fields_def($node);
if(!count($tode_fields))
return;
$default_language = language_default('language');
// purpose of that is to directly atribute the right language to the term
foreach ($tode_fields as $field_name => $field){
$tode_field = $node->$field_name;
$tode_field_term = $tode_field[$node->language][0]; // on node creation field language is always to und (sure ?)
// // test the language, if not default language create the term name translation
if( module_exists('i18n_taxonomy') && ( $node->language != 'und' || $node->language != $default_language ) ){
$context= array('term',$tode_field_term['tid'],'name');
i18n_string_textgroup('taxonomy')->update_translation($context, $node->language, $tode_field_term['name']);
}
}
}
/*
TODO Sélectionner une traduction pour test tode fr
merge two terms when translation is made by selecting a node whiche already exists
*/
/**
* Implementation of hook_form_alter().
*
* node deletion to delete also the tode term
*
*/
function tode_form_alter(&$form, $form_state, $form_id){
/*
TODO block the deletion if tode term has children !! because this will delete them to …
*/
if (stripos($form_id, 'node_delete_confirm') !== false){
// dsm($form_id, 'tode form_alter form_id');
_tode_node_delete_form_alter($form, $form_state);
// dsm($form);
}else if(stripos($form_id, 'node_admin_content') !== false){
if(isset($form['operation']) && $form['operation']['#value'] == 'delete'){
// dsm($form, 'node_admin_content form');
// dsm($form_state, 'form_state');
_tode_nodes_delete_form_alter($form, $form_state);
}
}
}
function _tode_node_delete_form_alter(&$form, $form_state){
// dsm($form, '_tode_node_delete_form_alter : form');
// get the node
$node = $form['#node'];
// dsm($node, '$node');
#get the fields defenition of node type
$tode_fields = _tode_get_tode_fields_def($node);
// dsm($tode_fields);
if(count($tode_fields) == 0)
return;
#get the terms value
$terms = array('names'=>array(), 'tids'=>array());
foreach ($tode_fields as $field_name => $field)
_tode_populate_terms_node_delete($terms, $node->$field_name);
_tode_node_delete_prepare_form($form, $terms);
}
function _tode_nodes_delete_form_alter(&$form, $form_state){
// dsm($form, '_tode_nodes_delete_form_alter : form');
$nodes = array();
foreach ($form_state['values']['nodes'] as $nid => $actif)
if($actif)
$nodes[] = node_load($nid);
#get the terms value
$terms = array('names'=>array(), 'tids'=>array());
foreach ($nodes as $node) {
#get the fields definition of node type
$tode_fields = _tode_get_tode_fields_def($node);
//dsm($tode_fields);
if(count($tode_fields) == 0)
continue;
foreach ($tode_fields as $field_name => $field)
_tode_populate_terms_node_delete($terms, $node->$field_name);
}
_tode_node_delete_prepare_form($form, $terms);
}
function _tode_populate_terms_node_delete(&$terms, $tode_field){
foreach ($tode_field as $language) {
foreach ($language as $term) {
$term = taxonomy_term_load($term['tid']);
if(!in_array($term->tid, $terms['tids'])){
$terms['names'][] = $term->name;
$terms['tids'][] = $term->tid;
}
}
}
}
function _tode_node_delete_prepare_form(&$form, $terms){
if(count($terms)){
/*
TODO add here a checkbox to select terms to delete
*/
#add some warning in form description
$form['description']['#markup'] .= '<br />'.t('this will also delete taxonomy terms : %terms', array('%terms'=>implode(', ', $terms['names'])));
$form['tode_delete'] = array( '#type' => 'hidden', '#value' => serialize($terms['tids']),);
$form['tode_terms'] = array('#type' => 'hidden', '#value' => serialize($terms['names']),);
$form['#submit'][] = 'tode_delete_submit';
}
}
function tode_delete_submit($form, &$form_state){
$tids = unserialize($form['tode_delete']['#value']);
foreach ($tids as $tid)
taxonomy_term_delete($tid);
$terms = unserialize($form['tode_terms']['#value']);
drupal_set_message(t('Following Taxonomy terms have been deleted : %terms', array('%terms' => implode(', ', $terms) )), 'status');
}
/**
* HELPERS
*/
function _tode_clean_form($form, $level = 0){
foreach ($form as $key => $value) {
if(strpos($key,'#') !== false || $key == 'form_build_id' || $key == 'form_id' || $key == 'form_token'){
if( $level == 0 || $key == "#element_validate")
unset($form[$key]);
}elseif(is_array($value)){
$form[$key] = _tode_clean_form($value, $level+1);
}
}
return $form;
}
function _tode_prefix_form($form, $prefix = '', $add = TRUE){
foreach ($form as $key => $value) {
if(strpos($key,'#') === false){
if((isset($value['#type']) && $value['#type'] == 'fieldset') || (!$add && is_array($value)))
$value = _tode_prefix_form($value, $prefix, $add);
if($add){
$form[$prefix.$key] = $value;
unset($form[$key]);
}elseif(strpos($key, $prefix) !== false ){
$form[str_replace($prefix, '', $key)] = $value;
unset($form[$key]);
}
}
}
return $form;
}
/**
* _tode_term_form($tid)
*
*/
function _tode_term_form($term){
// dsm('_tode_term_form');
if ($term) {
$form_state = array(
'build_info'=>array(
'args'=>array(0=>$term)
),
'method'=>'post',
);
// function taxonomy_form_term($form, &$form_state, $edit = array(), $vocabulary = NULL) {
$term_form = drupal_retrieve_form('taxonomy_form_term', $form_state);
drupal_prepare_form('taxonomy_form_term', $term_form, $form_state);
return $term_form;
}else{
return false;
}
}
/**
* _tode_trim_options(&$form, $element)
*
*/
function _tode_trim_options(&$form, $item){
foreach ($form[$item] as $field_name => $field) {
if(((is_array($field)) && $field['#type'] == 'select') && $field['#multiple']){
$options = $field['#options'];
for ($i=0; $i < count($options); $i++) {
if(!isset($options[$i]->option))
continue;
$op = array();
foreach ($options[$i]->option as $key => $value)
$op[$key] = strlen($value) > 25 ? substr_replace ($value, ' [...] ', 15, -10) : $value; // affiche 'abc...xyz'
$options[$i]->option = $op;
}
$field['#options'] = $options;
$form[$item][$field_name] = $field;
}
}
}
/**
* OK OK OK
*/
function _tode_get_tode_fields_def($node){
// dsm($node, '_tode_get_fields_def');
#get the fields defenition of node type
$type_fields = field_info_instances('node');
// dsm($type_fields, 'type_fields definition');
#get the tode node fields
$tode_fields = array();
foreach ($type_fields[$node->type] as $field_name => $field) {
if($field['widget']['type'] == 'tode')
$tode_fields[$field_name] = $field;
}
return $tode_fields;
}
-136
View File
@@ -1,136 +0,0 @@
<?php
/**
* @file
* Views integration for Entity Reference.
*/
/**
* Implements hook_field_views_data().
*/
function entityreference_field_views_data($field) {
$data = field_views_field_default_views_data($field);
$entity_info = entity_get_info($field['settings']['target_type']);
foreach ($data as $table_name => $table_data) {
if (isset($entity_info['base table'])) {
$entity = $entity_info['label'];
if ($entity == t('Node')) {
$entity = t('Content');
}
$field_name = $field['field_name'] . '_target_id';
$parameters = array('@entity' => $entity, '!field_name' => $field['field_name']);
$data[$table_name][$field_name]['relationship'] = array(
'handler' => 'views_handler_relationship',
'base' => $entity_info['base table'],
'base field' => $entity_info['entity keys']['id'],
'label' => t('@entity entity referenced from !field_name', $parameters),
'group' => t('Entity Reference'),
'title' => t('Referenced Entity'),
'help' => t('A bridge to the @entity entity that is referenced via !field_name', $parameters),
);
}
}
// Invoke the behaviors to allow them to change the properties.
foreach (entityreference_get_behavior_handlers($field) as $handler) {
$handler->views_data_alter($data, $field);
}
return $data;
}
/**
* Options callback for Views handler views_handler_filter_in_operator.
*/
function entityreference_views_handler_options_list($field_name) {
$field = field_info_field($field_name);
return entityreference_options_list($field);
}
/**
* Implements hook_field_views_data_views_data_alter().
*
* Views integration to provide reverse relationships on entityreference fields.
*/
function entityreference_field_views_data_views_data_alter(&$data, $field) {
foreach ($field['bundles'] as $entity_type => $bundles) {
$target_entity_info = entity_get_info($field['settings']['target_type']);
if (isset($target_entity_info['base table'])) {
$entity_info = entity_get_info($entity_type);
$entity = $entity_info['label'];
if ($entity == t('Node')) {
$entity = t('Content');
}
$target_entity = $target_entity_info['label'];
if ($target_entity == t('Node')) {
$target_entity = t('Content');
}
$pseudo_field_name = 'reverse_' . $field['field_name'] . '_' . $entity_type;
$replacements = array('@entity' => $entity, '@target_entity' => $target_entity, '!field_name' => $field['field_name']);
$data[$target_entity_info['base table']][$pseudo_field_name]['relationship'] = array(
'handler' => 'views_handler_relationship_entity_reverse',
'field_name' => $field['field_name'],
'field table' => _field_sql_storage_tablename($field),
'field field' => $field['field_name'] . '_target_id',
'base' => $entity_info['base table'],
'base field' => $entity_info['entity keys']['id'],
'label' => t('@entity referencing @target_entity from !field_name', $replacements),
'group' => t('Entity Reference'),
'title' => t('Referencing entity'),
'help' => t('A bridge to the @entity entity that is referencing @target_entity via !field_name', $replacements),
);
}
}
}
/**
* Implements hook_views_plugins().
*/
function entityreference_views_plugins() {
$plugins = array(
'display' => array(
'entityreference' => array(
'title' => t('Entity Reference'),
'admin' => t('Entity Reference Source'),
'help' => 'Selects referenceable entities for an entity reference field',
'handler' => 'entityreference_plugin_display',
'uses hook menu' => FALSE,
'use ajax' => FALSE,
'use pager' => FALSE,
'accept attachments' => FALSE,
// Custom property, used with views_get_applicable_views() to retrieve
// all views with a 'Entity Reference' display.
'entityreference display' => TRUE,
),
),
'style' => array(
'entityreference_style' => array(
'title' => t('Entity Reference list'),
'help' => 'Returns results as a PHP array of labels and rendered rows.',
'handler' => 'entityreference_plugin_style',
'theme' => 'views_view_unformatted',
'uses row plugin' => TRUE,
'uses fields' => TRUE,
'uses options' => TRUE,
'type' => 'entityreference',
'even empty' => TRUE,
),
),
'row' => array(
'entityreference_fields' => array(
'title' => t('Inline fields'),
'help' => t('Displays the fields with an optional template.'),
'handler' => 'entityreference_plugin_row_fields',
'theme' => 'views_view_fields',
'theme path' => drupal_get_path('module', 'views') . '/theme',
'theme file' => 'theme.inc',
'uses fields' => TRUE,
'uses options' => TRUE,
'type' => 'entityreference',
),
),
);
return $plugins;
}
-118
View File
@@ -1,118 +0,0 @@
<?php
/**
* @file
* Handler for entityreference_plugin_display.
*/
class entityreference_plugin_display extends views_plugin_display {
function option_definition() {
$options = parent::option_definition();
// Force the style plugin to 'entityreference_style' and the row plugin to
// 'fields'.
$options['style_plugin']['default'] = 'entityreference_style';
$options['defaults']['default']['style_plugin'] = FALSE;
$options['defaults']['default']['style_options'] = FALSE;
$options['row_plugin']['default'] = 'entityreference_fields';
$options['defaults']['default']['row_plugin'] = FALSE;
$options['defaults']['default']['row_options'] = FALSE;
// Set the display title to an empty string (not used in this display type).
$options['title']['default'] = '';
$options['defaults']['default']['title'] = FALSE;
return $options;
}
function get_style_type() {
return 'entityreference';
}
function execute() {
return $this->view->render($this->display->id);
}
function render() {
if (!empty($this->view->result) || !empty($this->view->style_plugin->definition['even empty'])) {
return $this->view->style_plugin->render($this->view->result);
}
return '';
}
function uses_exposed() {
return FALSE;
}
function query() {
$options = $this->get_option('entityreference_options');
// Play nice with Views UI 'preview' : if the view is not executed through
// EntityReference_SelectionHandler_Views::getReferencableEntities(),
// don't alter the query.
if (empty($options)) {
return;
}
// Make sure the id field is included in the results, and save its alias
// so that references_plugin_style can retrieve it.
$this->id_field_alias = $id_field = $this->view->query->add_field($this->view->base_table, $this->view->base_field);
if (strpos($id_field, '.') === FALSE) {
$id_field = $this->view->base_table . '.' . $this->id_field_alias;
}
// Restrict the autocomplete options based on what's been typed already.
if (isset($options['match'])) {
$style_options = $this->get_option('style_options');
$value = db_like($options['match']) . '%';
if ($options['match_operator'] != 'STARTS_WITH') {
$value = '%' . $value;
}
// Multiple search fields are OR'd together
$conditions = db_or();
// Build the condition using the selected search fields
foreach ($style_options['search_fields'] as $field_alias) {
if (!empty($field_alias)) {
// Get the table and field names for the checked field
$field = $this->view->query->fields[$this->view->field[$field_alias]->field_alias];
// Add an OR condition for the field
$conditions->condition($field['table'] . '.' . $field['field'], $value, 'LIKE');
}
}
$this->view->query->add_where(NULL, $conditions);
}
// Add an IN condition for validation.
if (!empty($options['ids'])) {
$this->view->query->add_where(NULL, $id_field, $options['ids']);
}
$this->view->set_items_per_page($options['limit']);
}
/**
* Extend the default validation.
*/
function validate() {
$errors = parent::validate();
// Verify that search fields are set up.
$style_options = $this->get_option('style_options');
if (!isset($style_options['search_fields'])) {
$errors[] = t('Display "@display" needs a selected search fields to work properly. See the settings for the Entity Reference list format.', array('@display' => $this->display->display_title));
}
else {
// Verify that the search fields used actually exist.
//$fields = array_keys($this->view->get_items('field'));
$fields = array_keys($this->handlers['field']);
foreach ($style_options['search_fields'] as $field_alias => $enabled) {
if ($enabled && !in_array($field_alias, $fields)) {
$errors[] = t('Display "@display" uses field %field as search field, but the field is no longer present. See the settings for the Entity Reference list format.', array('@display' => $this->display->display_title, '%field' => $field_alias));
}
}
}
return $errors;
}
}
@@ -1,36 +0,0 @@
<?php
/**
* @file
* Handler for entityreference_plugin_row_fields.
*/
class entityreference_plugin_row_fields extends views_plugin_row_fields {
function option_definition() {
$options = parent::option_definition();
$options['separator'] = array('default' => '-');
return $options;
}
/**
* Provide a form for setting options.
*/
function options_form(&$form, &$form_state) {
parent::options_form($form, $form_state);
// Expand the description of the 'Inline field' checkboxes.
$form['inline']['#description'] .= '<br />' . t("<strong>Note:</strong> In 'Entity Reference' displays, all fields will be displayed inline unless an explicit selection of inline fields is made here." );
}
function pre_render($row) {
// Force all fields to be inline by default.
if (empty($this->options['inline'])) {
$fields = $this->view->get_items('field', $this->display->id);
$this->options['inline'] = drupal_map_assoc(array_keys($fields));
}
return parent::pre_render($row);
}
}
-66
View File
@@ -1,66 +0,0 @@
<?php
/**
* @file
* Handler for entityreference_plugin_style.
*/
class entityreference_plugin_style extends views_plugin_style {
function option_definition() {
$options = parent::option_definition();
$options['search_fields'] = array('default' => NULL);
return $options;
}
// Create the options form.
function options_form(&$form, &$form_state) {
parent::options_form($form, $form_state);
$options = array();
if (isset($form['grouping'])) {
$options = $form['grouping'][0]['field']['#options'];
unset($options['']);
$form['search_fields'] = array(
'#type' => 'checkboxes',
'#title' => t('Search fields'),
'#options' => $options,
'#required' => TRUE,
'#default_value' => $this->options['search_fields'],
'#description' => t('Select the field(s) that will be searched when using the autocomplete widget.'),
'#weight' => -3,
);
}
}
function render() {
$options = $this->display->handler->get_option('entityreference_options');
// Play nice with Views UI 'preview' : if the view is not executed through
// EntityReference_SelectionHandler_Views::getReferencableEntities(), just
// display the HTML.
if (empty($options)) {
return parent::render();
}
// Group the rows according to the grouping field, if specified.
$sets = $this->render_grouping($this->view->result, $this->options['grouping']);
// Grab the alias of the 'id' field added by entityreference_plugin_display.
$id_field_alias = $this->display->handler->id_field_alias;
// @todo We don't display grouping info for now. Could be useful for select
// widget, though.
$results = array();
$this->view->row_index = 0;
foreach ($sets as $records) {
foreach ($records as $values) {
// Sanitize html, remove line breaks and extra whitespace.
$results[$values->{$id_field_alias}] = filter_xss_admin(preg_replace('/\s\s+/', ' ', str_replace("\n", '', $this->row_plugin->render($values))));
$this->view->row_index++;
}
}
unset($this->view->row_index);
return $results;
}
}