Convert lead into a contact using a logic hook - sugarcrm

I looked in the dev guide and online but can't seem to find any code examples. I'm just trying to convert a lead into a contact.
For example I have a lead with ID: 7, what I'm trying to do is possibly modify a bean property to convert that lead into a contact (not sure if this approach is correct). Something like
$bean->convert("Contact");
$bean->save();
Thank you for your advice

In sugar/suite, conversion is a process which is copying a bean from one module to another module e.g. lead into contact.
I have been using this function to make it happen.
function outright_copy_bean($old_bean){
$new_bean = new $old_bean->object_name;
foreach($new_bean->field_defs as $key => $value){
if(in_array($key, array("id", "date_entered"))){
continue;
}
if($value["type"] == "link"){
continue;
}
$new_bean->$key = $old_bean->$key;
}
$new_id = $new_bean->save();
return $new_id
}

Related

Phalcon form validation messages

There are some misunderstandings about how the messaging works for the Forms in Phalcon. Say we have a form and trying to add some extended error message for one of fields named 'code' in controller:
$form = new SampleForm();
Implementation of SampleForm is done in a corresponding class through initialize and the code element is $code = new \Phalcon\Forms\Element\Text('code');
The next code adds the message :
$form->get('code')->appendMessage(new \Phalcon\Validation\Message("The Code desn\'t exist or not valid"));
but trying to receive this message like
$form->getMessagesFor('code')
gives me nothing (the dump):
Phalcon\Validation\Message\Group Object
(
[_position:protected] =>
[_messages:protected] =>
)
Another attempt via
$form->get('code')->getMessages()
gives (the dump):
Phalcon\Validation\Message\Group Object
(
[_position:protected] =>
[_messages:protected] => Array
(
[0] => Phalcon\Validation\Message Object
(
[_type:protected] =>
[_message:protected] => The Code desn\'t exist or not valid
[_field:protected] =>
[_code:protected] => 0
)
)
)
My question: what am I doing wrong and why $form->[get/has]MessagesFor($name) doesn't work as expected?
I'm sorry to tell you, form handling is really poorly implemented and messed up in Phalcon, as I can see now, after a few months work.
In this case, you have multiple getMessage functions and they DO NOT return the same value. Even some of them returns a reference and some of them returns a copy of the error messages, and if you are appending messages to the copy, they won't be available elsewhere through the getMessage functions.
This even changed form version 1.2 to 1.3, we had a hard time figuring out which functions should we use. If you like, you could check out the C code behind this, in the Phalcon repository, it has been a great help for me to figure out why things don't work the way I expected.
My advices is, print the values of getMessage functions: Form::getMessages(), Form::getMessagesFor(), Form::get('element_name')->getMessages(). Then try appending new messages to them and print them again. See which one contains your messages.
I ended up getting messages for Phalcon's built in validation classes by $form->get('email')->getMessages() and getting my own added in the controller by $form->getMessagesFor('email'). I am still searching for a solution to get all the messages in one place.
Serin is right, messages are saved into different objects, so i came up with getting all of those like this
<?php foreach ($form as $element) {
//Get any generated messages for the current element
foreach ([$form->getMessagesFor($element->getName()), $element->getMessages()] as $messages) {
if (count($messages)) {
//Print each element
foreach ($messages as $message) {
echo $message;
}
}
}
}?>
Let's hope easier method will be added in nearest future:

DBIx::Class Wrapping/overloading a column accessor

Using DBIx::Class I am trying to manipulate the data of a column whenever it is being updated or retrieved. For instance, before it goes into the database I would like to encrypt it, and whenever it is being accessed I would like to decrypt it. I am following this example in the DBIx::Class::Manual::Cookbook, however I can't seem to get it to work. I have placed the following in my User schema. For testing I am just using the name column, I know it doesn't make sense:
__PACKAGE__->add_columns("name" => { accessor => '_name' });
sub name {
my $self = shift;
# If there is an update to the column, we'll let the original accessor
# deal with it.
if(#_) {
return $self->_name('test 1');
}
# Fetch the column value.
my $name = $self->_name;
$name = 'test 2';
return $name;
}
I can't see what I'm doing any different than what the cookbook says. Can't anyone help me understand what I'm doing wrong? Thanks!
DBIx::Class has a component for that called FilterColumn.
There are various modules on CPAN using that component like DBIx::Class::EncodedColumn and PassphraseColumn.
If you tell us what you use case is we might give you more/better suggestions.

Silex / Symfony2 Post-Validation

Im sure this must be a RTM question, but I must be looking in the wrong places. In symfony 1.4 I used post validator callbacks quite a lot. For example checking that start and end dates were in the correct order. I am developing an app in Silex but cant figure out how to add similar functionality as a validator. This is what I am working with (basically):
$app['form.example'] = function ($app) {
$constraints = new Assert\Collection(array(
'date1' => new Assert\Date(),
'date2' => new Assert\Date(),
));
$builder = $app['form.factory']->createNamedBuilder('form', 'example', array(), array('validation_constraint' => $constraints));
return $builder
->add('date1', 'date')
->add('date2', 'date')
->getForm();
};
I can put my own validation test in the 'process form' part, like: if ($form->isValid() && --my datetest--) but it doesnt feel right to me there.
Any help? Thanks!
I guess you can use form events for this kind of thing; certainly for Symfony2, so I assume Silex too? There's a cookbook article about using it to generate dynamic forms:
http://symfony.com/doc/current/cookbook/form/dynamic_form_generation.html
Some useful detail in another SO question:
Description of Symfony2 form events?
Could have sworn I had a SO discussion about this with someone before but I cannot find the question. I used BIND_CLIENT_DATA to calculate some form fields in some code a while back; I'll see if I can dig it out.
EDIT
Okay, I found something but I'm modifying this from Symfony code so I'm not 100% on this but it might be a starting point (I hope):
$builder->addEventListener(FormEvents::BIND_NORM_DATA, function($event) {
// your form data
$data = $event->getData();
// get date objects - if you cannot dereference this way try getters
$d1 = $data['date1'];
$d2 = $data['date2'];
// naive comparison :)
$isCorrectDateOrder = $d1->getTimestamp() < $d2->getTimestamp();
// check the comparison
if (!$isCorrectDateOrder) {
// trouble... create and add a FormError object to the form
$event->getForm()->get('date1')->addError(new \Symfony\Component\Form\FormError('uh oh...'));
}
});
Hope this helps :)

zend loading models using eval in helpers

i want to load models from helpers... im using eval to insert the modelname etc.
public function getMod($mName) {
// this works but need a dynamic one
$model = $this->users = new Application_Model_Users();
// so i did this:
$model = $this->_listsMod = eval ("new Application_Model_$mName();");
return $model;
and you can call it by: $this->_helper->getmod->getMod('Users')->myuserFunc();
but it doesnt work, its says Fatal error: Call to a member function myuserFunc() on a non-object
Updated answer:
Have you tried:
$modelName = 'Application_Model_'.$mName;
$model = $this->_lists = new $modelName ;
?
You should have a look at the Factory Pattern (which is effectively what you're doing here) eg here and here.
As you probably know, its best to avoid using eval if possible. Also, it seems a bit odd needing to load Models like this - can you tell us why you need to load them like this?
Note: I've updated this answer following comments below, to make it quicker for future readers of the question / answer.

How does the session state work in MVC 2.0?

I have a controller that stores various info (Ie. FormID, QuestionAnswerList, etc). Currently I am storing them in the Controller.Session and it works fine.
I wanted to break out some logic into a separate class (Ie. RulesController), where I could perform certain checks, etc, but when I try and reference the Session there, it is null. It's clear that the Session remains valid only within the context of the specific controller, but what is everyone doing regarding this?
I would imagine this is pretty common, you want to share certain "global" variables within the different controllers, what is best practice?
Here is a portion of my code:
In my BaseController class:
public List<QuestionAnswer> QuestionAnswers
{
get
{
if (Session["QuestionAnswers"] == null)
{
List<QuestionAnswer> qAnswers = qaRepository.GetQuestionAnswers(CurrentSection, UserSmartFormID);
Session["QuestionAnswers"] = qAnswers;
return qAnswers;
}
else
{
return (List<QuestionAnswer>)Session["QuestionAnswers"];
}
}
set
{
Session["QuestionAnswers"] = value;
}
}
In my first Controller (derived from BaseController):
QuestionAnswers = qaRepository.GetQuestionAnswers(CurrentSection, UserSmartFormID);
I stepped through the code and the above statement executes fine, setting the Session["QuestionAnswers"], but then when I try to get from another controller below, the Session["QuestionAnswers"] is null!
My second controller (also derived from BaseController):
List<QuestionAnswer> currentList = (List<QuestionAnswer>)QuestionAnswers;
The above line fails! It looks like the Session object itself is null (not just Session["QuestionAnswers"])
does it make a difference if you retrieve your session using
HttpContext.Current.Session("mySpecialSession") ''# note this is VB, not C#
I believe TempData will solve your problem, it operates with in the session and persists across multiple requests, however by default it will clear the stored data once you access it again, if that's a problem you can tell it to keep the info with the newly added Keep() function.
So in your case:
...
TempData["QuestionAnswers"] = qAnswers;
...
There's much more info at:
http://weblogs.asp.net/jacqueseloff/archive/2009/11/17/tempdata-improvements.aspx
Where are you accessing the session in the second controller? The session object is not available in the constructor because it is injected later on in the lifecycle.
Ok, finally got it working, although a bit kludgy. I found the solution from another related SO post.
I added the following to my BaseController:
public new HttpContextBase HttpContext
{
get
{
HttpContextWrapper context =
new HttpContextWrapper(System.Web.HttpContext.Current);
return (HttpContextBase)context;
}
}
Then set/retrieved my Session variables using HttpContext.Session and works fine!